Levels Strength Index [BigBeluga]Levels Strength Index provides a unique perspective on market strength by comparing price positions relative to predefined levels, delivering a dynamic probability-based outlook for potential up and down moves.
🔵 Idea:
The Levels Strength Index analyzes the price position against a series of calculated levels, assigning probabilities for upward and downward movements. These probabilities are displayed in percentage form, providing actionable insights into market momentum and strength. The color-coded display visually reinforces whether the price is predominantly above or below key levels, simplifying trend analysis.
🔵 Key Features:
Dynamic Probability Calculation: The indicator compares the current price position relative to 10 predefined levels, assigning an "Up" and "Down" percentage. For example, if the price is above 8 levels, it will display 80% upward and 20% downward probabilities.
Color-Coded Trend Visualization: When the price is above the majority of levels, the display turns green, signaling strength. Conversely, when below, it shifts to orange, reflecting bearish momentum.
Clear Up/Down Probability Labels: Probabilities are displayed with directional arrows next to the price, instantly showing the likelihood of upward or downward moves.
Probability-Based Price Line: The price line is color-coded based on the probability percentages, allowing a quick glance at the prevailing trend and market strength. This can be toggled in the settings.
Customizable Transparency: Adjust the transparency of the levels to seamlessly integrate the indicator with your preferred chart setup.
Fully Configurable: Control key parameters such as the length of levels and price color mode (trend, neutral, or none) through intuitive settings.
🔵 When to Use:
The Levels Strength Index is ideal for traders looking to:
Identify strong upward or downward market momentum using quantified probabilities.
Visualize price strength relative to key levels with intuitive color coding.
Supplement existing level-based strategies by combining probabilities and market positioning.
Gain instant clarity on potential market moves with percentage-based insights.
Whether you're trading trends or ranges, this tool enhances decision-making by combining level-based analysis with a dynamic probability system, offering a clear, actionable perspective on market behavior.
อินดิเคเตอร์และกลยุทธ์
Macd and RSI % Change Signals Devis'SoLong Signal Strategy
RSI-Based Long Signals:
A long signal is triggered when the percentage change in RSI of the close price crosses over thresholds like 10 or 20.
Similarly, a long signal is triggered when the percentage change in RSI of the low price crosses over 20.
MACD-Based Long Signals:
A long signal is triggered when the MACD, its signal line, or the midpoint of the two crosses over thresholds such as 2, 3, 4, or 5.
When a long signal is triggered, the low of the corresponding candle is recorded as the "pullback level." This pullback level is displayed on the chart to help identify potential areas of support.
Short Signal Strategy
RSI-Based Short Signals:
A short signal is triggered when the percentage change in RSI of the low price crosses under -20.
Similarly, a short signal is triggered when the percentage change in RSI of the close price crosses under thresholds like -10 or -20.
MACD-Based Short Signals:
A short signal is triggered when the MACD, its signal line, or the midpoint of the two crosses under thresholds such as -2, -3, -4, or -5.
When a short signal is triggered, the high of the corresponding candle is recorded as the "pullback level." This pullback level is displayed on the chart to help identify potential areas of resistance.
Visualization
Signals:
Long signals are plotted as green upward triangles below the price bars.
Short signals are plotted as red downward triangles above the price bars.
Pullback Levels:
Long pullback levels are plotted as a green line below the price.
Short pullback levels are plotted as a red line above the price.
Alerts
Alerts are defined for specific signals, allowing traders to receive notifications when important levels are crossed, such as:
Long signal based on RSI or MACD changes.
Short signal based on RSI or MACD changes.
MA Deviation Suite [InvestorUnknown]This indicator combines advanced moving average techniques with multiple deviation metrics to offer traders a versatile tool for analyzing market trends and volatility.
Moving Average Types :
SMA, EMA, HMA, DEMA, FRAMA, VWMA: Standard moving averages with different characteristics for smoothing price data.
Corrective MA: This method corrects the MA by considering the variance, providing a more responsive average to price changes.
f_cma(float src, simple int length) =>
ma = ta.sma(src, length)
v1 = ta.variance(src, length)
v2 = math.pow(nz(ma , ma) - ma, 2)
v3 = v1 == 0 or v2 == 0 ? 1 : v2 / (v1 + v2)
var tolerance = math.pow(10, -5)
float err = 1
// Gain Factor
float kPrev = 1
float k = 1
for i = 0 to 5000 by 1
if err > tolerance
k := v3 * kPrev * (2 - kPrev)
err := kPrev - k
kPrev := k
kPrev
ma := nz(ma , src) + k * (ma - nz(ma , src))
Fisher Least Squares MA: Aims to reduce lag by using a Fisher Transform on residuals.
f_flsma(float src, simple int len) =>
ma = src
e = ta.sma(math.abs(src - nz(ma )), len)
z = ta.sma(src - nz(ma , src), len) / e
r = (math.exp(2 * z) - 1) / (math.exp(2 * z) + 1)
a = (bar_index - ta.sma(bar_index, len)) / ta.stdev(bar_index, len) * r
ma := ta.sma(src, len) + a * ta.stdev(src, len)
Sine-Weighted MA & Cosine-Weighted MA: These give more weight to middle bars, creating a smoother curve; Cosine weights are shifted for a different focus.
Deviation Metrics :
Average Absolute Deviation (AAD) and Median Absolute Deviation (MAD): AAD calculates the average of absolute deviations from the MA, offering a measure of volatility. MAD uses the median, which can be less sensitive to outliers.
Standard Deviation (StDev): Measures the dispersion of prices from the mean.
Average True Range (ATR): Reflects market volatility by considering the day's range.
Average Deviation (adev): The average of previous deviations.
// Calculate deviations
float aad = f_aad(src, dev_len, ma) * dev_mul
float mad = f_mad(src, dev_len, ma) * dev_mul
float stdev = ta.stdev(src, dev_len) * dev_mul
float atr = ta.atr(dev_len) * dev_mul
float avg_dev = math.avg(aad, mad, stdev, atr)
// Calculated Median with +dev and -dev
float aad_p = ma + aad
float aad_m = ma - aad
float mad_p = ma + mad
float mad_m = ma - mad
float stdev_p = ma + stdev
float stdev_m = ma - stdev
float atr_p = ma + atr
float atr_m = ma - atr
float adev_p = ma + avg_dev
float adev_m = ma - avg_dev
// upper and lower
float upper = f_max4(aad_p, mad_p, stdev_p, atr_p)
float upper2 = f_min4(aad_p, mad_p, stdev_p, atr_p)
float lower = f_min4(aad_m, mad_m, stdev_m, atr_m)
float lower2 = f_max4(aad_m, mad_m, stdev_m, atr_m)
Determining Trend
The indicator generates trend signals by assessing where price stands relative to these deviation-based lines. It assigns a trend score by summing individual signals from each deviation measure. For instance, if price crosses above the MAD-based upper line, it contributes a bullish point; crossing below an ATR-based lower line contributes a bearish point.
When the aggregated trend score crosses above zero, it suggests a shift towards a bullish environment; crossing below zero indicates a bearish bias.
// Define Trend scores
var int aad_t = 0
if ta.crossover(src, aad_p)
aad_t := 1
if ta.crossunder(src, aad_m)
aad_t := -1
var int mad_t = 0
if ta.crossover(src, mad_p)
mad_t := 1
if ta.crossunder(src, mad_m)
mad_t := -1
var int stdev_t = 0
if ta.crossover(src, stdev_p)
stdev_t := 1
if ta.crossunder(src, stdev_m)
stdev_t := -1
var int atr_t = 0
if ta.crossover(src, atr_p)
atr_t := 1
if ta.crossunder(src, atr_m)
atr_t := -1
var int adev_t = 0
if ta.crossover(src, adev_p)
adev_t := 1
if ta.crossunder(src, adev_m)
adev_t := -1
int upper_t = src > upper ? 3 : 0
int lower_t = src < lower ? 0 : -3
int upper2_t = src > upper2 ? 1 : 0
int lower2_t = src < lower2 ? 0 : -1
float trend = aad_t + mad_t + stdev_t + atr_t + adev_t + upper_t + lower_t + upper2_t + lower2_t
var float sig = 0
if ta.crossover(trend, 0)
sig := 1
else if ta.crossunder(trend, 0)
sig := -1
Backtesting and Performance Metrics
The code integrates with a backtesting library that allows traders to:
Evaluate the strategy historically
Compare the indicator’s signals with a simple buy-and-hold approach
Generate performance metrics (e.g., mean returns, Sharpe Ratio, Sortino Ratio) to assess historical effectiveness.
Practical Usage and Calibration
Default settings are not optimized: The given parameters serve as a starting point for demonstration. Users should adjust:
len: Affects how smooth and lagging the moving average is.
dev_len and dev_mul: Influence the sensitivity of the deviation measures. Larger multipliers widen the bands, potentially reducing false signals but introducing more lag. Smaller multipliers tighten the bands, producing quicker signals but potentially more whipsaws.
This flexibility allows the trader to tailor the indicator for various markets (stocks, forex, crypto) and time frames.
Disclaimer
No guaranteed results: Historical performance does not guarantee future outcomes. Market conditions can vary widely.
User responsibility: Traders should combine this indicator with other forms of analysis, appropriate risk management, and careful calibration of parameters.
Collatz 3x+1 Devis'SoThis system combines the Collatz 3x+1 theory with technical indicators (RSI, ADX, DI) to analyze price movements and generate trading signals. The working mechanism can be explained as follows:
ADX and Directional Indicators:
ADX and DI+ with DI- are used to calculate the strength and direction of the trend in the market. The difference between DI+ and DI- serves as the basis for determining the directional movement of the price.
Collatz Sequence Application:
The difference between DI+ and DI- is normalized (to a range between 0 and 100), and the Collatz 3x+1 theory is applied to generate a sequence of numbers. Each number in this sequence represents a simplified model of price movements.
A specific step of this sequence (e.g., the 4th step) is selected to calculate a value that abstractly represents price behavior.
RSI and Signal Generation:
RSI is calculated based on the selected step from the Collatz sequence.
When RSI reaches certain levels (e.g., 10) and depending on the direction of the closing prices, the first group of signals is generated (indicating whether the trend is likely to continue or reverse).
Pullback Levels and Collatz Average:
Based on the generated signals, pullback levels are identified for long and short positions.
These levels are averaged to calculate a new reference level called the "Collatz Level," which serves as a midpoint for analyzing price movements.
Subsequent Signals:
The system generates a second group of signals depending on whether the price crosses above or below the Collatz Level. These signals trigger buy or sell positions based on market conditions.
Visualization:
The signals are visualized on the chart using specific shapes and colors (e.g., upward triangles indicate buy signals, downward triangles indicate sell signals).
Overall Objective: This system aims to produce comprehensive and creative trading signals by evaluating price movements through both a mathematical model (Collatz theory) and technical analysis tools.
Scalping 3-Min Forecast This is a multi-feature strategy that combines technical analysis, volume tracking, and dynamic visual elements on the chart. Its purpose is to generate buy/sell signals, plot near-future price forecasts, and display important support/resistance zones. Additionally, it monitors buying versus selling volume to add further insight into potential market bias. Below is a detailed explanation of each component:
1. Technical Indicators & Signals
- RSI (Relative Strength Index)
- Stochastic Oscillator
- Moving Average Cross
When RSI, Stoch, and MA-cross conditions align for bullish or bearish signals, the strategy triggers long or short entries accordingly.
2. Price Forecast Projection
It draws forecast lines and a forecast label on the chart to visualize where price might head over the next bars.
The script ensures the forecast lines have reduced opacity for clarity and color-coded based on trend direction (green for bullish, red for bearish).
3. Support & Resistance
- Important S/R (Last 100 Bars)
- Less Important S/R (Last 50 Bars)
4. Volume Tracking & Label
The script sums buy volume (on up-close bars) and sell volume (on down-close bars) starting from the most recent time price touches an important S/R level (100-bar).
Whenever price hits either the 100-bar support or 100-bar resistance, the cumulative volumes reset to 0 and start summing again.
Near the forecast label, the script displays a single additional label indicating “BUY” or “SELL” based on which volume sum (buy vs. sell) is larger:
If sumBuyVol > sumSellVol, the label is green with text “BUY.”
Otherwise, it is red with text “SELL.”
This gives quick insight into whether bulls or bears have dominated since the last major support/resistance touch.
RS ScanThis indicator is primarily used in Pine Screener to filter stocks with relative strength. There are three screening modes: daily close range percentage, weekly close range percentage, and stock price change.
The close range is used to filter stocks where the close price is positioned at a certain percentage of the entire bar within a day or a week. For example, in the weekly close range percentage, selecting "above 90" means that the weekly closing price is above 90% of the entire bar.
The stock price change is used to filter stocks based on price changes within a specified date range. We can use TradingView to determine the distance from the recent high of SPX to today's closing price: the number of bars X and the price change value Y. Then, in the indicator settings, select the date range X for the number of bars and choose "above Y" in the manual setup. This way, we can filter out stocks that have a price change greater than Y within X bars.
RSI, MACD ve Bollinger Bantları Al/SatAzerbaycanli tarafından hazırlanmış olan indicator çok iyi çalışıyor.
Alarm Kurma:
Kodunuzu kaydedin ve grafiğe ekleyin.
Grafiğin sağ üst köşesindeki saat simgesine (🔔) tıklayın.
"Create Alert" seçeneğini seçin.
Condition kısmından indikatörünüzü ve istediğiniz sinyali seçin (AL veya SAT).
Alarm mesajını özelleştirin veya varsayılan mesajı kullanın.
Daha Esnek Sinyal Koşulları:
RSI ve MACD’nin birlikte veya Bollinger Bantlarının tek başına sinyal vermesi sağlandı.
Daha Net Grafik Etiketleri:
Bollinger Bantları ve diğer unsurların görselliği artırıldı.
Kod Temizliği:
Daha düzenli bir yapı ve kullanıcı dostu açıklamalar eklendi.
ForecastPro by BinhMyco1. Overview:
This Pine Script implements a custom forecasting tool on TradingView, labeled "BinhMyco." It provides a method to predict future price movements based on historical data and a comparison with similar historical patterns. The script supports two types of forecasts: **Prediction** and **Replication**, where the forecasted price can be either based on price peaks/troughs or an average direction. The script also calculates a confidence probability, showing how closely the forecasted data aligns with historical trends.
2. Inputs:
- Source (`src`): The input data source for forecasting, which defaults to `open`.
- Length (`len`): The length of the training data used for analysis (fixed at 200).
- Reference Length (`leng`): A fixed reference length for comparing similar historical patterns (set to 70).
- Forecast Length (`length`): The length of the forecast period (fixed at 60).
- Multiplier (`mult`): A constant multiplier for the forecast confidence cone (set to 4.0).
- Forecast Type (`typ`): Type of forecast, either **Prediction** or **Replication**.
- Direction Type (`dirtyp`): Defines how the forecast is calculated — either based on price **peaks/troughs** or an **average direction**.
- Forecast Divergence Cone (`divcone`): A boolean option to enable the display of a confidence cone around the forecast.
3. Color Constants:
- Green (`#00ffbb`): Color used for upward price movements.
- Red (`#ff0000`): Color used for downward price movements.
- Reference Data Color (`refcol`): Blue color for the reference data.
- Similar Data Color (`simcol`): Orange color for the most similar data.
- Forecast Data Color (`forcol`): Yellow color for forecasted data.
4. Error Checking:
- The script checks if the reference length is greater than half the training data length, and if the forecast length exceeds the reference length, raising errors if either condition is true.
5. Arrays for Calculation:
- Correlation Array (`c`): Holds the correlation values between the data source (`src`) and historical data points.
- Index Array (`index`): Stores the indices of the historical data for comparison.
6. Forecasting Logic:
- Correlation Calculation: The script calculates the correlation between the historical data (`src`) and the reference data over the given reference length. It then identifies the point in history most similar to the current data.
- Forecast Price Calculation: Based on the type of forecast (Prediction or Replication), the script calculates future prices either by predicting based on similar bars or by replicating past data. The forecasted prices are stored in the `forecastPrices` array.
- Forecast Line Drawing: The script draws lines to represent the forecasted price movements. These lines are color-coded based on whether the forecasted price is higher or lower than the current price.
7. Divergence Cone (Optional):
- If the **divcone** option is enabled, the script calculates and draws a confidence cone around the forecasted prices. The upper and lower bounds of the cone are calculated using a standard deviation factor, providing a visual representation of forecast uncertainty.
8. Probability Table:
- A table is displayed on the chart, showing the probability of the forecast being accurate. This probability is calculated using the correlation between the current data and the most similar historical pattern. If the probability is positive, the table background turns green; if negative, it turns red. The probability is presented as a percentage.
9. Key Functions:
- `highest_range` and `lowest_range`: Functions to find the highest and lowest price within a range of bars.
- `ftype`: Determines the forecast type (Prediction or Replication) and adjusts the forecasting logic accordingly.
- `ftypediff`: Computes the difference between the forecasted and actual prices based on the selected forecast type.
- `ftypelim`, `ftypeleft`, `ftyperight`: Additional functions to adjust the calculation of the forecast based on the forecast type.
10. Conclusion:
The "ForecastPro" script is a unique tool for forecasting future price movements on TradingView. It compares historical price data with similar historical trends to generate predictions. The script also offers a customizable confidence cone and displays the probability of the forecast's accuracy. This tool provides traders with valuable insights into future price action, potentially enhancing decision-making in trading strategies.
---
This script provides advanced functionality for traders who wish to explore price forecasting, and can be customized to fit various trading styles.
Enhanced SMA Signal Box With TargetsOverview
The Enhanced SMA Signal Box With Targets is a versatile trading indicator designed for scalping any asset or instrument across markets. Combining a 20-period Simple Moving Average (SMA) with ATR-based target levels and advanced filtering options, it provides a streamlined approach to identifying high-probability setups. This tool caters to traders seeking clear signals and adaptive profit targets for fast-paced, disciplined trades.
Key Features
Scalping Focus: Tailored for quick trades on any asset, including indices, forex, commodities, and crypto.
20 SMA-Based Signals: Generates buy/sell signals based on price-SMA crossovers for trend clarity.
Signal Boxes: Highlights entry opportunities with visually distinct yellow boxes.
Adaptive Targets: Plots three ATR-based profit-taking levels for dynamic trade management.
Custom Filters: Refine signals using MACD, RSI, and volume to enhance precision.
Real-Time Alerts: Stay informed with alerts for buy and sell signals.
How It Works
Buy Signal: Triggered when the closing price crosses above the SMA.
Sell Signal: Triggered when the price drops below the SMA.
Profit Targets: Three ATR-based levels guide trade exits dynamically:
Target 1: 1:1 risk-reward based on the signal candle size.
Target 2 & 3: Expanded targets based on ATR.
Customization Options
Adjust SMA settings, colors, and signal visuals for any trading style.
Enable or disable MACD, RSI, and volume filters to suit market conditions.
Personalize target line extensions and colors for improved clarity.
Disclaimer
This indicator is intended for educational purposes only. Trading involves significant risk, including potential loss of capital. Past performance is not indicative of future results. Users should test the indicator and seek advice from licensed professionals before live trading. The author is not liable for any losses incurred. Always trade responsibly.
Intelligent Support & Resistance Lines (MTF)This script automatically detects and updates key Support & Resistance (S/R) levels using a higher timeframe (MTF) approach. By leveraging volume confirmation, levels are only identified when significant volume (relative to the SMA of volume) appears. Each level is drawn horizontally in real time, and whenever the market breaks above a resistance level (and retests it), the script automatically converts that resistance into support. The opposite occurs if the market breaks below a support level.
Key Features:
Multi-Timeframe (MTF) Data
Select a higher timeframe for more robust S/R calculations.
The script fetches High, Low, Volume, and SMA of Volume from the chosen timeframe.
Automatic Role Reversal
Resistance becomes Support if a breakout retest occurs.
Support becomes Resistance if a breakdown retest occurs.
Dynamic Line Width & Labeling
Each S/R line’s thickness increases with additional touches, making frequently tested levels easier to spot.
Labels automatically display the number of touches (e.g., “R 3” or “S 2”) and can have adjustable text size.
Volume Threshold
Only significant pivots (where volume exceeds a specified multiplier of average volume) are plotted, reducing noise.
Horizontal Offset for Clarity
Lines are drawn with timestamps instead of bar_index, ensuring that old levels remain visible without chart limitations.
Adjustable Maximum Levels
Maintain a clean chart by limiting how many S/R lines remain at once.
How It Works:
Pivot Detection: The script identifies swing highs and lows from the higher timeframe (timeframeSR).
Volume Check: Only pivots with volume ≥ (SMA Volume * volumeThreshold) qualify.
Line Creation & Updates: New lines are drawn at these pivots, labeled “R #” or “S #,” indicating how many times they’ve been touched.
Role Reversal: If price breaks above a resistance and retests it from above, that line is removed from the resistance array and re-created in the support array (and vice versa).
Inputs:
Timeframe for S/R: Choose the higher timeframe for S/R calculations.
Swing Length: Number of bars to consider in a pivot calculation.
Minimum Touches: Minimum required touches before drawing or updating a level.
Volume Threshold (Multiplier): Determines how much volume (relative to SMA) is needed to confirm a pivot.
Maximum Number of Levels: Caps how many S/R lines can be shown at once.
Color for Resistance & Color for Support: Customize your preferred colors for lines and labels.
Label Size: Select from "tiny", "small", "normal", "large", or "huge" to resize the labels.
Disclaimer:
This script is intended for educational purposes and should not be interpreted as financial or investment advice. Always conduct your own research or consult a qualified professional before making trading decisions.
RSI Divergence + Sweep + Signal + Alerts Toolkit [TrendX_]The RSI Toolkit is a powerful set of tools designed to enhance the functionality of the traditional Relative Strength Index (RSI) indicator. By integrating advanced features such as Moving Averages, Divergences, and Sweeps, it helps traders identify key market dynamics, potential reversals, and newly-approach trading stragies.
The toolkit expands on standard RSI usage by incorporating features from smart money concepts (Just try to be creative 🤣 Hope you like it), providing a deeper understanding of momentum, liquidity sweeps, and trend reversals. It is suitable for RSI traders who want to make more informed and effective trading decisions.
💎 FEATURES
RSI Moving Average
The RSI Moving Average (RSI MA) is the moving average of the RSI itself. It can be customized to use various types of moving averages, including Simple Moving Average (SMA), Exponential Moving Average (EMA), Relative Moving Average (RMA), and Volume-Weighted Moving Average (VWMA).
The RSI MA smooths out the RSI fluctuations, making it easier to identify trends and crossovers. It helps traders spot momentum shifts and potential entry/exit points by observing when the RSI crosses above or below its moving average.
RSI Divergence
RSI Divergence identifies discrepancies between price action and RSI momentum. There are two types of divergences: Regular Divergence - Indicates a potential trend reversal; Hidden Divergence - Suggests the continuation of the current trend.
Divergence is a critical signal for spotting weakness or strength in a trend. Regular divergence highlights potential trend reversals, while hidden divergence confirms trend continuation, offering traders valuable insights into market momentum and possible trade setups.
RSI Sweep
RSI Sweep detects moments when the RSI removes liquidity from a trend structure by sweeping above or below the price at key momentum level crossing. These sweeps are overlaid on the RSI chart for easier visualized.
RSI Sweeps are significant because they indicate potential turning points in the market. When RSI sweeps occur: In an uptrend - they suggest buyers' momentum has peaked, possibly leading to a reversal; In a downtrend - they indicate sellers’ momentum has peaked, also hinting at a reversal.
(Note: This feature incorporates Liquidity Sweep concepts from Smart Money Concepts into RSI analysis, helping RSI traders identify areas where liquidity has been removed, which often precedes a trend reversal)
🔎 BREAKDOWN
RSI Moving Average
How MA created: The RSI value is calculated first using the standard RSI formula. The MA is then applied to the RSI values using the trader’s chosen type of MA (SMA, EMA, RMA, or VWMA). The flexibility to choose the type of MA allows traders to adjust the smoothing effect based on their trading style.
Why use MA: RSI by itself can be noisy and difficult to interpret in volatile markets. Applying moving average would provide a smoother, more reliable view of RSI trends.
RSI Divergence
How Regular Divergence created: Regular Divergence is detected when price forms HIGHER highs while RSI forms LOWER highs (bearish divergence) or when price forms LOWER lows while RSI forms HIGHER lows (bullish divergence).
How Hidden Divergence created: Hidden Divergence is identified when price forms HIGHER lows while RSI forms LOWER lows (bullish hidden divergence) or when price forms LOWER highs while RSI forms HIGHER highs (bearish hidden divergence).
Why use Divergence: Divergences provide early warning signals of a potential trend change. Regular divergence helps traders anticipate reversals, while hidden divergence supports trend continuation, enabling traders to align their trades with market momentum.
RSI Sweep
How Sweep created: Trend Structure Shift are identified based on the RSI crossing key momentum level of 50. To track these sweeps, the indicator pinpoints moments when liquidity is removed from the Trend Structure Shift. This is a direct application of Liquidity Sweep concepts used in Smart Money theories, adapted to RSI.
Why use Sweep: RSI Sweeps are created to help traders detect potential trend reversals. By identifying areas where momentum has exhausted during a certain trend direction, the indicator highlights opportunities for traders to enter trades early in a reversal or continuation phase.
⚙️ USAGES
Divergence + Sweep
This is an example of combining Devergence & Sweep in BTCUSDT (1 hour)
Wait for a divergence (regular or hidden) to form on the RSI. After the divergence is complete, look for a sweep to occur. A potential entry might be formed at the end of the sweep.
Divergences indicate a potential trend change, but confirmation is required to ensure the setup is valid. The RSI Sweep provides that confirmation by signaling a liquidity event, increasing the likelihood of a successful trade.
Sweep + MA Cross
This is an example of combining Devergence & Sweep in BTCUSDT (1 hour)
Wait for an RSI Sweep to form then a potential entry might be formed when the RSI crosses its MA.
The RSI Sweep highlights a potential turning point in the market. The MA cross serves as additional confirmation that momentum has shifted, providing a more reliable and more potential entry signal for trend continuations.
DISCLAIMER
This indicator is not financial advice, it can only help traders make better decisions. There are many factors and uncertainties that can affect the outcome of any endeavor, and no one can guarantee or predict with certainty what will occur. Therefore, one should always exercise caution and judgment when making decisions based on past performance.
Santa's Adventure [AlgoAlpha]Introducing "Santa's Adventure," a unique and festive TradingView indicator designed to bring the holiday spirit to your trading charts. With this indicator, watch as Santa, his sleigh, Rudolf the reindeer, and a flurry of snowflakes come to life, creating a cheerful visual experience while you monitor the markets.
Key Features:
🎁 Dynamic Santa Sleigh Visualization : Santa's sleigh, Rudolf, and holiday presents adapt to price movements and chart structure.
🎨 Customizable Holiday Colors : Adjust colors for Santa’s outfit, Rudolf’s nose, sleigh, presents, and more.
❄️ Realistic Snow Animation : A cascade of snowflakes decorates your charts, with density and range adjustable to suit your preferences.
📏 Adaptive Scaling : All visuals scale based on price volatility and market dynamics.
🔄 Rotation by Trend : Santa and his entourage tilt to reflect market trends, making it both functional and fun!
How to Use :
Add the Indicator to Your Chart : Search for "Santa's Adventure" in the TradingView indicator library and add it to your favorites. Use the input menu to adjust snow density, sleigh colors, and other festive elements to match your trading style or holiday mood.
Observe the Market : Watch Santa’s sleigh glide across the chart while Rudolf leads the way, with snowflakes gently falling to enhance the visual charm.
How It Works :
The indicator uses price volatility and market data to dynamically position Santa, his sleigh, Rudolf, and presents on the chart. Santa's Sleigh angle adjusts based on price trends, reflecting market direction. Santa's sleigh and the snowstorm are plotted using advanced polyline arrays for a smooth and interactive display. A festive algorithm powers the snowfall animation, ensuring a consistent and immersive holiday atmosphere. The visuals are built to adapt seamlessly to any market environment, combining holiday cheer with market insights.
Add "Santa's Adventure" to your TradingView charts today and bring the holiday spirit to your trading journey, Merry Christmas! 🎅🎄
[EmreKb] Santa Clause🎅 Ho Ho Ho! Santa Claus on Your Chart! 🎅
Bring the holiday spirit to your charts with this special Pine Script indicator! Add a cheerful Santa Claus drawing to your charts and celebrate the most wonderful time of the year. 🎄✨
This indicator is purely for fun and designed to spread joy and festive vibes within the Pine Script community. Whether you’re a charting enthusiast or just looking to embrace the holiday cheer, this indicator brings the magic of Santa Claus directly to your charts.
All-in-One: VWAP, Ichimoku, EMAs, ADX, RSI + AlertsTitle: All-in-One: VWAP, Ichimoku, EMAs, ADX, RSI + Alerts
Short Title: Multi-Indicator + Alerts
Description:
This script combines several popular trading tools into a single indicator, giving traders a comprehensive view of market conditions alongside convenient alerts. Whether you are monitoring intraday trends, identifying breakouts, or looking for overbought/oversold zones, this script centralizes all the major signals you need.
Features & Options
VWAP (Volume-Weighted Average Price)
Multi-timeframe VWAP on 1H, 4H, and Daily
Helps identify key support/resistance zones based on volume distribution
EMAs (Exponential Moving Averages)
EMAs of 10, 20, 50, and 200 periods (customizable)
Quick visualization of short-term vs. long-term trends
Ichimoku Cloud
Full Ichimoku suite (Tenkan, Kijun, Senkou A/B, Chikou)
Auto-filled cloud for bullish/bearish scenarios
Detect momentum shifts and potential support/resistance zones
RSI & ADX Table
RSI(14) and ADX(14) displayed on a small on-chart table
Compare values across three custom timeframes for multi-timeframe confluence
Labels on Last Bar
Optional labels for VWAP, EMAs, and Ichimoku values on the latest candle
Keeps critical numeric data in sight
Alerts
RSI Overbought/Oversold : Triggers when RSI crosses above/below user-defined thresholds (default 70/30).
ADX Strong Trend : Fires when ADX surpasses a chosen level (default 25), indicating strong momentum.
EMA Cross : Set an alert whenever a faster EMA crosses over or under a slower EMA (default EMA10 vs. EMA50).
Ichimoku Kumo Breakout : Informs you when price closes above or below the Ichimoku cloud.
With everything in one place, this script helps traders streamline their workflow and spot potential opportunities faster. All alert messages are static to ensure compliance with TradingView’s requirement for constant strings in alerts.
Disclaimer:
All trading involves risk. The signals generated by this script do not guarantee profits or prevent losses. Always combine multiple forms of analysis and exercise your own judgment before making any trading decisions.
Super Billion VVIPThis Pine Script code implements a Supertrend indicator in TradingView. The script highlights trends on the chart and optionally displays buy/sell signals when the trend changes. Here is a breakdown of its key components:
Inputs
ATR Period: Determines the look-back period for the Average True Range (ATR) calculation.
Source: Defines the price data to use (default is hl2, the average of high and low).
ATR Multiplier: Adjusts the sensitivity of the Supertrend lines.
Change ATR Calculation Method: Allows switching between simple moving average (sma) and standard ATR calculations.
Show Buy/Sell Signals: Toggles the display of buy/sell signals.
Highlighter On/Off: Toggles background highlighting for uptrends and downtrends.
Calculations
ATR: Computes either a simple moving average of tr or the standard ATR, depending on the changeATR input.
Trend Lines:
up: Defines the upper trendline using the formula src - Multiplier * ATR.
dn: Defines the lower trendline using the formula src + Multiplier * ATR.
Both lines are adjusted to prevent flipping when conditions do not warrant it.
Trend Direction
The trend is determined using:
1 for uptrend (price above dn).
-1 for downtrend (price below up).
Plots
Uptrend Line: Green line plotted when the trend is upward.
Downtrend Line: Red line plotted when the trend is downward.
Buy/Sell Signals: Circles and labels appear where the trend changes.
Highlighter: Colors the background based on the current trend.
Alerts
Three alert conditions are defined:
SuperTrend Buy: Triggered when an uptrend begins.
SuperTrend Sell: Triggered when a downtrend begins.
Direction Change: Triggered whenever the trend switches.
If you have any specific requests or modifications you'd like to make to this script,
feel free to ask!
Ultra Trade JournalThe Ultra Trade Journal is a powerful TradingView indicator designed to help traders meticulously document and analyze their trades. Whether you're a novice or an experienced trader, this tool offers a clear and organized way to visualize your trading strategy, monitor performance, and make informed decisions based on detailed trade metrics.
Detailed Description
The Ultra Trade Journal indicator allows users to input and visualize critical trade information directly on their TradingView charts.
.........
User Inputs
Traders can specify entry and exit prices , stop loss levels, and up to four take profit targets.
.....
Dynamic Plotting
Once the input values are set, the indicator automatically plots horizontal lines for entry, exit, stop loss, and each take profit level on the chart. These lines are visually distinct, using different colors and styles (solid, dashed, dotted) to represent each element clearly.
.....
Live Position Tracking
If enabled, the indicator can adjust the exit price in real-time based on the current market price, allowing traders to monitor live positions effectively.
.....
Tick Calculations
The script calculates the number of ticks between the entry price and each exit point (stop loss and take profits). This helps in understanding the movement required for each target and assessing the potential risk and reward.
.....
Risk-Reward Ratios
For each take profit level, the indicator computes the risk-reward (RR) ratio by comparing the ticks at each target against the stop loss ticks. This provides a quick view of the potential profitability versus the risk taken.
.....
Comprehensive Table Display
A customizable table is displayed on the chart, summarizing all key trade details. This includes the entry and exit prices, stop loss and take profit levels, tick counts, and their respective RR ratios.
Users can adjust the table's Position and text color to suit their preferences.
.....
Visual Enhancements
The indicator uses adjustable background shading between entry and stop loss/take profit lines to visually represent potential trade outcomes. This shading adjusts based on whether the trade is long or short, providing an intuitive understanding of trade performance.
.........
Overall, the Ultra Trade Journal combines visual clarity with detailed analytics, enabling traders to keep a well-organized record of their trades and enhance their trading strategies through insightful data.
VolumeMACD M5 Devis'So1. Inputs and Parameters:
Fast and Slow Lengths: These define the moving averages used for calculating the MACD.
Source: The volume data is used as the primary source.
Signal Smoothing: The signal line is smoothed with the specified length.
Oscillator and Signal MA Types: The user can select between SMA (Simple Moving Average) and EMA (Exponential Moving Average).
2. MACD Calculation:
Fast and Slow MA: The script computes fast and slow moving averages of the volume data using the selected type (SMA or EMA).
MACD: The difference between the fast and slow moving averages is calculated, and the RSI of this difference is further modified with a change function.
Signal Line: A smoothed version of the MACD using either SMA or EMA.
Top Line: The midpoint average between the MACD and the Signal Line.
3. Signal Generation:
Long Signals (Green Candles Only):
The script identifies potential buy signals when:
The MACD, Signal Line, or Top Line crosses above specific thresholds (2, 3, 4, or 5).
The candle is green (close price > open price).
Short Signals (Red Candles Only):
It identifies potential sell signals when:
The MACD, Signal Line, or Top Line crosses below specific thresholds (-2, -3, -4, or -5).
The candle is red (close price < open price).
Each signal is categorized by its strength (M2, M3, M4, M5), depending on the threshold level.
4. Visualization:
Long Signals: Represented as upward triangles of different sizes and colors based on their strength.
Short Signals: Represented as downward triangles of different sizes and colors based on their strength.
5. Pullback Levels:
The script calculates pullback levels based on the low (for long signals) and high (for short signals) of the candles where the signals occur:
Long Pullback Level: Updated to the low of the candle when a long signal is detected.
Short Pullback Level: Updated to the high of the candle when a short signal is detected.
These pullback levels are plotted as step lines:
Green Line: Represents the Long Pullback Level.
Red Line: Represents the Short Pullback Level.
6. Average Pullback Level (Topk):
The average of the Long Pullback Level and the Short Pullback Level is calculated and plotted:
Pink Line: Represents the midpoint of the pullback levels, providing an additional reference for market movement.
Overall Purpose:
This script is designed to identify potential entry and exit points in the market based on volume-based MACD signals, categorized by strength, and complemented with pullback levels for better decision-making and visualization.
CHECHEU_MONSTERO indicador CHECHEU foi desenvolvido para identificar de forma precisa as tendências de mercado e pontos de reversão com base em uma combinação de ferramentas técnicas robustas. Este indicador é ideal para traders que buscam clareza visual em operações de curto e médio prazo, oferecendo sinais confiáveis de compra e venda diretamente sobre o gráfico.
Principais Funcionalidades:
Nuvem Dinâmica de Tendência:
A nuvem acompanha a movimentação dos preços, fornecendo suporte e resistência dinâmicos. A mudança de cor da nuvem indica a transição entre momentos de alta e baixa, permitindo uma rápida interpretação visual do mercado.
Sinal de Compra e Venda:
O CHECHEU gera sinais diretos de compra e venda, exibidos como etiquetas no gráfico. Esses sinais são baseados em uma análise que leva em consideração a estrutura de mercado e a dinâmica dos preços, minimizando o ruído e priorizando sinais de alta probabilidade.
Média Móvel com Fractais de Williams:
Uma média móvel de 55 períodos é plotada sobre o gráfico, mudando de cor conforme o contexto do mercado. Essa média é ajustada para refletir fractais, oferecendo uma leitura mais responsiva em relação aos movimentos de preço.
Cores dos Candles Personalizadas:
Os candles mudam de cor conforme a direção do mercado, simplificando a identificação de tendências em andamento e momentos críticos de possível reversão.
Benefícios para o Trader:
Clareza Visual: A apresentação de dados é limpa e organizada, permitindo decisões rápidas sem sobrecarregar o gráfico com informações desnecessárias.
Redução de Ruído: O indicador filtra sinais falsos, focando em entradas mais seguras com maior confiabilidade.
Facilidade de Interpretação: Ideal para traders que buscam sinais diretos e práticos, sem a necessidade de interpretações complexas.
Aplicações:
Swing Trade e Day Trade
Criptomoedas, Ações e Forex
Gráficos de qualquer timeframe, com ênfase em períodos de 4 horas e diário.
Nota:
Este indicador é uma ferramenta personalizada, desenvolvida com base em anos de experiência e refinamento técnico. Disponível para uso privado ou sob convite.
Consecutive Candles DevisSoHi Traders !!!
Level Calculation:
50% and 23.6% Fibonacci levels are calculated based on the open and close of the previous candles.
Consecutive Candle Check:
For an uptrend: Each candle's low must not touch the 50% levels of the previous candles.
For a downtrend: Each candle's high must not touch the 50% levels of the previous candles.
Pullback Level:
When a long signal is triggered, the current candle's low is recorded as a pullback level.
When a short signal is triggered, the current candle's high is recorded as a pullback level.
Breakout and Signal Generation:
If the price breaks above the calculated level, a long signal is generated; if it breaks below, a short signal is generated.
These signals are visualized on the chart.
Continuity:
The system checks the last signal to ensure the validity of new signals, maintaining the consistency of consecutive signals.
Enigma Endgame with Dynamic Trend-Based FibonacciThe Enigma Endgame script combines dynamic trend-based Fibonacci levels with the core principles of the ENIGMA strategy. It provides traders with actionable signals by identifying key levels of fractal support and resistance and highlighting opportunities to trade with market momentum. This tool is designed for multi-timeframe analysis and is especially effective during high-volatility sessions like London and New York.
Purpose and Usefulness
This script was developed to simplify complex market dynamics by integrating Fibonacci principles with ENIGMA's logic of fractal support and resistance. Traders can use it to:
- Identify key breakout and retracement levels dynamically.
- Understand the shift between support and resistance as price action evolves.
- Gain confidence in their entries with real-time signals derived from logical fractal behavior.
By merging Fibonacci levels with fractal-based trading insights, this script offers a unique and comprehensive approach to analyzing market structure.
How It Works
The script uses a dual approach to provide insights:
1. Dynamic Fibonacci Levels:
- Automatically plots Fibonacci retracement and extension levels based on recent high and low swings, adjusting dynamically to current market trends.
- Allows traders to visualize key levels where price might reverse or extend.
2. Fractal Support and Resistance Logic:
- The script identifies fractal support and resistance by analyzing candle formations.
- When a candle body closes below the low of a previous candle, the previous low, which was fractal support, now becomes fractal resistance. The script generates a bearish signal, encouraging traders to look for sell opportunities at or above the previous low.
- Conversely, when a candle body closes above the high of a previous candle, the previous high, which was fractal resistance, becomes fractal support. The script generates a bullish signal, encouraging traders to look for buy opportunities at or below the previous high.
Real-Time Signals
The script marks these transitions with arrows on the chart:
- Bearish arrows indicate broken fractal support turning into resistance.
- Bullish arrows** indicate broken fractal resistance turning into support.
These signals help traders stay aligned with the trend and trade with market momentum.
Key Features
1. Session-Based Analysis: Focuses on high-probability setups by allowing traders to customize session times, such as London or US sessions.
2. Multi-Timeframe Support: Works seamlessly across multiple timeframes for both scalpers and swing traders.
3. Real-Time Alerts: Sends customizable alerts when price interacts with critical Fibonacci levels or fractal support/resistance shifts.
How to Use the Script
1. Apply the script to a clean chart for clear visualization. Avoid combining it with other scripts unless necessary.
2. Use the arrows to identify shifts in fractal support and resistance and validate opportunities for buy/sell trades.
3. Monitor the dynamic Fibonacci levels to find confluence with key price areas.
4. Customize session times to focus on high-probability trading hours.
Key Notes for Traders
- This script provides insights based on logical market structure but should be used alongside proper risk management and trading plans.
- The fractal-based approach works well in conjunction with dynamic Fibonacci levels, helping traders build confidence in their strategy.
- Adapt the script settings to match your unique trading style and timeframe preferences.
By offering a seamless integration of fractal logic and Fibonacci principles, Enigma Endgame empowers traders with actionable insights to navigate markets effectively.
[Linus] VWAO DeviationThe VWAP (Volume Weighted Average Price) Deviation Script is a sophisticated tool designed to help traders analyze the interplay between price and volume. By calculating deviations from the VWAP, it identifies critical support and resistance levels, enabling more informed trading decisions.
This script computes the VWAP based on a selected data source (defaulting to the closing price) and determines deviations above and below it using either the Average Deviation or Standard Deviation method. Users can customize their preference through the script's input settings. These deviations are visually plotted as bands on the chart, offering clear insights into areas where price may revert or break out.
A standout feature of the script is its Cross Count Monitor, which tracks how often the price crosses above the Upper Deviation Level 2 and below the Lower Deviation Level 2 within a user-defined lookback period. This data is displayed in a table at the bottom-right corner of the chart and can be toggled on or off via an input setting.
The Cross Count Monitor provides traders with valuable historical insights into the frequency of price interactions with deviation levels, helping to identify potential trading opportunities based on established price behaviors. This functionality makes the script an indispensable tool for traders seeking to enhance their market analysis and strategy development.
luusang//@version=5
indicator('Swing', shorttitle='GoodLuck', overlay=true, max_lines_count=500)
//-----Input-------
customTF = input.timeframe(defval="",title = "Show Other TimeFrame")
GroupGann = "Gann"
showGann = input.bool(false, 'Show Gann/Color/Width', group = GroupGann, inline = "Gann1")
colorGann = input.color(color.aqua, '', group = GroupGann,inline = "Gann1")
widthGann = input.int(defval=1,title = "",minval=1,step=1, group = GroupGann,inline = "Gann1")
GroupSGann = "Swing of Gann"
showSGann = input.bool(true, 'Show Swing/Color/Width', group = GroupSGann,inline = "Swing1")
colorSGann = input.color(color.blue, '', group = GroupSGann,inline = "Swing1")
widthSGann = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann,inline = "Swing1")
showChoCh = input.bool(false, 'Show ChoCh/Color/Width', group = GroupSGann,inline = "Choch")
colorChoch = input.color(color.red, '', group = GroupSGann,inline = "Choch")
widthChoch = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann,inline = "Choch")
show2ChoCh = input.bool(false, 'Show 2Choch/Color/Width', group = GroupSGann,inline = "2Choch")
color2Choch = input.color(color.purple, '', group = GroupSGann,inline = "2Choch")
width2Choch = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann,inline = "2Choch")
showtargetOTL = input.bool(true, 'Show Target OTL/Color/Width',group = GroupSGann, inline = "target")
colortargetOTL = input.color(color.purple, '', group = GroupSGann, inline = "target")
widthtargetOTL = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann,inline = "target")
showLabel = input.bool(false, 'Show Label TimeFrame',group = GroupSGann)
//showLinePrice = input.bool(true, 'Show LinePrice/Color/Width', group = GroupSGann,inline = "LinePrice")
//colorLinePrice = input.color(color.blue, '', group = GroupSGann,inline = "LinePrice")
//widthLinePrice = input.int(defval=1,title = "",minval=1,step=1, group = GroupSGann,inline = "LinePrice")
///tùy chọn line//
lineGann = input.string(title="",options= ,defval='(╌)', group = GroupGann, inline = "Gann1")
lineStyleGann = lineGann == "(┈)" ? line.style_dotted : lineGann == "(╌)" ? line.style_dashed : line.style_solid
lineSGann = input.string(title="",options= ,defval="(─)", group = GroupSGann, inline = "Swing1")
lineStyleSGann = lineSGann == "(┈)" ? line.style_dotted : lineSGann == "(╌)" ? line.style_dashed : line.style_solid
line2Choch = input.string(title="",options= ,defval="(╌)", group = GroupSGann, inline = "2Choch")
lineStyle2Choch = line2Choch == "(┈)" ? line.style_dotted : line2Choch == "(╌)" ? line.style_dashed : line.style_dashed
lineChoch = input.string(title="",options= ,defval="(─)", group = GroupSGann, inline = "Choch")
lineStyleChoch = lineChoch == "(┈)" ? line.style_dotted : lineChoch == "(╌)" ? line.style_dashed : lineChoch == "(←)" ? line.style_arrow_left : lineChoch == "(→)" ? line.style_arrow_right : lineChoch == "(↔)" ? line.style_arrow_both : line.style_solid
linetargetOTL = input.string(title="",options= ,defval="(→)", group = GroupSGann, inline = "target")
lineStyletargetOTL = linetargetOTL == "(┈)" ? line.style_dotted : linetargetOTL == "(╌)" ? line.style_dashed : linetargetOTL == "(←)" ? line.style_arrow_left : linetargetOTL == "(→)" ? line.style_arrow_right : linetargetOTL == "(↔)" ? line.style_arrow_both : line.style_arrow_both
//in out side bar//
OSB_up_down ="Ousidebar up down"
//////////////////////////Global//////////////////////////
var arrayLineTemp = array.new_line()
// Funtion
f_resInMinutes() =>
_resInMinutes = timeframe.multiplier * (
timeframe.isseconds ? 1. / 60. :
timeframe.isminutes ? 1. :
timeframe.isdaily ? 1440. :
timeframe.isweekly ? 10080. :
timeframe.ismonthly ? 43800. : na)
// Converts a resolution expressed in minutes into a string usable by "security()"
f_resFromMinutes(_minutes) =>
_minutes < 1 ? str.tostring(math.round(_minutes*60)) + "S" :
_minutes < 60 ? str.tostring(math.round(_minutes)) + "m" :
_minutes < 1440 ? str.tostring(math.round(_minutes/60)) + "H" :
_minutes < 10080 ? str.tostring(math.round(math.min(_minutes / 1440, 7))) + "D" :
_minutes < 43800 ? str.tostring(math.round(math.min(_minutes / 10080, 4))) + "W" :
str.tostring(math.round(math.min(_minutes / 43800, 12))) + "M"
f_tfRes(_res,_exp) =>
request.security(syminfo.tickerid,_res,_exp,lookahead=barmerge.lookahead_on)
var arrayLineChoCh = array.new_line()
var label labelTF = label.new(time, close, text = "",color = color.new(showSGann ? colorSGann : colorGann,95), textcolor = showSGann ? colorSGann : colorGann,xloc = xloc.bar_time, textalign = text.align_left)
var line lineChoChOTLTarget = line.new(x1= time , y1=close,x2=time, y2= close,color = showSGann ? colortargetOTL : colorGann,xloc = xloc.bar_time,style = lineStyletargetOTL,width = widthtargetOTL)
var line lineBosOTLTarget = line.new(x1= time , y1=close,x2=time, y2= close,color = showSGann ? colortargetOTL : colorGann,xloc = xloc.bar_time,style = lineStyletargetOTL, width = widthtargetOTL)
//var line line_Price = line.new(x1= time , y1=close,x2=time, y2= close,color = showSGann ? colorLinePrice : colorGann,xloc = xloc.bar_time,style = lineStyleLinePrice, width = widthLinePrice)
styleGann = showSGann ? line.style_dashed : line.style_solid
var arrayXGann = array.new_int(5,time)
var arrayYGann = array.new_float(5,close)
var arrayLineGann = array.new_line()
int drawLineGann = 0
_high = high
_low = low
_close = close
_open = open
if(customTF != timeframe.period)
_high := f_tfRes(customTF,high)
_low := f_tfRes(customTF,low)
_close := f_tfRes(customTF,close)
_open := f_tfRes(customTF,open)
highPrev = _high
lowPrev = _low
// drawLineGann => 2:Tiếp tục 1:Đảo chiều; // Outsidebar 2:Tiếp tục 3:Tiếp tục và Đảo chiều 4 : Đảo chiều 2 lần
drawLineGann := 0
if(_high > highPrev and _low > lowPrev )
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
drawLineGann := 2
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 1
else if(_high < highPrev and _low < lowPrev )
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 1
else
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
drawLineGann := 2
else if(_high >= highPrev and _low < lowPrev or _high > highPrev and _low <= lowPrev )
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(_high >= array.get(arrayYGann,0) and array.get(arrayYGann,1) < _low )
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
drawLineGann := 2
else if(_high >= array.get(arrayYGann,0) and array.get(arrayYGann,1) > _low )
if(_close < _open)
if(_high <= high)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _high )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 3
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 4
else if(array.get(arrayYGann,0) < array.get(arrayYGann,1))
if(_low <= array.get(arrayYGann,0) and _high < array.get(arrayYGann,1))
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
drawLineGann := 2
else if(_low <= array.get(arrayYGann,0) and _high > array.get(arrayYGann,1))
if(_close > _open)
if(_low >= low)
array.set(arrayXGann, 0, time)
array.set(arrayYGann, 0, _low )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
drawLineGann := 3
else
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_high )
array.unshift(arrayXGann,time)
array.unshift(arrayYGann,_low )
drawLineGann := 4
else if((_high <= highPrev and _low >= lowPrev ))
highPrev := highPrev
lowPrev := lowPrev
if(f_resInMinutes() < f_tfRes(customTF,f_resInMinutes()) and drawLineGann == 0)
if(array.get(arrayYGann,0) > array.get(arrayYGann,1))
if(array.get(arrayYGann,0) <= high)
array.set(arrayXGann, 0, time)
drawLineGann := 2
else
if(array.get(arrayYGann,0) >= low)
array.set(arrayXGann, 0, time)
drawLineGann := 2
if(showGann and f_resInMinutes() <= f_tfRes(customTF,f_resInMinutes()))
if(drawLineGann == 2)
if(array.size(arrayLineGann) >0)
line.set_xy2(array.get(arrayLineGann,0),array.get(arrayXGann,0),array.get(arrayYGann,0))
else
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
else if(drawLineGann == 1)
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
else if(drawLineGann == 3)
if(array.size(arrayLineGann) >0)
line.set_xy2(array.get(arrayLineGann,0),array.get(arrayXGann,1),array.get(arrayYGann,1))
else
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,2),array.get(arrayYGann,2),array.get(arrayXGann,1),array.get(arrayYGann,1), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
else if(drawLineGann == 4)
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,2),array.get(arrayYGann,2),array.get(arrayXGann,1),array.get(arrayYGann,1), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
array.unshift(arrayLineGann,line.new(array.get(arrayXGann,1),array.get(arrayYGann,1),array.get(arrayXGann,0),array.get(arrayYGann,0), color = colorGann,xloc = xloc.bar_time, style = lineStyleGann,width = widthGann))
//////////////////////////Swing Gann//////////////////////////
var arrayXSGann = array.new_int(5,time)
var arrayYSGann = array.new_float(5,close)
var arrayLineSGann = array.new_line()
int drawLineSGann = 0
int drawLineSGann1 = 0
bool runCheckChoChSGann = false
runCheckChoChSGann := runCheckChoChSGann
if(showSGann)
if(math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1)) < math.min(array.get(arrayYGann,0),array.get(arrayYGann,1)) or math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1)) > math.max(array.get(arrayYGann,0),array.get(arrayYGann,1)))
//Khởi tạo bắt đầu
drawLineSGann1 := 5
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
array.set(arrayYSGann, 0, array.get(arrayYGann,1))
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
// drawLineSGann kiểm tra điểm 1 => 13:Tiếp tục có sóng hồi // 12|19(reDraw):Tiếp tục không có sóng hồi // 14:Đảo chiều
if(array.get(arrayXGann,0) == array.get(arrayXGann,1))
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,2) and array.get(arrayYSGann,0) != array.get(arrayYGann,1) and ((array.get(arrayYGann,1) > array.get(arrayYGann,2) and array.get(arrayYSGann,0) > array.get(arrayYSGann,1)) or (array.get(arrayYGann,1) < array.get(arrayYGann,2) and array.get(arrayYSGann,0) < array.get(arrayYSGann,1))))
drawLineSGann1 := 12
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
array.set(arrayYSGann, 0, array.get(arrayYGann,1))
else if(array.get(arrayXSGann,0) <= array.get(arrayXGann,2))
if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,1) < array.get(arrayYSGann,1)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,1) > array.get(arrayYSGann,1)))
drawLineSGann1 := 14
runCheckChoChSGann := true
array.unshift(arrayXSGann,array.get(arrayXGann,1))
array.unshift(arrayYSGann,array.get(arrayYGann,1))
else if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,1) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,1) < array.get(arrayYSGann,0)))
drawLineSGann1 := 13
_max = math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_min = math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_max_idx = 0
_min_idx = 0
for i = 2 to array.size(arrayXGann)
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,i))
break
if(_min > array.get(arrayYGann,i))
_min := array.get(arrayYGann,i)
_min_idx := array.get(arrayXGann,i)
if(_max < array.get(arrayYGann,i))
_max := array.get(arrayYGann,i)
_max_idx := array.get(arrayXGann,i)
if(array.get(arrayYSGann,0) > array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_min_idx)
array.unshift(arrayYSGann,_min)
else if(array.get(arrayYSGann,0) < array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_max_idx)
array.unshift(arrayYSGann,_max)
array.unshift(arrayXSGann,array.get(arrayXGann,1))
array.unshift(arrayYSGann,array.get(arrayYGann,1))
if(f_resInMinutes() < f_tfRes(customTF,f_resInMinutes()))
if(array.get(arrayYSGann,0) == array.get(arrayYGann,1) and array.get(arrayXSGann,0) != array.get(arrayXGann,1))
array.set(arrayXSGann, 0, array.get(arrayXGann,1))
drawLineSGann1 := 19
if(f_resInMinutes() <= f_tfRes(customTF,f_resInMinutes()))
if(drawLineSGann1 == 12 or drawLineSGann1 == 19)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,0),array.get(arrayYSGann,0))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann, style = lineStyleSGann))
else if(drawLineSGann1 == 14)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
else if(drawLineSGann1 == 13)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
else if(drawLineSGann1 == 15)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,1),array.get(arrayYSGann,1))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
if(runCheckChoChSGann)
runCheckChoChSGann := false
// ChoCh Trường hợp chữ N ngược, chữ N
if((array.get(arrayYSGann,3) > array.get(arrayYSGann,2) and array.get(arrayYSGann,3) < array.get(arrayYSGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,2)) or (array.get(arrayYSGann,3) < array.get(arrayYSGann,2) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,2)))
alert(syminfo.ticker + " : " + timeframe.period + " => Swing of Gann ChoCh" + (array.get(arrayYSGann,0) > array.get(arrayYSGann,1) ? "+ ⇑" : "- ⇓"))
if(showChoCh)
array.unshift(arrayLineChoCh,line.new(x1= array.get(arrayXSGann,2) , y1=array.get(arrayYSGann,2),x2=array.get(arrayXSGann,0), y2=array.get(arrayYSGann,2),color = colorChoch,xloc = xloc.bar_time,style = lineStyleChoch,width = widthChoch))
// ChoCh 2 Đầu Trường hợp chữ N ngược, chữ N
if(show2ChoCh and ((array.get(arrayYSGann,1) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1))))
line.set_width(array.get(arrayLineSGann,1),width2Choch)
line.set_style(array.get(arrayLineSGann,1), lineStyle2Choch)
line.set_color(array.get(arrayLineSGann,1),color2Choch)
// drawLineSGann kiểm tra điểm 0 => 3:Tiếp tục có sóng hồi // 2|9(reDraw):Tiếp tục không có sóng hồi // 4:Đảo chiều
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,1) and array.get(arrayYSGann,0) != array.get(arrayYGann,0) and ((array.get(arrayYGann,0) > array.get(arrayYGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,1)) or (array.get(arrayYGann,0) < array.get(arrayYGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,1))))
drawLineSGann := 2
array.set(arrayXSGann, 0, array.get(arrayXGann,0))
array.set(arrayYSGann, 0, array.get(arrayYGann,0))
else if(array.get(arrayXSGann,0) <= array.get(arrayXGann,1))
if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,0) < array.get(arrayYSGann,1)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,0) > array.get(arrayYSGann,1)))
drawLineSGann := 4
runCheckChoChSGann := true
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
else if((array.get(arrayYSGann,0) > array.get(arrayYSGann,1) and array.get(arrayYGann,0) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) < array.get(arrayYSGann,1) and array.get(arrayYGann,0) < array.get(arrayYSGann,0)))
drawLineSGann := 3
_max = math.min(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_min = math.max(array.get(arrayYSGann,0),array.get(arrayYSGann,1))
_max_idx = 0
_min_idx = 0
for i = 1 to array.size(arrayXGann)
if(array.get(arrayXSGann,0) >= array.get(arrayXGann,i))
break
if(_min > array.get(arrayYGann,i))
_min := array.get(arrayYGann,i)
_min_idx := array.get(arrayXGann,i)
if(_max < array.get(arrayYGann,i))
_max := array.get(arrayYGann,i)
_max_idx := array.get(arrayXGann,i)
if(array.get(arrayYSGann,0) > array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_min_idx)
array.unshift(arrayYSGann,_min)
else if(array.get(arrayYSGann,0) < array.get(arrayYSGann,1))
array.unshift(arrayXSGann,_max_idx)
array.unshift(arrayYSGann,_max)
array.unshift(arrayXSGann,array.get(arrayXGann,0))
array.unshift(arrayYSGann,array.get(arrayYGann,0))
if(f_resInMinutes() < f_tfRes(customTF,f_resInMinutes()))
if(array.get(arrayYSGann,0) == array.get(arrayYGann,0) and array.get(arrayXSGann,0) != array.get(arrayXGann,0))
array.set(arrayXSGann, 0, array.get(arrayXGann,0))
drawLineSGann := 9
if(f_resInMinutes() <= f_tfRes(customTF,f_resInMinutes()))
if(drawLineSGann == 2 or drawLineSGann == 9)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,0),array.get(arrayYSGann,0))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
else if(drawLineSGann == 4)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
else if(drawLineSGann == 3)
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
else if(drawLineSGann == 5)
if(array.size(arrayLineSGann) >0)
line.set_xy2(array.get(arrayLineSGann,0),array.get(arrayXSGann,1),array.get(arrayYSGann,1))
else
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,2),array.get(arrayYSGann,2),array.get(arrayXSGann,1),array.get(arrayYSGann,1), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
array.unshift(arrayLineSGann,line.new(array.get(arrayXSGann,1),array.get(arrayYSGann,1),array.get(arrayXSGann,0),array.get(arrayYSGann,0), color = colorSGann,xloc = xloc.bar_time,width = widthSGann,style = lineStyleSGann))
if(runCheckChoChSGann)
runCheckChoChSGann := false
// ChoCh Trường hợp chữ N ngược, chữ N
if((array.get(arrayYSGann,3) > array.get(arrayYSGann,2) and array.get(arrayYSGann,3) < array.get(arrayYSGann,1) and array.get(arrayYSGann,0) < array.get(arrayYSGann,2)) or (array.get(arrayYSGann,3) < array.get(arrayYSGann,2) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1) and array.get(arrayYSGann,0) > array.get(arrayYSGann,2)))
alert(syminfo.ticker + " : " + timeframe.period + " => Swing of Gann ChoCh" + (array.get(arrayYSGann,0) > array.get(arrayYSGann,1) ? "+ ⇑" : "- ⇓"))
if(showChoCh)
array.unshift(arrayLineChoCh,line.new(x1= array.get(arrayXSGann,2) , y1=array.get(arrayYSGann,2),x2=array.get(arrayXSGann,0), y2=array.get(arrayYSGann,2),color = colorChoch,xloc = xloc.bar_time,style = lineStyleChoch,width = widthChoch))
// ChoCh 2 Đầu Trường hợp chữ N ngược, chữ N
if(show2ChoCh and ((array.get(arrayYSGann,1) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,0)) or (array.get(arrayYSGann,0) > array.get(arrayYSGann,2) and array.get(arrayYSGann,2) > array.get(arrayYSGann,4) and array.get(arrayYSGann,4) > array.get(arrayYSGann,3) and array.get(arrayYSGann,3) > array.get(arrayYSGann,1))))
line.set_width(array.get(arrayLineSGann,1),width2Choch)
line.set_style(array.get(arrayLineSGann,1),lineStyle2Choch)
line.set_color(array.get(arrayLineSGann,1),color2Choch)
///////////////////////Other//////////////////////////////////
if(f_resInMinutes() <= f_tfRes(customTF,f_resInMinutes()))
if(showSGann)
if(showtargetOTL)
if(drawLineSGann1 == 14)
line.set_xy1(lineChoChOTLTarget,array.get(arrayXSGann,3),array.get(arrayYSGann,3))
line.set_xy2(lineChoChOTLTarget,array.get(arrayXSGann,3),array.get(arrayYSGann,3)*2 - array.get(arrayYSGann,2))
else if(drawLineSGann1 == 13)
line.set_xy1(lineBosOTLTarget,array.get(arrayXSGann,3),array.get(arrayYSGann,3))
line.set_xy2(lineBosOTLTarget,array.get(arrayXSGann,3),array.get(arrayYSGann,3)*2 - array.get(arrayYSGann,2))
if(drawLineSGann == 4)
line.set_xy1(lineChoChOTLTarget,array.get(arrayXSGann,2),array.get(arrayYSGann,2))
line.set_xy2(lineChoChOTLTarget,array.get(arrayXSGann,2),array.get(arrayYSGann,2)*2 - array.get(arrayYSGann,1))
else if(drawLineSGann == 3)
line.set_xy1(lineBosOTLTarget,array.get(arrayXSGann,2),array.get(arrayYSGann,2))
line.set_xy2(lineBosOTLTarget,array.get(arrayXSGann,2),array.get(arrayYSGann,2)*2 - array.get(arrayYSGann,1))
if(showLabel and (barstate.islast or barstate.islastconfirmedhistory))
texLabel = f_resInMinutes() == f_tfRes(customTF,f_resInMinutes()) ? f_resFromMinutes(f_resInMinutes()) : f_resFromMinutes(f_tfRes(customTF,f_resInMinutes()))
label.set_xy(labelTF,array.get(arrayXSGann,0),array.get(arrayYSGann,0))
label.set_text(labelTF,texLabel)
label.set_style(labelTF,array.get(arrayYSGann,0) < array.get(arrayYSGann,1) ? label.style_label_upper_right : label.style_label_lower_right)
else if(showGann)
if(showLabel and (barstate.islast or barstate.islastconfirmedhistory))
texLabel = f_resInMinutes() == f_tfRes(customTF,f_resInMinutes()) ? f_resFromMinutes(f_resInMinutes()) : f_resFromMinutes(f_tfRes(customTF,f_resInMinutes()))
label.set_xy(labelTF,array.get(arrayXGann,0),array.get(arrayYGann,0))
label.set_text(labelTF,texLabel)
label.set_style(labelTF,array.get(arrayYGann,0) < array.get(arrayYGann,1) ? label.style_label_upper_right : label.style_label_lower_right)
///ema///
EMA = "EMA Setting"
len = input.int(21, minval=1, title="EMA Length")
len1= input.int(34, minval=1, title="EMA Length")
len2 = input.int(89, minval=1, title="EMA Length")
len3 = input.int(200, minval=1, title="EMA Length")
src = close
ema = ta.ema(src, len)
ema1 = ta.ema(close,len1) //34
ema2 = ta.ema(close,len2) //89
ema3 = ta.ema (close,len3)//200
up = ema > ema
down = ema < ema
mycolor = up ? #00a7bc : down ? #b91002 : color.blue
plot(ema, title="EMA", color=mycolor, linewidth=1)
//plot(ema1, title="EMA", color=mycolor, linewidth=1,editable = false)
//plot(ema2, title="EMA", color=mycolor, linewidth=1,editable = false)
//plot(ema3, title="EMA", color=mycolor, linewidth=1,editable = false)
table_color_up = color.new(#00a7bc,70)
table_color_down = color.new(#b91002,70)
//vẽ bảng ema + rsi//
t = table.new(position = position.bottom_right, columns = 5, rows = 9, bgcolor = #fde9c9)
table.cell(t, 0, 0, "Time",text_size = size.small)
table.cell(t, 1, 0, "EMA",text_size = size.small)
table.cell(t, 0, 1, "5m",text_size = size.small)
table.cell(t, 0, 2, "15m",text_size = size.small)
table.cell(t, 0, 3, "4h",text_size = size.small)
table.cell(t, 0, 4, "1d",text_size = size.small)
// tính toán giá EMA của các khung thời gian khác nhau
ema5 = request.security(syminfo.tickerid, "5", ta.ema(src, len))
ema15 = request.security(syminfo.tickerid, "15", ta.ema(src, len))
ema4h = request.security(syminfo.tickerid, "240", ta.ema(src, len))
ema1d = request.security(syminfo.tickerid, "D", ta.ema(src, len))
//tô màu cho bảng chứa EMA
ema5_color = ema5 < close ? table_color_up : table_color_down
ema15_color = ema15 < close ? table_color_up :table_color_down
ema4h_color = ema4h < close ? table_color_up : table_color_down
ema1d_color = ema1d < close ? table_color_up : table_color_down
//tính toán ema 123_5
//ema5_1 = request.security(syminfo.tickerid, "5", ta.ema(close, len1))
//ema5_2 = request.security(syminfo.tickerid, "5", ta.ema(close, len2))
//ema5_3 = request.security(syminfo.tickerid, "5", ta.ema(close, len3))
//trend_ema5_color = (ema5_1 > ema5_2 and ema5_2 > ema5_3) ? color.green : (ema5_1 > ema5_2 and ema5_2 < ema5_3)? color.new(color.green,70) : (ema5_1 < ema5_2 and ema5_2 < ema5_3) ? color.red : (ema5_1 < ema5_2 and ema5_2 > ema5_3) ? color.new(color.red,70) : color.orange
//tính toán ema 123_15
ema15_1 = request.security(syminfo.tickerid, "15", ta.ema(close, len1))
ema15_2 = request.security(syminfo.tickerid, "15", ta.ema(close, len2))
ema15_3 = request.security(syminfo.tickerid, "15", ta.ema(close, len3))
trend_ema15_color = (ema15_1 > ema15_2 and ema15_2 > ema15_3) ? color.green : (ema15_1 > ema15_2 and ema15_2 < ema15_3)? color.new(color.green,70) : (ema15_1 < ema15_2 and ema15_2 < ema15_3) ? color.red : (ema15_1 < ema15_2 and ema15_2 > ema15_3) ? color.new(color.red,70) : color.orange
//tính toán ema 123_4h
ema4h_1 = request.security(syminfo.tickerid, "240", ta.ema(close, len1))
ema4h_2 = request.security(syminfo.tickerid, "240", ta.ema(close, len2))
ema4h_3 = request.security(syminfo.tickerid, "240", ta.ema(close, len3))
trend_ema4h_color = (ema4h_1 > ema4h_2 and ema4h_2 > ema4h_3) ? color.green : (ema4h_1 > ema4h_2 and ema4h_2 < ema4h_3)? color.new(color.green,70) : (ema4h_1 < ema4h_2 and ema4h_2 < ema4h_3) ? color.red : (ema4h_1 < ema4h_2 and ema4h_2 > ema4h_3) ? color.new(color.red,70) : color.orange
// tính toán RSI của các khung thời gian khác nhau
rsi5 = request.security(syminfo.tickerid, "5", ta.rsi(src, 14))
rsi15 = request.security(syminfo.tickerid, "15", ta.rsi(src, 14))
rsi4h = request.security(syminfo.tickerid, "240", ta.rsi(src, 14))
rsi1d = request.security(syminfo.tickerid, "D", ta.rsi(src, 14))
//tô màu cho bảng chứa RSI
rsi5_color = rsi5 > 70 ? table_color_down : rsi5 < 30 ? table_color_up : color.orange
rsi15_color = rsi15 > 70 ? table_color_down : rsi15 < 30 ? table_color_up : color.orange
rsi4h_color = rsi4h > 70 ? table_color_down : rsi4h < 30 ? table_color_up : color.orange
rsi1d_color = rsi1d > 70 ? table_color_down : rsi1d < 30 ? table_color_up : color.orange
//tính toán % thay đổi 1d, 7d, 30d
// Lấy giá trị giá đóng cửa của các ngày trước đó
yesterday_close = request.security(syminfo.tickerid, "D", close )
last_week_close = request.security(syminfo.tickerid, "W", close )
last_month_close = request.security(syminfo.tickerid, "M", close )
// Tính toán phần trăm thay đổi giá so với các ngày trước đó
day_change = math.round((close / yesterday_close - 1) * 100,1)
week_change = math.round((close / last_week_close - 1) * 100,1)
month_change = math.round((close / last_month_close - 1) * 100,1)
//tô màu cho bảng chứa % thay đổi
day_change_color = day_change < 0 ? table_color_down : table_color_up
weak_change_color = week_change < 0 ? table_color_down : table_color_up
month_change_color = month_change < 0 ? table_color_down : table_color_up
// tính toán btc.d usdt.d dxy
btc_d = request.security("CRYPTOCAP:BTC.D", timeframe.period, close)
usdt_d = request.security("CRYPTOCAP:USDT.D", timeframe.period, close)
dxy = request.security("TVC:DXY", timeframe.period, close)
yesterday_btc_d = request.security("CRYPTOCAP:BTC.D", timeframe.period, close )
yesterday_usdt_d = request.security("CRYPTOCAP:USDT.D", timeframe.period, close )
yesterday_dxy = request.security("TVC:DXY", timeframe.period, close )
btc_d_color = btc_d < yesterday_btc_d ? table_color_down : table_color_up //too mau
usdt_d_color = usdt_d < yesterday_usdt_d ? table_color_down : table_color_up
dxy_color = dxy < yesterday_dxy ? table_color_down : table_color_up
// điền giá EMA vào bảng
table.cell(t, 1, 1, str.tostring(math.round(ema5, 3)), bgcolor = ema5_color,text_size = size.small)
table.cell(t, 1, 2, str.tostring(math.round(ema15, 3)), bgcolor = ema15_color,text_size = size.small)
table.cell(t, 1, 3, str.tostring(math.round(ema4h, 3)), bgcolor = ema4h_color,text_size = size.small)
table.cell(t, 1, 4, str.tostring(math.round(ema1d, 3)), bgcolor = ema1d_color,text_size = size.small)
// điền rsi vào bảng
show_info_2 = input.bool(title = "Show % RSI",defval = true,group = "Table Setting")
if show_info_2
table.cell(t, 2, 0, "RSI",text_size = size.small)
table.cell(t, 2, 1, str.tostring(math.round(rsi5,0)), bgcolor = rsi5_color,text_size = size.small)
table.cell(t, 2, 2, str.tostring(math.round(rsi15,0)), bgcolor = rsi15_color,text_size = size.small)
table.cell(t, 2, 3, str.tostring(math.round(rsi4h,0)), bgcolor = rsi4h_color,text_size = size.small)
table.cell(t, 2, 4, str.tostring(math.round(rsi1d,0)), bgcolor = rsi1d_color,text_size = size.small)
// điển % change vào bảng
show_info_1 = input.bool(title = "Show % Change 1d, 7d, 30d",defval = true,group = "Table Setting")
if show_info_1
table.cell(t,0,5,"%",text_size = size.small)
table.cell(t,1,5,"1d",text_size = size.small)
table.cell(t,2,5,"7d",text_size = size.small)
table.cell(t,3,5,"30d",text_size = size.small)
table.cell(t, 1, 6, str.tostring(day_change, "#.##") + "%",bgcolor= day_change_color,text_size = size.small)
table.cell(t, 2, 6, str.tostring(week_change, "#.##") + "%",bgcolor = weak_change_color,text_size = size.small)
table.cell(t, 3, 6, str.tostring(month_change,"#.##") + "%", bgcolor = month_change_color,text_size = size.small)
//điện btc.d usdt.d dxy vào bảng
Table_Info = "Table Setting"
show_info = input.bool(title = "Show BTC.D, USSDT, DXY",defval = true,group = "Table Setting")
if show_info
table.cell(t,0,7,"#",text_size = size.small)
table.cell(t,1,7,"BTC.D",text_size = size.small)
table.cell(t,2,7,"USDT.D",text_size = size.small)
table.cell(t,3,7,"DXY",text_size = size.small)
table.cell(t, 1, 8, str.tostring(btc_d, "#.##") + "%",bgcolor= btc_d_color,text_size = size.small)
table.cell(t, 2, 8, str.tostring(usdt_d, "#.##") + "%",bgcolor = usdt_d_color,text_size = size.small)
table.cell(t, 3, 8, str.tostring(dxy,"#.##") + "%", bgcolor = dxy_color,text_size = size.small)
//điền trend ema vào bảng
show_info_3 = input.bool(title = "Show Trend",defval = true,group = "Table Setting")
if show_info_3
table.cell(t,3,0,"Trend",text_size = size.small)
//table.cell(t,3,1,"",bgcolor = trend_ema5_color)
table.cell(t,3,2,"",bgcolor = trend_ema15_color)
table.cell(t,3,3,"",bgcolor = trend_ema4h_color)
//đánh dấu volume với các osb + nến bulish bearish
//indicator("Color Ultra Volume Background", shorttitle = "UV",overlay=true, max_boxes_count=500, max_labels_count=500, max_lines_count=500, max_bars_back=1000)
UltraVol = "Ultra volume background"
colorultravol = input.color(color.new(color.purple,50),"Color UltraVol",group = UltraVol)
//Công thức//
lengthVolumeMA = input.int(20,minval=1,title="Length of MA applied on Volume",group = UltraVol)
ratioUltraVolume = input.float(2.2,minval=1,title="Ultra High Volume Ratio", group = UltraVol)
float volumeMA = 0
volumeMA := nz(volumeMA ) + (volume-nz(volumeMA )) / lengthVolumeMA
ultraHighVolumeMin = volumeMA * ratioUltraVolume
volUltraHigh = volume >= ultraHighVolumeMin? true : false
// Màu volume
color_cande_up_down = input.color(color.new(color.purple,100),"Color UltraVol",group = OSB_up_down)
Candle_body = input.float(0.5, 'Height of Engulfing candle body (%)', group = OSB_up_down)
//scan nến osb-eng - mera mera//
osb_up = high > high and low < low and close > close
osb_down = high > high and low < low and close < close
eng_up = open >= close and close > high and (close - open) >= Candle_body*(high - low)
eng_down = open <= close and close < low and (open - close) >= Candle_body*(high - low)
mm_up = osb_up and close > close and close > close
mm_down = osb_down and close < close and close < close
cande_up = close > close
cande_down = close < close
//tô màu nến//
colorOSB_up = input.color(#0ba4f9,'colorOSB_up',inline = "Up Outside Bar",group = OSB_up_down)
colorOSB_down = input.color(#fd1700,'colorOSB_dowwn',inline = "Down Outside Bar",group = OSB_up_down)
barcolor(osb_up ? colorOSB_up : na, title="Up Outside Bar")
barcolor(osb_down ? colorOSB_down : na, title="Down Outside Bar")
coloreng_up = input.color(#00a7bc,'coloreng_up',inline = "Bullish Bar",group = OSB_up_down)
coloreng_down = input.color(#b91002,'coloreng_dowwn',inline = "Bearlish Bar",group = OSB_up_down)
barcolor(eng_up ? coloreng_up : na, title="Bullish Bar")
barcolor(eng_down ? coloreng_down : na, title="Bearlish Bar")
//đánh dấu vol - mera mera
plotshape(volUltraHigh and cande_up,"Candle_UltraVol_up_shape",style = shape.circle,location = location.belowbar,color = coloreng_up,size = size.tiny)
plotshape(volUltraHigh and cande_down,"Candle_UltraVol_down_shape",style = shape.circle,location = location.abovebar,color = coloreng_down,size = size.tiny)
plotshape(volUltraHigh and osb_up,"Up Outside Bar+ Vol",style = shape.circle,location = location.belowbar,color = color_cande_up_down,size = size.tiny)
plotshape(volUltraHigh and osb_down,"Down Outside Bar+ Vol",style = shape.circle,location = location.abovebar,color = color_cande_up_down,size = size.tiny)
plotshape(volUltraHigh and eng_up,"Bullish Bar + Vol",style = shape.circle,location = location.belowbar,color = color_cande_up_down,size = size.tiny)
plotshape(volUltraHigh and eng_down,"Bearlish + Vol Bar",style = shape.circle,location = location.abovebar,color = color_cande_up_down,size = size.tiny)
plotshape(mm_up ? high : na, style=shape.circle, location=location.belowbar, color=#0ba4f9,title = "Mera UP",size = size.tiny)
plotshape(mm_down ? low : na, style=shape.circle, location=location.abovebar, color=#fd1700, title = "Mera Down", size = size.tiny)
//cảnh báo khi xuất hiện nến/
close_osb_up = close
close_osb_down = close
close_eng_up = close
close_eng_down = close
close_mm_up = close
close_mm_down = close
time_h4 = request.security(syminfo.tickerid, "240",close)
time_D1 = request.security(syminfo.tickerid, "D",close)
if (osb_up and barstate.isconfirmed)
if (close_osb_up > ema)
alert("OSB_UP: Above Ema: " + str.tostring(close_osb_up))
if volUltraHigh
alert("OSB_UP + Volume: Above Ema: " + str.tostring(close_osb_up))
else if (close_osb_up < ema)
alert("OSB_UP: Below Ema: " + str.tostring(close_osb_up))
if volUltraHigh
alert("OSB_UP + Volume: Below Ema: " + str.tostring(close_osb_up))
if (osb_down and barstate.isconfirmed)
if (close_osb_down > ema)
alert("OSB_DOWN: Above Ema: " + str.tostring(close_osb_down))
if volUltraHigh
alert("OSB_DOWN + Volume: Above Ema: " + str.tostring(close_osb_down))
else if (close_osb_down < ema)
alert("OSB_DOWN: Below Ema: " + str.tostring(close_osb_down))
if volUltraHigh
alert("OSB_DOWN + Volume: Below Ema: " + str.tostring(close_osb_down))
if (eng_up and barstate.isconfirmed)
if (close_eng_up > ema)
alert("Bar_UP: Above Ema: " + str.tostring(close_eng_up))
if volUltraHigh
alert("Bar_UP + Volume: Above Ema: " + str.tostring(close_eng_up))
else if (close_eng_up < ema)
alert("Bar_UP: Below Ema: " + str.tostring(close_eng_up))
if volUltraHigh
alert("Bar_UP + Volume: Below Ema: " + str.tostring(close_eng_up))
if (eng_down and barstate.isconfirmed)
if (close_eng_down > ema)
alert("Bar_DOWN: Above Ema: " + str.tostring(close_eng_down))
if volUltraHigh
alert("Bar_DOWN + Volume: Above Ema: " + str.tostring(close_eng_down))
else if (close_eng_down < ema)
alert("Bar_DOWN: Below Ema: " + str.tostring(close_eng_down))
if volUltraHigh
alert("Bar_DOWN + Volume: Below Ema: " + str.tostring(close_eng_down))
if (mm_up and barstate.isconfirmed)
if (close_mm_up > ema)
alert("Mera_UP: Above Ema: " + str.tostring(close_mm_up))
if volUltraHigh
alert("Mera_UP + Volume: Above Ema: " + str.tostring(close_mm_up))
else if (close_mm_up < ema)
alert("Mera_UP: Below Ema: " + str.tostring(close_mm_up))
if volUltraHigh
alert("Mera_UP + Volume: Below Ema: " + str.tostring(close_mm_up))
if (mm_down and barstate.isconfirmed)
if (close_mm_down > ema)
alert("Mera_DOWN: Above Ema: " + str.tostring(close_mm_down))
if volUltraHigh
alert("Mera_DOWN + Volume: Above Ema: " + str.tostring(close_mm_down))
else if (close_mm_down < ema)
alert("Mera_DOWN: Below Ema: " + str.tostring(close_mm_down))
if volUltraHigh
alert("Mera_DOWN + Volume: Below Ema: " + str.tostring(close_mm_down))
//indicator("Initial Balance", shorttitle="Initial Balance", overlay=true, max_bars_back=5000)
ib_session = input.session("2300-0000", title="Initial Balance", group="Calculation period")
show_extra_levels = input.bool(false, "Show extra levels (IBH x2 & IBL x2)", group="Information")
show_intermediate_levels = input.bool(false, "Show intermediate levels (50%)", group="Information")
show_ib_calculation_area = input.bool(false, "Initial balance calculation period coloration", group="Information")
show_labels = input.bool(false, "Show labels", group="Information")
fill_ib_areas = input.bool(false, "Colour IB areas", group="Information")
only_current_levels = input.bool(true, "Only display the current IB Levels", group="Information")
only_current_zone = input.bool(false, "Only display the current IB calculation area", group="Information")
label_size = input.string("Small", title="Label Size", options= , group="Drawings")
lvl_width = input.int(1, "Daily price level width", group="Drawings")
high_col = input.color(color.black, "Initial balance high levels color", group="Drawings")
low_col = input.color(color.black, "Initial balance low levels color", group="Drawings")
middle_col = input.color(#ffa726, "50% initial balance color", group="Drawings")
extend_level = input.string("Right", title="Extend current levels", options= , group="Drawings")
main_levels_style = input.string("Solid" , "Main levels line style", options= , group="Drawings")
ext_levels_style = input.string("Dashed" , "Extended levels line style", options= , group="Drawings")
int_levels_style = input.string("Dotted" , "Intermediate levels line style", options= , group="Drawings")
fill_ib_color= input.color(#b8851faa, "IB area background color", group="Drawings")
ext = extend_level == "Right" ? extend.right : extend_level == "Left" ? extend.left : extend_level == "Both" ? extend.both : extend.none
var delta_history = array.new_float(20)
inSession(sess) => na(time(timeframe.period, sess)) == false
get_line_style(s) =>
s == "Solid" ? line.style_solid : s == "Dotted" ? line.style_dotted : line.style_dashed
get_levels(n) =>
h = high
l = low
for i=1 to n
if low < l
l := low
if high > h
h := high
var line ibh = na
var line ibl = na
var line ibm = na
var line ib_plus = na
var line ib_minus = na
var line ib_plus2 = na
var line ib_minus2 = na
var line ibm_plus = na
var line ibm_minus = na
var label labelh = na
var label labell = na
var label labelm = na
var label label_plus = na
var label label_minus = na
var label label_plus2 = na
var label label_minus2 = na
var label labelm_plus = na
var label labelm_minus = na
var box ib_area = na
labelSize = (label_size == "Huge") ? size.huge :
(label_size == "Large") ? size.large :
(label_size == "Small") ? size.small :
(label_size == "Tiny") ? size.tiny :
(label_size == "Auto") ? size.auto : size.normal
var offset = 0
ins = inSession(ib_session)
bgcolor(show_ib_calculation_area and ins ? #673ab730 : na, title="IB calculation zone")
var float ib_delta = na
if ins
offset += 1
if ins and not ins
= get_levels(offset)
ib_delta := h - l
if array.size(delta_history) >= 20
array.shift(delta_history)
array.push(delta_history, ib_delta)
line.set_extend(ibh, extend.none)
line.set_extend(ibl, extend.none)
if show_intermediate_levels
line.set_extend(ibm, extend.none)
if show_extra_levels
line.set_extend(ib_plus, extend.none)
line.set_extend(ib_minus, extend.none)
line.set_extend(ib_plus2, extend.none)
line.set_extend(ib_minus2, extend.none)
if show_intermediate_levels
line.set_extend(ibm_plus, extend.none)
line.set_extend(ibm_minus, extend.none)
if show_labels
if only_current_levels
label.delete(labelh)
label.delete(labell)
label.delete(labelm)
label.delete(label_plus)
label.delete(label_minus)
label.delete(label_plus2)
label.delete(label_minus2)
label.delete(labelm_plus)
label.delete(labelm_minus)
labelh := label.new(bar_index , h, text="IBH 100%: "+str.tostring(h), style=label.style_none, textcolor=high_col, size=labelSize)
labell := label.new(bar_index , l, text="IBL 0%: "+str.tostring(l), style=label.style_none, textcolor=low_col, size=labelSize)
if show_intermediate_levels
labelm := label.new(bar_index , m, text="IBM 50%: "+str.tostring(m)+" IBΔ: "+str.tostring(h - l), style=label.style_none, textcolor=middle_col, size=labelSize)
if show_extra_levels
label_plus := label.new(bar_index , h + ib_delta, text="IBH x2 - "+str.tostring(h + ib_delta), style=label.style_none, textcolor=high_col, size=labelSize)
label_minus := label.new(bar_index , l - ib_delta, text="IBL x2: "+str.tostring(l - ib_delta), style=label.style_none, textcolor=low_col, size=labelSize)
label_plus2 := label.new(bar_index , h + (ib_delta*2), text="IBH x3 - "+str.tostring(h + (ib_delta*2)), style=label.style_none, textcolor=high_col, size=labelSize)
label_minus2 := label.new(bar_index , l - (ib_delta*2), text="IBL x3: "+str.tostring(l - (ib_delta*2)), style=label.style_none, textcolor=low_col, size=labelSize)
if fill_ib_areas
if only_current_zone
box.delete(ib_area)
ib_area := box.new(bar_index , h, bar_index, l, bgcolor=fill_ib_color, border_color=#00000000)//, extend=ext)
if only_current_levels
line.delete(ibh)
line.delete(ibl)
line.delete(ibm)
line.delete(ib_plus)
line.delete(ib_minus)
line.delete(ib_plus2)
line.delete(ib_minus2)
line.delete(ibm_plus)
line.delete(ibm_minus)
ibh := line.new(bar_index , h, bar_index, h, color=high_col, extend=ext, width=lvl_width, style=get_line_style(main_levels_style))
ibl := line.new(bar_index , l, bar_index, l, color=low_col, extend=ext, width=lvl_width, style=get_line_style(main_levels_style))
if show_intermediate_levels
ibm := line.new(bar_index , m, bar_index, m, color=middle_col, style=get_line_style(int_levels_style), extend=ext, width=lvl_width)
if show_extra_levels
ib_plus := line.new(bar_index , h + ib_delta, bar_index, h + ib_delta, color=high_col, style=get_line_style(ext_levels_style), extend=ext, width=lvl_width)
ib_minus := line.new(bar_index , l - ib_delta, bar_index, l - ib_delta, color=low_col, style=get_line_style(ext_levels_style), extend=ext, width=lvl_width)
ib_plus2 := line.new(bar_index , h + (ib_delta*2), bar_index, h + (ib_delta *2), color=high_col, style=get_line_style(ext_levels_style), extend=ext, width=lvl_width)
ib_minus2 := line.new(bar_index , l - (ib_delta*2), bar_index, l - (ib_delta*2), color=low_col, style=get_line_style(ext_levels_style), extend=ext, width=lvl_width)
if show_intermediate_levels
ibm_plus := line.new(bar_index , h + (ib_delta/2), bar_index, h + (ib_delta/2), color=middle_col, style=get_line_style(int_levels_style), extend=ext, width=lvl_width)
ibm_minus := line.new(bar_index , l - (ib_delta/2), bar_index, l - (ib_delta/2), color=middle_col, style=get_line_style(int_levels_style), extend=ext, width=lvl_width)
offset := 0
if (not ins) and (not ins )
line.set_x2(ibh, bar_index)
line.set_x2(ibl, bar_index)
if show_intermediate_levels
line.set_x2(ibm, bar_index)
if show_extra_levels
line.set_x2(ib_plus, bar_index)
line.set_x2(ib_minus, bar_index)
line.set_x2(ib_plus2, bar_index)
line.set_x2(ib_minus2, bar_index)
if show_intermediate_levels
line.set_x2(ibm_plus, bar_index)
line.set_x2(ibm_minus, bar_index)
var table ib_analytics = table.new(position.bottom_left, 2, 6)
ib_sentiment() =>
h = array.max(delta_history)
l = array.min(delta_history)
a = array.avg(delta_history)
h_comp = ib_delta > h ? ib_delta - h : (ib_delta - h) * -1
l_comp = ib_delta > l ? ib_delta - l : (ib_delta - l) * -1
a_comp = ib_delta > a ? ib_delta - a : (ib_delta - a) * -1
(h_comp < l_comp and h_comp < a_comp) ? "Huge" : (l_comp < h_comp and l_comp < a_comp) ? "Small" : "Medium"
//@version=5
//indicator('Key Levels', overlay=true)
group = 'KEYLVL_SETTINGS'
displaystyle = input.string('Standard', ' Display Style', group = group, inline='onest', options= )
linestyle = input.string('Solid', ' Line Style ', group = group, inline='twost', options= )
fontstyle = input.string('Monospace', ' Font Type ', group = group, inline='trest', options= )
labelpos = input.string('Middle', ' Label Pos ', group = group, inline=' ', options= )
bar_offset = input.int (30, ' Offset ', group = group, inline='onest', minval=0, maxval=450, step = 5)
threshold = input.float (0.1, ' Threshold %', group = group, inline='twost', minval=0, step=0.05, tooltip='Threshold - the distance between the levels after which the labels merge.')
index = input.int (0, ' Index ', group = group, inline='trest', minval=0, step=1, tooltip='Index - Default 0 allows you to see current and past price levels. Changing to 1 will shift the current levels to the previous levels, and the previous levels to the previous levels, etc.')
color_cD = input.color (#2a89c9, ' cD', group = group, inline='cols1')
color_cW = input.color (#b7d123, ' cW', group = group, inline='cols1')
color_cM = input.color (#8056b8, ' cM', group = group, inline='cols1')
color_cQ = input.color (#c23eb0, ' cQ', group = group, inline='cols1')
color_cY = input.color (#d62e28, ' cY', group = group, inline='cols1')
color_pD = input.color (#2a89c9, ' pD', group = group, inline='cols2')
color_pW = input.color (#b7d123, ' pW', group = group, inline='cols2')
color_pM = input.color (#8056b8, ' pM', group = group, inline='cols2')
color_pQ = input.color (#c23eb0, ' pQ', group = group, inline='cols2')
color_pY = input.color (#d62e28, ' pY', group = group, inline='cols2', tooltip="Prefix 'C' = Current/today. Prefix 'P' = Previous/yesterday. Prefix 'D' = Day. Prefix 'W' = Week. Prefix 'M' = Mounth. Prefix 'Q' = Quarterly. Prefix 'Y' = Year.'" )
i_tG = input.bool (true, ' Global Color Text', group = group, inline='colsg')
color_tG = input.color (color.black, ' ', group = group, inline='colsg')
i_lG = input.bool (true, ' Global Color Line', group = group, inline='colsg')
color_lG = input.color (color.black, ' ', group = group, inline='colsg')
fontstyles = switch fontstyle
"Default" => font.family_default
"Monospace" => font.family_monospace
linestyles = switch linestyle
"Solid" => line.style_solid
"Dashed" => line.style_dashed
"Dotted" => line.style_dotted
displaystyles = switch displaystyle
"Standard" => extend.none
"Right" => extend.right
"Both" => extend.both
"Left" => extend.left
getprice(TimeFrame, Index)=> // Get Open, High, Low, Close, Time data
i = Index
tf = TimeFrame
= request.security(syminfo.tickerid, tf, [open , high , low , close , time ], lookahead=barmerge.lookahead_on)
= getprice('D', 0+index) // Get Current Day Open, High, Low, Close, Time
= getprice('W', 0+index) // Get Current Weekly Open, High, Low, Close, Time
= getprice('M', 0+index) // Get Current Mounth Open, High, Low, Close, Time
= getprice('3M', 0+index) // Get Current Quarter Open, High, Low, Close, Time
= getprice('12M', 0+index) // Get Current Year Open, High, Low, Close, Time
= getprice('D', 1+index) // Get Previous Day Open, High, Low, Close, Time
= getprice('W', 1+index) // Get Previous Weekly Open, High, Low, Close, Time
= getprice('M', 1+index) // Get Previous Mounth Open, High, Low, Close, Time
= getprice('3M', 1+index) // Get Previous Quarter Open, High, Low, Close, Time
= getprice('12M', 1+index) // Get Previous Year Open, High, Low, Close, Time
extend(bars) => // Extends the current time by the product of the time difference between elements and the number of bars.
timenow + (time - time ) * bars
getlevel(time, level, txtcolor, linecolor, txtlabel)=> // Get draws a line and a label on the chart
if barstate.islast // The following code doesn't need to be processed on every candle
xindex = displaystyle == 'Standard' ? time : bar_index+bar_offset
xloc = displaystyle == 'Standard' ? xloc.bar_time : xloc.bar_index
xid = displaystyle == 'Standard' ? extend(bar_offset) : bar_index+bar_offset+1
lblpos = labelpos == 'Middle' ? label.style_label_center : label.style_none
lines = line.new (x1=xindex, x2=xid, y1=level, y2=level, xloc=xloc, style=linestyles, extend=displaystyles, color=linecolor)
labels = label.new(x=xid, y=level, text=txtlabel, style=lblpos, xloc=xloc, text_font_family=fontstyles, textcolor=txtcolor, color = #ffffff00)
line.delete(lines ) // remove the previous line when new bar appears
label.delete(labels ) // remove the previous label when new bar appears
// Get Inputs, Lines, Labels
i_cDO = input(false, 'DO ', group = group, inline='D'), = getlevel(cDtime, i_cDO ? cDopen : na, i_tG ? color_tG : color_cD, i_lG ? color_lG : color_cD, 'DO' )
i_cDH = input(false, 'DH ', group = group, inline='D'), = getlevel(cDtime, i_cDH ? cDhigh : na, i_tG ? color_tG : color_cD, i_lG ? color_lG : color_cD, 'DH' )
i_cDL = input(false, 'DL ', group = group, inline='D'), = getlevel(cDtime, i_cDL ? cDlow : na, i_tG ? color_tG : color_cD, i_lG ? color_lG : color_cD, 'DL' )
i_pDO = input(false, 'pDO', group = group, inline='D'), = getlevel(pDtime, i_pDO ? pDopen : na, i_tG ? color_tG : color_pD, i_lG ? color_lG : color_pD, 'pDO' )
i_pDH = input(true, 'pDH', group = group, inline='D'), = getlevel(pDtime, i_pDH ? pDhigh : na, i_tG ? color_tG : color_pD, i_lG ? color_lG : color_pD, 'pDH' )
i_pDL = input(true, 'pDL', group = group, inline='D'), = getlevel(pDtime, i_pDL ? pDlow : na, i_tG ? color_tG : color_pD, i_lG ? color_lG : color_pD, 'pDL' )
i_cWO = input(false, 'WO ', group = group, inline='W'), = getlevel(cWtime, i_cWO ? cWopen : na, i_tG ? color_tG : color_cW, i_lG ? color_lG : color_cW, 'WO' )
i_cWH = input(false, 'WH ', group = group, inline='W'), = getlevel(cWtime, i_cWH ? cWhigh : na, i_tG ? color_tG : color_cW, i_lG ? color_lG : color_cW, 'WH' )
i_cWL = input(false, 'WL ', group = group, inline='W'), = getlevel(cWtime, i_cWL ? cWlow : na, i_tG ? color_tG : color_cW, i_lG ? color_lG : color_cW, 'WL' )
i_pWO = input(false, 'pWO', group = group, inline='W'), = getlevel(pWtime, i_pWO ? pWopen : na, i_tG ? color_tG : color_pW, i_lG ? color_lG : color_pW, 'pWO' )
i_pWH = input(false, 'pWH', group = group, inline='W'), = getlevel(pWtime, i_pWH ? pWhigh : na, i_tG ? color_tG : color_pW, i_lG ? color_lG : color_pW, 'pWH' )
i_pWL = input(false, 'pWL', group = group, inline='W'), = getlevel(pWtime, i_pWL ? pWlow : na, i_tG ? color_tG : color_pW, i_lG ? color_lG : color_pW, 'pWL' )
i_cMO = input(false, 'MO ', group = group, inline='M'), = getlevel(cMtime, i_cMO ? cMopen : na, i_tG ? color_tG : color_cM, i_lG ? color_lG : color_cM, 'MO' )
i_cMH = input(false, 'MH ', group = group, inline='M'), = getlevel(cMtime, i_cMH ? cMhigh : na, i_tG ? color_tG : color_cM, i_lG ? color_lG : color_cM, 'MH' )
i_cML = input(false, 'ML ', group = group, inline='M'), = getlevel(cMtime, i_cML ? cMlow : na, i_tG ? color_tG : color_cM, i_lG ? color_lG : color_cM, 'ML' )
i_pMO = input(false, 'pMO', group = group, inline='M'), = getlevel(pMtime, i_pMO ? pMopen : na, i_tG ? color_tG : color_pM, i_lG ? color_lG : color_pM, 'pMO' )
i_pMH = input(false, 'pMH', group = group, inline='M'), = getlevel(pMtime, i_pMH ? pMhigh : na, i_tG ? color_tG : color_pM, i_lG ? color_lG : color_pM, 'pMH' )
i_pML = input(false, 'pML', group = group, inline='M'), = getlevel(pMtime, i_pML ? pMlow : na, i_tG ? color_tG : color_pM, i_lG ? color_lG : color_pM, 'pML' )
i_cQO = input(false, 'QO ', group = group, inline='Q'), = getlevel(cQtime, i_cQO ? cQopen : na, i_tG ? color_tG : color_cQ, i_lG ? color_lG : color_cQ, 'QO' )
i_cQH = input(false, 'QH ', group = group, inline='Q'), = getlevel(cQtime, i_cQH ? cQhigh : na, i_tG ? color_tG : color_cQ, i_lG ? color_lG : color_cQ, 'QH' )
i_cQL = input(false, 'QL ', group = group, inline='Q'), = getlevel(cQtime, i_cQL ? cQlow : na, i_tG ? color_tG : color_cQ, i_lG ? color_lG : color_cQ, 'QL' )
i_pQO = input(false, 'pQO', group = group, inline='Q'), = getlevel(pQtime, i_pQO ? pQopen : na, i_tG ? color_tG : color_pQ, i_lG ? color_lG : color_pQ, 'pQO' )
i_pQH = input(false, 'pQH', group = group, inline='Q'), = getlevel(pQtime, i_pQH ? pQhigh : na, i_tG ? color_tG : color_pQ, i_lG ? color_lG : color_pQ, 'pQH' )
i_pQL = input(false, 'pQL', group = group, inline='Q'), = getlevel(pQtime, i_pQL ? pQlow : na, i_tG ? color_tG : color_pQ, i_lG ? color_lG : color_pQ, 'pQL' )
i_cYO = input(false, 'YO ', group = group, inline='Y'), = getlevel(cYtime, i_cYO ? cYopen : na, i_tG ? color_tG : color_cY, i_lG ? color_lG : color_cY, 'YO' )
i_cYH = input(false, 'YH ', group = group, inline='Y'), = getlevel(cYtime, i_cYH ? cYhigh : na, i_tG ? color_tG : color_cY, i_lG ? color_lG : color_cY, 'YH' )
i_cYL = input(false, 'YL ', group = group, inline='Y'), = getlevel(cYtime, i_cYL ? cYlow : na, i_tG ? color_tG : color_cY, i_lG ? color_lG : color_cY, 'YL' )
i_pYO = input(false, 'pYO', group = group, inline='Y'), = getlevel(pYtime, i_pYO ? pYopen : na, i_tG ? color_tG : color_pY, i_lG ? color_lG : color_pY, 'pYO' )
i_pYH = input(false, 'pYH', group = group, inline='Y'), = getlevel(pYtime, i_pYH ? pYhigh : na, i_tG ? color_tG : color_pY, i_lG ? color_lG : color_pY, 'pYH' )
i_pYL = input(false, 'pYL', group = group, inline='Y'), = getlevel(pYtime, i_pYL ? pYlow : na, i_tG ? color_tG : color_pY, i_lG ? color_lG : color_pY, 'pYL' )
// Сollecting labels into an array for normalization
labels = array.from(cDOlabel,cDHlabel,cDLlabel,pDOlabel,pDHlabel,pDLlabel,cWOlabel,cWHlabel,cWLlabel,pWOlabel,pWHlabel,pWLlabel,cMOlabel,cMHlabel,cMLlabel,pMOlabel,pMHlabel,pMLlabel,cQOlabel,cQHlabel,cQLlabel,pQOlabel,pQHlabel,pQLlabel,cYOlabel,cYHlabel,cYLlabel,pYOlabel,pYHlabel,pYLlabel)
// This loop merge items in arrays "labels" into a single label if their difference is less than a certain threshold, and updates the label text.
for i = 0 to array.size(labels) - 2 // Loop through all the labels
txt = label.get_text(array.get(labels, i)) // Get the text of the current label
price_i = label.get_y(array.get(labels, i)) // Get the y coordinate of the current label
label_i = array.get(labels, i) // Store the current label
for j = i + 1 to array.size(labels) - 1 // Loop through the remaining labels
price_j = label.get_y(array.get(labels, j)) // Get the y coordinate of the current label
if math.abs(price_i - price_j) < (threshold/100) * price_i // Compare the prices
txt := txt + ' / ' + label.get_text(array.get(labels, j)) // Add the text of the second label
label.delete(array.get(labels, j)) // Delete the second label
label.set_text(label_i, txt) // Set the text of the current label
repeat(str, num) => // Returns a string that is created by repeating the input str num times
res = ""
len = str.length(str)
if num > 0 and len * num <= 4096
for r = 1 to num
res := res + str
res
// Loop to change the position of the Label
if labelpos == 'Middle'
for z = 0 to array.size(labels) - 1
label_z = array.get(labels, z) // Get the label at position z
texts = label.get_text(label_z) // Get the text of the label
spaces = fontstyle=='Default' ? repeat(' ', math.ceil(str.length(texts))*2) : repeat(' ', math.ceil(str.length(texts))) // Calculate the number of spaces needed
label.set_text(label_z, displaystyle=='Right'? texts + spaces + ' ' : spaces+' ' + texts) // Set the label text with the calculated spaces
//
//@version=5
//indicator("Congestion Zone", overlay=true)
Congestion_Zone = "Congestio_Zone"
Show_CZ = input.bool(true, title="On/off Congestion Zone", group="Congestion_Zone")
minbar = input(title="Minimum Bars in Zone", defval=5, group="Congestion_Zone", inline="Box",tooltip = "Số lượng nến tối thiểu để có 1 vùng CZ")
border_width = input.int(title="CZ boder width", defval=1, inline="Box1", group="Congestion_Zone", step=1,tooltip = "Viền CZ")
max_boxes = input.int(title="Max CZ", defval=50, group="Congestion_Zone", minval=1,tooltip = "Số vùng box tối đa muốn hiển thị để tránh rối mắt")
boxcolor_basic = input.color(title="CZ Color Basic", defval=color.new(color.orange, 80), group="Congestion_Zone",tooltip = "Nến thoát khỏi box không có xu hướng rõ ràng")
boxcolor_up = input.color(title="CZ Color Up", defval=color.new(color.green, 80), group="Congestion_Zone",tooltip = "Nến thoát khỏi box có giá đóng cửa > vùng CZ")
boxcolor_down = input.color(title="CZ Color Dowwn", defval=color.new(color.red, 80), group="Congestion_Zone",tooltip = "Nến thoát khỏi box có đóng cửa < vùng CZ")
var boxopen = array.new_float()
var boxclose = array.new_float()
var boxes = array.new_box()
congestion_condition = close >= low and close <= high and open >= low and open <= high
if congestion_condition and Show_CZ
array.push(boxopen, open > close ? open : close)
array.push(boxclose, open > close ? close : open)
else if array.size(boxopen) < minbar
array.clear(boxopen)
array.clear(boxclose)
if not congestion_condition and array.size(boxopen) >= minbar and Show_CZ
box_max = array.max(boxopen)
box_min = array.min(boxclose)
box_color = close >= box_max ? boxcolor_up : close <= box_min ? boxcolor_down : boxcolor_basic
if box_color == boxcolor_basic
alert("CZ basic")
else if box_color == boxcolor_up
alert("CZ UP")
else if box_color == boxcolor_down
alert("CZ DOWN")
// Determine box color based on last candle
new_box = box.new(bar_index - array.size(boxopen), box_max, bar_index - 1, box_min, bgcolor=box_color, border_width=border_width,border_color = box_color)
array.push(boxes, new_box)
array.clear(boxopen)
array.clear(boxclose)
//Remove old boxes if limit is reached
while array.size(boxes) > max_boxes
box.delete(array.shift(boxes))
Support and Resistance Levels TP/SLSupport and resistance levels are critical concepts in trading, often used to set Take Profit (TP) and Stop Loss (SL) levels. Here's a guide to effectively determine these levels:
1. Identifying Support and Resistance Levels
- Support Level: A price level where demand is strong enough to prevent the price from falling further. Think of it as a floor.
- Resistance Level: A price level where selling pressure is strong enough to prevent the price from rising further. Think of it as a ceiling.
Methods to Identify Levels:
- Horizontal Lines: Use historical price data to find levels where prices frequently reversed.
- **Trendlines**: Draw diagonal lines connecting higher lows (support) or lower highs (resistance).
- Fibonacci Retracement: Calculate levels based on key Fibonacci ratios (e.g., 23.6%, 38.2%, 61.8%).
- Moving Averages: Identify dynamic support and resistance based on moving average levels.
- Volume Profile: Spot areas of high trading activity, which often act as support or resistance.
---
2. Setting Take Profit (TP) Levels
- Conservative Approach: Place the TP level slightly below a resistance level to ensure execution.
- Aggressive Approach: Target higher levels, considering momentum and trend strength.
Example:
- Resistance at $50.
- Set TP at $49.80 to account for slippage or premature reversals.
3. Setting Stop Loss (SL) Levels
- Below Support: For long trades, set the SL slightly below the identified support level.
- Above Resistance: For short trades, set the SL slightly above the resistance.
Example:
- Support at $45.
- Set SL at $44.80 to allow for minor price fluctuations.
4. Risk-Reward Ratio
- Aim for at least a 1:2 risk-reward ratio (e.g., risk $1 to gain $2).
- Calculate TP and SL levels accordingly to maintain this balance.
5. Adjusting for Market Conditions
- Volatile Markets: Widen TP and SL levels to account for larger price swings.
- Stable Markets: Use tighter levels for precise risk management.
6. Automating TP/SL
- Use trading platforms to automate TP/SL placements, ensuring discipline and emotional control.
Would you like help applying this to a specific scenario or chart?