Custom Buy and Sell Signal with Body Ratio and RSI
Indicator Overview:
Name: Custom Buy and Sell Signal with Body Ratio and RSI
Description: This indicator is designed to detect buy and sell opportunities by analyzing the body size and wicks of candles in combination with the RSI indicator and volume. It helps identify trend reversals under high-volume market conditions, which enhances the reliability of the signals.
Indicator Features:
RSI (Relative Strength Index): The RSI indicator is used to assess oversold (RSI < 40) or overbought (RSI > 60) conditions. These zones signal potential reversals when combined with other technical signals.
Candle Body Analysis:
The indicator compares the size of the current and previous candles to validate signals.
For a buy signal, the current candle must be bullish and have a body size proportional to that of the previous bearish candle.
Similarly, for a sell signal, the current candle must be bearish with a body size comparable to the previous bullish candle.
Wick Validation:
The indicator analyzes the wick length to reinforce or exclude signals.
For a buy signal, the lower wick of the bullish candle must be shorter than that of the previous bearish candle.
For a sell signal, the upper wick of the bearish candle must be shorter than that of the previous bullish candle and smaller than 30% of the candle's body.
High Volume:
Signals are only generated when the volume exceeds a certain threshold, ensuring that signals are issued in active market conditions.
The minimum volume should be adjusted based on the asset. For example, for gold, a minimum volume of 9000 is recommended.
Trading Strategy:
Buy Signals:
A bearish (red) candle is followed by a bullish (green) candle with a body size that is comparable to the previous candle (0.9 to 3 times the body size).
The lower wick of the bullish candle is shorter than that of the previous bearish candle, confirming the validity of the signal.
The RSI must be below 40, indicating an oversold condition.
The volume must exceed the defined threshold (e.g., > 9000 for gold) to confirm an active market.
Sell Signals:
A bullish (green) candle is followed by a bearish (red) candle with a comparable body size.
The upper wick of the bearish candle must be shorter than that of the previous bullish candle and must not exceed 30% of the body size.
The RSI must be above 60, indicating an overbought condition.
The volume must also exceed the minimum threshold for a valid signal.
Usage Guidelines:
Volume Adjustment: It is crucial to adjust the volume threshold depending on the asset you're trading. For example, for assets like gold, a minimum volume of 9000 is recommended to filter out weak signals. Each asset has a different volume dynamic, so test different thresholds on historical data to find the optimal setting.
Time Frame:
It is recommended to use this indicator on a 1-hour (1H) chart for the best signal relevance. This time frame provides a good balance between reactivity and filtering false signals.
Confluence:
Combine the signals from this indicator with other tools like support and resistance levels, moving averages, or chart patterns to increase your chances of success. Confluence of indicators improves the reliability of signals.
Risk Management:
Implement strict risk management. Use stop-losses based on volatility, such as ATR (Average True Range), or the wick size to determine exit points.
Backtesting:
Before using it live, conduct backtesting on various assets to fine-tune the parameters, especially the volume threshold, and to verify performance across different market conditions.
This indicator is an excellent tool for traders looking to identify trend reversals based on solid technical criteria such as RSI, candle structure, and volume. It is particularly effective on volatile assets with precise volume adjustment.
อินดิเคเตอร์และกลยุทธ์
Multi-Ticker RS vs SPYThis Pine Script, titled "Multi-Ticker RS vs SPY," is a clean and efficient indicator designed for TradingView, enabling traders to monitor the relative strength (RS) of up to 10 ticker symbols compared to the S&P 500 ETF (SPY) on a single chart. Ideal for options traders, such as those managing a $1,400 account, it provides a simple way to assess which stocks are outperforming or underperforming the broader market. As of February 26, 2025, the script supports any chart timeframe, such as 5-minute or daily intervals, and calculates RS based on a user-defined lookback period, defaulting to 1 bar for real-time insights.
Users can input ticker symbols via customizable settings, with defaults set to popular stocks like AAPL, TSLA, NVDA, GOOGL, AMZN, MSFT, FB, NFLX, INTC, and PYPL. The script fetches closing prices for each ticker and SPY, computes their percentage changes over the lookback period, and determines RS as the ratio of each ticker’s change to SPY’s change, handling division by zero gracefully. It displays each ticker’s current RS score in a vertical column of labels on the chart’s top-left corner, updated on the last bar to avoid clutter. Users can adjust label size (tiny, small, normal, large) and text color for visibility, ensuring a tailored, error-free experience for quick market analysis.
Mile Runner - Swing Trade LONGMile Runner - Swing Trade LONG Indicator - By @jerolourenco
Overview
The Mile Runner - Swing Trade LONG indicator is designed for swing traders who focus on LONG positions in stocks, BDRs (Brazilian Depositary Receipts), and ETFs. It provides clear entry signals, stop loss, and take profit levels, helping traders identify optimal buying opportunities with a robust set of technical filters. The indicator is optimized for daily candlestick charts and combines multiple technical analysis tools to ensure high-probability trades.
Key Features
Entry Signals: Visualized as green triangles below the price bars, indicating a potential LONG entry.
Stop Loss and Take Profit Levels: Automatically plotted on the chart for easy reference.
Stop Loss: Based on the most recent pivot low (support level).
Take Profit: Calculated using a Fibonacci-based projection from the entry price to the stop loss.
Trend and Momentum Filters: Ensures trades align with the prevailing trend and have sufficient momentum.
Volume and Volatility Confirmation: Verifies market interest and price movement potential.
How It Works
The indicator uses a combination of technical tools to filter and confirm trade setups:
Exponential Moving Averages (EMAs):
A short EMA (default: 9 periods) and a long EMA (default: 21 periods) identify the trend.
A bullish crossover (EMA9 crosses above EMA21) signals a potential upward trend.
Money Flow Index (MFI):
Confirms buying pressure when MFI > 50.
Average True Range (ATR):
Ensures sufficient volatility by checking if ATR exceeds its 20-period moving average.
Volume:
Confirms market interest when volume exceeds its 20-period moving average.
Pivot Lows:
Identifies recent support levels (pivot lows) to set the stop loss.
Ensures the pivot low is recent (within the last 10 bars by default).
Additional Trend Filter:
Confirms the long EMA is rising, reinforcing the bullish trend.
Inputs and Customization
The indicator is highly customizable, allowing traders to tailor it to their strategies:
EMA Periods: Adjust the short and long EMA lengths.
ATR and MFI Periods: Modify lookback periods for volatility and momentum.
Pivot Lookback: Control the sensitivity of pivot low detection.
Fibonacci Level: Adjust the Fibonacci retracement level for take profit.
Take Profit Multiplier: Fine-tune the aggressiveness of the take profit target.
Max Pivot Age: Set the maximum bars since the last pivot low for relevance.
Usage Instructions
Apply the Indicator:
Add the "Mile Runner - Swing Trade LONG" indicator to your TradingView chart.
Best used on daily charts for swing trading.
Look for Entry Signals:
A green triangle below the price bar signals a potential LONG entry.
Set Stop Loss and Take Profit:
Stop Loss: Red dashed line indicating the stop loss level.
Take Profit: Purple dashed line showing the take profit level.
Monitor the Trade:
The entry price is marked with a green dashed line for reference.
Adjust trade management based on the plotted levels.
Set Alerts:
Use the built-in alert condition to get notified of new LONG entry signals.
Important Notes
For LONG Positions Only : Designed exclusively for swing trading LONG positions.
Timeframe: Optimized for daily charts but can be tested on other timeframes.
Asset Types: Works best with stocks, BDRs, and ETFs.
Risk Management: Always align stop loss and take profit levels with your risk tolerance.
Why Use Mile Runner?
The Mile Runner indicator simplifies swing trading by integrating trend, momentum, volume, and volatility filters into one user-friendly tool. It helps traders:
Identify high-probability entry points.
Establish clear stop loss and take profit levels.
Avoid low-volatility or low-volume markets.
Focus on assets with strong buying pressure and recent support.
By following its signals and levels, traders can make informed decisions and enhance their swing trading performance. Customize the inputs and test it on your favorite assets—happy trading!
Bitcoin Market Dominance with Moving AveragesBitcoin Market Dominance with Moving Averages
This Pine Script indicator tracks Bitcoin market dominance by calculating the percentage of Bitcoin's market capitalization relative to the total cryptocurrency market cap.
Features:
✅ Real-time BTC Dominance Calculation: Displays the percentage of Bitcoin’s market share.
✅ Moving Averages: Includes two customizable moving averages for trend analysis.
✅ Visual Alerts: Background colors indicate different dominance levels:
Green: BTC dominance is above 50% (strong BTC market control).
Red: BTC dominance is below 40% (altcoins gaining strength).
Orange: BTC dominance is between 40%-50% (neutral zone).
This tool helps traders analyze Bitcoin’s influence on the crypto market and identify key dominance trends.
Cometreon_Public📚 Cometreon Public Library – Advanced Functions for Pine Script
This library contains advanced functions used in my public indicators on TradingView. The goal is to make the code more modular and efficient, allowing users to call pre-built functions for complex calculations without rewriting them from scratch.
🔹 Currently Available Functions:
1️⃣ Moving Average Function – Provides multiple types of moving averages to choose from, including:
SMA (Simple Moving Average)
EMA (Exponential Moving Average)
WMA (Weighted Moving Average)
RMA (Smoothed Moving Average)
HMA (Hull Moving Average)
JMA (Jurik Moving Average)
DEMA (Double Exponential Moving Average)
TEMA (Triple Exponential Moving Average)
LSMA (Least Squares Moving Average)
VWMA (Volume-Weighted Moving Average)
SMMA (Smoothed Moving Average)
KAMA (Kaufman’s Adaptive Moving Average)
ALMA (Arnaud Legoux Moving Average)
FRAMA (Fractal Adaptive Moving Average)
VIDYA (Variable Index Dynamic Average)
2️⃣ Custom RSI – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
3️⃣ Custom MACD – Uses the Moving Average function to modify the calculation method, with an additional option for a dynamic version.
4️⃣ Custom Alligator – Uses the Moving Average function to modify generic calculations, allowing users to change the calculation method.
Crypto Fear & Greed Score [Underblock]Crypto Fear & Greed Score - Methodology & Functioning
Introduction
The Crypto Fear & Greed Score is a comprehensive indicator designed to assess market sentiment by detecting extreme conditions of panic (fear) and euphoria (greed). By combining multiple technical factors, it helps traders identify potential buying and selling opportunities based on the emotional state of the market.
This indicator is highly customizable, allowing users to adjust weight parameters for RSI, volatility, Bitcoin dominance, and trading volume, making it adaptable to different market conditions.
Key Components
The indicator consists of two primary sub-scores:
Fear Score (Panic) - Measures the intensity of fear in the market.
Greed Score (Euphoria) - Measures the level of overconfidence and excessive optimism.
The difference between these two values results in the Net Score, which indicates the dominant market sentiment at any given time.
1. Relative Strength Index (RSI)
The indicator utilizes multiple RSI timeframes to measure momentum and overbought/oversold conditions:
RSI 1D (Daily) - Captures medium-term sentiment shifts.
RSI 4H (4-hour) - Identifies short-term market movements.
RSI 1W (Weekly) - Helps detect long-term overbought/oversold conditions.
2. Volatility Analysis
High volatility is often associated with fear and panic-driven selling.
Low volatility in bullish markets may indicate complacency and overconfidence.
3. Bitcoin Dominance (BTC.D)
Bitcoin dominance provides insights into capital flow between Bitcoin and altcoins:
Rising BTC dominance suggests fear as investors move into BTC for safety.
Declining BTC dominance indicates increased risk appetite and potential market euphoria.
4. Buying and Selling Volume
The indicator analyzes both buying and selling volume, ensuring a clearer confirmation of market sentiment.
High buying volume in uptrends reinforces bullish momentum.
Spikes in selling volume indicate panic and possible market bottoms.
Calculation Methodology
The indicator allows users to adjust weight parameters for each component, making it adaptable to different trading strategies. The formulas are structured as follows:
Fear Score (Panic Calculation)
Fear Score = (1 - RSI_1D) * W_RSI1D + (1 - RSI_4H) * W_RSI4H + (1 - Dominance) * W_Dominance + Volatility * W_Volatility + Sell Volume * W_SellVolume
Greed Score (Euphoria Calculation)
Greed Score = RSI_1D * W_RSI1D + RSI_4H * W_RSI4H + Dominance * W_Dominance + (1 - Volatility) * W_Volatility + Buy Volume * W_BuyVolume
Net Fear & Greed Score
Net Score = (Greed Score - Fear Score) * 100
Interpretation:
Above 70: Extreme greed -> possible overbought conditions.
Below -70: Extreme fear -> potential buying opportunity.
Near 0: Neutral market sentiment.
Trend Reversal Detection
The indicator includes two moving averages for enhanced trend detection:
Short-term SMA (50-periods) - Reacts quicklier to changes in sentiment.
Long-term SMA (200-periods) - Captures broader trend reversals.
How Crossovers Work:
Short SMA crossing above Long SMA -> Potential bullish reversal.
Short SMA crossing below Long SMA -> Possible bearish trend shift.
Alerts for SMA crossovers help traders act on momentum shifts in real-time.
Customization and Visualization
The Net Score dynamically changes color: green for greed, red for fear.
Users can adjust weightings directly from settings, avoiding manual script modifications.
Reference levels at 70 and -70 provide clarity on extreme market conditions.
Conclusion
The Crypto Fear & Greed Score provides a powerful and objective measure of market sentiment, helping traders navigate extreme conditions effectively.
🟢 If the Net Score is below -70, panic may present a buying opportunity.
🔴 If the Net Score is above 70, excessive euphoria may indicate a selling opportunity.
⚖️ Neutral values suggest a balanced market sentiment.
By customizing weight parameters and utilizing trend reversal alerts, traders can gain a deeper insight into market psychology and make more informed trading decisions. 🚀
Breakout and Retest Signals [AlgoAlpha]OVERVIEW
This script detects breakout and retest signals by identifying key pivot points in price action and analyzing their relationship with historical swing highs and lows. It highlights breakout structures using ATR-based tolerance levels and volume analysis to confirm potential trend continuations or reversals. The script marks significant price levels with dynamic boxes and dashed lines to help traders visualize breakout and retest areas effectively.
CONCEPTS
The script relies on pivot point analysis, a technique used to identify significant price levels where the market has previously reversed. It dynamically tracks a set number of recent swing highs and lows, allowing traders to see if the price is revisiting a previously significant level. The concept of breakouts and retests is widely used in technical analysis to determine potential entry points. A breakout occurs when the price moves beyond a resistance or support level, and a retest happens when the price returns to test that level before continuing in the breakout direction. This script enhances that analysis by incorporating ATR-based tolerance levels, ensuring that price zones are not too large.
FEATURES
Breakout and Retest Markings : Highlights breakout and retest areas with shaded boxes, allowing traders to visualize where price action is confirming key levels.
Volume Delta and Ratio : Analyzes volume at breakout levels to gauge the strength of the move, displaying volume delta information for additional context. The script also displays the ratio of selling to buying at the retest along traders to make better judgement on their entries.
Multi-Timeframe Adaptability : Dynamically adjusts volume analysis to align with the appropriate lower timeframe, ensuring reliable volume comparisons.
Alerts for Breakout and Retest Events : Traders can receive real-time notifications when bullish or bearish breakout retests are detected.
USAGE
This script is best suited for traders looking to identify strong breakout and retest setups across different timeframes. Users can customize the pivot detection period and swing point memory to adjust sensitivity based on their trading style. The ATR length and multiplier allow further refinement of breakout tolerance, reducing noise in volatile markets. The breakout zones are displayed as shaded boxes, where traders can assess whether a price retest is occurring under favorable conditions. Alerts can be set to notify traders of potential trade opportunities.
Enhanced BarUpDn StrategyEnhanced BarUpDn Strategy
The Enhanced BarUpDn Strategy is a refined price action-based trading approach that identifies market trends and reversals using bar formations. It focuses on detecting bullish and bearish momentum by analyzing consecutive price bars and key support/resistance levels.
Key Features:
✅ Trend Confirmation – Uses a combination of bar patterns and indicators (e.g., moving averages, RSI) to confirm momentum shifts.
✅ Entry Signals – A buy signal is triggered when an "Up Bar" (higher high, higher low) follows a bullish setup; a sell signal when a "Down Bar" (lower high, lower low) confirms bearish momentum.
✅ Enhanced Filters – Incorporates volume analysis and additional conditions to reduce false signals.
✅ Stop-Loss & Risk Management – Uses recent swing highs/lows for stop placement and dynamic trailing stops for maximizing gains.
Anchored Powered KAMA [LuxAlgo]The Anchored Powered KAMA tool is a new flavor of the famous Kaufman's Adaptive Moving Average (KAMA).
It adds 5 different anchoring periods, a power exponent to the original KAMA calculation to increase the degree of filtering during ranging trends, and standard deviation bands calculated against the KAMA itself.
🔶 USAGE
In the image above we can see the different parts of the tool, it displays the Anchored Powered KAMA surrounded by standard deviation bands at 2x (solid) and 1x (dashed) by default.
This tool provides a simple and easy way to determine if the current market is ranging or trending and where the market extremes are in the current period.
As a rule of thumb, traders may want to trade extremes in ranges and pullbacks in trends.
When the KAMA is flat, a range is in place, so traders may want to wait for the price to reach an extreme before opening a trade in the other direction.
Conversely, if the KAMA is moving up or down, a trend is in place and traders may want to wait for the price to pull back to the KAMA before opening a trade in the direction of the trend.
🔹 Anchor Period
On the above chart, we can see different anchor periods on different chart timeframes.
This option is very useful for those traders who use multi-timeframe analysis, allowing them to see how the market behaves over different timeframes.
The valid values for this parameter are:
Hourly
Daily
Weekly
Monthly
Yearly
The tool has a built-in Auto feature for traders convenience, it automatically selects the optimal Anchor Period in function of the chart timeframe.
timeframes up to 2m: Hourly
timeframes up to 15m: Daily
timeframes up to 1H: Weekly
timeframes up to 4H: Monthly
larger timeframes: Yearly
🔹 Choosing the Right Anchor Period
In the chart above we can see the custom error message that the tool displays when the Auto feature is disabled and the Anchor Period is too large for the current chart timeframe.
Traders can select a smaller Anchor Period or a larger chart timeframe for the tool to display correctly.
🔶 DETAILS
The tool uses Welford's algorithm to calculate the KAMA's standard deviation, then plots the outer bands at the multiplier specified in the settings panel, and the inner bands at the multiplier specified minus 1.
🔹 Power Exponent
The graph above shows how different values of this parameter can affect the output.
To display the original KAMA a value of 1 must be set, by default this parameter is set to 2.
The higher the value, the better the tool's ability to detect ranges.
🔶 SETTINGS
Anchor Period: Select up to 5 different time periods from Hourly, Daily, Weekly, Monthly, and Yearly.
Source: Choose the source for all calculations.
Power Exponent: Fine-tune the KAMA calculation, a value of 1 will output the original KAMA, and is set to 2 by default.
Band Multiplier: Select the multiplier for the standard deviation bands.
Impulse MACD enhancedThis indicator is designed to provide robust trade entry signals by combining multiple technical filters. Here’s a summary of its key components:
Impulse MACD Calculation:
Uses a Zero-Lag EMA (ZLEMA) based approach to generate a momentum indicator (with a signal line and histogram) that identifies shifts in market momentum.
Simulated Higher Timeframe (HTF) Trend Filter:
Computes an SMA over a multiplied period to simulate a higher timeframe trend. It requires the price to be in line with this broader trend before signaling an entry.
RSI Filter:
Ensures that for bullish entries the RSI is above a set threshold (indicating momentum) and for bearish entries it’s below a threshold.
ADX Filter:
Uses a manually calculated ADX to confirm that the market is in a strong trend (ADX > 30) to reduce false signals in weakly trending or sideways markets.
Volume Filter:
Compares the current volume to a 20‑bar SMA of volume, requiring volume to be significantly higher (by a user-defined percentage) to confirm the strength of the move.
VWAP Confirmation:
Uses the Volume-Weighted Average Price as an extra layer of confirmation: bullish signals require the price to be above VWAP, bearish signals below.
Optional Long-Term & Short-Term MA Filters:
These filters can be enabled to ensure the price is trading above (or below) longer-term and shorter-term moving averages, further aligning the trade with the prevailing trend.
ATR Volatility Filter:
Checks that volatility (as measured by the ATR relative to price) is below a maximum threshold, which helps avoid taking trades in overly volatile conditions.
Price Action Filter:
Ensures that for a bullish signal the current close is above the highest high over a specified lookback period (and vice versa for bearish), indicating a clear breakout.
Signal Throttling:
Signals are limited to one every 10 bars to prevent excessive trading.
When all these conditions are met, the indicator outputs an entry signal for either a bullish or bearish trade.
This multi-filter approach aims to increase win rate by reducing false signals and aligning trades with strong, confirmed trends while filtering out noise.
Shavarie's MCV IndicatorShavarie's MCV Indicator (MACD + CCI + Volume Delta) is a custom-built trend-following and volume-based indicator that helps traders confirm market direction with high accuracy. It combines the MACD (Moving Average Convergence Divergence), CCI (Commodity Channel Index), and Volume Delta, ensuring that all three indicators align before making a trading decision. The goal is to filter out false signals and provide high-probability trade setups.
History & Development
Shavarie's MCV Indicator was developed by Shavarie Gordon, an experienced swing trader, to improve trend confirmation on Gold (XAUUSD) and other markets. After testing various indicators, Shavarie discovered that MACD, CCI, and Volume Delta together provide the best combination of trend strength, momentum, and real-time volume flow. This indicator was designed to eliminate lagging signals, improve win rates, and enhance market timing for both swing and scalping strategies.
How It Works & Calculations
MACD (Moving Average Convergence Divergence)
Measures momentum and trend strength using the difference between a 12-period EMA and a 26-period EMA.
The MACD line and Signal line crossover confirms buy/sell signals.
A rising MACD histogram confirms bullish strength, while a falling histogram confirms bearish strength.
CCI (Commodity Channel Index)
Measures how far the price is from its statistical average.
Above +100 → Overbought (strong trend continuation or reversal).
Below -100 → Oversold (strong trend continuation or reversal).
When CCI aligns with MACD, it confirms momentum strength.
Volume Delta
Measures the difference between buying and selling volume in real time.
A positive delta means more aggressive buying (bullish).
A negative delta means more aggressive selling (bearish).
Helps confirm MACD and CCI trends by showing real volume strength.
Key Takeaways & Features
✅ No false signals: All three indicators must align before entering a trade.
✅ Trend confirmation: Ensures momentum and volume agree before trading.
✅ Works on multiple timeframes: Designed for swing trading on the daily and scalping on 45 min + 5 min.
✅ Great for Gold & Metals: Optimized for XAUUSD, XAUJPY, XAU/AUD, and possibly Palladium (XPDUSD).
✅ Custom-built by a professional trader: Developed by Shavarie Gordon after extensive testing.
Summary
Shavarie’s MCV Indicator is a powerful and reliable trading tool that combines momentum, trend, and volume analysis. By ensuring that MACD, CCI, and Volume Delta align, it eliminates false signals and increases trade accuracy. Whether used for swing trading or scalping, this indicator helps traders enter high-probability trades with confidence.
Trend Vanguard StrategyHow to Use:
Trend Vanguard Strategy is a multi-feature Pine Script strategy designed to identify market pivots, draw dynamic support/resistance, and generate trade signals via ZigZag breakouts. Here’s how it works and how to use it:
ZigZag Detection & Pivot Points
The script locates significant swing highs and lows using configurable Depth, Deviation, and Backstep values.
It then connects these pivots with lines (ZigZag) to highlight directional changes and prints labels (“Buy,” “Sell,” etc.) at key turning points.
Support & Resistance Trendlines
Pivot highs and lows are used to draw dashed S/R lines in real-time.
When price crosses these lines, the script triggers a breakout signal (long or short).
EMA Overlays
Up to four EMAs (with customizable lengths and colors) can be overlaid on the chart for added trend confirmation.
Enable/disable each EMA independently via the settings.
Repaint Option
Turning on “Smooth Indicator Lines” (repaint) uses future data to refine past pivots.
This can make historical signals look cleaner but does not reflect true historical conditions.
Turning it off ensures signals remain fixed once they appear.
Strategy Entries & Exits
On each new ZigZag “Buy” or “Sell” signal, the script closes any open position and flips to the opposite side (if desired).
Works with the built-in TradingView Strategy engine for backtesting.
Additional Inputs (Placeholders)
Volume Filter and RSI Filter settings exist but are not fully implemented in the current code. Future versions may incorporate these filters more directly.
How to Use
Add to Chart: Click “Indicators” → “Invite-Only Scripts” (or “My Scripts”) and select “Trend Vanguard Strategy.”
Configure Settings:
Adjust ZigZag Depth, Deviation, and Backstep to fine-tune pivot sensitivity.
Enable or disable each EMA to see how it aligns with market trends.
Toggle “Smooth Indicator Lines” on or off depending on whether you want repainting.
Backtest and Forward Test:
Use TradingView’s “Strategy Tester” tab to review hypothetical performance.
Remember that repainting can alter past signals if enabled.
Monitor Live:
Watch for breakout triangles or ZigZag labels to identify potential reversal or breakout trades in real time.
Disclaimer: This script is purely educational and not financial advice. Always combine it with sound risk management and thorough analysis. Enjoy exploring the script, and feel free to experiment with the different settings to match your trading style!
TCTDailyBiasLibraryLibrary "TCTDailyBiasLibrary"
Provides a simple function to return a daily bias based on the break of the morning range
getDailyBias()
Returns the daily bias based on the break of the morning range
Returns: bias
Casa_VolumeProfileSessionLibrary "Casa_VolumeProfileSession"
Analyzes price and volume during regular trading hours to provide a session volume profile,
including Point of Control (POC), Value Area High (VAH), and Value Area Low (VAL).
Calculates and displays these levels historically and for the developing session.
Offers customizable visualization options for the Value Area, POC, histogram, and labels.
Uses lower timeframe data for increased accuracy and supports futures sessions.
The number of rows used for the volume profile can be fixed or dynamically calculated based on the session's price range and the instrument's minimum tick increment, providing optimal resolution.
calculateEffectiveRows(configuredRows, dayHigh, dayLow)
Determines the optimal number of rows for the volume profile, either using the configured value or calculating dynamically based on price range and tick size
Parameters:
configuredRows (int) : User-specified number of rows (0 means auto-calculate)
dayHigh (float) : Highest price of the session
dayLow (float) : Lowest price of the session
Returns: The number of rows to use for the volume profile
debug(vp, position)
Helper function to write some information about the supplied SVP object to the screen in a table.
Parameters:
vp (Object) : The SVP object to debug
position (string) : The position.* to place the table. Defaults to position.bottom_center
getLowerTimeframe()
Depending on the timeframe of the chart, determines a lower timeframe to grab volume data from for the analysis
Returns: The timeframe string to fetch volume for
get(volumeProfile, lowerTimeframeHigh, lowerTimeframeLow, lowerTimeframeVolume, lowerTimeframeTime, lowerTimeframeSessionIsMarket)
Populated the provided SessionVolumeProfile object with vp data on the session.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to populate
lowerTimeframeHigh (array) : The lower timeframe high values
lowerTimeframeLow (array) : The lower timeframe low values
lowerTimeframeVolume (array) : The lower timeframe volume values
lowerTimeframeTime (array) : The lower timeframe time values
lowerTimeframeSessionIsMarket (array) : The lower timeframe session.ismarket values (that are futures-friendly)
drawPriorValueAreas(todaySessionVolumeProfile, extendYesterdayOverToday, showLabels, labelSize, pocColor, pocStyle, pocWidth, vahlColor, vahlStyle, vahlWidth, vaColor)
Given a SessionVolumeProfile Object, will render the historical value areas for that object.
Parameters:
todaySessionVolumeProfile (Object) : The SessionVolumeProfile Object to draw
extendYesterdayOverToday (bool) : Defaults to true
showLabels (bool) : Defaults to true
labelSize (string) : Defaults to size.small
pocColor (color) : Defaults to #e500a4
pocStyle (string) : Defaults to line.style_solid
pocWidth (int) : Defaults to 1
vahlColor (color) : The color of the value area high/low lines. Defaults to #1592e6
vahlStyle (string) : The style of the value area high/low lines. Defaults to line.style_solid
vahlWidth (int) : The width of the value area high/low lines. Defaults to 1
vaColor (color) : The color of the value area background. Defaults to #00bbf911)
drawHistogram(volumeProfile, bgColor, showVolumeOnHistogram)
Given a SessionVolumeProfile object, will render the histogram for that object.
Parameters:
volumeProfile (Object) : The SessionVolumeProfile object to draw
bgColor (color) : The baseline color to use for the histogram. Defaults to #00bbf9
showVolumeOnHistogram (bool) : Show the volume amount on the histogram bars. Defaults to false.
Object
Object Contains all settings and calculated values for a Volume Profile Session analysis
Fields:
numberOfRows (series int) : Number of price levels to divide the range into. If set to 0, auto-calculates based on price range and tick size
valueAreaCoverage (series int) : Percentage of total volume to include in the Value Area (default 70%)
trackDevelopingVa (series bool) : Whether to calculate and display the Value Area as it develops during the session
valueAreaHigh (series float) : Upper boundary of the Value Area - price level containing specified % of volume
pointOfControl (series float) : Price level with the highest volume concentration
valueAreaLow (series float) : Lower boundary of the Value Area
startTime (series int) : Session start time in Unix timestamp format
endTime (series int) : Session end time in Unix timestamp format
dayHigh (series float) : Highest price of the session
dayLow (series float) : Lowest price of the session
step (series float) : Size of each price row (calculated as price range divided by number of rows)
pointOfControlLevel (series int) : Index of the row containing the Point of Control
valueAreaHighLevel (series int) : Index of the row containing the Value Area High
valueAreaLowLevel (series int) : Index of the row containing the Value Area Low
lastTime (series int) : Tracks the most recent timestamp processed
volumeRows (map) : Stores volume data for each price level row (key=row number, value=volume)
ltfSessionHighs (array) : Stores high prices from lower timeframe data
ltfSessionLows (array) : Stores low prices from lower timeframe data
ltfSessionVols (array) : Stores volume data from lower timeframe data
[COG]TMS Crossfire 🔍 TMS Crossfire: Guide to Parameters
📊 Core Parameters
🔸 Stochastic Settings (K, D, Period)
- **What it does**: These control how the first stochastic oscillator works. Think of it as measuring momentum speed.
- **K**: Determines how smooth the main stochastic line is. Lower values (1-3) react quickly, higher values (3-9) are smoother.
- **D**: Controls the smoothness of the signal line. Usually kept equal to or slightly higher than K.
- **Period**: How many candles are used to calculate the stochastic. Standard is 14 days, lower for faster signals.
- **For beginners**: Start with the defaults (K:3, D:3, Period:14) until you understand how they work.
🔸 Second Stochastic (K2, D2, Period2)
- **What it does**: Creates a second, independent stochastic for stronger confirmation.
- **How to use**: Can be set identical to the first one, or with slightly different values for dual confirmation.
- **For beginners**: Start with the same values as the first stochastic, then experiment.
🔸 RSI Length
- **What it does**: Controls the period for the RSI calculation, which measures buying/selling pressure.
- **Lower values** (7-9): More sensitive, good for short-term trading
- **Higher values** (14-21): More stable, better for swing trading
- **For beginners**: The default of 11 is a good balance between speed and reliability.
🔸 Cross Level
- **What it does**: The centerline where crosses generate signals (default is 50).
- **Traditional levels**: Stochastics typically use 20/80, but 50 works well for this combined indicator.
- **For beginners**: Keep at 50 to focus on trend following strategies.
🔸 Source
- **What it does**: Determines which price data is used for calculations.
- **Common options**:
- Close: Most common and reliable
- Open: Less common
- High/Low: Used for specialized indicators
- **For beginners**: Stick with "close" as it's most commonly used and reliable.
🎨 Visual Theme Settings
🔸 Bullish/Bearish Main
- **What it does**: Sets the overall color scheme for bullish (up) and bearish (down) movements.
- **For beginners**: Green for bullish and red for bearish is intuitive, but choose any colors that are easy for you to distinguish.
🔸 Bullish/Bearish Entry
- **What it does**: Colors for the entry signals shown directly on the chart.
- **For beginners**: Use bright, attention-grabbing colors that stand out from your chart background.
🌈 Line Colors
🔸 K1, K2, RSI (Bullish/Bearish)
- **What it does**: Controls the colors of each indicator line based on market direction.
- **For beginners**: Use different colors for each line so you can quickly identify which line is which.
⏱️ HTF (Higher Timeframe) Settings
🔸 HTF Timeframe
- **What it does**: Sets which higher timeframe to use for filtering (e.g., 240 = 4 hour chart).
- **How to choose**: Should be at least 4x your current chart timeframe (e.g., if trading on 15min, use 60min or higher).
- **For beginners**: Start with a timeframe 4x higher than your trading chart.
🔸 Use HTF Filter
- **What it does**: Toggles whether the higher timeframe filter is applied or not.
- **For beginners**: Keep enabled to reduce false signals, especially when learning.
🔸 HTF Confirmation Bars
- **What it does**: How many bars must confirm a trend change on higher timeframe.
- **Higher values**: More reliable but slower to react
- **Lower values**: Faster signals but more false positives
- **For beginners**: Start with 2-3 bars for a good balance.
📈 EMA Settings
🔸 Use EMA Filter
- **What it does**: Toggles price filtering with an Exponential Moving Average.
- **For beginners**: Keep enabled for better trend confirmation.
🔸 EMA Period
- **What it does**: Length of the EMA for filtering (shorter = faster reactions).
- **Common values**:
- 5-13: Short-term trends
- 21-50: Medium-term trends
- 100-200: Long-term trends
- **For beginners**: 5-10 is good for short-term trading, 21 for swing trading.
🔸 EMA Offset
- **What it does**: Shifts the EMA forward or backward on the chart.
- **For beginners**: Start with 0 and adjust only if needed for visual clarity.
🔸 Show EMA on Chart
- **What it does**: Toggles whether the EMA appears on your main price chart.
- **For beginners**: Keep enabled to see how price relates to the EMA.
🔸 EMA Color, Style, Width, Transparency
- **What it does**: Customizes how the EMA line looks on your chart.
- **For beginners**: Choose settings that make the EMA visible but not distracting.
🌊 Trend Filter Settings
🔸 Use EMA Trend Filter
- **What it does**: Enables a multi-EMA system that defines the overall market trend.
- **For beginners**: Keep enabled for stronger trend confirmation.
🔸 Show Trend EMAs
- **What it does**: Toggles visibility of the trend EMAs on your chart.
- **For beginners**: Enable to see how price moves relative to multiple EMAs.
🔸 EMA Line Thickness
- **What it does**: Controls how the thickness of EMA lines is determined.
- **Options**:
- Uniform: All EMAs have the same thickness
- Variable: Each EMA has its own custom thickness
- Hierarchical: Automatically sized based on period (longer periods = thicker)
- **For beginners**: "Hierarchical" is most intuitive as longer-term EMAs appear more dominant.
🔸 EMA Line Style
- **What it does**: Sets the line style (solid, dotted, dashed) for all EMAs.
- **For beginners**: "Solid" is usually clearest unless you have many lines overlapping.
🎭 Trend Filter Colors/Width
🔸 EMA Colors (8, 21, 34, 55)
- **What it does**: Sets the color for each individual trend EMA.
- **For beginners**: Use a logical progression (e.g., shorter EMAs brighter, longer EMAs darker).
🔸 EMA Width Settings
- **What it does**: Controls the thickness of each EMA line.
- **For beginners**: Thicker lines for longer EMAs make them easier to distinguish.
🔔 How These Parameters Work Together
The power of this indicator comes from how these components interact:
1. **Base Oscillator**: The stochastic and RSI components create the main oscillator
2. **HTF Filter**: The higher timeframe filter prevents trading against larger trends
3. **EMA Filter**: The EMA filter confirms signals with price action
4. **Trend System**: The multi-EMA system identifies the overall market environment
Think of it as multiple layers of confirmation, each adding more reliability to your trading signals.
💡 Tips for Beginners
1. **Start with defaults**: Use the default settings first and understand what each element does
2. **One change at a time**: When customizing, change only one parameter at a time
3. **Keep notes**: Write down how each change affects your results
4. **Backtest thoroughly**: Test any changes on historical data before trading real money
5. **Less is more**: Sometimes simpler settings work better than complicated ones
Remember, no indicator is perfect - always combine this with proper risk management and other forms of analysis!
3cfThis indicator identifies and signals the points of swing highs and swing lows on the price chart using an algorithm based on market structure. Local highs and lows are highlighted with a colored dot, making it easier to perform technical analysis and recognize trend reversals.
The indicator analyzes a predefined number of bars (e.g., 5 candles) to determine relative highs and lows:
Swing High (Local High) → The current candle has a higher high compared to the previous and subsequent candle.
Swing Low (Local Low) → The current candle has a lower low compared to the previous and subsequent candle.
When a candle meets one of these conditions, a visual dot is placed to indicate the potential reversal point.
Casa_SessionsLibrary "Casa_Sessions"
Advanced trading session management library that enhances TradingView's default functionality:
Key Features:
- Accurate session detection for futures markets
- Custom session hour definitions
- Drop-in replacements for standard TradingView session functions
- Flexible session map customization
- Full control over trading windows and market hours
Perfect for traders who need precise session timing, especially when working
with futures markets or custom trading schedules.
SetSessionTimes(session_type_input, custom_session_times_input, syminfo_type, syminfo_root, syminfo_timezone)
Parameters:
session_type_input (simple string) : Input string for session selection:
- 'Custom': User-defined session times
- 'FX-Tokyo': Tokyo forex session
- 'FX-London': London forex session
- 'FX-New York': NY forex session
- 'Overnight Session (ON)': After-hours trading
- 'Day Session (RTH)': Regular trading hours
custom_session_times_input (simple string) : Session parameter for custom time windows
Only used when session_type_input is 'Custom'
syminfo_type (simple string)
syminfo_root (simple string)
syminfo_timezone (simple string)
Returns:
session_times: Trading hours for selected session
session_timezone: Market timezone (relevant for forex)
getSessionMap()
Get futures trading session hours map
Keys are formatted as 'symbol:session', examples:
- 'ES:market' - Regular trading hours (RTH)
- 'ES:overnight' - Extended trading hours (ETH)
- 'NQ:market' - NASDAQ futures RTH
- 'CL:overnight' - Crude Oil futures ETH
Returns: Map
Key: Symbol:session identifier
Value: Session hours in format "HH:MM-HH:MM"
getSessionString(session, symbol, sessionMap)
Returns a session string representing the session hours (and days) for the requested symbol (or the chart's symbol if the symbol value is not provided). If the session string is not found in the collection, it will return a blank string.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
symbol (string) : The symbol to check. Optional. Defaults to chart symbol.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
inSession(session, sessionMap, barsBack)
Returns true if the current symbol is currently in the session parameters defined by sessionString.
Parameters:
session (string) : A string representing the session hour being requested. One of: market (regular trading hours), overnight (extended/electronic trading hours), postmarket (after-hours), premarket
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
barsBack (int) : Private. Only used by futures to check islastbar. Optional. The default is 0.
ismarket(sessionMap)
Returns true if the current bar is a part of the regular trading hours (i.e. market hours), false otherwise. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar()
Returns true if the current bar is the first bar of the day's session, false otherwise. If extended session information is used, only returns true on the first bar of the pre-market bars. Works for futures (TradingView's methods do not).
Returns: bool
islastbar()
Returns true if the current bar is the last bar of the day's session, false otherwise. If extended session information is used, only returns true on the last bar of the post-market bars. Works for futures (TradingView's methods do not).
Returns: bool
ispremarket(sessionMap)
Returns true if the current bar is a part of the pre-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
ispostmarket(sessionMap)
Returns true if the current bar is a part of the post-market, false otherwise. On non-intraday charts always returns false. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isfirstbar_regular(sessionMap)
Returns true on the first regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
islastbar_regular(sessionMap)
Returns true on the last regular session bar of the day, false otherwise. The result is the same whether extended session information is used or not. Works for futures (TradingView's methods do not).
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
isovernight(sessionMap)
Returns true if the current bar is a part of the pre-market or post-market, false otherwise. On non-intraday charts always returns false.
Parameters:
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: bool
getSessionHighAndLow(session, sessionMap)
Returns a tuple containing the high and low print during the specified session.
Parameters:
session (string) : The session for which to get the high & low prints. Defaults to market.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: A tuple containing
getSessionHigh(session, sessionMap)
Convenience function to return the session high. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
Parameters:
session (string) : The session for which to get the high & low prints. Defaults to market.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: The high of the session
getSessionLow(session, sessionMap)
Convenience function to return the session low. Necessary if you want to call this function from within a request.security expression where you can't return a tuple.
Parameters:
session (string) : The session for which to get the high & low prints. Defaults to market.
sessionMap (map) : The map of futures session hours. Optional. Uses default if not provided.
Returns: The low of the session
Casa_TableLibrary "Casa_Table"
A powerful library for creating customizable tables from data arrays and matrices.
Features flexible formatting options including:
- Multiple function implementations for different levels of control
- Consistent column counts required across matrix rows
- Matching dimensions needed for color arrays/matrices
- Cell spanning capabilities across rows/columns
- Rich examples demonstrating proper data structure setup
The library makes it easy to transform your data into professional-looking
tables while maintaining full control over their visual appearance.
floatArrayToCellArray(floatArray)
Helper function that converts a float array to a Cell array so it can be rendered with the fromArray function
Parameters:
floatArray (array) : (array) the float array to convert to a Cell array.
Returns: array The Cell array to return.
stringArrayToCellArray(stringArray)
Helper function that converts a string array to a Cell array so it can be rendered with the fromArray function
Parameters:
stringArray (array) : (array) the array to convert to a Cell array.
Returns: array The Cell array to return.
floatMatrixToCellMatrix(floatMatrix)
Helper function that converts a float matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
floatMatrix (matrix) : (matrix) the float matrix to convert to a string matrix.
Returns: matrix The Cell matrix to render.
stringMatrixToCellMatrix(stringMatrix)
Helper function that converts a string matrix to a Cell matrix so it can be rendered with the fromMatrix function
Parameters:
stringMatrix (matrix) : (matrix) the string matrix to convert to a Cell matrix.
Returns: matrix The Cell matrix to return.
fromMatrix(CellMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Takes a CellMatrix and renders it as a table.
Parameters:
CellMatrix (matrix) : (matrix) The Cells to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a float matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromMatrix(dataMatrix, position, verticalOffset, transposeTable, textSize, borderWidth, tableNumRows, blankCellText)
Renders a string matrix as a table.
Parameters:
dataMatrix (matrix) : (matrix_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
tableNumRows (int) : (int) Optional. The number of rows in the table. Not required, defaults to the number of rows in the provided matrix. If your matrix will have a variable number of rows, you must provide the max number of rows or the function will error when it attempts to set a cell value on a row that the table hadn't accounted for when it was defined.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a Cell array as a table.
Parameters:
dataArray (array) : (array) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a string array as a table.
Parameters:
dataArray (array) : (array_string) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
fromArray(dataArray, position, verticalOffset, transposeTable, textSize, borderWidth, blankCellText)
Renders a float array as a table.
Parameters:
dataArray (array) : (array_float) The data to be rendered in a table
position (string) : (string) Optional. The position of the table. Defaults to position.top_right
verticalOffset (int) : (int) Optional. The vertical offset of the table from the top or bottom of the chart. Defaults to 0.
transposeTable (bool) : (bool) Optional. Will transpose all of the data in the matrices before rendering. Defaults to false.
textSize (string) : (string) Optional. The size of text to render in the table. Defaults to size.small.
borderWidth (int) : (int) Optional. The width of the border between table cells. Defaults to 2.
blankCellText (string) : (string) Optional. Text to use cells when adding blank rows for vertical offsetting.
debug(message, position)
Renders a debug message in a table at the desired location on screen.
Parameters:
message (string) : (string) The message to render.
position (string) : (string) Optional. The position of the debug message. Defaults to position.middle_right.
Cell
Type for each cell's content and appearance
Fields:
content (series string)
bgColor (series color)
textColor (series color)
align (series string)
colspan (series int)
rowspan (series int)
Casa_UtilsLibrary "Casa_Utils"
A collection of convenience and helper functions for indicator and library authors on TradingView
formatNumber(num)
My version of format number that doesn't have so many decimal places...
Parameters:
num (float) : The number to be formatted
Returns: The formatted number
getDateString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getDateTimeString(timestamp)
Convenience function returns timestamp in yyyy/MM/dd hh:mm format.
Parameters:
timestamp (int) : The timestamp to stringify
Returns: The date string
getInsideBarCount()
Gets the number of inside bars for the current chart. Can also be passed to request.security to get the same for different timeframes.
Returns: The # of inside bars on the chart right now.
getLabelStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the label styles into a dropdown for configuration settings. So, I specify them in the following format: "Center", "Left", "Lower Left", "Lower Right", "Right", "Up", "Upper Left", "Upper Right", "Plain Text", "No Labels". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string)
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getTime(hourNumber, minuteNumber)
Given an hour number and minute number, adds them together and returns the sum. To be used by getLevelBetweenTimes when fetching specific price levels during a time window on the day.
Parameters:
hourNumber (int) : The hour number
minuteNumber (int) : The minute number
Returns: The sum of all the minutes
getHighAndLowBetweenTimes(start, end)
Given a start and end time, returns the high or low price during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The high or low value
getPremarketHighsAndLows()
Returns an expression that can be used by request.security to fetch the premarket high & low levels in a tuple.
Returns: (tuple)
getAfterHoursHighsAndLows()
Returns an expression that can be used by request.security to fetch the after hours high & low levels in a tuple.
Returns: (tuple)
getOvernightHighsAndLows()
Returns an expression that can be used by request.security to fetch the overnight high & low levels in a tuple.
Returns: (tuple)
getNonRthHighsAndLows()
Returns an expression that can be used by request.security to fetch the high & low levels for premarket, after hours and overnight in a tuple.
Returns: (tuple)
getLineStyleFromString(styleString, acceptGivenIfNoMatch)
Tradingview doesn't give you a nice way to put the line styles into a dropdown for configuration settings. So, I specify them in the following format: "Solid", "Dashed", "Dotted", "None/Hidden". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
styleString (string) : Plain english (or TV Standard) version of the style string
acceptGivenIfNoMatch (bool) : If no match for styleString is found and this is true, the function will return styleString, otherwise it will return tradingview's preferred default
Returns: The string expected by tradingview functions
getPercentFromPrice(price)
Get the % the current price is away from the given price.
Parameters:
price (float)
Returns: The % the current price is away from the given price.
getPositionFromString(position)
Tradingview doesn't give you a nice way to put the positions into a dropdown for configuration settings. So, I specify them in the following format: "Top Left", "Top Center", "Top Right", "Middle Left", "Middle Center", "Middle Right", "Bottom Left", "Bottom Center", "Bottom Right". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
position (string) : Plain english position string
Returns: The string expected by tradingview functions
getRsiAvgsExpression(rsiLength)
Call request.security with this as the expression to get the average up/down values that can be used with getRsiPrice (below) to calculate the price level where the supplied RSI level would be reached.
Parameters:
rsiLength (simple int) : The length of the RSI requested.
Returns: A tuple containing the avgUp and avgDown values required by the getRsiPrice function.
getRsiPrice(rsiLevel, rsiLength, avgUp, avgDown)
use the values returned by getRsiAvgsExpression() to calculate the price level when the provided RSI level would be reached.
Parameters:
rsiLevel (float) : The RSI level to find price at.
rsiLength (int) : The length of the RSI to calculate.
avgUp (float) : The average move up of RSI.
avgDown (float) : The average move down of RSI.
Returns: The price level where the provided RSI level would be met.
getSizeFromString(sizeString)
Tradingview doesn't give you a nice way to put the sizes into a dropdown for configuration settings. So, I specify them in the following format: "Auto", "Huge", "Large", "Normal", "Small", "Tiny". This function takes care of converting those custom strings back to the ones expected by tradingview scripts.
Parameters:
sizeString (string) : Plain english size string
Returns: The string expected by tradingview functions
getTimeframeOfChart()
Get the timeframe of the current chart for display
Returns: The string of the current chart timeframe
getTimeNowPlusOffset(candleOffset)
Helper function for drawings that use xloc.bar_time to help you know the time offset if you want to place the end of the drawing out into the future. This determines the time-size of one candle and then returns a time n candleOffsets into the future.
Parameters:
candleOffset (int) : The number of items to find singular/plural for.
Returns: The future time
getVolumeBetweenTimes(start, end)
Given a start and end time, returns the sum of all volume across bars during that time window.
Parameters:
start (int) : The timestamp to start with (# of seconds)
end (int) : The timestamp to end with (# of seconds)
Returns: The volume
isToday()
Returns true if the current bar occurs on today's date.
Returns: True if current bar is today
padLabelString(labelText, labelStyle)
Pads a label string so that it appears properly in or not in a label. When label.style_none is used, this will make sure it is left-aligned instead of center-aligned. When any other type is used, it adds a single space to the right so there is padding against the right end of the label.
Parameters:
labelText (string) : The string to be padded
labelStyle (string) : The style of the label being padded for.
Returns: The padded string
plural(num, singular, plural)
Helps format a string for plural/singular. By default, if you only provide num, it will just return "s" for plural and nothing for singular (eg. plural(numberOfCats)). But you can optionally specify the full singular/plural words for more complicated nomenclature (eg. plural(numberOfBenches, 'bench', 'benches'))
Parameters:
num (int) : The number of items to find singular/plural for.
singular (string) : The string to return if num is singular. Defaults to an empty string.
plural (string) : The string to return if num is plural. Defaults to 's' so you can just add 's' to the end of a word.
Returns: The singular or plural provided strings depending on the num provided.
timeframeInSeconds(timeframe)
Get the # of seconds in a given timeframe. Tradingview's timeframe.in_seconds() expects a simple string, and we often need to use series string, so this is an alternative to get you the value you need.
Parameters:
timeframe (string)
Returns: The number of secondsof that timeframe
timeframeOfChart()
Convert a timeframe string to a consistent standard.
Returns: The standard format for the string, or the unchanged value if it is unknown.
timeframeToString(timeframe)
Convert a timeframe string to a consistent standard.
Parameters:
timeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
stringToTimeframe(strTimeframe)
Convert an english-friendly timeframe string to a value that can be used by request.security. Specifically, this corrects hour strings (eg. 4h) to their numeric "minute" equivalent (eg. 240)
Parameters:
strTimeframe (string)
Returns: (string) The standard format for the string, or the unchanged value if it is unknown.
getPriceLabel(price, labelOffset, labelStyle, labelSize, labelColor, textColor)
Defines a label for the end of a price level line.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelStyle (string) : A plain english string as defined in getLabelStyleFromString.
labelSize (string) : The size of the label.
labelColor (color) : The color of the label.
textColor (color) : The color of the label text (defaults to #ffffff)
Returns: The label that was created.
setPriceLabel(label, labelName, price, labelOffset, labelTemplate, labelStyle, labelColor, textColor)
Updates the label position & text based on price changes.
Parameters:
label (label) : The label to update.
labelName (string) : The name of the price level to be placed on the label.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelTemplate (string) : The str.format template to use for the label. Defaults to: '{0}: {1} {2}{3,number,#.##}%' which means '{price}: {labelName} {+/-}{percentFromPrice}%'
labelStyle (string)
labelColor (color)
textColor (color)
getPriceLabelLine(price, labelOffset, labelColor, lineWidth)
Defines a line that will stretch from the plot line to the label.
Parameters:
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
labelColor (color)
lineWidth (int) : The width of the line. Defaults to 1.
setPriceLabelLine(line, price, labelOffset, lastTime, lineColor)
Updates the price label line based on price changes.
Parameters:
line (line) : The line to update.
price (float) : The price level to render the label at.
labelOffset (int) : The number of candles to place the label to the right of price.
lastTime (int) : The last time that the line should stretch from. Defaults to time.
lineColor (color)
IBS (Internal Bar Strength) Trading Strategy for SPY and NDQImplementation by AlgoTradeKit
Overview
The IBS Trading Strategy is a daily bars long-only trading system, based on the concept of Internal Bar Strength (IBS). The strategy aims to identify potential reversals by monitoring how the previous bar’s close positions itself within its high-low range. It is suitable for stock and US indices. The default parameters are optimized for SPY/SPX and NDQ/QQQ
Strategy Concept
The Internal Bar Strength (IBS) is calculated using the formula:
IBS = (Previous Close - Previous Low) / (Previous High - Previous Low)
This value always lies between 0 and 1. An IBS value below 0.2 is typically interpreted as an oversold condition, while a value above 0.9 suggests an overbought state.
Trading Rules
- Long Entry :
- Condition 1 : IBS is below the user-defined entry threshold (default is 0.2).
- Condition 2 : The current price is above an N-period Exponential Moving Average (EMA) (default period is 252).
- Note : You can disable the EMA condition by setting the EMA period to 0.
- Long Exit
- The position is closed when IBS rises above the user-defined exit threshold (default is 0.9).
Customization Options
- IBS Entry Threshold : Adjust to set the sensitivity for entering a long trade based on oversold conditions.
- IBS Exit Threshold : Customize to define the exit point when the market becomes overbought.
- EMA Period : Set the lookback period for the EMA to align with your trend bias; disable this condition by setting the period to 0.
Risk Management & Trading Considerations
- Designed for daily charts, the strategy captures higher timeframe trends and minimizes noise.
- The entry and exit conditions are straightforward, aiming to avoid over-trading while letting clear signals dictate trade management.
- Always use proper risk management techniques and test the strategy thoroughly on historical data and in a simulated environment before applying it in live markets.
Disclaimer
This strategy is for educational and informational purposes only and does not constitute financial advice. Trading involves risk, and past performance is not indicative of future results. Always conduct your own research and consider your risk tolerance before making any trades.
Wave Modulation Demo█ OVERVIEW
This script demonstrates Stacked Wave Modulation by visualizing four interconnected waves. Wave 1 is the base wave, influencing Wave 2's frequency, which in turn modulates Wave 3's amplitude, and finally, Wave 3 modulates Wave 4's phase. Explore the fascinating effects of wave modulation by adjusting the inputs for each wave and their modulation scales.
══════════════════════════════════════════════════
█ CONCEPTS
This script visualizes a cascade of wave modulations:
1 — Base Wave (Wave 1): This is the foundational wave. Its parameters (type, frequency, amplitude, phase, vertical shift) are directly controlled and serve as the basis for subsequent modulations.
2 — Frequency Modulation (Wave 2): Wave 2's frequency is modulated by Wave 1 . As Wave 1 oscillates, it dynamically changes the frequency of Wave 2 , creating interesting frequency variations. The Frequency Mod Scale input controls the intensity of this modulation.
3 — Amplitude Modulation (Wave 3): Building upon the cascade, Wave 3 's amplitude is modulated by Wave 2 . The peaks and troughs of Wave 2 influence the amplitude of Wave 3 , resulting in amplitude variations. The Amplitude Mod Scale input adjusts the strength of this amplitude modulation.
4 — Phase Modulation (Wave 4): Finally, Wave 4 's phase is modulated by Wave 3 . Wave 3 's oscillations shift the phase of Wave 4 , leading to phase-related distortions and dynamic wave patterns. The Phase Mod Scale input determines the extent of phase modulation.
5 — Stacked Wave (Average): The script calculates and plots the average of all four waves, providing a composite view of the combined modulation effects.
══════════════════════════════════════════════════
█ FEATURES
The script is organized into input groups for each wave, allowing for detailed customization:
1 — Wave 1: Base Wave
• Type : Select the waveform type for Wave 1 (Sine, Cosine, Triangle, Square).
• Frequency (Hz) : Sets the base frequency of Wave 1 in Hertz (cycles per second).
• Amplitude : Controls the vertical amplitude or height of Wave 1.
• Phase Shift (deg) : Adjusts the phase shift of Wave 1 in degrees, shifting the wave horizontally.
• Vertical Shift : Sets the vertical position of Wave 1 on the chart.
2 — Wave 2: Frequency Modulation
• Type : Select the waveform type for Wave 2.
• Base Frequency (Hz) : Sets the base frequency of Wave 2, before modulation.
• Amplitude : Controls the amplitude of Wave 2.
• Phase Shift (deg) : Adjusts the phase shift of Wave 2.
• Vertical Shift : Sets the vertical position of Wave 2.
• Frequency Mod Scale : Determines the degree to which Wave 1 modulates Wave 2's frequency. Higher values increase the modulation effect.
3 — Wave 3: Amplitude Modulation
• Type : Select the waveform type for Wave 3.
• Base Frequency (Hz) : Sets the base frequency of Wave 3.
• Amplitude : Controls the base amplitude of Wave 3, before modulation.
• Phase Shift (deg) : Adjusts the phase shift of Wave 3.
• Vertical Shift : Sets the vertical position of Wave 3.
• Amplitude Mod Scale : Determines the degree to which Wave 2 modulates Wave 3's amplitude. Higher values increase the modulation effect.
4 — Wave 4: Phase Modulation
• Type : Select the waveform type for Wave 4.
• Base Frequency (Hz) : Sets the base frequency of Wave 4.
• Amplitude : Controls the amplitude of Wave 4.
• Phase Shift (deg) : Sets the base phase shift of Wave 4, before modulation.
• Vertical Shift : Sets the vertical position of Wave 4.
• Phase Mod Scale : Determines the degree to which Wave 3 modulates Wave 4's phase. Higher values increase the modulation effect.
══════════════════════════════════════════════════
█ HOW TO USE
1. Add the "Stacked Wave Modulation Demo" script to your TradingView chart.
2. Explore the input settings. Each wave has its own group of customizable parameters.
3. Adjust the Type , Frequency , Amplitude , Phase Shift , and Vertical Shift for each wave to define their base characteristics.
4. Experiment with the modulation scales ( Frequency Mod Scale , Amplitude Mod Scale , Phase Mod Scale ) to control the intensity of the modulation effects between the waves.
5. Observe how the waves interact and how the modulations shape their forms and the final stacked wave (average).
══════════════════════════════════════════════════
█ NOTES
* This script utilizes the `waves` and `hsvColor` libraries. Look for other scripts on my profile.
* The frequencies are set in Hertz (cycles per second), which relate to bars on the chart. A frequency of 0.5 Hz means 0.5 cycles per bar, or 1 cycle every 2 bars.
* Adjusting the modulation scales allows you to fine-tune the visual impact of the modulation effects.
* The color of each wave plot is dynamically generated based on its value using the HSV color model for visual distinction.
* Feel free to modify and experiment with the script to create different modulation schemes or stacking methods.
Let me know if you have any other questions or would like further refinements!
Nirmal Fair Value GapsICT Fair Value Gaps
Trade Wisely
How a Fair Value Gap Works
Formation:
A Fair Value Gap occurs when a strong price movement (usually from institutional orders) creates an imbalance between buyers and sellers.
This is typically seen in a three-candle pattern, where the middle candle has a large body, and the two surrounding candles have wicks but little overlap with the middle candle’s range.
Identification:
The FVG is marked between the high of the first candle and the low of the third candle (for bullish gaps).
For bearish gaps, it’s the low of the first candle and the high of the third candle.
Market Behavior Around FVG:
Price often retraces into the gap before resuming its original direction.
This happens because the market seeks to "fill" the imbalance where few trades occurred.
Traders use FVGs as potential entry zones for trend continuation trades.
Trading Fair Value Gaps
In an Uptrend:
Look for bullish fair value gaps as potential support zones for buy entries.
Price may dip into the gap and then continue upward.
In a Downtrend:
Look for bearish fair value gaps as potential resistance zones for sell entries.
Price may retrace into the gap and then drop further.
Confluence Factors:
FVGs work best when combined with other strategies like order blocks, liquidity zones, or key Fibonacci levels.
Kulahli - KLSIDynamic Price Levels & Trend Tracker
Description
This indicator focuses on identifying dynamically changing price levels and determining the trend direction.
Key Features:
Dynamic Level Calculation: Price levels are continuously recalculated in a way that is sensitive to market conditions.
Trend Indicator: Based on how long the price stays above or below a certain level, the indicator shows the trend direction (uptrend or downtrend).
Color Coding: Price levels and trend direction are coded with different colors for easy visual identification.
Customizable Sensitivity: Offers sensitivity settings to adjust how quickly the indicator reacts to price changes.
Alert Options: Can be configured to receive alerts when the price crosses a specific level or when the trend direction changes.
How to Use:
Disclaimer:
This indicator is for educational and informational purposes only and should not be considered financial advice.
Past performance is not indicative of future results.1
Use at your own risk.
Feel free to adjust this draft according to the specific features and functions of your indicator.