TLA20 - Multi-Session Box and Level ToolTLA20 is a highly customizable indicator designed to enhance intraday analysis by marking predefined trading sessions, key levels, and midpoints directly on your charts. With its versatile features, TLA20 is ideal for traders looking to visualize multiple time zones, daily price ranges, and historical reference levels efficiently.
Key Features:
Session Visualization: Mark up to three custom trading sessions with distinct start and end times, adjustable for different time zones and weekend inclusions.
Dynamic Highlights: Automatically draw session highs, lows, midlines, and open prices with options to extend beyond session bounds.
Custom Styling: Configure border colors, styles, and fill options for each session box to match your chart preferences.
Historical Levels: Highlight previous daily highs/lows, weekly highs/lows, and monthly highs/lows for improved context in your trading.
Intuitive Adjustments: Enable or disable each feature and customize settings for precise alignment with your trading strategy.
Use Cases:
Track trading sessions across different markets and time zones.
Identify key price levels like session midpoints and opens for entry/exit strategies.
Overlay historical levels to recognize potential support and resistance areas.
This indicator does not provide direct trading signals but serves as a robust tool for enhancing technical analysis.
Disclaimer: The script is provided “as is” without warranties of any kind. Always test on a demo account before applying in live markets.
Educational
Average Price Range Screener [KFB Quant]Average Price Range Screener
Overview:
The Average Price Range Screener is a technical analysis tool designed to provide insights into the average price volatility across multiple symbols over user-defined time periods. The indicator compares price ranges from different assets and displays them in a visual table and chart for easy reference. This can be especially helpful for traders looking to identify symbols with high or low volatility across various time frames.
Key Features:
Multiple Symbols Supported:
The script allows for analysis of up to 10 symbols, such as major cryptocurrencies and market indices. Symbols can be selected by the user and configured for tracking price volatility.
Dynamic Range Calculation:
The script calculates the average price range of each symbol over three distinct time periods (default are 30, 60, and 90 bars). The price range for each symbol is calculated as a percentage of the bar's high-to-low difference relative to its low value.
Range Visualization:
The results are visually represented using:
- A color-coded table showing the calculated average ranges of each symbol and the current chart symbol.
- A line plot that visually tracks the volatility for each symbol on the chart, with color gradients representing the range intensity from low (red/orange) to high (blue/green).
Customizable Inputs:
- Length Inputs: Users can define the time lengths (default are 30, 60, and 90 bars) for calculating average price ranges for each symbol.
- Symbol Inputs: 10 symbols can be tracked at once, with default values set to popular crypto pairs and indices.
- Color Inputs: Users can customize the color scheme for the range values displayed in the table and chart.
Real-Time Ranking:
The indicator ranks symbols by their average price range, providing a clear view of which assets are exhibiting higher volatility at any given time.
Each symbol's range value is color-coded based on its relative volatility within the selected symbols (using a gradient from low to high range).
Data Table:
The table shows the average range values for each symbol in real-time, allowing users to compare volatility across multiple assets at a glance. The table is dynamically updated as new data comes in.
Interactive Labels:
The indicator adds labels to the chart, showing the average range for each symbol. These labels adjust in real-time as the price range values change, giving users an immediate view of volatility rankings.
How to Use:
Set Time Periods: Adjust the time periods (lengths) to match your trading strategy's timeframe and volatility preference.
Symbol Selection: Add and track the price range for your preferred symbols (cryptocurrencies, stocks, indices).
Monitor Volatility: Use the visual table and plot to identify symbols with higher or lower volatility, and adjust your trading strategy accordingly.
Interpret the Table and Chart: Ranges that are color-coded from red/orange (lower volatility) to blue/green (higher volatility) allow you to quickly gauge which symbols are most volatile.
Disclaimer: This tool is provided for informational and educational purposes only and should not be considered as financial advice. Always conduct your own research and consult with a licensed financial advisor before making any investment decisions.
DCA Valuation & Unrealized GainsThis Pine Script for TradingView calculates and visualizes the relationship between a Dollar Cost Average (DCA) price and the All-Time High (ATH) price for over 50 different cryptocurrencies. Here's what it does:
1. Inputs for DCA Prices:
- Users can manually input DCA prices for specific cryptocurrencies (e.g., BTC, ETH, BNB).
2. Dynamic ATH Calculation:
- Dynamically calculates the ATH price for the current asset using the highest price in the chart's loaded data and persists this value across bars.
3. Percentage Change from DCA to ATH:
- Computes the percentage gain from the DCA price to the ATH price.
4. Visualizations:
- Draws a line at the DCA price and the ATH price, both extended to the right.
- Adds an arrow pointing from the DCA price to the ATH, offset by 10 bars into the future.
- Displays labels for:
- The percentage gain from DCA to ATH.
- "No DCA Configured" if no valid DCA price is set for the asset.
5. Color Coding:
- Labels and arrows are color-coded to indicate positive or negative percentage changes:
- Green for gains.
- Red for losses.
6. Adaptability:
- The script dynamically adjusts to the current asset based on its ticker and uses the corresponding DCA price.
This functionality provides traders with clear insights into their investment's performance relative to its ATH, aiding in decision-making.
-----
To add a new asset to the script:
1. Define the DCA Input: Add a new input for the asset's DCA price using the `input.float` function. For example:
dcaPriceNEW = input.float(title="NEW DCA Price", defval=0.1, tooltip="Set the DCA price for NEW")
2. Add the Asset Logic: Include a conditional check for the new asset in the ticker matching logic:
if str.contains(currentAsset, "NEW") and dcaPriceNEW != 0
dcaPrice := dcaPriceNEW
Where NEW is the ticker symbol of the asset you're adding.
NOTE: SOLO had to be put before SOL because otherwise the indicator was pulling the DCA price from SOL even on the SOLO chart. If you have a similar issue, try that fix.
Adding an asset requires only these two changes. Once done, the script dynamically incorporates the new asset into its calculations and visualizations.
IU VaR (Value at Risk) Historical MethodThis Pine Script indicator calculates the **Value at Risk (VaR)** using the **Historical Method** to help traders understand potential losses during a given period( Chart Timeframe) with a specific level of confidence.
What is Value at Risk (VaR) ?
Value at Risk (VaR) is a measure used in finance to estimate the potential loss in value of an asset, portfolio, or investment over a specific time period, given normal market conditions, and at a certain confidence level.
Example:
Suppose you invest ₹1,00,000 in stocks. A VaR of 5% at a 95% confidence level means:
- There is a **95% chance** that you won’t lose more than **₹5,000** in a day.
- Conversely, there is a **5% chance** that your loss could exceed ₹5,000 in a day.
VaR is a helpful tool for understanding risk and making informed investment decisions!
How It Works:
1. The indicator calculates the percentage difference between consecutive bars.
2. The differences are sorted, and the VaR is determined based on the assurance level you specify.
3. A label displays the VaR value on the chart, indicating the potential maximum loss with the selected assurance level within one period eg - ( 1h, 4h , 1D, 1W, 1M etc as per your chart timeframe )
Key Features:
- Customizable Assurance Level:
Set the confidence level (e.g., 95%) to determine the probability of loss.
-Historical Approach:
Uses the past percentage changes in price to calculate the risk.
-Clear Insights:
Displays the calculated VaR value on the chart with an informative tooltip explaining the risk.
Use this tool to better understand your market exposure and manage risk!
Volume Weighted TWAP (VW-TWAP)The Volume Weighted Time Weighted Average Price (VW-TWAP) is an indicator that combines the principles of price averaging with volume sensitivity. Unlike the traditional TWAP, which calculates a simple time-weighted average, VW-TWAP integrates volume into its computation, emphasizing price movements that occur during periods of higher trading activity. This makes it particularly effective for identifying realistic price levels influenced by significant market participation. It is computed by summing the volume-weighted prices over a specified period and dividing by the total volume, providing a more accurate reflection of the price participants value most.
The key benefits of VW-TWAP lie in its ability to guide both traders and investors with a data-driven perspective. By accounting for both time and volume, it highlights fair value zones where significant accumulation or distribution might occur. This can improve trade entries and exits by aligning decisions with zones of substantial market consensus. Furthermore, its adaptability to different timeframes enhances its utility in multi-timeframe analysis, making it suitable for intraday scalpers and long-term swing traders alike. The VW-TWAP's focus on volume sensitivity also minimizes noise from low-volume, erratic price movements, offering a clearer view of market dynamics.
Relative Price Strength (RPS)Relative Price Strength (RPS) is a technical analysis indicator that measures the performance of a specific symbol relative to a benchmark or "Base Symbol".
It's essentially a ratio that compares the price of the specific symbol to the price of the benchmark.
Rising RPS: Indicates that the symbol is outperforming the benchmark.
Falling RPS: Suggests that the symbol is underperforming the benchmark.
RSP is smoothed over a period for better visualization.
Bitcoin Events HistoryWith this tool, you can travel back to Bitcoin’s very first price quote and retrace its entire history directly on your chart. Major events are plotted as labels or markers, providing context for how significant moments shaped Bitcoin’s journey.
Key Features
Comprehensive Event Coverage: From Bitcoin’s inception to the most recent updates.
Custom View: Change label colors, styles, sizes, and fonts using the script’s settings.
Regular Updates: New events are added regularly to keep the history current.
Replay History
Use Bar Replay Mode to step through Bitcoin’s price history and see events unfold in sequence.
Follow the on-screen instructions for a more immersive experience.
Community Contributions
If you notice a significant event missing or misplaced on a particular date, feel free to leave a comment! Your suggestions will be considered for the next update.
To all Bitcoin enthusiasts, traders, and anyone eager to explore the history of cryptocurrency from its inception, I hope you enjoy this indicator :)
CandelaCharts - Volume Imbalance (VI) 📝 Overview
Volume Imbalance occurs when there’s a noticeable gap between the bodies of two consecutive candlesticks, with no overlap between them. While the wicks of the candles might intersect, the candle bodies remain entirely separate. This phenomenon often signifies that the algorithm driving market activity did not evenly distribute prices between these two levels, leaving behind a small Fair Value Gap (FVG).
A Bullish Volume Imbalance forms when the body of a green candlestick gaps above the previous candle’s body, with no overlap, indicating strong upward momentum and insufficient sell-side liquidity.
A Bearish Volume Imbalance forms when the body of a red candlestick gaps below the previous candle’s body, with no overlap, signaling intense downward pressure and a lack of buy-side liquidity.
This indicator can automatically identify volume imbalances by scanning candlestick patterns and detecting gaps between consecutive candle bodies. These volume imbalances act as price magnets, often attracting the market back to fill the gap before resuming its original direction. Recognizing and leveraging these gaps can be a powerful tool in technical analysis for predicting price movements.
📦 Features
MTF
Mitigation
Consequent Encroachment
Threshold
Hide Overlap
Advanced Styling
⚙️ Settings
Show: Controls whether FVGs are displayed on the chart.
Show Last: Sets the number of FVGs you want to display.
Length: Determines the length of each FVG.
Mitigation: Highlights when an FVG has been touched, using a different color without marking it as invalid.
Timeframe: Specifies the timeframe used to detect FVGs.
Threshold: Sets the minimum gap size required for FVG detection on the chart.
Show Mid-Line: Configures the midpoint line's width and style within the FVG. (Consequent Encroachment - CE)
Show Border: Defines the border width and line style of the FVG.
Hide Overlap: Removes overlapping FVGs from view.
Extend: Extends the FVG length to the current candle.
Elongate: Fully extends the FVG length to the right side of the chart.
⚡️ Showcase
Simple
Mitigated
Bordered
Consequent Encroachment
Extended
🚨 Alerts
This script provides alert options for all signals.
Bearish Signal
A bearish alert triggers when a red candlestick gaps below the previous body, signaling downward pressure.
Bullish Signal
A bullish alert triggers when a green candlestick gaps above the previous body, indicating upward momentum.
⚠️ Disclaimer
Trading involves significant risk, and many participants may incur losses. The content on this site is not intended as financial advice and should not be interpreted as such. Decisions to buy, sell, hold, or trade securities, commodities, or other financial instruments carry inherent risks and are best made with guidance from qualified financial professionals. Past performance is not indicative of future results.
ETF-Benchmark AnalyzerHave you ever wondered which ETF performs the best? Which one is the most volatile, or which one has the smallest drawdown?
This Pine Script™ "ETF-Benchmark Analyzer" compares the performance of an ETF (such as SPY, the S&P 500 ETF) against a benchmark, which can also be adjusted by the user. It provides several key financial metrics, such as:
Performance (%): Displays the total return over a specified lookback period (e.g., 1 year). It compares the performance of the ETF against the benchmark and shows the difference.
Alpha (%): Measures the excess return of the ETF over the expected return, which is calculated using the benchmark’s return. Positive alpha indicates that the ETF has outperformed the benchmark, while negative alpha suggests underperformance. This metric is important because it isolates performance that cannot be explained by exposure to the benchmark's movements.
Sharpe Ratio: A risk-adjusted measure of return. It is calculated by dividing the excess return of the ETF (above the risk-free rate) by its standard deviation (volatility). A higher Sharpe ratio indicates better risk-adjusted returns. The Sharpe ratio is calculated for both the ETF and the benchmark, and their difference is displayed as well.
Drawdown: The percentage decrease from the highest price to the lowest price over the lookback period. This is a critical measure of risk, as it shows the largest potential loss an investor might face during a specific period.
Beta: Measures the ETF’s sensitivity to movements in the benchmark. A beta of 1 means the ETF moves in line with the benchmark; greater than 1 means it is more volatile, while less than 1 means it is less volatile.
These metrics provide a holistic view of the ETF’s performance compared to the benchmark, allowing traders to assess the risk and return profile more effectively.
Scientific Sources
Sharpe Ratio: Sharpe, W. F. (1994). The Sharpe Ratio. Journal of Portfolio Management, 21(1), 49-58. This paper defines and develops the Sharpe ratio as a measure of risk-adjusted return.
Alpha and Beta: Jensen, M. C. (1968). The Performance of Mutual Funds in the Period 1945–1964. The Journal of Finance, 23(2), 389-416. This paper discusses the concepts of alpha and beta in the context of mutual fund performance.
SMT Divergence ICT 01 [TradingFinder] Smart Money Technique🔵 Introduction
SMT Divergence (short for Smart Money Technique Divergence) is a trading technique in the ICT Concepts methodology that focuses on identifying divergences between two positively correlated assets in financial markets.
These divergences occur when two assets that should move in the same direction move in opposite directions. Identifying these divergences can help traders spot potential reversal points and trend changes.
Bullish and Bearish divergences are clearly visible when an asset forms a new high or low, and the correlated asset fails to do so. This technique is applicable in markets like Forex, stocks, and cryptocurrencies, and can be used as a valid signal for deciding when to enter or exit trades.
Bullish SMT Divergence : This type of divergence occurs when one asset forms a higher low while the correlated asset forms a lower low. This divergence is typically a sign of weakness in the downtrend and can act as a signal for a trend reversal to the upside.
Bearish SMT Divergence : This type of divergence occurs when one asset forms a higher high while the correlated asset forms a lower high. This divergence usually indicates weakness in the uptrend and can act as a signal for a trend reversal to the downside.
🔵 How to Use
SMT Divergence is an analytical technique that identifies divergences between two correlated assets in financial markets.
This technique is used when two assets that should move in the same direction move in opposite directions.
Identifying these divergences can help you pinpoint reversal points and trend changes in the market.
🟣 Bullish SMT Divergence
This divergence occurs when one asset forms a higher low while the correlated asset forms a lower low. This divergence indicates weakness in the downtrend and can signal a potential price reversal to the upside.
In this case, when the correlated asset is forming a lower low, and the main asset is moving lower but the correlated asset fails to continue the downward trend, there is a high probability of a trend reversal to the upside.
🟣 Bearish SMT Divergence
Bearish divergence occurs when one asset forms a higher high while the correlated asset forms a lower high. This type of divergence indicates weakness in the uptrend and can signal a potential trend reversal to the downside.
When the correlated asset fails to make a new high, this divergence may be a sign of a trend reversal to the downside.
🟣 Confirming Signals with Correlation
To improve the accuracy of the signals, use assets with strong correlation. Forex pairs like OANDA:EURUSD and OANDA:GBPUSD , or cryptocurrencies like COINBASE:BTCUSD and COINBASE:ETHUSD , or commodities such as gold ( FX:XAUUSD ) and silver ( FX:XAGUSD ) typically have significant correlation. Identifying divergences between these assets can provide a strong signal for a trend change.
🔵 Settings
Second Symbol : This setting allows you to select another asset for comparison with the primary asset. By default, "XAUUSD" (Gold) is set as the second symbol, but you can change it to any currency pair, stock, or cryptocurrency. For example, you can choose currency pairs like EUR/USD or GBP/USD to identify divergences between these two assets.
Divergence Fractal Periods : This parameter defines the number of past candles to consider when identifying divergences. The default value is 2, but you can change it to suit your preferences. This setting allows you to detect divergences more accurately by selecting a greater number of candles.
Bullish Divergence Line : Displays a line showing bullish divergence from the lows.
Bearish Divergence Line : Displays a line showing bearish divergence from the highs.
Bullish Divergence Label : Displays the "+SMT" label for bullish divergences.
Bearish Divergence Label : Displays the "-SMT" label for bearish divergences.
🔵 Conclusion
SMT Divergence is an effective tool for identifying trend changes and reversal points in financial markets based on identifying divergences between two correlated assets. This technique helps traders receive more accurate signals for market entry and exit by analyzing bullish and bearish divergences.
Identifying these divergences can provide opportunities to capitalize on trend changes in Forex, stocks, and cryptocurrency markets. Using SMT Divergence along with risk management and confirming signals with other technical analysis tools can improve the accuracy of trading decisions and reduce risks from sudden market changes.
Pine Script Boilerplate ExampleI frequently receive questions about my coding style and logic, so I decided to publish a simple indicator that draws the OHLC of a higher timeframe as an example of my coding style. This example will also explain my approach to writing indicators.
This indicator showcases how I use Types and Methods to structure my code and maintain clarity in logic. It demonstrates how I collect input data, organize the flow of the code, and utilize the TradingView method feature.
The example illustrates:
1. The use of input settings within a settings object to keep configurations grouped together.
2. The use of Types to create an object that consolidates relevant data.
3. The collection of objects to create, update, and render elements on the chart.
1 Percent Range TrackerThis indicator is a simple yet effective tool designed to calculate and display ±1% levels relative to the current market price. These levels are dynamically updated in real time, providing clear horizontal lines on the chart to visualize the 1% range above and below the current price.
The indicator also displays the precise numerical values of these levels on the right-hand price axis, making it easy to monitor critical thresholds at a glance.
MktCumTickThis script is a market sentiment indicator that calculates the cumulative TICK (Trade Imbalance Sentiment) for four major markets: NYSE (New York Stock Exchange), NASDAQ (National Association of Securities Dealers Automated Quotations), Dow Jones, and AMEX (American Stock Exchange).
Here's a breakdown of the script:
1. Market data requests: The script requests data for the four markets, including:
- TICK (Trade Imbalance Sentiment) data
- HLC3 (High, Low, Close) data
- ADVN (Advancing issues), DECL (Declining issues), and UNCH (Unchanged issues) data
2. Cumulative TICK calculation: The script calculates the cumulative TICK for each market by dividing the TICK data by the maximum TICK value for each market.
3. Plotting: The script plots the cumulative TICK values for each market as separate lines on the chart.
4. Background color: The script changes the background color of the chart based on the cumulative TICK values. If all four markets have decreasing cumulative TICK values, the background color turns red. If all four markets have increasing cumulative TICK values, the background color turns green.
The purpose of this indicator is to provide a visual representation of market sentiment across multiple markets. By analyzing the cumulative TICK values, traders can gain insights into market trends and make more informed trading decisions.
Some possible uses of this indicator include:
- Identifying market trends and sentiment
- Confirming trade entries and exits
- Monitoring market conditions and adjusting trading strategies accordingly
RagiBaba's 3:1 Risk-to-Reward Tool with LeverageThis indicator allows you to visualize a 3:1 risk-to-reward ratio for your trades on the chart. It automatically calculates and displays the Stop Loss and Take Profit levels based on your input for:
Entry Price
Trade Amount ($)
Risk Amount ($)
Leverage (x)
You can adjust the following settings:
Trade Direction: Choose between a Long or Short position.
Leverage: Enter the leverage value (e.g., 25x).
Entry Price: Set the price at which you plan to enter the trade.
Risk and Reward: Input the amount of money you're willing to risk and the desired reward (automatically calculated as 3 times your risk).
Label Position: Choose the label position for Entry, Stop, and Target (left, center, or right on the chart).
Each line has a corresponding label showing the price for Entry, Stop Loss, and Take Profit. The labels can be positioned on the left, center, or right side of the chart for better readability.
This tool helps you manage your trades by giving you clear visual cues for your entry, stop loss, and take profit levels with the option to adjust for leverage.
Gold Friday Anomaly StrategyThis script implements the " Gold Friday Anomaly Strategy ," a well-known historical trading strategy that leverages the gold market's behavior from Thursday evening to Friday close. It is a backtesting-focused strategy designed to assess the historical performance of this pattern. Traders use this anomaly as it captures a recurring market tendency observed over the years.
What It Does:
Entry Condition: The strategy enters a long position at the beginning of the Friday trading session (Thursday evening close) within the defined backtesting period.
Exit Condition: Friday evening close.
Backtesting Controls: Allows users to set custom backtesting periods to evaluate strategy performance over specific date ranges.
Key Features:
Custom Backtest Periods: Easily configurable inputs to set the start and end date of the backtesting range.
Fixed Slippage and Commission Settings: Ensures realistic simulation of trading conditions.
Process Orders on Close: Backtesting is optimized by processing orders at the bar's close.
Important Notes:
Backtesting Only: This script is intended purely for backtesting purposes. Past performance is not indicative of future results.
Live Trading Recommendations: For live trading, it is highly recommended to use limit orders instead of market orders, especially during evening sessions, as market order slippage can be significant.
Default Settings:
Entry size: 10% of equity per trade.
Slippage: 1 tick.
Commission: 0.05% per trade.
Volatility and Tick Size DataThis indicator, titled "Tick Information & Standard Deviation Table," provides detailed insights into market microstructure, including tick size, point value, and standard deviation values calculated based on the True Range. It helps visualize essential trading parameters that influence transaction costs, risk management, and portfolio performance, including volatility measures that can guide investment strategies.
Why These Data Points Are Important for Portfolio Management
Tick Size and Point Value:
Tick size refers to the smallest possible price movement in a given asset. It defines the granularity of the price changes, affecting how precise the market price can be at any moment. Point value reflects the monetary value of a single price movement (one tick). These two data points are essential for understanding transaction costs and for evaluating how much capital is at risk per price movement. Smaller tick sizes may lead to more efficient pricing in high-frequency trading strategies (Hasbrouck, 2009).
Reference: Hasbrouck, J. (2009). Empirical Market Microstructure. Foundations and Trends® in Finance, 3(4), 169-272.
Standard Deviations and Volatility:
Standard deviation measures the variability or volatility of an asset's price over a set period. This data point is critical for portfolio management, as it helps to quantify risk and predict potential price movements. True Range and its standard deviations provide a more comprehensive measure of market volatility than just price fluctuations, as they include gaps and extreme price changes. Investors use volatility data to assess the potential risk and adjust portfolio allocations accordingly (Ang, 2006).
Reference: Ang, A. (2006). Asset Management: A Systematic Approach to Factor Investing. Oxford University Press.
Risk Management:
The ability to quantify risk through metrics like the 1st, 2nd, and 3rd standard deviations of the true range is essential for implementing risk controls within a portfolio. By incorporating volatility data, portfolio managers can adjust their strategies for different market conditions, potentially reducing exposure to high-risk environments. These volatility measures help in setting stop-loss levels, optimizing position sizes, and managing the portfolio’s overall risk-return profile (Black & Scholes, 1973).
Reference: Black, F., & Scholes, M. (1973). The Pricing of Options and Corporate Liabilities. Journal of Political Economy, 81(3), 637-654.
Portfolio Diversification and Hedging:
Understanding asset volatility and transaction costs is critical when constructing a diversified portfolio. By using the standard deviations from this indicator, investors can better identify assets that may provide diversification benefits, potentially reducing the overall portfolio risk. Moreover, the point values and tick sizes help assess the cost-effectiveness of various assets, enabling portfolio managers to implement more efficient hedging strategies (Markowitz, 1952).
Reference: Markowitz, H. (1952). Portfolio Selection. The Journal of Finance, 7(1), 77-91.
Conclusion
The Tick Information & Standard Deviation Table provides critical market data that informs the risk management, diversification, and pricing strategies used in portfolio management. By incorporating tick size, point value, and volatility metrics, investors can make more informed decisions, better manage risk, and optimize the returns on their portfolios. The data serves as an essential tool for aligning asset selection and portfolio allocations with the investor's risk tolerance and market conditions.
[w3ss1] Colored candlesA simple script that colors the candles in a color of choise on specific times of choice.
You can use it if you want to color like Asia session, or if you want to focus on specific times of day.
This keeps the chart clean, it just colors the candles in the choosen timings.
Daily Directional Bias Indicator (S&P 500)This indicator is designed to help you be on the right side of the trade.
Most traders who struggle to know which way price may move are only looking at part of the picture. This Directional Bias Indicator uses both the Accumulation/Distribution Line and VIX for directional confirmation.
The Accumulation/Distribution Line
The Accumulation/Distribution (ACC) line helps us gauge market momentum by showing the cumulative flow of money into or out of an asset. When the ACC line is rising, it suggests that buying pressure is dominating, indicating a bullish market. Conversely, when the ACC line is falling, it suggests that selling pressure is stronger, indicating a bearish market. By comparing the ACC line with the VWAP, traders can see if the price is moving in line with the overall market sentiment. If the ACC line is above the VWAP, it suggests the market is in a bullish phase; if it's below, it indicates a bearish phase.
The VIX
The VIX (Volatility Index) is often referred to as the "fear gauge" of the market. When the VIX is rising, it typically signals increased market fear and higher volatility, which can be a sign of bearish market conditions. Conversely, when the VIX is falling, it suggests lower volatility and a more stable, bullish market. Using the VIX with the VWAP helps us confirm market direction, particularly in relation to the S&P 500.
VWAP
For both the ACC Line and VIX, we use a VWAP line to gauge whether the ACC line or the VIX is above or below the average. When the ACC line is above the VWAP, we view it as a sign that price will go up. However, because the VIX has an inverse relationship, when the VIX falls below the VWAP, we take that as a sign to go long.
How to use
The yellow line represents the ACC Line.
The red line represents the VWAP based on the ACC line.
The triangles at the bottom simply show when the ACC line is above or below the VWAP.
The triangles at the top show whether the VIX is bullish or bearish.
If both triangles (top or bottom) are bullish, this confirms that the price of an asset like the S&P 500 will likely go up. If both triangles are pointing down, it suggests that price will fall.
As always, test for yourself.
Happy trading!
2.5% Risk High Reward Strategy with DebuggingKey Features:
Loosened RSI Conditions: Adjusted to allow trades when RSI is below 50 (long) or above 50 (short).
Buy/Sell Labels: Visual labels added for buy and sell signals.
Stop-Loss (SL) and Take-Profit (TP): Dotted lines displayed for SL and TP levels.
Account Balance: Plots account balance over time for backtesting purposes.
Debugging Visuals: EMA, RSI, and volume threshold plotted to validate entry conditions.
Data extraction to clipboardHow to extract data from indicators/stratagies to clipbaord
///// Educational purpose only /////
This could be useful to store the best parameters for a strategy for instance...
to store and reuse them, to build some code in automatic , to transfer...
using the " log.info() " function ...
Trading Sessions with Highs and LowsTrading Sessions with Highs and Lows is designed to visually highlight specific trading sessions on the chart, providing traders with key insights into market behavior during these time periods. Here’s a detailed explanation of how the indicator works:
Key Features
1. Session Boxes:
• The indicator plots colored boxes on the chart to represent the price range of defined trading sessions.
• Each box spans the session’s start and end times and encapsulates the high and low prices during that period.
• Two trading sessions are defined by default:
• USA Trading Session: 9:30 AM - 4:00 PM (New York Time).
• UK Trading Session: 8:00 AM - 4:30 PM (London Time).
2. Session Labels:
• The name of the session (e.g., “USA” or “UK”) is displayed above the session box for clear identification.
3. High and Low Markers:
• Markers are added to the chart at the session’s high and low points:
• High Marker: A green label indicating the session high.
• Low Marker: A red label indicating the session low.
4. Dynamic Reset:
• After the session ends, the session high and low values are reset to na to prepare for the next trading day.
5. Customizable Background Colors:
• Each session’s box has a distinct, semi-transparent background color for better visual separation.
How It Works
1. Core Functionality:
• A function, plot_box, takes the session name, start time, end time, and background color as input.
• It calculates whether the current time is within the session.
• During the session:
• It tracks the session’s highest and lowest prices.
• It identifies the bars where the high and low occurred.
• At the session’s end:
• It plots a box on the chart covering the session’s time and price range.
• Labels are created for the session name and its high/low points.
2. Session Timing:
• Timestamps for the USA and UK trading sessions are calculated using the timestamp function with respective time zones.
3. Visual Elements:
• The box.new function draws the session boxes on the chart.
• The label.new function creates session name and high/low labels.
Usage
• Overlay Mode: The indicator is applied directly on the price chart (overlay=true), making it easy to visualize session-specific price behavior.
• Trading Strategy:
• Identify session-specific support and resistance levels.
• Observe price action trends during key trading periods.
• Align trading decisions with session dynamics.
Customization
While the indicator is preset for the USA and UK trading sessions, it can be easily modified:
1. Add/Remove Sessions: Define additional sessions by providing their start and end times.
2. Change Colors: Update the background_color in the plot_box calls to use different colors for sessions.
3. Adjust Time Zones: Replace the current time zones with others relevant to your trading style.
Visualization Example
• USA Session:
• Time: 9:30 AM - 4:00 PM (New York Time).
• Box Color: Semi-transparent orange.
• UK Session:
• Time: 8:00 AM - 4:30 PM (London Time).
• Box Color: Semi-transparent green.
Why Use This Indicator?
1. Market Awareness: Easily spot price behavior during high-liquidity trading periods.
2. Trend Analysis: Analyze how sessions overlap or affect each other.
3. Session Boundaries: Use session high/low levels as dynamic support and resistance zones.
This indicator is an essential tool for intraday and swing traders who want to align their strategies with key market timings.
Simple Decesion Matrix Classification Algorithm [SS]Hello everyone,
It has been a while since I posted an indicator, so thought I would share this project I did for fun.
This indicator is an attempt to develop a pseudo Random Forest classification decision matrix model for Pinescript.
This is not a full, robust Random Forest model by any stretch of the imagination, but it is a good way to showcase how decision matrices can be applied to trading and within Pinescript.
As to not market this as something it is not, I am simply calling it the "Simple Decision Matrix Classification Algorithm". However, I have stolen most of the aspects of this machine learning algo from concepts of Random Forest modelling.
How it works:
With models like Support Vector Machines (SVM), Random Forest (RF) and Gradient Boosted Machine Learning (GBM), which are commonly used in Machine Learning Classification Tasks (MLCTs), this model operates similarity to the basic concepts shared amongst those modelling types. While it is not very similar to SVM, it is very similar to RF and GBM, in that it uses a "voting" system.
What do I mean by voting system?
How most classification MLAs work is by feeding an input dataset to an algorithm. The algorithm sorts this data, categorizes it, then introduces something called a confusion matrix (essentially sorting the data in no apparently order as to prevent over-fitting and introduce "confusion" to the algorithm to ensure that it is not just following a trend).
From there, the data is called upon based on current data inputs (so say we are using RSI and Z-Score, the current RSI and Z-Score is compared against other RSI's and Z-Scores that the model has saved). The model will process this information and each "tree" or "node" will vote. Then a cumulative overall vote is casted.
How does this MLA work?
This model accepts 2 independent variables. In order to keep things simple, this model was kept as a three node model. This means that there are 3 separate votes that go in to get the result. A vote is casted for each of the two independent variables and then a cumulative vote is casted for the overall verdict (the result of the model's prediction).
The model actually displays this system diagrammatically and it will likely be easier to understand if we look at the diagram to ground the example:
In the diagram, at the very top we have the classification variable that we are trying to predict. In this case, we are trying to predict whether there will be a breakout/breakdown outside of the normal ATR range (this is either yes or no question, hence a classification task).
So the question forms the basis of the input. The model will track at which points the ATR range is exceeded to the upside or downside, as well as the other variables that we wish to use to predict these exceedences. The ATR range forms the basis of all the data flowing into the model.
Then, at the second level, you will see we are using Z-Score and RSI to predict these breaks. The circle will change colour according to "feature importance". Feature importance basically just means that the indicator has a strong impact on the outcome. The stronger the importance, the more green it will be, the weaker, the more red it will be.
We can see both RSI and Z-Score are green and thus we can say they are strong options for predicting a breakout/breakdown.
So then we move down to the actual voting mechanisms. You will see the 2 pink boxes. These are the first lines of voting. What is happening here is the model is identifying the instances that are most similar and whether the classification task we have assigned (remember out ATR exceedance classifier) was either true or false based on RSI and Z-Score.
These are our 2 nodes. They both cast an individual vote. You will see in this case, both cast a vote of 1. The options are either 1 or 0. A vote of 1 means "Yes" or "Breakout likely".
However, this is not the only voting the model does. The model does one final vote based on the 2 votes. This is shown in the purple box. We can see the final vote and result at the end with the orange circle. It is 1 which means a range exceedance is anticipated and the most likely outcome.
The Data Table Component
The model has many moving parts. I have tried to represent the pivotal functions diagrammatically, but some other important aspects and background information must be obtained from the companion data table.
If we bring back our diagram from above:
We can see the data table to the left.
The data table contains 2 sections, one for each independent variable. In this case, our independent variables are RSI and Z-Score.
The data table will provide you with specifics about the independent variables, as well as about the model accuracy and outcome.
If we take a look at the first row, it simply indicates which independent variable it is looking at. If we go down to the next row where it reads "Weighted Impact", we can see a corresponding percent. The "weighted impact" is the amount of representation each independent variable has within the voting scheme. So in this case, we can see its pretty equal, 45% and 55%, This tells us that there is a slight higher representation of z-score than RSI but nothing to worry about.
If there was a major over-respresentation of greater than 30 or 40%, then the model would risk being skewed and voting too heavily in favour of 1 variable over the other.
If we move down from there we will see the next row reads "independent accuracy". The voting of each independent variable's accuracy is considered separately. This is one way we can determine feature importance, by seeing how well one feature augments the accuracy. In this case, we can see that RSI has the greatest importance, with an accuracy of around 87% at predicting breakouts. That makes sense as RSI is a momentum based oscillator.
Then if we move down one more, we will see what each independent feature (node) has voted for. In this case, both RSI and Z-Score voted for 1 (Breakout in our case).
You can weigh these in collaboration, but its always important to look at the final verdict of the model, which if we move down, we can see the "Model prediction" which is "Bullish".
If you are using the ATR breakout, the model cannot distinguish between "Bullish" or "Bearish", must that a "Breakout" is likely, either bearish or bullish. However, for the other classification tasks this model can do, the results are either Bullish or Bearish.
Using the Function:
Okay so now that all that technical stuff is out of the way, let's get into using the function. First of all this function innately provides you with 3 possible classification tasks. These include:
1. Predicting Red or Green Candle
2. Predicting Bullish / Bearish ATR
3. Predicting a Breakout from the ATR range
The possible independent variables include:
1. Stochastics,
2. MFI,
3. RSI,
4. Z-Score,
5. EMAs,
6. SMAs,
7. Volume
The model can only accept 2 independent variables, to operate within the computation time limits for pine execution.
Let's quickly go over what the numbers in the diagram mean:
The numbers being pointed at with the yellow arrows represent the cases the model is sorting and voting on. These are the most identical cases and are serving as the voting foundation for the model.
The numbers being pointed at with the pink candle is the voting results.
Extrapolating the functions (For Pine Developers:
So this is more of a feature application, so feel free to customize it to your liking and add additional inputs. But here are some key important considerations if you wish to apply this within your own code:
1. This is a BINARY classification task. The prediction must either be 0 or 1.
2. The function consists of 3 separate functions, the 2 first functions serve to build the confusion matrix and then the final "random_forest" function serves to perform the computations. You will need all 3 functions for implementation.
3. The model can only accept 2 independent variables.
I believe that is the function. Hopefully this wasn't too confusing, it is very statsy, but its a fun function for me! I use Random Forest excessively in R and always like to try to convert R things to Pinescript.
Hope you enjoy!
Safe trades everyone!