Z-Score RSI StrategyOverview
The Z-Score RSI Indicator is an experimental take on momentum analysis. By applying the Relative Strength Index (RSI) to a Z-score of price data, it measures how far prices deviate from their mean, scaled by standard deviation. This isn’t your traditional use of RSI, which is typically based on price data alone. Nevertheless, this unconventional approach can yield unique insights into market trends and potential reversals.
Theory and Interpretation
The RSI calculates the balance between average gains and losses over a set period, outputting values from 0 to 100. Typically, people look at the overbought or oversold levels to identify momentum extremes that might be likely to lead to a reversal. However, I’ve often found that RSI can be effective for trend-following when observing the crossover of its moving average with the midline or the crossover of the RSI with its own moving average. These crossovers can provide useful trend signals in various market conditions.
By combining RSI with a Z-score of price, this indicator estimates the relative strength of the price’s distance from its mean. Positive Z-score trends may signal a potential for higher-than-average prices in the near future (scaled by the standard deviation), while negative trends suggest the opposite. Essentially, when the Z-Score RSI indicates a trend, it reflects that the Z-score (the distance between the average and current price) is likely to continue moving in the trend’s direction. Generally, this signals a potential price movement, though it’s important to note that this could also occur if there’s a shift in the mean or standard deviation, rather than a meaningful change in price itself.
While the Z-Score RSI could be an insightful addition to a comprehensive trading system, it should be interpreted carefully. Mean shifts may validate the indicator’s predictions without necessarily indicating any notable price change, meaning it’s best used in tandem with other indicators or strategies.
Recommendations
Before putting this indicator to use, conduct thorough backtesting and avoid overfitting. The added parameters allow fine-tuning to fit various assets, but be careful not to optimize purely for the highest historical returns. Doing so may create an overly tailored strategy that performs well in backtests but fails in live markets. Keep it balanced and look for robust performance across multiple scenarios, as overfitting is likely to lead to disappointing real-world results.
Göstergeler ve stratejiler
Quick scan for cycles🙏🏻
The followup for
As I told before, ML based algorading is all about detecting any kind of non-randomness & exploiting it (cuz allegedly u cant trade randomness), and cycles are legit patterns that can be leveraged
But bro would u really apply Fourier / Wavelets / 'whatever else heavy' on every update of thousands of datasets, esp in real time on HFT / nearly HFT data? That's why this metric. It works much faster & eats hell of a less electicity, will do initial rough filtering of time series that might contain any kind of cyclic behaviour. And then, only on these filtered datasets u gonna put Periodograms / Autocorrelograms and see what's going there for real. Better to do it 10x times less a day on 10x less datasets, right?
I ended up with 2 methods / formulas, I called em 'type 0' and 'type 1':
- type 0: takes sum of abs deviations from drift line, scales it by max abs deviation from the same drift line;
- type 1: takes sum of abs deviations from drift line, scales it by range of non-abs deviations from the same drift line.
Finnaly I've chosen type 0 , both logically (sum of abs dev divided by max abs dev makes more sense) and experimentally. About that actually, here are both formulas put on sine waves with uniform noise:
^^ generated sine wave with uniform noise
^^ both formulas on that wave
^^ both formulas on real data
As you can see type 0 is less affected by noise and shows higher values on synthetic data, but I decided to put type 1 inside as well, in case my analysis was not complete and on real data type 1 can actually be better since it has a lil higher info gain / info content (still not sure). But I can assure u that out of all other ways I've designed & tested for quite a time I tell you, these 2 are really the only ones who got there.
Now about dem thresholds and how to use it.
Both type 0 and type 1 can be modelled with Beta distribution, and based on it and on some obvious & tho non mainstream statistical modelling techniques, I got these thresholds, so these are not optimized overfitted values, but natural ones. Each type has 3 thresholds (from lowest to highest):
- typical value (turned off by default). aka basis ;
- typical deviation from typical value, aka deviation ;
- maximum modelled deviation from typical value (idk whow to call it properly for now, this is my own R&D), aka extension .
So when the metric is above one of these thresholds (which one is up to you, you'll read about it in a sec), it means that there might be a strong enough periodic signal inside the data, and the data got to be put through proper spectral analysis tools to confirm / deny it.
If you look at the pictures above again, you'll see gray signal, that's uniform noise. Take a look at it and see where does it sit comparing to the thresholds. Now you just undertand that picking up a threshold is all about the amount of false positives you care to withstand.
If you take basis as threshold, you'll get tons of false positives (that's why it's even turned off by default), but you'll almost never miss a true positive. If you take deviation as threshold, it's gonna be kinda balanced approach. If you take extension as threshold, you gonna miss some cycles, and gonna get only the strongest ones.
More true positives -> more false positives, less false positives -> less true positives, can't go around that mane
Just to be clear again, I am not completely sure yet, but I def lean towards type 0 as metric, and deviation as threshold.
Live Long and Prosper
P.S.: That was actually the main R&D of the last month, that script I've released earlier came out as derivative.
P.S.: These 2 are the first R&Ds made completely in " art-space", St. Petersburg. Come and see me, say wassup🤘🏻
S&P 100 Option Expiration Week StrategyThe Option Expiration Week Strategy aims to capitalize on increased volatility and trading volume that often occur during the week leading up to the expiration of options on stocks in the S&P 100 index. This period, known as the option expiration week, culminates on the third Friday of each month when stock options typically expire in the U.S. During this week, investors in this strategy take a long position in S&P 100 stocks or an equivalent ETF from the Monday preceding the third Friday, holding until Friday. The strategy capitalizes on potential upward price pressures caused by increased option-related trading activity, rebalancing, and hedging practices.
The phenomenon leveraged by this strategy is well-documented in finance literature. Studies demonstrate that options expiration dates have a significant impact on stock returns, trading volume, and volatility. This effect is driven by various market dynamics, including portfolio rebalancing, delta hedging by option market makers, and the unwinding of positions by institutional investors (Stoll & Whaley, 1987; Ni, Pearson, & Poteshman, 2005). These market activities intensify near option expiration, causing price adjustments that may create short-term profitable opportunities for those aware of these patterns (Roll, Schwartz, & Subrahmanyam, 2009).
The paper by Johnson and So (2013), Returns and Option Activity over the Option-Expiration Week for S&P 100 Stocks, provides empirical evidence supporting this strategy. The study analyzes the impact of option expiration on S&P 100 stocks, showing that these stocks tend to exhibit abnormal returns and increased volume during the expiration week. The authors attribute these patterns to intensified option trading activity, where demand for hedging and arbitrage around options expiration causes temporary price adjustments.
Scientific Explanation
Research has found that option expiration weeks are marked by predictable increases in stock returns and volatility, largely due to the role of options market makers and institutional investors. Option market makers often use delta hedging to manage exposure, which requires frequent buying or selling of the underlying stock to maintain a hedged position. As expiration approaches, their activity can amplify price fluctuations. Additionally, institutional investors often roll over or unwind positions during expiration weeks, creating further demand for underlying stocks (Stoll & Whaley, 1987). This increased demand around expiration week typically leads to temporary stock price increases, offering profitable opportunities for short-term strategies.
Key Research and Bibliography
Johnson, T. C., & So, E. C. (2013). Returns and Option Activity over the Option-Expiration Week for S&P 100 Stocks. Journal of Banking and Finance, 37(11), 4226-4240.
This study specifically examines the S&P 100 stocks and demonstrates that option expiration weeks are associated with abnormal returns and trading volume due to increased activity in the options market.
Stoll, H. R., & Whaley, R. E. (1987). Program Trading and Expiration-Day Effects. Financial Analysts Journal, 43(2), 16-28.
Stoll and Whaley analyze how program trading and portfolio insurance strategies around expiration days impact stock prices, leading to temporary volatility and increased trading volume.
Ni, S. X., Pearson, N. D., & Poteshman, A. M. (2005). Stock Price Clustering on Option Expiration Dates. Journal of Financial Economics, 78(1), 49-87.
This paper investigates how option expiration dates affect stock price clustering and volume, driven by delta hedging and other option-related trading activities.
Roll, R., Schwartz, E., & Subrahmanyam, A. (2009). Options Trading Activity and Firm Valuation. Journal of Financial Markets, 12(3), 519-534.
The authors explore how options trading activity influences firm valuation, finding that higher options volume around expiration dates can lead to temporary price movements in underlying stocks.
Cao, C., & Wei, J. (2010). Option Market Liquidity and Stock Return Volatility. Journal of Financial and Quantitative Analysis, 45(2), 481-507.
This study examines the relationship between options market liquidity and stock return volatility, finding that increased liquidity needs during expiration weeks can heighten volatility, impacting stock returns.
Summary
The Option Expiration Week Strategy utilizes well-researched financial market phenomena related to option expiration. By positioning long in S&P 100 stocks or ETFs during this period, traders can potentially capture abnormal returns driven by option market dynamics. The literature suggests that options-related activities—such as delta hedging, position rollovers, and portfolio adjustments—intensify demand for underlying assets, creating short-term profit opportunities around these key dates.
Payday Anomaly StrategyThe "Payday Effect" refers to a predictable anomaly in financial markets where stock returns exhibit significant fluctuations around specific pay periods. Typically, these are associated with the beginning, middle, or end of the month when many investors receive wages and salaries. This influx of funds, often directed automatically into retirement accounts or investment portfolios (such as 401(k) plans in the United States), temporarily increases the demand for equities. This phenomenon has been linked to a cycle where stock prices rise disproportionately on and around payday periods due to increased buy-side liquidity.
Academic research on the payday effect suggests that this pattern is tied to systematic cash flows into financial markets, primarily driven by employee retirement and savings plans. The regularity of these cash infusions creates a calendar-based pattern that can be exploited in trading strategies. Studies show that returns on days around typical payroll dates tend to be above average, and this pattern remains observable across various time periods and regions.
The rationale behind the payday effect is rooted in the behavioral tendencies of investors, specifically the automatic reinvestment mechanisms used in retirement funds, which align with monthly or semi-monthly salary payments. This regular injection of funds can cause market microstructure effects where stock prices temporarily increase, only to stabilize or reverse after the funds have been invested. Consequently, the payday effect provides traders with a potentially profitable opportunity by predicting these inflows.
Scientific Bibliography on the Payday Effect
Ma, A., & Pratt, W. R. (2017). Payday Anomaly: The Market Impact of Semi-Monthly Pay Periods. Social Science Research Network (SSRN).
This study provides a comprehensive analysis of the payday effect, exploring how returns tend to peak around payroll periods due to semi-monthly cash flows. The paper discusses how systematic inflows impact returns, leading to predictable stock performance patterns on specific days of the month.
Lakonishok, J., & Smidt, S. (1988). Are Seasonal Anomalies Real? A Ninety-Year Perspective. The Review of Financial Studies, 1(4), 403-425.
This foundational study explores calendar anomalies, including the payday effect. By examining data over nearly a century, the authors establish a framework for understanding seasonal and monthly patterns in stock returns, which provides historical support for the payday effect.
Owen, S., & Rabinovitch, R. (1983). On the Predictability of Common Stock Returns: A Step Beyond the Random Walk Hypothesis. Journal of Business Finance & Accounting, 10(3), 379-396.
This paper investigates predictability in stock returns beyond random fluctuations. It considers payday effects among various calendar anomalies, arguing that certain dates yield predictable returns due to regular cash inflows.
Loughran, T., & Schultz, P. (2005). Liquidity: Urban versus Rural Firms. Journal of Financial Economics, 78(2), 341-374.
While primarily focused on liquidity, this study provides insight into how cash flows, such as those from semi-monthly paychecks, influence liquidity levels and consequently impact stock prices around predictable pay dates.
Ariel, R. A. (1990). High Stock Returns Before Holidays: Existence and Evidence on Possible Causes. The Journal of Finance, 45(5), 1611-1626.
Ariel’s work highlights stock return patterns tied to certain dates, including paydays. Although the study focuses on pre-holiday returns, it suggests broader implications of predictable investment timing, reinforcing the calendar-based effects seen with payday anomalies.
Summary
Research on the payday effect highlights a repeating pattern in stock market returns driven by scheduled payroll investments. This cyclical increase in stock demand aligns with behavioral finance insights and market microstructure theories, offering a valuable basis for trading strategies focused on the beginning, middle, and end of each month.
XAUUSD 10-Minute StrategyThis XAUUSD 10-Minute Strategy is designed for trading Gold vs. USD on a 10-minute timeframe. By combining multiple technical indicators (MACD, RSI, Bollinger Bands, and ATR), the strategy effectively captures both trend-following and reversal opportunities, with adaptive risk management for varying market volatility. This approach balances high-probability entries with robust volatility management, making it suitable for traders seeking to optimise entries during significant price movements and reversals.
Key Components and Logic:
MACD (12, 26, 9):
Generates buy signals on MACD Line crossovers above the Signal Line and sell signals on crossovers below the Signal Line, helping to capture momentum shifts.
RSI (14):
Utilizes oversold (below 35) and overbought (above 65) levels as a secondary filter to validate entries and avoid overextended price zones.
Bollinger Bands (20, 2):
Uses upper and lower Bollinger Bands to identify potential overbought and oversold conditions, aiming to enter long trades near the lower band and short trades near the upper band.
ATR-Based Stop Loss and Take Profit:
Stop Loss and Take Profit levels are dynamically set as multiples of ATR (3x for stop loss, 5x for take profit), ensuring flexibility with market volatility to optimise exit points.
Entry & Exit Conditions:
Buy Entry: T riggered when any of the following conditions are met:
MACD Line crosses above the Signal Line
RSI is oversold
Price drops below the lower Bollinger Band
Sell Entry: Triggered when any of the following conditions are met:
MACD Line crosses below the Signal Line
RSI is overbought
Price moves above the upper Bollinger Band
Exit Strategy: Trades are closed based on opposing entry signals, with adaptive spread adjustments for realistic exit points.
Backtesting Configuration & Results:
Backtesting Period: July 21, 2024, to October 30, 2024
Symbol Info: XAUUSD, 10-minute timeframe, OANDA data source
Backtesting Capital: Initial capital of $700, with each trade set to 10 contracts (equivalent to approximately 0.1 lots based on the broker’s contract size for gold).
Users should confirm their broker's contract size for gold, as this may differ. This script uses 10 contracts for backtesting purposes, aligned with 0.1 lots on brokers offering a 100-contract specification.
Key Backtesting Performance Metrics:
Net Profit: $4,733.90 USD (676.27% increase)
Total Closed Trades: 526
Win Rate: 53.99%
Profit Factor: 1.44 (1.96 for Long trades, 1.14 for Short trades)
Max Drawdown: $819.75 USD (56.33% of equity)
Sharpe Ratio: 1.726
Average Trade: $9.00 USD (0.04% of equity per trade)
This backtest reflects realistic conditions, with a spread adjustment of 38 points and no slippage or commission applied. The settings aim to simulate typical retail trading conditions. However, please adjust the initial capital, contract size, and other settings based on your account specifics for best results.
Usage:
This strategy is tuned specifically for XAUUSD on a 10-minute timeframe, ideal for both trend-following and reversal trades. The ATR-based stop loss and take profit levels adapt dynamically to market volatility, optimising entries and exits in varied conditions. To backtest this script accurately, ensure your broker’s contract specifications for gold align with the parameters used in this strategy.
Asian Session ShadingDescription
The "Asian Session Shading" indicator is designed to highlight the trading hours of the Asian market session on TradingView charts. This script shades the background of the chart in a pale blue color to visually distinguish the time period of the Asian trading session. By using this indicator, traders can easily identify when the Asian session is active, helping them to analyze and make informed trading decisions based on time-specific market behavior.
Features
Customizable Timing: The session start and end times can be adjusted to fit different Asian market hours.
Visual Clarity: The pale blue shading helps to visually separate the Asian session from other trading sessions.
Easy to Use: Simple implementation with clear visual cues on the chart.
Best Use Cases
Market Analysis: Traders can use this indicator to analyze market movements and trends specific to the Asian trading session.
Trading Strategies: This tool can assist in developing and implementing trading strategies that take into account the unique characteristics of the Asian market.
Time Management: Helps traders to manage their trading schedule by clearly marking the start and end of the Asian session.
How to Use
Apply to Chart: Save and apply the indicator to your chart to see the shaded Asian session.
This indicator is particularly useful for forex traders, stock traders, and anyone looking to incorporate the Asian market's influence into their trading strategy.
Equilibrium Candles + Pattern [Honestcowboy]The Equilibrium Candles is a very simple trend continuation or reversal strategy depending on your settings.
How an Equilibrium Candle is created:
We calculate the equilibrium by measuring the mid point between highest and lowest point over X amount of bars back.
This now is the opening price for each bar and will be considered a green bar if price closes above equilibrium.
Bars get shaded by checking if regular candle close is higher than open etc. So you still see what the normal candles are doing.
Why are they useful?
The equilibrium is calculated the same as Baseline in Ichimoku Cloud. Which provides a point where price is very likely to retrace to. This script visualises the distance between close and equilibrium using candles. To provide a clear visual of how price relates to this equilibrium point.
This also makes it more straightforward to develop strategies based on this simple concept and makes the trader purely focus on this relationship and not think of any Ichimoku Cloud theories.
Script uses a very simple pattern to enter trades:
It will count how many candles have been one directional (above or below equilibrium)
Based on user input after X candles (7 by default) script shows we are in a trend (bg colors)
On the first pullback (candle closes on other side of equilibrium) it will look to enter a trade.
Places a stop order at the high of the candle if bullish trend or reverse if bearish trend.
If based on user input after X opposite candles (2 by default) order is not filled will cancel it and look for a new trend.
Use Reverse Logic:
There is a use reverse logic in the settings which on default is turned on. It will turn long orders into short orders making the stop orders become limit orders. It will use the normal long SL as target for the short. And TP as stop for the short. This to provide a means to reverse equity curve in case your pair is mean reverting by nature instead of trending.
ATR Calculation:
Averaged ATR, which is using ta.percentile_nearest_rank of 60% of a normal ATR (14 period) over the last 200 bars. This in simple words finds a value slightly above the mean ATR value over that period.
Big Candle Exit Logic:
Using Averaged ATR the script will check if a candle closes X times that ATR from the equilibrium point. This is then considered an overextension and all trades are closed.
This is also based on user input.
Simple trade management logic:
Checks if the user has selected to use TP and SL, or/and big candle exit.
Places a TP and SL based on averaged ATR at a multiplier based on user Input.
Closes trade if there is a Big Candle Exit or an opposite direction signal from indicator.
Script can be fully automated to MT5
There are risk settings in % and symbol settings provided at the bottom of the indicator. The script will send alert to MT5 broker trying to mimic the execution that happens on tradingview. There are always delays when using a bridge to MT5 broker and there could be errors so be mindful of that. This script sends alerts in format so they can be read by tradingview.to which is a bridge between the platforms.
Use the all alert function calls feature when setting up alerts and make sure you provide the right webhook if you want to use this approach.
There is also a simple buy and sell alert feature if you don't want to fully automate but still get alerts. These are available in the dropdown when creating an alert.
Almost every setting in this indicator has a tooltip added to it. So if any setting is not clear hover over the (?) icon on the right of the setting.
The backtest uses a 4% exposure per trade and a 10 point slippage. I did not include a commission cause I'm not personaly aware what the commissions are on most forex brokers. I'm only aware of minimal slippage to use in a backtest. Trading conditions vary per broker you use so always pay close attention to trading costs on your own broker. Use a full automation at your own risk and discretion and do proper backtesting.
Economic Profit (YavuzAkbay)The Economic Profit Indicator is a Pine Script™ tool for assessing a company’s economic profit based on key financial metrics like Return on Invested Capital (ROIC) and Weighted Average Cost of Capital (WACC). This indicator is designed to give traders a more accurate understanding of risk-adjusted returns.
Features
Customizable inputs for Risk-Free Rate and Corporate Tax Rate assets for people who are trading in other countries.
Calculates Economic Profit based on ROIC and WACC, with values shown as both plots and in an on-screen table.
Provides detailed breakdowns of all key calculations, enabling deeper insights into financial performance.
How to Use
Open the stock to be analyzed. In the settings, enter the risk-free asset (usually a 10-year bond) of the country where the company to be analyzed is located. Then enter the corporate tax of the country (USCTR for the USA, DECTR for Germany). Then enter the average return of the index the stock is in. I prefer 10% (0.10) for the SP500, different rates can be entered for different indices. Finally, the beta of the stock is entered. In future versions I will automatically pull beta and index returns, but in order to publish the indicator a bit earlier, I have left it entirely up to the investor.
How to Interpret
We see 3 pieces of data on the indicator. The dark blue one is ROIC, the dark orange one is WACC and the light blue line represents the difference between WACC and ROIC.
In a scenario where both ROIC and WACC are negative, if ROIC is lower than WACC, the share is at a complete economic loss.
In a scenario where both ROIC and WACC are negative, if ROIC has started to rise above WACC and is moving towards positive, the share is still in an economic loss but tending towards profit.
A scenario where ROIC is positive and WACC is negative is the most natural scenario for a company. In this scenario, we know that the company is doing well by a gradually increasing ROIC and a stable WACC.
In addition, if the ROIC and WACC difference line goes above 0, the company is now economically in net profit. This is the best scenario for a company.
My own investment strategy as a developer of the code is to look for the moment when ROIC is greater than WACC when ROIC and WACC are negative. At that point the stock is the best time to invest.
Trading is risky, and most traders lose money. The indicators Yavuz Akbay offers are for informational and educational purposes only. All content should be considered hypothetical, selected after the facts to demonstrate my product, and not constructed as financial advice. Decisions to buy, sell, hold, or trade in securities, commodities, and other investments involve risk and are best made based on the advice of qualified financial professionals. Past performance does not guarantee future results.
This indicator is experimental and will always remain experimental. The indicator will be updated by Yavuz Akbay according to market conditions.
MFI Strategy with Oversold Zone Exit and AveragingThis strategy is based on the Money Flow Index (MFI) and aims to enter a long position when the MFI exits an oversold zone, with specific rules for limit orders, stop-loss, and take-profit settings. Here's a detailed breakdown:
Key Components
1. **Money Flow Index (MFI)**: The strategy uses the MFI, a volume-weighted indicator, to gauge whether the market is in an oversold condition (default threshold of MFI < 20). Once the MFI rises above the oversold threshold, it signals a potential buying opportunity.
2. **Limit Order for Long Entry**: Instead of entering immediately after the oversold condition is cleared, the strategy places a limit order at a price slightly below the current price (by a user-defined percentage). This helps achieve a better entry price.
3. **Stop-Loss and Take-Profit**:
- **Stop-Loss**: A stop-loss is set to protect against significant losses, calculated as a percentage below the entry price.
- **Take-Profit**: A take-profit target is set as a percentage above the entry price to lock in gains.
4. **Order Cancellation**: If the limit order isn’t filled within a specific number of bars (default is 5 bars), it’s automatically canceled to avoid being filled at a potentially suboptimal price as market conditions change.
Strategy Workflow
1. **Identify Oversold Zone**: The strategy checks if the MFI falls below a defined oversold level (default is 20). Once this condition is met, the flag `inOversoldZone` is set to `true`.
2. **Wait for Exit from Oversold Zone**: When the MFI rises back above the oversold level, it’s considered a signal that the market is potentially recovering, and the strategy prepares to enter a position.
3. **Place Limit Order**: Upon exiting the oversold zone, the strategy places a limit order for a long position at a price below the current price, defined by the `Long Entry Percentage` parameter.
4. **Monitor Limit Order**: A counter (`barsSinceEntryOrder`) starts counting the bars since the limit order was placed. If the order isn’t filled within the specified number of bars, it’s canceled automatically.
5. **Set Stop-Loss and Take-Profit**: Once the order is filled, a stop-loss and take-profit are set based on user-defined percentages relative to the entry price.
6. **Exit Strategy**: The trade will close automatically when either the stop-loss or take-profit level is hit.
Advantages
- **Risk Management**: With configurable stop-loss and take-profit, the strategy ensures losses are limited while capturing profits at pre-defined levels.
- **Controlled Entry**: The use of a limit order below the current price helps secure a better entry point, enhancing risk-reward.
- **Oversold Exit Trigger**: Using the exit from an oversold zone as an entry condition can help catch reversals.
Disadvantages
- **Missed Entries**: If the limit order isn’t filled due to insufficient downward movement after the oversold signal, potential opportunities may be missed.
- **Dependency on MFI Sensitivity**: As the MFI is sensitive to both price and volume, its fluctuations might not always accurately represent oversold conditions.
Overall Purpose
The strategy is suited for traders who want to capture potential reversals after oversold conditions in the market, with a focus on precise entries, risk management, and an automated exit plan.
Pine Execution MapPine Script Execution Map
Overview:
This is an educational script for Pine Script developers. The script includes data structure, functions/methods, and process to capture and print Pine Script execution map of functions called while pine script execution.
Map of execution is produced for last/latest candle execution.
The script also has example code to call execution map methods and generate Pine Execution map.
Use cases:
Pine script developers can get view of how the functions are called
This can also be used while debugging the code and know which functions are called vs what developer expect code to do
One can use this while using any of the open source published script and understand how public script is organized and how functions of the script are called.
Code components:
User defined type
type EMAP
string group
string sub_group
int level
array emap = array.new()
method called internally by other methods to generate level of function being executed
method id(string tag) =>
if(str.startswith(tag, "MAIN"))
exe_level.set(0, 0)
else if(str.startswith(tag, "END"))
exe_level.set(0, exe_level.get(0) - 1)
else
exe_level.set(0, exe_level.get(0) + 1)
exe_level.get(0)
Method called from main/global scope to record execution of main scope code. There should be only one call to this method at the start of global scope.
method main(string tag) =>
this = EMAP.new()
this.group := "MAIN"
this.sub_group := tag
this.level := "MAIN".id()
emap.push(this)
Method called from main/global scope to record end of execution of main scope code. There should be only one call to this method at the end of global scope.
method end_main(string tag) =>
this = EMAP.new()
this.group := "END_MAIN"
this.sub_group := tag
this.level := 0
emap.push(this)
Method called from start of each function to record execution of function code
method call(string tag) =>
this = EMAP.new()
this.group := "SUB"
this.sub_group := tag
this.level := "SUB".id()
emap.push(this)
Method called from end of each function to record end of execution of function code
method end_call(string tag) =>
this = EMAP.new()
this.group := "END_SUB"
this.sub_group := tag
this.level := "END_SUB".id()
emap.push(this)
Pine code which generates execution map and show it as a label tooltip.
if(barstate.islast)
for rec in emap
if(not str.startswith(rec.group, "END"))
lvl_tab = str.repeat("", rec.level+1, "\t")
txt = str.format("=> {0} {1}> {2}", lvl_tab, rec.level, rec.sub_group)
debug.log(txt)
debug.lastr()
Snapshot 1:
This is the output of the script and can be viewed by hovering mouse pointer over the blue color diamond shaped label
Snapshot 2:
How to read the Pine execution map
Customizable BTC Seasonality StrategyThis strategy leverages intraday seasonality effects in Bitcoin, specifically targeting hours of statistically significant returns during periods when traditional financial markets are closed. Padysak and Vojtko (2022) demonstrate that Bitcoin exhibits higher-than-average returns from 21:00 UTC to 23:00 UTC, a period in which all major global exchanges, such as the New York Stock Exchange (NYSE), Tokyo Stock Exchange, and London Stock Exchange, are closed. The absence of competing trading activity from traditional markets during these hours appears to contribute to these statistically significant returns.
The strategy proceeds as follows:
Entry Time: A long position in Bitcoin is opened at a user-specified time, which defaults to 21:00 UTC, aligning with the beginning of the identified high-return window.
Holding Period: The position is held for two hours, capturing the positive returns typically observed during this period.
Exit Time: The position is closed at a user-defined time, defaulting to 23:00 UTC, allowing the strategy to exit as the favorable period concludes.
This simple seasonality strategy aims to achieve a 33% annualized return with a notably reduced volatility of 20.93% and maximum drawdown of -22.45%. The results suggest that investing only during these high-return hours is more stable and less risky than a passive holding strategy (Padysak & Vojtko, 2022).
References
Padysak, M., & Vojtko, R. (2022). Seasonality, Trend-following, and Mean reversion in Bitcoin.
SuperATR 7-Step Profit - Strategy [presentTrading] Long time no see!
█ Introduction and How It Is Different
The SuperATR 7-Step Profit Strategy is a multi-layered trading approach that integrates adaptive Average True Range (ATR) calculations with momentum-based trend detection. What sets this strategy apart is its sophisticated 7-step take-profit mechanism, which combines four ATR-based exit levels and three fixed percentage levels. This hybrid approach allows traders to dynamically adjust to market volatility while systematically capturing profits in both long and short market positions.
Traditional trading strategies often rely on static indicators or single-layered exit strategies, which may not adapt well to changing market conditions. The SuperATR 7-Step Profit Strategy addresses this limitation by:
- Using Adaptive ATR: Enhances the standard ATR by making it responsive to current market momentum.
- Incorporating Momentum-Based Trend Detection: Identifies stronger trends with higher probability of continuation.
- Employing a Multi-Step Take-Profit System: Allows for gradual profit-taking at predetermined levels, optimizing returns while minimizing risk.
BTCUSD 6hr Performance
█ Strategy, How It Works: Detailed Explanation
The strategy revolves around detecting strong market trends and capitalizing on them using an adaptive ATR and momentum indicators. Below is a detailed breakdown of each component of the strategy.
🔶 1. True Range Calculation with Enhanced Volatility Detection
The True Range (TR) measures market volatility by considering the most significant price movements. The enhanced TR is calculated as:
TR = Max
Where:
High and Low are the current bar's high and low prices.
Previous Close is the closing price of the previous bar.
Abs denotes the absolute value.
Max selects the maximum value among the three calculations.
🔶 2. Momentum Factor Calculation
To make the ATR adaptive, the strategy incorporates a Momentum Factor (MF), which adjusts the ATR based on recent price movements.
Momentum = Close - Close
Stdev_Close = Standard Deviation of Close over n periods
Normalized_Momentum = Momentum / Stdev_Close (if Stdev_Close ≠ 0)
Momentum_Factor = Abs(Normalized_Momentum)
Where:
Close is the current closing price.
n is the momentum_period, a user-defined input (default is 7).
Standard Deviation measures the dispersion of closing prices over n periods.
Abs ensures the momentum factor is always positive.
🔶 3. Adaptive ATR Calculation
The Adaptive ATR (AATR) adjusts the traditional ATR based on the Momentum Factor, making it more responsive during volatile periods and smoother during consolidation.
Short_ATR = SMA(True Range, short_period)
Long_ATR = SMA(True Range, long_period)
Adaptive_ATR = /
Where:
SMA is the Simple Moving Average.
short_period and long_period are user-defined inputs (defaults are 3 and 7, respectively).
🔶 4. Trend Strength Calculation
The strategy quantifies the strength of the trend to filter out weak signals.
Price_Change = Close - Close
ATR_Multiple = Price_Change / Adaptive_ATR (if Adaptive_ATR ≠ 0)
Trend_Strength = SMA(ATR_Multiple, n)
🔶 5. Trend Signal Determination
If (Short_MA > Long_MA) AND (Trend_Strength > Trend_Strength_Threshold):
Trend_Signal = 1 (Strong Uptrend)
Elif (Short_MA < Long_MA) AND (Trend_Strength < -Trend_Strength_Threshold):
Trend_Signal = -1 (Strong Downtrend)
Else:
Trend_Signal = 0 (No Clear Trend)
🔶 6. Trend Confirmation with Price Action
Adaptive_ATR_SMA = SMA(Adaptive_ATR, atr_sma_period)
If (Trend_Signal == 1) AND (Close > Short_MA) AND (Adaptive_ATR > Adaptive_ATR_SMA):
Trend_Confirmed = True
Elif (Trend_Signal == -1) AND (Close < Short_MA) AND (Adaptive_ATR > Adaptive_ATR_SMA):
Trend_Confirmed = True
Else:
Trend_Confirmed = False
Local Performance
🔶 7. Multi-Step Take-Profit Mechanism
The strategy employs a 7-step take-profit system
█ Trade Direction
The SuperATR 7-Step Profit Strategy is designed to work in both long and short market conditions. By identifying strong uptrends and downtrends, it allows traders to capitalize on price movements in either direction.
Long Trades: Initiated when the market shows strong upward momentum and the trend is confirmed.
Short Trades: Initiated when the market exhibits strong downward momentum and the trend is confirmed.
█ Usage
To implement the SuperATR 7-Step Profit Strategy:
1. Configure the Strategy Parameters:
- Adjust the short_period, long_period, and momentum_period to match the desired sensitivity.
- Set the trend_strength_threshold to control how strong a trend must be before acting.
2. Set Up the Multi-Step Take-Profit Levels:
- Define ATR multipliers and fixed percentage levels according to risk tolerance and profit goals.
- Specify the percentage of the position to close at each level.
3. Apply the Strategy to a Chart:
- Use the strategy on instruments and timeframes where it has been tested and optimized.
- Monitor the positions and adjust parameters as needed based on performance.
4. Backtest and Optimize:
- Utilize TradingView's backtesting features to evaluate historical performance.
- Adjust the default settings to optimize for different market conditions.
█ Default Settings
Understanding default settings is crucial for optimal performance.
Short Period (3): Affects the responsiveness of the short-term MA.
Effect: Lower values increase sensitivity but may produce more false signals.
Long Period (7): Determines the trend baseline.
Effect: Higher values reduce noise but may delay signals.
Momentum Period (7): Influences adaptive ATR and trend strength.
Effect: Shorter periods react quicker to price changes.
Trend Strength Threshold (0.5): Filters out weaker trends.
Effect: Higher thresholds yield fewer but stronger signals.
ATR Multipliers: Set distances for ATR-based exits.
Effect: Larger multipliers aim for bigger moves but may reduce hit rate.
Fixed TP Levels (%): Control profit-taking on smaller moves.
Effect: Adjusting these levels affects how quickly profits are realized.
Exit Percentages: Determine how much of the position is closed at each TP level.
Effect: Higher percentages reduce exposure faster, affecting risk and reward.
Adjusting these variables allows you to tailor the strategy to different market conditions and personal risk preferences.
By integrating adaptive indicators and a multi-tiered exit strategy, the SuperATR 7-Step Profit Strategy offers a versatile tool for traders seeking to navigate varying market conditions effectively. Understanding and adjusting the key parameters enables traders to harness the full potential of this strategy.
PDF Smoothed Moving Average [BackQuant]PDF Smoothed Moving Average
Introducing BackQuant’s PDF Smoothed Moving Average (PDF-MA) — an innovative trading indicator that applies Probability Density Function (PDF) weighting to moving averages, creating a unique, trend-following tool that offers adaptive smoothing to price movements. This advanced indicator gives traders an edge by blending PDF-weighted values with conventional moving averages, helping to capture trend shifts with enhanced clarity.
Core Concept: Probability Density Function (PDF) Smoothing
The Probability Density Function (PDF) provides a mathematical approach to applying adaptive weighting to data points based on a specified variance and mean. In the PDF-MA indicator, the PDF function is used to weight price data, adding a layer of probabilistic smoothing that enhances the detection of trend strength while reducing noise.
The PDF weights are controlled by two key parameters:
Variance: Determines the spread of the weights, where higher values spread out the weighting effect, providing broader smoothing.
Mean : Centers the weights around a particular price value, influencing the trend’s directionality and sensitivity.
These PDF weights are applied to each price point over the chosen period, creating an adaptive and smooth moving average that more closely reflects the underlying price trend.
Blending PDF with Standard Moving Averages
To further improve the PDF-MA, this indicator combines the PDF-weighted average with a traditional moving average, selected by the user as either an Exponential Moving Average (EMA) or Simple Moving Average (SMA). This blended approach leverages the strengths of each method: the responsiveness of PDF smoothing and the robustness of conventional moving averages.
Smoothing Method: Traders can choose between EMA and SMA for the additional moving average layer. The EMA is more responsive to recent prices, while the SMA provides a consistent average across the selected period.
Smoothing Period: Controls the length of the lookback period, affecting how sensitive the average is to price changes.
The result is a PDF-MA that provides a reliable trend line, reflecting both the PDF weighting and traditional moving average values, ideal for use in trend-following and momentum-based strategies.
Trend Detection and Candle Coloring
The PDF-MA includes a built-in trend detection feature that dynamically colors candles based on the direction of the smoothed moving average:
Uptrend: When the PDF-MA value is increasing, the trend is considered bullish, and candles are colored green, indicating potential buying conditions.
Downtrend: When the PDF-MA value is decreasing, the trend is considered bearish, and candles are colored red, signaling potential selling or shorting conditions.
These color-coded candles provide a quick visual reference for the trend direction, helping traders make real-time decisions based on the current market trend.
Customization and Visualization Options
This indicator offers a range of customization options, allowing traders to tailor it to their specific preferences and trading environment:
Price Source : Choose the price data for calculation, with options like close, open, high, low, or HLC3.
Variance and Mean : Fine-tune the PDF weighting parameters to control the indicator’s sensitivity and responsiveness to price data.
Smoothing Method : Select either EMA or SMA to customize the conventional moving average layer used in conjunction with the PDF.
Smoothing Period : Set the lookback period for the moving average, with a longer period providing more stability and a shorter period offering greater sensitivity.
Candle Coloring : Enable or disable candle coloring based on trend direction, providing additional clarity in identifying bullish and bearish phases.
Trading Applications
The PDF Smoothed Moving Average can be applied across various trading strategies and timeframes:
Trend Following : By smoothing price data with PDF weighting, this indicator helps traders identify long-term trends while filtering out short-term noise.
Reversal Trading : The PDF-MA’s trend coloring feature can help pinpoint potential reversal points by showing shifts in the trend direction, allowing traders to enter or exit positions at optimal moments.
Swing Trading : The PDF-MA provides a clear trend line that swing traders can use to capture intermediate price moves, following the trend direction until it shifts.
Final Thoughts
The PDF Smoothed Moving Average is a highly adaptable indicator that combines probabilistic smoothing with traditional moving averages, providing a nuanced view of market trends. By integrating PDF-based weighting with the flexibility of EMA or SMA smoothing, this indicator offers traders an advanced tool for trend analysis that adapts to changing market conditions with reduced lag and increased accuracy.
Whether you’re trading trends, reversals, or swings, the PDF-MA offers valuable insights into the direction and strength of price movements, making it a versatile addition to any trading strategy.
FS Scorpion TailKey Features & Components:
1. Custom Date & Chart-Based Controls
The software allows users to define whether they want signals to start on a specific date (useSpecificDate) or base calculations on the visible chart’s range (useRelativeScreenSumLeft and useRelativeScreenSumRight).
Users can input the number of stocks to buy/sell per signal and decide whether to sell only for profit.
2. Technical Indicators Used
EMA (Exponential Moving Average): Users can define the length of the EMA and specify if buy/sell signals should occur when the EMA is rising or falling.
MACD (Moving Average Convergence Divergence): MACD crossovers, slopes of the MACD line, signal line, and histogram are used for generating buy/sell signals.
ATR (Average True Range): Signals are generated based on rising or falling ATR.
Aroon Indicator: Buy and sell signals are based on the behavior of the Aroon upper and lower lines.
RSI (Relative Strength Index): Tracks whether the RSI and its moving average are rising or falling to generate signals.
Bollinger Bands: Buy/sell signals depend on the basis, upper, and lower band behavior (rising or falling).
3. Signal Detection
The software creates arrays for each indicator to store conditions for buy/sell signals.
The allTrue() function checks whether all conditions for buy/sell signals are true, ensuring that only valid signals are plotted.
Signals are differentiated between buy-only, sell-only, and both buy and sell (dual signal).
4. Visual Indicators
Vertical Lines: When buy, sell, or dual signals are detected, vertical lines are drawn at the corresponding bar with configurable colors (green for buy, red for sell, silver for dual).
Buy/Sell Labels: Visual labels are plotted directly on the chart to denote buy or sell signals, allowing for clear interpretation of the strategy.
5. Cash Flow & Metrics Display
The software maintains an internal ledger of how many stocks are bought/sold, their prices, and whether a profit is being made.
A table is displayed at the bottom right of the chart, showing:
Initial investment
Current stocks owned
Last buy price
Market stake
Net profit
The table background turns green for profit and red for loss.
6. Dynamic Decision Making
Buy Condition: If a valid buy signal is generated, the software decrements the cash balance and adds stocks to the inventory.
Sell Condition: If the sell signal is valid (and meets the profit requirement), stocks are sold, and cash is incremented.
A fallback check ensures the sell logic prevents selling more stocks than are available and adjusts stock holding appropriately (e.g., sell half).
Customization and Usage
Indicator Adjustments: The user can choose which indicators to activate (e.g., EMA, MACD, RSI) via input controls. Each indicator has specific customizable parameters such as lengths, slopes, and conditions.
Signal Flexibility: The user can adjust conditions for buying and selling based on various technical indicators, which adds flexibility in implementing trading strategies. For example, users may require the RSI to be higher than its moving average or trigger sales only when MACD crosses under the signal line.
Profit Sensitivity: The software allows the option to sell only when a profit is assured by checking if the current price is higher than the last buy price.
Summary of Usage:
Indicator Selection: Enable or disable technical indicators like EMA, MACD, RSI, Aroon, ATR, and Bollinger Bands to fit your trading strategy.
Custom Date/Chart Settings: Choose whether to calculate based on specific time ranges or visible portions of the chart.
Dynamic Signal Plotting: Once buy or sell conditions are met, the software will visually plot signals on your chart, giving clear entry and exit points.
Investment Tracking: Real-time tracking of stock quantities, investments, and profit ensures a clear view of your trading performance.
Backtesting: Use this software for backtesting your strategy by analyzing how buy and sell signals would have performed historically based on the chosen indicators.
Conclusion
The FS Scorpion Tail software is a robust and flexible trading tool, allowing traders to develop custom strategies based on multiple well-known technical indicators. Its visual aid, coupled with real-time investment tracking, makes it valuable for systematic traders looking to automate or refine their trading approach.
Mean Trend OscillatorMean Trend Oscillator
The Mean Trend Oscillator offers an original approach to trend analysis by integrating multiple technical indicators, using statistic to get a probable signal, and dynamically adapting to market volatility.
This tool aggregates signals from four popular indicators—Relative Strength Index (RSI), Simple Moving Average (SMA), Exponential Moving Average (EMA), and Relative Moving Average (RMA)—and adjusts thresholds using the Average True Range (ATR). By using this, we can use Statistics to aggregate or take the average of each indicators signal. Mathematically, Taking an average of these indicators gives us a better probability on entering a trending state.
By consolidating these distinct perspectives, the Mean Trend Oscillator provides a comprehensive view of market direction, helping traders make informed decisions based on a broad, data-driven trend assessment. Traders can use this indicator to enter long spot or leveraged positions. The Mean Trend Oscillator is intended to be use in long term trending markets. Scalping MUST NOT be used with this indicator. (This indicator will give false signals when the Timeframe is too low. The best intended use for high-quality signals are longer timeframes).
The current price of a beginning trend series may tell us something about the next move. Thus, the Mean Trend Oscillator allows us to spot a high probability trending market and potentially exploit this information enter long or shorts strategy. (again, this indicator will give false signals when the Timeframe is too low. The best intended use for high-quality signals are longer timeframes).
Concept and Calculation and Inputs
The Mean Trend Oscillator calculates a “net trend” score as follows:
RSI evaluates market momentum, identifying overbought and oversold conditions, essential for confirming trend direction.
SMA, EMA, and RMA introduce varied smoothing methods to capture short- to medium-term trends, balancing quick price changes with smoothed averages.
ATR-Enhanced Thresholds: ATR is used as a dynamic multiplier, adjusting each indicator’s thresholds to current volatility levels, which helps reduce noise in low-volatility conditions and emphasizes significant signals when volatility spikes.
Length could be used to adjust how quickly each indicator can more or how slower each indicator can be.
Time Coherency for Inputs: Each indicator must be calculated where each signal is relatively around the same area.
For example:
Simply:
SMA, RMA, EMA, and RSI enters long around each intended trend period. Doesn't have to be perfect, but the indicators all enter long around there.
Each indicator contributes a score (+1 for bullish and -1 for bearish), and these scores are averaged to generate the final trend score:
A positive score, shown as a green line, suggests bullish conditions.
A negative score, indicated by a red line, signifies bearish conditions.
Thus, giving us a signal to long or short.
How to Use the Mean Trend Oscillator
This indicator’s output is straightforward and can fit into various trading strategies:
Bullish Signal: A green line shows that the trend is bullish, based on a positive average score across the indicators, signaling a consideration of longing an asset.
Bearish Signal: A red line indicates bearish conditions, with an overall negative trend score, signaling a consideration to shorting an asset.
By aggregating these indicators, the Mean Trend Oscillator helps traders identify strong trends while filtering out minor fluctuations, making it a versatile tool for both short- and long-term analysis. This multi-layered, adaptive approach to trend detection sets it apart from traditional single-indicator trend tools.
MCD - Meme Coin Dominance [Da_Prof]I took the meme coins in the top 100 according to CoinMarketCap and added their market caps together and divided by TOTAL. Ultimately, I see Tradingview doing a much better job once they create a dedicated symbol for this, but in the interim, I thought this might help all you degens.
Enjoy.
Da_Prof
Alpine Predictive BandsAlpine Predictive Bands - ADX & Trend Projection is an advanced indicator crafted to estimate potential price zones and trend strength by integrating dynamic support/resistance bands, ADX-based confidence scoring, and linear regression-based price projections. Designed for adaptive trend analysis, this tool combines multi-timeframe ADX insights, volume metrics, and trend alignment for improved confidence in trend direction and reliability.
Key Calculations and Components:
Linear Regression for Price Projection:
Purpose: Provides a trend-based projection line to illustrate potential price direction.
Calculation: The Linear Regression Centerline (LRC) is calculated over a user-defined lookbackPeriod. The slope, representing the rate of price movement, is extended forward using predictionLength. This projected path only appears when the confidence score is 70% or higher, revealing a white dotted line to highlight high-confidence trends.
Adaptive Prediction Bands:
Purpose: ATR-based bands offer dynamic support/resistance zones by adjusting to volatility.
Calculation: Bands are calculated using the Average True Range (ATR) over the lookbackPeriod, multiplied by a volatilityMultiplier to adjust the width. These shaded bands expand during higher volatility, guiding traders in identifying flexible support/resistance zones.
Confidence Score (ADX, Volume, and Trend Alignment):
Purpose: Reflects the reliability of trend projections by combining ADX, volume status, and EMA alignment across multiple timeframes.
ADX Component: ADX values from the current timeframe and two higher timeframes assess trend strength on a broader scale. Strong ADX readings across timeframes boost the confidence score.
Volume Component: Volume strength is marked as “High” or “Low” based on a moving average, signaling trend participation.
Trend Alignment: EMA alignment across timeframes indicates “Bullish” or “Bearish” trends, confirming overall trend direction.
Calculation: ADX, volume, and trend alignment integrate to produce a confidence score from 0% to 100%. When the score exceeds 70%, the white projection line is activated, underscoring high-confidence trend continuations.
User Guide
Projection Line: The white dotted line, which appears only when the confidence score is 70% or higher, highlights a high-confidence trend.
Prediction Bands: Adaptive bands provide potential support/resistance zones, expanding with market volatility to help traders visualize price ranges.
Confidence Score: A high score indicates a stronger, more reliable trend and can support trend-following strategies.
Settings
Prediction Length: Determines the forward length of the projection.
Lookback Period: Sets the data range for calculating regression and ATR.
Volatility Multiplier: Adjusts the width of bands to match volatility levels.
Disclaimer: This indicator is for educational purposes and does not guarantee future price outcomes. Additional analysis is recommended, as trading carries inherent risks.
MACD Cloud with Moving Average and ATR BandsThe algorithm implements a technical analysis indicator that combines the MACD Cloud, Moving Averages (MA), and volatility bands (ATR) to provide signals on market trends and potential reversal points. It is divided into several sections:
🎨 Color Bars:
Activated based on user input.
Controls bar color display according to price relative to ATR levels and moving average (MA).
Logic:
⚫ Black: Potential bearish reversal (price above the upper ATR band).
🔵 Blue: Potential bullish reversal (price below the lower ATR band).
o
🟢 Green: Bullish trend (price between the MA and upper ATR band).
o
🔴 Red: Bearish trend (price between the lower ATR band and MA).
o
📊 MACD Bars:
Description:
The MACD Bars section is activated by default and can be modified based on user input.
🔴 Red: Indicates a bearish trend, shown when the MACD line is below the Signal line (Signal line is a moving average of MACD).
🔵 Blue: Indicates a bullish trend, shown when the MACD line is above the Signal line.
Matching colors between MACD Bars and MACD Cloud visually confirms trend direction.
MACD Cloud Logic: The MACD Cloud is based on Moving Average Convergence Divergence (MACD), a momentum indicator showing the relationship between two moving averages of price.
MACD and Signal Lines: The cloud visualizes the MACD line relative to the Signal line. If the MACD line is above the Signal line, it indicates a potential bullish trend, while below it suggests a potential bearish trend.
☁️ MA Cloud:
The MA Cloud uses three moving averages to analyze price direction:
Moving Average Relationship: Three MAs of different periods are plotted. The cloud turns green when the shorter MA is above the longer MA, indicating an uptrend, and red when below, suggesting a downtrend.
Trend Visualization: This graphical representation shows the trend direction.
📉 ATR Bands:
The ATR bands calculate overbought and oversold limits using a weighted moving average (WMA) and ATR.
Center (matr): Shows general trend; prices above suggest an uptrend, while below indicate a downtrend.
Up ATR 1: Marks the first overbought level, suggesting a potential bearish reversal if the price moves above this band.
Down ATR 1: Marks the first oversold level, suggesting a possible bullish reversal if the price moves below this band.
Up ATR 2: Extends the overbought range to an extreme, reinforcing the possibility of a bearish reversal at this level.
Down ATR 2: Extends the oversold range to an extreme, indicating a stronger bullish reversal possibility if price reaches here.
Español:
El algoritmo implementa un indicador de análisis técnico que combina la nube MACD, promedios móviles (MA) y bandas de volatilidad (ATR) para proporcionar señales sobre tendencias del mercado y posibles puntos de reversión. Se divide en varias secciones:
🎨 Barras de Color:
- Activado según la entrada del usuario.
- Controla la visualización del color de las barras según el precio en relación con los niveles de ATR y el promedio móvil (MA).
- **Lógica:**
- ⚫ **Negro**: Reversión bajista potencial (precio por encima de la banda superior ATR).
- 🔵 **Azul**: Reversión alcista potencial (precio por debajo de la banda inferior ATR).
- 🟢 **Verde**: Tendencia alcista (precio entre el MA y la banda superior ATR).
- 🔴 **Rojo**: Tendencia bajista (precio entre la banda inferior ATR y el MA).
### 📊 Barras MACD:
- **Descripción**:
- La sección de barras MACD se activa por defecto y puede modificarse según la entrada del usuario.
- 🔴 **Rojo**: Indica una tendencia bajista, cuando la línea MACD está por debajo de la línea de señal (la línea de señal es una media móvil de la MACD).
- 🔵 **Azul**: Indica una tendencia alcista, cuando la línea MACD está por encima de la línea de señal.
- La coincidencia de colores entre las barras MACD y la nube MACD confirma visualmente la dirección de la tendencia.
### 🌥️ Nube MACD:
- **Lógica de la Nube MACD**: Basada en el indicador de convergencia-divergencia de medias móviles (MACD), que muestra la relación entre dos medias móviles del precio.
- **Líneas MACD y de Señal**: La nube visualiza la relación entre la línea MACD y la línea de señal. Si la línea MACD está por encima de la de señal, indica una tendencia alcista potencial; si está por debajo, sugiere una tendencia bajista.
### ☁️ Nube MA:
- **Relación entre Medias Móviles**: Se trazan tres medias móviles de diferentes períodos. La nube se vuelve verde cuando la media más corta está por encima de la más larga, indicando una tendencia alcista, y roja cuando está por debajo, sugiriendo una tendencia bajista.
- **Visualización de Tendencias**: Proporciona una representación gráfica de la dirección de la tendencia.
### 📉 Bandas ATR:
- Las bandas ATR calculan límites de sobrecompra y sobreventa usando una media ponderada y el ATR.
- **Centro (matr)**: Muestra la tendencia general; precios por encima indican tendencia alcista y debajo, bajista.
- **Up ATR 1**: Marca el primer nivel de sobrecompra, sugiriendo una reversión bajista potencial si el precio sube por encima de esta banda.
- **Down ATR 1**: Marca el primer nivel de sobreventa, sugiriendo una reversión alcista potencial si el precio baja por debajo de esta banda.
- **Up ATR 2**: Amplía el rango de sobrecompra a un nivel extremo, reforzando la posibilidad de reversión bajista.
- **Down ATR 2**: Extiende el rango de sobreventa a un nivel extremo, sugiriendo una reversión alcista más fuerte si el precio alcanza esta banda.
Austin's Apex AcceleratorIndicator Name: Austin’s Apex Accelerator
Overview
The Austin’s Apex Accelerator is a highly aggressive trading indicator designed specifically for high-frequency Forex trading. It combines several technical analysis tools to identify rapid entry and exit points, making it well-suited for intraday or even lower timeframe trades. The indicator leverages a combination of exponential moving averages (EMAs), Bollinger Bands, volume filters, and volatility-adjusted ranges to detect breakout opportunities and manage risk with precision.
Core Components
Fast and Slow EMAs: The two EMAs act as trend and momentum indicators. When the shorter EMA crosses the longer EMA, it signals a change in momentum. The crossover of these EMAs often indicates a potential entry point, especially when combined with volume and volatility filters.
ATR-Based Range Filter: Using the Average True Range (ATR) for dynamic range calculation, the indicator adapts to market volatility. Higher ATR values widen the range, helping the indicator adjust for volatile conditions.
Volume Filter: A volume condition ensures that buy and sell signals only trigger when there’s significant market interest, reducing the likelihood of false signals in low-liquidity environments.
Bollinger Bands: The Bollinger Bands provide additional context for potential overbought or oversold conditions, highlighting opportunities for price reversals or trend continuations.
Key Features
Aggressive Buy and Sell Signals:
Buy Signal: A buy signal is generated when the fast EMA crosses above the slow EMA, confirming bullish momentum, and the volume condition is met. If the price is also near the lower Bollinger Band, it adds further confirmation of an oversold condition.
Sell Signal: A sell signal is generated when the fast EMA crosses below the slow EMA, confirming bearish momentum, with sufficient trading volume. If the price is near the upper Bollinger Band, it signals a potential overbought condition, which supports the sell signal.
Dynamic Range with ATR:
The indicator uses a volatility-based range, derived from the ATR, to adjust the signal sensitivity based on recent price fluctuations. This dynamic range ensures that signals are responsive in both high and low volatility conditions.
The range’s upper and lower bands act as thresholds, with trades often occurring when the price breaches these levels, signaling momentum shifts or trend reversals.
Trend Background Color:
A green background highlights bullish trends when the fast EMA is above the slow EMA.
A red background signifies bearish trends when the fast EMA is below the slow EMA, providing a visual indication of the overall market trend direction.
Trend Line:
The indicator plots a dynamic trend line that changes color based on the price's relationship to the EMAs, helping traders quickly assess the current trend’s strength and direction.
Alerts:
The indicator includes configurable alerts for buy and sell signals, allowing traders to be notified of entry opportunities without needing to monitor the chart continuously.
How to Use Austin’s Apex Accelerator
Identify Entry Points:
Buy Entry: When the fast EMA crosses above the slow EMA, a buy signal is triggered. Confirm this signal by checking if the price is near or below the lower Bollinger Band (indicating an oversold condition) and if trading volume meets the set threshold.
Sell Entry: When the fast EMA crosses below the slow EMA, a sell signal is triggered. Confirm the signal by ensuring the price is near or above the upper Bollinger Band (suggesting an overbought condition) and that volume is sufficient.
Exit Strategy:
Take Profit: The take profit level is calculated as 1.5 times the ATR from the entry point. This ensures that each trade aims to achieve a positive risk/reward ratio.
Stop Loss: The stop loss is set at 1 ATR from the entry, providing a tight risk control mechanism that limits potential losses on each trade.
Trend Identification and Background Colors:
Use the background colors to assess the trend direction. A green background indicates a bullish trend, while a red background suggests a bearish trend. These colors can help you filter signals that go against the trend, increasing the chances of a successful trade.
Volume Confirmation:
This indicator has an inbuilt volume filter to prevent trading in low-volume conditions. Look for signals only when volume exceeds the average volume threshold, which is set by the multiplier. This helps avoid trading during quieter times when false signals are more likely.
Alerts:
Set up alerts for buy and sell signals to be notified in real-time whenever a new trading opportunity arises, so you can act on high-quality signals promptly.
Practical Tips for Using Austin’s Apex Accelerator
Timeframe: Best suited for short timeframes such as 5-minute or 15-minute charts for high-frequency trading.
CustomAlertLibLibrary "CustomAlertLib"
Custom alert formatting library
customAlert(format, message, freq)
Formats and triggers custom alerts with placeholders
Parameters:
format (string) : String containing the alert format template
message (string) : String containing the alert message
freq (simple string) : (optional) Alert frequency as string, defaults to "once_per_bar_close"
Returns: void
BTC Dominance Trend CheckerThis monitors the Bitcoin dominance (BTC.D) in the market. It retrieves the current and previous day's BTC dominance values, determines whether dominance is increasing or decreasing, and visually displays the trend.
Valid Pullbacks and Trend by kpt. GonzoThis script helps identify valid pullbacks. Based on the marked pullbacks, it can draw both internal and external structure trendlines.
A pullback is marked with a small triangle above or below the candle that created the local high or low.
A new local high is marked with a red triangle above the candle if at least one subsequent candle has a low lower than the low of the candle that created the new local high.
A new local low is marked with a green triangle below the candle if at least one subsequent candle has a high higher than the high of the candle that created the new local low.
Based on the marked local highs and lows, the internal structure trendline is created by simply connecting all highs and lows with a line.
The external structure is drawn in a similar way, but only highs and lows that have broken the previous structure are connected. This helps focus on important pivots and better understand the market structure.
Performance Summary and Shading (Offset Version)Modified "Recession and Crisis Shading" Indicator by @haribotagada (Original Link: )
The updated indicator accepts a days offset (positive or negative) to calculate performance between the offset date and the input date.
Potential uses include identifying performance one week after company earnings or an FOMC meeting.
This feature simplifies input by enabling standardized offset dates, while still allowing flexibility to adjust ranges by overriding inputs as needed.
Summary of added features and indicator notes:
Inputs both positive and negative offset.
By default, the script calculates performance from the close of the input date to the close of the date at (input date + offset) for positive offsets, and from the close of (input date - offset) to the close of the input date for negative offsets. For example, with an input date of November 1, 2024, an offset of 7 calculates performance from the close on November 1 to the close on November 8, while an offset of -7 calculates from the close on October 25 to the close on November 1.
Allows user to perform the calculation using the open price on the input date instead of close price
The input format has been modified to allow overrides for the default duration, while retaining the original capabilities of the indicator.
The calculation shows both the average change and the average annualized change. For bar-wise calculations, annualization assumes 252 trading days per year. For date-wise calculations, it assumes 365 days for annualization.
Carries over all previous inputs to retain functionality of the previous script. Changes a few small settings:
Calculates start to end date performance by default instead of peak to trough performance.
Updates visuals of label text to make it easier to read and less transparent.
Changed stat box color scheme to make the text easier to read
Updated default input data to new format of input with offsets
Changed default duration statistic to number of days instead of number of bars with an option to select number of bars.
Potential Features to Add:
Import dataset from CSV files or by plugging into TradingView calendar
Example Input Datasets:
Recessions:
2020-02-01,COVID-19,59
2007-12-01,Subprime mortgages,547
2001-03-01,Dot-com,243
1990-07-01,Oil shock,243
1981-07-01,US unemployment,788
1980-01-01,Volker,182
1973-11-01,OPEC,485
Japan Revolving Door Elections
2006-09-26, Shinzo Abe
2007-09-26, Yasuo Fukuda
2008-09-24, Taro Aso
2009-09-16, Yukio Hatoyama
2010-07-08, Naoto Kan
2011-09-02, Yoshihiko Noda
Hope you find the modified indicator useful and let me know if you would like any features to be added!