Global Index Spread RSI StrategyThis strategy leverages the relative strength index (RSI) to monitor the price spread between a global benchmark index (such as AMEX) and the currently opened asset in the chart window. By calculating the spread between these two, the strategy uses RSI to identify oversold and overbought conditions to trigger buy and sell signals.
Key Components:
Global Benchmark Index: The strategy compares the current asset with a predefined global index (e.g., AMEX) to measure relative performance. The choice of a global benchmark allows the trader to analyze the current asset's movement in the context of broader market trends.
Spread Calculation:
The spread is calculated as the percentage difference between the current asset's closing price and the global benchmark index's closing price:
Spread=Current Asset Close−Global Index CloseGlobal Index Close×100
Spread=Global Index CloseCurrent Asset Close−Global Index Close×100
This metric provides a measure of how the current asset is performing relative to the global index. A positive spread indicates the asset is outperforming the benchmark, while a negative spread signals underperformance.
RSI of the Spread: The RSI is then calculated on the spread values. The RSI is a momentum oscillator that ranges from 0 to 100 and is commonly used to identify overbought or oversold conditions in asset prices. An RSI below 30 is considered oversold, indicating a potential buying opportunity, while an RSI above 70 is overbought, suggesting that the asset may be due for a pullback.
Strategy Logic:
Entry Condition: The strategy enters a long position when the RSI of the spread falls below the oversold threshold (default 30). This suggests that the asset may have been oversold relative to the global benchmark and might be due for a reversal.
Exit Condition: The strategy exits the long position when the RSI of the spread rises above the overbought threshold (default 70), indicating that the asset may have become overbought and a price correction is likely.
Visual Reference:
The RSI of the spread is plotted on the chart for visual reference, making it easier for traders to monitor the relative strength of the asset in relation to the global benchmark.
Overbought and oversold levels are also drawn as horizontal reference lines (70 and 30), along with a neutral level at 50 to show market equilibrium.
Theoretical Basis:
The strategy is built on the mean reversion principle, which suggests that asset prices tend to revert to a long-term average over time. When prices move too far from this mean—either being overbought or oversold—they are likely to correct back toward equilibrium. By using RSI to identify these extremes, the strategy aims to profit from price reversals.
Mean Reversion: According to financial theory, asset prices oscillate around a long-term average, and any extreme deviation (overbought or oversold conditions) presents opportunities for price corrections (Poterba & Summers, 1988).
Momentum Indicators (RSI): The RSI is widely used in technical analysis to measure the momentum of an asset. Its application to the spread between the asset and a global benchmark allows for a more nuanced view of relative performance and potential turning points in the asset's price trajectory.
Practical Application:
This strategy works best in markets where relative strength is a key factor in decision-making, such as in equity indices, commodities, or forex markets. By assessing the performance of the asset relative to a global benchmark and utilizing RSI to identify extremes in price movements, the strategy helps traders to make more informed decisions based on potential mean reversion points.
While the "Global Index Spread RSI Strategy" offers a method for identifying potential price reversals based on relative strength and oversold/overbought conditions, it is important to recognize that no strategy is foolproof. The strategy assumes that the historical relationship between the asset and the global benchmark will hold in the future, but financial markets are subject to a wide array of unpredictable factors that can lead to sudden changes in price behavior.
Risk of False Signals:
The strategy relies heavily on the RSI to trigger buy and sell signals. However, like any momentum-based indicator, RSI can generate false signals, particularly in highly volatile or trending markets. In such conditions, the strategy may enter positions too early or exit too late, leading to potential losses.
Market Context:
The strategy may not account for macroeconomic events, news, or other market forces that could cause sudden shifts in asset prices. External factors, such as geopolitical developments, monetary policy changes, or financial crises, can cause a divergence between the asset and the global benchmark, leading to incorrect conclusions from the strategy.
Overfitting Risk:
As with any strategy that uses historical data to make decisions, there is a risk of overfitting the model to past performance. This could result in a strategy that works well on historical data but performs poorly in live trading conditions due to changes in market dynamics.
Execution Risks:
The strategy does not account for slippage, transaction costs, or liquidity issues, which can impact the execution of trades in real-market conditions. In fast-moving markets, prices may move significantly between order placement and execution, leading to worse-than-expected entry or exit prices.
No Guarantee of Profit:
Past performance is not necessarily indicative of future results. The strategy should be used with caution, and risk management techniques (such as stop losses and position sizing) should always be implemented to protect against significant losses.
Traders should thoroughly test and adapt the strategy in a simulated environment before applying it to live trades, and consider seeking professional advice to ensure that their trading activities align with their risk tolerance and financial goals.
References:
Poterba, J. M., & Summers, L. H. (1988). Mean Reversion in Stock Prices: Evidence and Implications. Journal of Financial Economics, 22(1), 27-59.
Göstergeler ve stratejiler
Adaptive Squeeze Momentum StrategyThe Adaptive Squeeze Momentum Strategy is a versatile trading algorithm designed to capitalize on periods of low volatility that often precede significant price movements. By integrating multiple technical indicators and customizable settings, this strategy aims to identify optimal entry and exit points for both long and short positions.
Key Features:
Long/Short Trade Control:
Toggle Options: Easily enable or disable long and short trades according to your trading preferences or market conditions.
Flexible Application: Adapt the strategy for bullish, bearish, or neutral market outlooks.
Squeeze Detection Mechanism:
Bollinger Bands and Keltner Channels: Utilizes the convergence of Bollinger Bands inside Keltner Channels to detect "squeeze" conditions, indicating a potential breakout.
Dynamic Squeeze Length: Calculates the average squeeze duration to adapt to changing market volatility.
Momentum Analysis:
Linear Regression: Applies linear regression to price changes over a specified momentum length to gauge the strength and direction of momentum.
Dynamic Thresholds: Sets momentum thresholds based on standard deviations, allowing for adaptive sensitivity to market movements.
Momentum Multiplier: Adjustable setting to fine-tune the aggressiveness of momentum detection.
Trend Filtering:
Exponential Moving Average (EMA): Implements a trend filter using an EMA to align trades with the prevailing market direction.
Customizable Length: Adjust the EMA length to suit different trading timeframes and assets.
Relative Strength Index (RSI) Filtering:
Overbought/Oversold Signals: Incorporates RSI to avoid entering trades during overextended market conditions.
Adjustable Levels: Set your own RSI oversold and overbought thresholds for personalized signal generation.
Advanced Risk Management:
ATR-Based Stop Loss and Take Profit:
Adaptive Levels: Uses the Average True Range (ATR) to set stop loss and take profit points that adjust to market volatility.
Custom Multipliers: Modify ATR multipliers for both stop loss and take profit to control risk and reward ratios.
Minimum Volatility Filter: Ensures trades are only taken when market volatility exceeds a user-defined minimum, avoiding periods of low activity.
Time-Based Exit:
Holding Period Multiplier: Defines a maximum holding period based on the momentum length to reduce exposure to adverse movements.
Automatic Position Closure: Closes positions after the specified holding period is reached.
Session Filtering:
Trading Session Control: Limits trading to predefined market hours, helping to avoid illiquid periods.
Custom Session Times: Set your preferred trading session to match market openings, closings, or specific timeframes.
Visualization Tools:
Indicator Plots: Displays Bollinger Bands, Keltner Channels, and trend EMA on the chart for visual analysis.
Squeeze Signals: Marks squeeze conditions on the chart, providing clear visual cues for potential trade setups.
Customization Options:
Indicator Parameters: Fine-tune lengths and multipliers for Bollinger Bands, Keltner Channels, momentum calculation, and ATR.
Entry Filters: Choose to use trend and RSI filters to refine trade entries based on your strategy.
Risk Management Settings: Adjust stop loss, take profit, and holding periods to match your risk tolerance.
Trade Direction Control: Enable or disable long and short trades independently to align with your market strategy or compliance requirements.
Time Settings: Modify the trading session times and enable or disable the time filter as needed.
Use Cases:
Trend Traders: Benefit from aligning entries with the broader market trend while capturing breakout movements.
Swing Traders: Exploit periods of low volatility leading to significant price swings.
Risk-Averse Traders: Utilize advanced risk management features to protect capital and manage exposure.
Disclaimer:
This strategy is a tool to assist in trading decisions and should be used in conjunction with other analyses and risk management practices. Past performance is not indicative of future results. Always test the strategy thoroughly and adjust settings to suit your specific trading style and market conditions.
Buy When There's Blood in the Streets StrategyStatistical Analysis of Drawdowns in Stock Markets
Drawdowns, defined as the decline from a peak to a trough in asset prices, are an essential measure of risk and market dynamics. Their statistical properties provide insights into market behavior during extreme stress periods.
Distribution of Drawdowns: Research suggests that drawdowns follow a power-law distribution, implying that large drawdowns, while rare, are more frequent than expected under normal distributions (Sornette et al., 2003).
Impacts of Extreme Drawdowns: During significant drawdowns (e.g., financial crises), the average recovery time is significantly longer, highlighting market inefficiencies and behavioral biases. For example, the 2008 financial crisis led to a 57% drawdown in the S&P 500, requiring years to recover (Cont, 2001).
Using Standard Deviations: Drawdowns exceeding two or three standard deviations from their historical mean are often indicative of market overreaction or capitulation, creating contrarian investment opportunities (Taleb, 2007).
Behavioral Finance Perspective: Investors often exhibit panic-selling during drawdowns, leading to oversold conditions that can be exploited using statistical thresholds like standard deviations (Kahneman, 2011).
Practical Implications: Studies on mean reversion show that extreme drawdowns are frequently followed by periods of recovery, especially in equity markets. This underpins strategies that "buy the dip" under specific, statistically derived conditions (Jegadeesh & Titman, 1993).
References:
Sornette, D., & Johansen, A. (2003). Stock market crashes and endogenous dynamics.
Cont, R. (2001). Empirical properties of asset returns: stylized facts and statistical issues. Quantitative Finance.
Taleb, N. N. (2007). The Black Swan: The Impact of the Highly Improbable.
Kahneman, D. (2011). Thinking, Fast and Slow.
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency.
SMB MagicSMB Magic
Overview: SMB Magic is a powerful technical strategy designed to capture breakout opportunities based on price movements, volume spikes, and trend-following logic. This strategy works exclusively on the XAU/USD symbol and is optimized for the 15-minute time frame. By incorporating multiple factors, this strategy identifies high-probability trades with a focus on risk management.
Key Features:
Breakout Confirmation:
This strategy looks for price breakouts above the previous high or below the previous low, with a significant volume increase. A breakout is considered valid when it is supported by strong volume, confirming the strength of the price move.
Price Movement Filter:
The strategy ensures that only significant price movements are considered for trades, helping to avoid low-volatility noise. This filter targets larger price swings to maximize potential profits.
Exponential Moving Average (EMA):
A long-term trend filter is applied to ensure that buy trades occur only when the price is above the moving average, and sell trades only when the price is below it.
Fibonacci Levels:
Custom Fibonacci retracement levels are drawn based on recent price action. These levels act as dynamic support and resistance zones and help determine the exit points for trades.
Take Profit/Stop Loss:
The strategy incorporates predefined take profit and stop loss levels, designed to manage risk effectively. These levels are automatically applied to trades and are adjusted based on the market's volatility.
Volume Confirmation:
A volume multiplier confirms the strength of the breakout. A trade is only considered when the volume exceeds a certain threshold, ensuring that the breakout is supported by sufficient market participation.
How It Works:
Entry Signals:
Buy Signal: A breakout above the previous high, accompanied by significant volume and price movement, occurs when the price is above the trend-following filter (e.g., EMA).
Sell Signal: A breakout below the previous low, accompanied by significant volume and price movement, occurs when the price is below the trend-following filter.
Exit Strategy:
Each position (long or short) has predefined take-profit and stop-loss levels, which are designed to protect capital and lock in profits at key points in the market.
Fibonacci Levels:
Fibonacci levels are drawn to identify potential areas of support or resistance, which can be used to guide exits and stop-loss placements.
Important Notes:
Timeframe Restriction: This strategy is designed specifically for the 15-minute time frame.
Symbol Restriction: The strategy works exclusively on the XAU/USD (Gold) symbol and is not recommended for use with other instruments.
Best Performance in Trending Markets: It works best in trending conditions where breakouts occur frequently.
Disclaimer:
Risk Warning: Trading involves risk, and past performance is not indicative of future results. Always conduct your own research and make informed decisions before trading.
XAUUSD Trend Strategy### Description of the XAUUSD Trading Strategy with Pine Script
This strategy is designed to trade gold (**XAUUSD**) using proven technical analysis principles. It combines key indicators such as **Exponential Moving Averages (EMA)**, the **Relative Strength Index (RSI)**, and **Bollinger Bands** to identify trading opportunities in trending market conditions.
---
#### Objective:
To maximize profits by identifying trend-aligned entry points while minimizing risks through well-defined Stop Loss and Take Profit levels.
---
### How It Works
1. **Indicators Used:**
- **Exponential Moving Averages (EMA):** Tracks short-term and long-term trends to confirm market direction.
- **Relative Strength Index (RSI):** Detects overbought or oversold conditions for potential reversals or trend continuation.
- **Bollinger Bands:** Measures volatility to identify breakout or reversion points.
2. **Entry Rules:**
- **Long (Buy):** Triggered when:
- The short-term EMA crosses above the long-term EMA (bullish trend confirmation).
- RSI exits oversold territory (<30), signaling buying momentum.
- The price breaks above the upper Bollinger Band, indicating a strong trend.
- **Short (Sell):** Triggered when:
- The short-term EMA crosses below the long-term EMA (bearish trend confirmation).
- RSI exits overbought territory (>70), signaling selling momentum.
- The price breaks below the lower Bollinger Band, indicating a strong downtrend.
3. **Risk Management:**
- **Stop Loss:** Automatically calculated based on a percentage of equity risk (customizable via inputs).
- **Take Profit:** Defined using a risk-to-reward ratio, ensuring consistent profitability when trades succeed.
4. **Visualization:**
- The chart displays the EMAs, Bollinger Bands, and entry/exit points for clear analysis.
---
### Key Features:
- **Customizable Parameters:** You can adjust EMAs, RSI thresholds, Bollinger Band settings, and risk levels to suit your trading style.
- **Alerts:** Automatic alerts for potential trade setups.
- **Backtesting-Ready:** Easily test historical performance on TradingView.
---
This strategy is ideal for gold traders looking for a systematic, rule-based approach to trading trends with minimal emotional interference.
STRATEGY Fibonacci Levels with High/Low Criteria - AYNET
Here is an explanation of the Fibonacci Levels Strategy with High/Low Criteria script:
Overview
This strategy combines Fibonacci retracement levels with high/low criteria to generate buy and sell signals based on price crossing specific thresholds. It utilizes higher timeframe (HTF) candlesticks and user-defined lookback periods for high/low levels.
Key Features
Higher Timeframe Integration:
The script calculates the open, high, low, and close values of the higher timeframe (HTF) candlestick.
Users can choose to calculate levels based on the current or the last HTF candle.
Fibonacci Levels:
Fibonacci retracement levels are dynamically calculated based on the HTF candlestick's range (high - low).
Users can customize the levels (0.000, 0.236, 0.382, 0.500, 0.618, 0.786, 1.000).
High/Low Lookback Criteria:
The script evaluates the highest high and lowest low over user-defined lookback periods.
These levels are plotted on the chart for visual reference.
Trade Signals:
Long Signal: Triggered when the close price crosses above both:
The lowest price criteria (lookback period).
The Fibonacci level 3 (default: 0.5).
Short Signal: Triggered when the close price crosses below both:
The highest price criteria (lookback period).
The Fibonacci level 3 (default: 0.5).
Visualization:
Plots Fibonacci levels and high/low criteria on the chart for easy interpretation.
Inputs
Higher Timeframe:
Users can select the timeframe (default: Daily) for the HTF candlestick.
Option to calculate based on the current or last HTF candle.
Lookback Periods:
lowestLookback: Number of bars for the lowest low calculation (default: 20).
highestLookback: Number of bars for the highest high calculation (default: 10).
Fibonacci Levels:
Fully customizable Fibonacci levels ranging from 0.000 to 1.000.
Visualization
Fibonacci Levels:
Plots six customizable Fibonacci levels with distinct colors and transparency.
High/Low Criteria:
Plots the highest and lowest levels based on the lookback periods as reference lines.
Trading Logic
Long Condition:
Price must close above:
The lowest price criteria (lowcriteria).
The Fibonacci level 3 (50% retracement).
Short Condition:
Price must close below:
The highest price criteria (highcriteria).
The Fibonacci level 3 (50% retracement).
Use Case
Trend Reversal Strategy:
Combines Fibonacci retracement with recent high/low criteria to identify potential reversal or breakout points.
Custom Timeframe Analysis:
Incorporates higher timeframe data for multi-timeframe trading strategies.
Balthazar by Aloupay📈 BALTHAZAR BY ALOUPAY: Advanced Trading Strategy for Precision and Reliability
BALTHAZAR BY ALOUPAY is a comprehensive trading strategy developed for TradingView, designed to assist traders in making informed and strategic trading decisions. By integrating multiple technical indicators, this strategy aims to identify optimal entry and exit points, manage risk effectively, and enhance overall trading performance.
🌟 Key Features
1. Integrated Indicator Suite
Exponential Moving Averages (EMAs) : Utilizes Fast (12), Medium (26), and Slow (50) EMAs to determine trend direction and strength.
Stochastic RSI : Employs Stochastic RSI with customizable smoothing periods to assess momentum and potential reversal points.
Average True Range (ATR) : Calculates dynamic stop loss and take profit levels based on market volatility using ATR multipliers.
MACD Confirmation : Incorporates MACD histogram analysis to validate trade signals, enhancing the reliability of entries.
2. Customizable Backtesting Parameters
Date Range Selection: Allows users to define specific backtesting periods to evaluate strategy performance under various market conditions.
Timezone Adaptability: Ensures accurate time-based filtering in alignment with the chart's timezone settings.
3. Advanced Risk Management
Dynamic Stop Loss & Take Profit: Automatically adjusts exit points using ATR multipliers to adapt to changing market volatility.
Position Sizing: Configurable to risk a sustainable percentage of equity per trade (recommended: 5-10%) to maintain disciplined money management.
4. Clear Trade Signals
Long & Short Entries: Generates actionable signals based on the convergence of EMA alignment, Stochastic RSI crossovers, and MACD confirmation.
Automated Exits: Implements predefined take profit and stop loss levels to secure profits and limit losses without emotional interference.
5. Visual Enhancements
EMA Visualization: Displays Fast, Medium, and Slow EMAs on the chart for easy trend identification.
Stochastic RSI Indicators: Uses distinct shapes to indicate bullish and bearish momentum shifts.
Risk Levels Display: Clearly marks take profit and stop loss levels on the chart for transparent risk-reward assessment.
🔍 Strategy Mechanics
Trend Identification with EMAs
Bullish Trend: Fast EMA (12) > Medium EMA (26) > Slow EMA (50)
Bearish Trend: Fast EMA (12) < Medium EMA (26) < Slow EMA (50)
Momentum Confirmation with Stochastic RSI
Bullish Signal: %K line crosses above %D line, indicating upward momentum.
Bearish Signal: %K line crosses below %D line, signaling downward momentum.
Volatility-Based Risk Management with ATR
Stop Loss: Positioned at 1.0 ATR below (for long) or above (for short) the entry price.
Take Profit: Positioned at 4.0 ATR above (for long) or below (for short) the entry price.
MACD Confirmation
Long Trades: Executed only when the MACD histogram is positive.
Short Trades: Executed only when the MACD histogram is negative.
💱 Recommended Forex Pairs
While BALTHAZAR BY ALOUPAY has shown robust performance on the 4-hour timeframe for Gold (XAU/USD), it is also well-suited for the following highly liquid forex pairs:
EUR/USD (Euro/US Dollar)
GBP/USD (British Pound/US Dollar)
USD/JPY (US Dollar/Japanese Yen)
AUD/USD (Australian Dollar/US Dollar)
USD/CAD (US Dollar/Canadian Dollar)
NZD/USD (New Zealand Dollar/US Dollar)
EUR/GBP (Euro/British Pound)
These pairs offer high liquidity and favorable trading conditions that complement the strategy's indicators and risk management features.
⚙️ Customization Options
Backtesting Parameters
Start Date: Define the beginning of the backtesting period.
End Date: Define the end of the backtesting period.
EMAs Configuration
Fast EMA Length: Default is 12.
Medium EMA Length: Default is 26.
Slow EMA Length: Default is 50.
Source: Default is Close price.
Stochastic RSI Configuration
%K Smoothing: Default is 5.
%D Smoothing: Default is 4.
RSI Length: Default is 14.
Stochastic Length: Default is 14.
RSI Source: Default is Close price.
ATR Configuration
ATR Length: Default is 14.
ATR Smoothing Method: Options include RMA, SMA, EMA, WMA (default: RMA).
Stop Loss Multiplier: Default is 1.0 ATR.
Take Profit Multiplier: Default is 4.0 ATR.
MACD Configuration
MACD Fast Length: Default is 12.
MACD Slow Length: Default is 26.
MACD Signal Length: Default is 9.
📊 Why Choose BALTHAZAR BY ALOUPAY?
Comprehensive Integration: Combines trend, momentum, and volatility indicators for a multifaceted trading approach.
Automated Precision: Eliminates emotional decision-making with rule-based entry and exit signals.
Robust Risk Management: Protects capital through dynamic stop loss and take profit levels tailored to market conditions.
User-Friendly Customization: Easily adjustable settings to align with individual trading styles and risk tolerance.
Proven Reliability: Backtested over extensive periods across various market environments to ensure consistent performance.
Disclaimer : Trading involves significant risk of loss and is not suitable for every investor. Past performance is not indicative of future results. Always conduct your own research and consider your financial situation before engaging in trading activities.
Zero-Lag MA Trend FollowingScript Name: Zero-Lag MA Trend Following Auto-Trading
Purpose and Unique Features:
This script is designed to implement a trend-following auto-trading strategy by combining the Zero-Lag Moving Average (ZLMA), Exponential Moving Average (EMA), and ATR Bands. To differentiate it from similar scripts, the following key aspects are emphasized:
Zero-Lag MA (ZLMA):
Responds quickly to price changes, minimizing lag compared to EMA.
Detects crossovers with EMA and generates Diamond Signals to indicate trend reversals.
ATR Bands:
Measures market volatility to set stop-loss levels.
Helps optimize entry points and manage risk effectively.
Diamond Signals:
A vital visual cue indicating the early stages of trend reversals.
Green diamonds signal an uptrend, while red diamonds signal a downtrend.
Each component plays a distinct role, working synergistically to enhance trend detection and risk management. This system doesn’t merely combine indicators but optimizes them for comprehensive trend-following and risk control.
Usage Instructions:
Entry Conditions:
Long Entry:
Enter when a green Diamond Signal appears (ZLMA crosses above EMA).
Short Entry:
Enter when a red Diamond Signal appears (ZLMA crosses below EMA).
Exit Conditions:
Stop Loss:
Set at the lower boundary of the ATR band for BUY or the upper boundary for SELL at entry.
Take Profit:
Automatically executed based on a 1:2 risk-reward ratio.
Account Size: ¥100,0000
Commissions and Slippage: Assumed commission of 90 pips per trade and slippage of 1 pip.
Risk per Trade: 10% of account equity (adjustable based on risk tolerance).
Improvements and Original Features:
While based on open-source code, this script incorporates the following critical enhancements:
Diamond Signals from ZLMA and EMA Integration:
Improves entry accuracy with a proprietary trend detection strategy.
ATR Bands Utilization:
Adds a volatility-based risk management function.
Optimized Visual Entry Signals:
Includes plotted triangles (▲, ▼) to clearly indicate trend-following entry points.
Credits:
This script builds upon indicators developed by ChartPrime, whose innovative approach and insights have enabled a more advanced trend-following strategy. We extend our gratitude for their foundational work.
Additionally, it integrates technical methods based on Zero-Lag Moving Average (ZLMA), EMA, and ATR Bands, leveraging insights from the trading community.
Chart Display Options:
The script offers options to toggle the visual signals (Diamond Signals, trend lines, and entry points) on or off, keeping the chart clean while maximizing analytical efficiency.
Disclaimer:
This script is provided for educational purposes and past performance does not guarantee future results.
Use it responsibly with proper risk management.
Fibonacci Levels Strategy with High/Low Criteria-AYNETThis code represents a TradingView strategy that uses Fibonacci levels in conjunction with high/low price criteria over specified lookback periods to determine buy (long) and sell (short) conditions. Below is an explanation of each main part of the code:
Explanation of Key Sections
User Inputs for Higher Time Frame and Candle Settings
Users can select a higher time frame (timeframe) for analysis and specify whether to use the "Current" or "Last" higher time frame (HTF) candle for calculating Fibonacci levels.
The currentlast setting allows flexibility between using real-time or the most recent closed higher time frame candle.
Lookback Periods for High/Low Criteria
Two lookback periods, lowestLookback and highestLookback, allow users to set the number of bars to consider when finding the lowest and highest prices, respectively.
This determines the criteria for entering trades based on how recent highs or lows compare to current prices.
Fibonacci Levels Configuration
Fibonacci levels (0%, 23.6%, 38.2%, 50%, 61.8%, 78.6%, and 100%) are configurable. These are used to calculate price levels between the high and low of the higher time frame candle.
Each level represents a retracement or extension relative to the high/low range of the HTF candle, providing important price levels for decision-making.
HTF Candle Calculation
HTF candle data is calculated based on the higher time frame selected by the user, using the newbar check to reset htfhigh, htflow, and htfopen values.
The values are updated with each new HTF bar or as prices move within the same HTF bar to track the highest high and lowest low accurately.
Set Fibonacci Levels Array
Using the calculated HTF candle's high, low, and open, the Fibonacci levels are computed by interpolating these values according to the user-defined Fibonacci levels.
A fibLevels array stores these computed values.
Plotting Fibonacci Levels
Each Fibonacci level is plotted on the chart with a different color, providing visual indicators for potential support/resistance levels.
High/Low Price Criteria Calculation
The lowest and highest prices over the specified lookback periods (lowestLookback and highestLookback) are calculated and plotted on the chart. These serve as dynamic levels to trigger long or short entries.
Trade Signal Conditions
longCondition: A long (buy) signal is generated when the price crosses above both the lowest price criteria and the 50% Fibonacci level.
shortCondition: A short (sell) signal is generated when the price crosses below both the highest price criteria and the 50% Fibonacci level.
Executing Trades
Based on the longCondition and shortCondition, trades are entered with the strategy.entry() function, using the labels "Long" and "Short" for tracking on the chart.
Strategy Use
This strategy allows traders to utilize Fibonacci retracement levels and recent highs/lows to identify trend continuation or reversal points, potentially providing entry points aligned with larger market structure. Adjusting the lowestLookback and highestLookback along with Fibonacci levels enables a customizable approach to suit different trading styles and market conditions.
TFMTFM Strategy Explanation
Overview
The TFM (Timeframe Multiplier) strategy is a PineScript trading bot that utilizes multiple timeframes to identify entry and exit points.
Inputs
1. tfm (Timeframe Multiplier): Multiplies the chart's timeframe to create a higher timeframe for analysis.
2. lns (Long and Short): Enables or disables short positions.
Logic
Calculations
1. chartTf: Gets the chart's timeframe in seconds.
2. tfTimes: Calculates the higher timeframe by multiplying chartTf with tfm.
3. MintickerClose and MaxtickerClose: Retrieve the minimum and maximum closing prices from the higher timeframe using request.security.
- MintickerClose: Finds the lowest low when the higher timeframe's close is below its open.
- MaxtickerClose: Finds the highest high when the higher timeframe's close is above its open.
Entries and Exits
1. Long Entry: When the current close price crosses above MaxtickerClose.
2. Short Entry (if lns is true): When the current close price crosses below MintickerClose.
3. Exit Long: When the short condition is met (if lns is false) or when the trade is manually closed.
Strategy
1. Attach the script to a chart.
2. Adjust tfm and lns inputs.
3. Monitor entries and exits.
Example Use Cases
1. Intraday trading with tfm = 2-5.
2. Swing trading with tfm = 10-30.
Tips
1. Experiment with different tfm values.
2. Use lns to control short positions.
3. Combine with other indicators for confirmation.
Honest Volatility Grid [Honestcowboy]The Honest Volatility Grid is an attempt at creating a robust grid trading strategy but without standard levels.
Normal grid systems use price levels like 1.01;1.02;1.03;1.04... and place an order at each of these levels. In this program instead we create a grid using keltner channels using a long term moving average.
🟦 IS THIS EVEN USEFUL?
The idea is to have a more fluid style of trading where levels expand and follow price and do not stick to precreated levels. This however also makes each closed trade different instead of using fixed take profit levels. In this strategy a take profit level can even be a loss. It is useful as a strategy because it works in a different way than most strategies, making it a good tool to diversify a portfolio of trading strategies.
🟦 STRATEGY
There are 10 levels below the moving average and 10 above the moving average. For each side of the moving average the strategy uses 1 to 3 orders maximum (3 shorts at top, 3 longs at bottom). For instance you buy at level 2 below moving average and you increase position size when level 6 is reached (a cheaper price) in order to spread risks.
By default the strategy exits all trades when the moving average is reached, this makes it a mean reversion strategy. It is specifically designed for the forex market as these in my experience exhibit a lot of ranging behaviour on all the timeframes below daily.
There is also a stop loss at the outer band by default, in case price moves too far from the mean.
What are the risks?
In case price decides to stay below the moving average and never reaches the outer band one trade can create a very substantial loss, as the bands will keep following price and are not at a fixed level.
Explanation of default parameters
By default the strategy uses a starting capital of 25000$, this is realistic for retail traders.
Lot sizes at each level are set to minimum lot size 0.01, there is no reason for the default to be risky, if you want to risk more or increase equity curve increase the number at your own risk.
Slippage set to 20 points: that's a normal 2 pip slippage you will find on brokers.
Fill limit assumtion 20 points: so it takes 2 pips to confirm a fill, normal forex spread.
Commission is set to 0.00005 per contract: this means that for each contract traded there is a 5$ or whatever base currency pair has as commission. The number is set to 0.00005 because pinescript does not know that 1 contract is 100000 units. So we divide the number by 100000 to get a realistic commission.
The script will also multiply lot size by 100000 because pinescript does not know that lots are 100000 units in forex.
Extra safety limit
Normally the script uses strategy.exit() to exit trades at TP or SL. But because these are created 1 bar after a limit or stop order is filled in pinescript. There are strategy.orders set at the outer boundaries of the script to hedge against that risk. These get deleted bar after the first order is filled. Purely to counteract news bars or huge spikes in price messing up backtest.
🟦 VISUAL GOODIES
I've added a market profile feature to the edge of the grid. This so you can see in which grid zone market has been the most over X bars in the past. Some traders may wish to only turn on the strategy whenever the market profile displays specific characteristics (ranging market for instance).
These simply count how many times a high, low, or close price has been in each zone for X bars in the past. it's these purple boxes at the right side of the chart.
🟦 Script can be fully automated to MT5
There are risk settings in lot sizes or % for alerts 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.
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.
BarRange StrategyHello,
This is a long-only, volatility-based strategy that analyzes the range of the previous bar (high - low).
If the most recent bar’s range exceeds a threshold based on the last X bars, a trade is initiated.
You can customize the lookback period, threshold value, and exit type.
For exits, you can choose to exit after X bars or when the close price exceeds the previous bar’s high.
The strategy is designed for instruments with a long-term upward-sloping curves, such as ES1! or NQ1!. It may not perform well on other instruments.
Commissions are set to $2.50 per side ($5.00 per round trip).
Recommended timeframes are 1h and higher. With adjustments to the lookback period and threshold, it could potentially achieve similar results on lower timeframes as well.
Bollinger Bands + RSI StrategyThe Bollinger Bands + RSI strategy combines volatility and momentum indicators to spot trading opportunities in intraday settings. Here’s a concise summary:
Components:
Bollinger Bands: Measures market volatility. The lower band signals potential buying opportunities when the price is considered oversold.
Relative Strength Index (RSI): Evaluates momentum to identify overbought or oversold conditions. An RSI below 30 indicates oversold, suggesting a buy, and above 70 indicates overbought, suggesting a sell.
Strategy Execution:
Buy Signal : Triggered when the price falls below the lower Bollinger Band while the RSI is also below 30.
Sell Signal : Activated when the price exceeds the upper Bollinger Band with an RSI above 70.
Exit Strategy : Exiting a buy position is considered when the RSI crosses back above 50, capturing potential rebounds.
Advantages:
Combines price levels with momentum for more reliable signals.
Clearly defined entry and exit points help minimize emotional trading.
Considerations:
Can produce false signals in very volatile or strongly trending markets.
Best used in markets without a strong prevailing trend.
This strategy aids traders in making decisions based on technical indicators, enhancing their ability to profit from short-term price movements.
Strategy Tester [Cometreon]The Strategy Tester is a powerful backtesting tool that allows you to evaluate and optimize strategies created with the Strategy Builder or signals generated by the Signal Tester. It offers a comprehensive suite of options for risk management and optimization of trading performance.
Key Features:
Testing strategies on different symbols and timeframes
Advanced risk management with multiple Take Profit and Stop Loss options
Customization of trading sessions and initial capital
Generation of customized alerts for entry, exit, and TP/SL modifications
Technical Details and Customizable Inputs:
Source Entry Long and Short: Select entry conditions for the strategy from the "Signal Tester" or "Strategy Builder".
Source Exit Long and Short: Select exit conditions for the strategy from the "Signal Tester" or "Strategy Builder".
Trading Session: Choose the period in which the strategy will enter positions, selecting from: Months, Days, up to 3 hourly sessions, and the strategy's activity range, i.e., start and end date.
Alert Message: Set custom messages for each type of Alert, such as Entry Long, Exit Short, or Change SL Long
Plot: Choose whether to show Long and Short positions on the chart
Risk Management:
Customize the exits and risk management of your strategy, with a wide range of options including:
Initial Capital: Set the starting capital for the strategy
Quantity: Choose the entry quantity for each type of position, selecting from: Contracts, USD, Percentage of equity, and percentage of initial capital.
Take Profit: Configure up to 4 different Take Profits, choosing each type of level from:
- % : Percentage from the entry price.
- USD : Distance in USD from the entry price.
- Pip : Distance in Pips from the entry price.
- ATR : Set the ATR Take Profit multiplier using the length of the "ATR Period Long".
- Swing : Set the length to calculate the Swing as Take Profit Level
- Risk Reward : Set the Take Profit based on the Risk-Reward of the Stop Loss, vice versa for the Stop Loss (Take Profit or Stop Loss cannot both have the Risk Reward option).
Stop Loss: Set the Stop Loss to reduce the loss in case of defeat, also choosing the type of level as for the "Take Profit".
Break Even: Choose whether to modify the Stop Loss level when the price breaks a certain Take Profit level, you can choose the Stop level, adding or removing (%, USD, or Pip) from the entry level.
Trailing Take Profit: When the price breaks a set price, it allows activating an exit level by subtracting/increasing from the chosen Stop level, the level will continue to update every time the Stop source is updated, for example in Long every time High exceeds the previous one.
Trailing Stop Loss: When the price breaks a set price, it allows activating an exit level by subtracting/increasing from the chosen Stop level, the level will continue to update every time the Stop source is updated, for example in Long every time Low exceeds the previous one.
Exit Before End Session: Allows setting an exit time, for example to exit 1 candle before the end of the daily session.
How to Use The Indicator:
Add the Strategy Tester to the chart
Input signals generated by other TradeLab Beta indicators
Configure risk and capital management settings
Run the strategy backtesting and analyze the results
Optimize the strategy based on the obtained results
Take your trading to the next level with TradeLab Beta's Strategy Tester this powerful backtesting tool and start optimizing your trading strategies today.
Don't waste any more time and visit the link to get access to all Cometreon indicators.
Candle Range Theory [Advanced] - AlgoVisionUnderstanding Candle Range Theory (CRT) in the AlgoVision Indicator
Candle Range Theory (CRT) is a structured approach to analyzing market movements within the price ranges of candlesticks. CRT is founded on the idea that each candlestick on a chart, regardless of timeframe, represents a distinct range of price action, marked by the candle's open, high, low, and close. This range gives insights into market dynamics, and when analyzed in lower timeframes, reveals patterns that indicate underlying market sentiment and institutional behaviors.
Key Concepts of Candle Range Theory
Candlestick Range: The range of a candlestick is simply the distance between its high and low. Across timeframes, this range highlights significant price behavior, with each candlestick representing a snapshot of price movement. The body (distance between open and close) shows the primary price action, while wicks (shadows) reflect price fluctuations or "noise" around this movement.
Multi-Timeframe Analysis: A higher-timeframe (HTF) candlestick can be dissected into smaller, structured price movements in lower timeframes (LTFs). By analyzing these smaller movements, traders gain a detailed view of the market’s progression within the HTF candlestick’s range. Each HTF candlestick’s high and low provide support and resistance levels on the LTF, where the price can "sweep," break out, or retest these levels.
Market Behavior within the Range: Price action within a range doesn’t move randomly; it follows structured behavior, often revealing patterns. By analyzing these patterns, CRT provides insights into the market’s intention to accumulate, manipulate, or distribute assets within these ranges. This behavior can indicate future market direction and increase the probability of accurate trading signals.
CRT and ICT Power of 3: Accumulation, Manipulation, and Distribution (AMD)
A foundational element of our CRT indicator is its combination with ICT’s Power of 3 (Accumulation, Manipulation, and Distribution or AMD). This approach identifies three stages of market movement:
Accumulation: During this phase, institutions accumulate positions within a tight price range, often leading to sideways movement. Here, price consolidates as institutions carefully enter or exit positions, erasing traces of their intent from public view.
Manipulation: Institutions often use manipulation to create false breakouts, targeting retail traders who enter the market on perceived breakouts or reversals. Manipulation is characterized by liquidity grabs, false breakouts, or stop hunts, as price momentarily moves outside the established range before quickly returning.
Distribution: Following accumulation and manipulation, the distribution phase aligns with the true market direction. Institutions now allow the market to move with the trend, initiating a stronger and more sustained price movement that aligns with their intended position.
This AMD cycle is often observed across multiple timeframes, allowing traders to refine entries and exits by identifying accumulation, manipulation, and distribution phases on smaller timeframes within the range of a higher-timeframe candle. CRT views this cycle as the "heartbeat" of the market—a continuous loop of price movements. With our indicator, you can identify this cycle on your current timeframe, with the signal candle acting as the "manipulation" candle.
How to Use the Premium AlgoVision CRT Indicator
1. Indicator Display Options
Bullish/Bearish Plot Indication: Toggles the display of bullish or bearish CRT signals. Turn this on to display signals on your chart or off to reduce screen clutter.
Order Block Indication: Highlights the order block entry price, which is the preferred entry point for CRT trades.
Purge Time Indication: Shows when the low or high of Candle 1 is purged by Candle 2, helping to identify potential manipulation points.
2. Filter Options
Match Indicator Candle with Signal: Ensures that only bullish Candle 2s (for longs) or bearish Candle 2s (for shorts) are signaled. This filter helps eliminate signals where the candlestick’s direction does not align with the CRT model.
Take Profit Already Reached: When enabled, this filter removes CRT signals if take profit levels are reached within Candle 2. This helps focus on setups where there’s still room for price movement.
Midnight Price Filter: Filters signals based on midnight price levels:
Longs: Only signals if the order block entry price is below the midnight price.
Shorts: Only signals if the order block entry price is above the midnight price.
3. Entry and Exit Settings
Wick out prevention: Allows positions to stay open and prevent getting wicked out. Positions will still be able to close if determined by the algorithm.
Buy/Sell: This allows you to set you daily bias. You can select to only see buys or sells.
Custom Stop Loss: Sets a custom stop loss distance from the entry price (e.g., $100 or $200 away) if the predefined stop loss based on Candle 2’s low/high doesn’t suit your preference.
Take Profit Levels: Choose from three take profit levels:
Optimized Take Profit: Uses an optimized take profit level based on CRT’s recommended exit point.
Take Profit 1: Sets an initial take profit level.
Take Profit 2: Sets a secondary take profit level for a more extended exit target.
Timeframe of Order Block: Select the timeframe of the order block entry, which can be tailored based on the timeframe of the CRT signal.
Risk-to-Reward Filter: Filters trades based on a specified risk-to-reward ratio, using the indicator’s stop loss as the base. This helps to ensure trades meet minimum reward criteria.
4. Risk Management
Fixed Entry QTY: This will allow you to open all positions with a fixed QTY
Risk to Reward Ratio: This allows you to set a minimum risk to reward ratio, the strategy will only take trades if this risk to reward is met.
Risk Type:
Fixed Amount: Allows you to risk a fixed $ amount.
% of account: Allows you to risk % of account equity.
5. Day and Time Filters
Filter by Days: Specify the days of the week for CRT signals to appear. For instance, you could enable signals only on Thursdays. This setting can be adjusted to any day or combination of days.
Purge Time Filter: Filters CRT signals based on specific purge times when Candle 1’s low/high is breached by Candle 2, as CRT setups are observed to work best during certain times.
Hour Filters for CRT Signals:
1-Hour CRT Times: Allows filtering CRT signals based on specific 1-hour time intervals.
4-Hour CRT Times: Filter 4-hour CRT signals based on specified times.
Forex and Futures Conversion: Adjusts times based on standard sessions for Forex (e.g., 9:00 AM 4-hour candle) and Futures (e.g., 10 PM candle for Futures or 8 AM for Crypto).
6. Currency and Asset-Specific Filters
Crypto vs. Forex Mode: This setting adjusts the indicator’s timing to match market sessions specific to either crypto or Forex/Futures, ensuring the CRT model aligns with the asset type.
Additional Notes
Backtesting Options: Adjust these to test risk management, such as risking a fixed amount or a percentage of the account, for historical performance insights.
Optimized Settings: This version includes all features and optimized settings, with the most refined data analysis.
Conclusion By combining CRT with ICT Power of 3, the AlgoVision Indicator allows traders to leverage the CRT candlestick as a versatile tool for identifying potential market moves. This method provides beginners and seasoned traders alike with a robust framework to understand market dynamics and refine trade strategies across timeframes. Setting alerts on the higher timeframe to catch bullish or bearish CRT signals allows you to plan and execute trades on the lower timeframe, aligning your strategy with the broader market flow.
- Trading Bot – TopBot Anomaly LITE Robot Strategy -- Trading Bot - TopBot Anomaly LITE -
- Ready to use and automate robot strategy -
1 - Introduction
This strategy is based on a search for abnormal market price movements relative to a time-shifted basic moving average. Different variations of the basic moving average are created and shifted proportionally rather than linearly, giving the strategy greater reactivity to serve as position entry points. What's more, this strategy stands out with a major innovation, allowing position exits to be set on moving average variations (and not on the moving average itself, like all strategies that close positions on return to the moving average), which greatly improves actual results.
2 - Detailed operation of the strategy
It defines a function that calculates various moving averages (depending on the type of moving average defined by the user) and the length chosen. The function takes into account different types of moving averages: SMA, PCMA, EMA, WMA, DEMA, ZLEMA and HMA, and is offset in time so that it can be an entry or exit condition in real time. To do this, it sets up LIMIT positions which it monitors to place an order the instant the price is crossed (otherwise it would have to wait for the next candle for the moving average to be calculated).
It calculates shifted variants (“semi” parallels) as a percentage of this basic moving average, high and low, to define position entry points (depending on user settings, up to 2 shifted levels for 2 Long position entries). Because the offset is calculated as a percentage rather than a fixed value, the resulting deviations are not parallel to the basic moving average, but enable the detection of a sudden price contraction. By adjusting these deviations proportionally, we can more clearly observe variations relative to the basic moving average, enabling us to detect dynamic support and resistance zones that adapt to market fluctuations. The fact that they are not strictly parallel avoids too rigid an interpretation and gives a more nuanced reading of trends, capturing small divergences that could indicate more subtle changes in market dynamics.
The most distinctive feature of this strategy concerns position exits: the script calculates a new moving average shifted proportionally to the base moving average (adjustable) to define the position exit price level. A classic moving-average exit can also be used, leaving the deviation value at 0.
The strategy enters the position when one of the deviations from the position entry moving average is crossed, and exits the position when the deviation from the position exit moving average is crossed.
3 - “Ready to use” anduser-adjustable parameters
The strategy interface has been optimized for easy creation of trading robots, with all settings underlying the calculations and numerous options for optimization.
Here are the contents of the strategy settings interface:
Visually show/hide entry zones on the chart
Define position output deviation level (0 - 0.4%)
Define position entry deviation levels (up to 2 levels)
Define type of capital management (% available balance, % total capital or fixed amount in $)
Define the amount of each position entry (in % or $)
Define the leverage used
Define source of data used (ohlc4, open, high, low, close, hl2, hlc3, ohlc4, hlcc4)
Define type of moving average used for calculations (SMA, PCMA, EMA, WMA, DEMA, ZLEMA, HMA)
Define moving average length (period)
Define a message to be sent to a bot via the webhook for a LONG entry
Define a message to be sent to a bot via the webhook for a LONG output
Define a stoploss (optional for this type of strategy)
In addition, important information about strategy settings and results is displayed directly on the chart. The percentage profit displayed may differ slightly from that of the backtest, as it includes potential profits from open trades (strategy.openprofit) in its calculation.
4 - Chart and backtest display conditions, options and settings
Here are the conditions and settings of the graph presented on the screen:
Its result is obtained over 2 months. Position entry is in cash to balance the two entries, with 50% of capital per entry leveraged x2
L3USDT.P - BITGET - 5M - LONG - Backtest : 03/09/2024 - 09/11/2024 - CASH : 500 (1/2 Equity By Entry - x2 Leverage) - SMA Lenght : 33 – Exit Deviation : 0.004 - LONGS : 0.029 - 0.04 : Stop-Loss - 100% (none)
5 - How to adjust and apply the strategy?
Generally speaking, the strategy works well on a large proportion of cryptocurrencies. The recommended timeframes are: 5M - 15M - 30M - 45M - 1H - 2H - 3H - 4H and the most appropriate timeframe will vary according to the crypto-currency. It is also possible, with certain assets, to run the strategy on shorter timeframes such as 5M or 15M with success.
Generally speaking, if set “wide”, the winrate is usually very high and most result curves are nice and progressive, with good stability over time.
The strategy can be used with a single position entry level, maximizing the use of capital on each trade and/or having several strategies active on a single account at the same time.
It can also be used on a “safe” basis, using up to 2 successive entries to smooth out unforeseen market movements and minimize risk.
Recommended leverage is x1 or x2 for controlled long-term trading, especially with 2 levels of entries used, although sometimes higher leverage could be considered with controlled risk.
Here's how to set up the strategy:
Start by finding a cryptocurrency displaying a nice curve with the default settings. The SMA Lenght setting is very important and can vary greatly from asset to asset (between SMA 2 and SMA 80).
Then try the default settings on all timesframes, and select the timeframe with the best curve or the best result.
Set the first triggerlevel to the value that gives the best result
(optional): Change the moving average type, period and data source to find the most optimized setting before proceeding to the next step.
Set the 2nd inputlevel to the last value modifying the result.
Then set the output level, which can greatly improve the results.
Enter your bot's Enter_Long and Exit_Long commands
Create an alarm linked via webhook to your bot or trading intermediary (info below)
6 - How to program robots for automated trading using this strategy
If you want to use this strategy for automated trading, it's very simple. All you need is an account with a cryptocurrency broker that allows APIs, and an intermediary between TradinView and your broker who will manage your orders.
Here's how it works:
On your intermediary, create a bot that will manage the details of your orders (amount, single or multiple entries, exit conditions). This bot is linked to the broker via an API and will be able to place real orders. Each bot has four different signals that enable it to be activated via a webhook. When one of the signals is received, it executes the orders for you.
On TradingView, set the strategy to a suitable asset and timeframe. Once set, enter in the strategy parameters the signals specific to the bot you've created. Confirm and close the parameters.
Still on TradingView, create an alarm based on your set strategy (on the strategy tester). Give the alarm the name of your choice and in “Message” enter only{{strategy.order.comment}}.
In alarm notifications, activate the webhook and enter the webhook of your trading intermediary. Confirm the alarm.
As long as the alarm is activated in TradingView, the strategy will monitor the market and send an order to enter or exit a position as soon as the conditions are met. Your bot will receive the instruction and place orders with your broker. Subsequent changes to the strategy settings do not change those stored in the alarm. If you wish to change the settings for one of your bots, simply delete the old alarm and create a new one.
Note: In your bot settings, on your intermediary, make sure to allow: - Multiple entries - A single exit signal to close all positions - Stoploss disabled (if necessary, use the strategy one)
Happy automated trading!
Pavan CPR Strategy Pavan CPR Strategy (Pine Script)
The Pavan CPR Strategy is a trading system based on the Central Pivot Range (CPR), designed to identify price breakouts and generate long trade signals. This strategy uses key CPR levels (Pivot, Top CPR, and Bottom CPR) calculated from the daily high, low, and close to inform trade decisions. Here's an overview of how the strategy works:
Key Components:
CPR Calculation:
The strategy calculates three critical CPR levels for each trading day:
Pivot (P): The central value, calculated as the average of the high, low, and close prices.
Top Central Pivot (TC): The midpoint of the daily high and low, acting as the resistance level.
Bottom Central Pivot (BC): Derived from the pivot and the top CPR, providing a support level.
The script uses request.security to fetch these CPR values from the daily timeframe, even when applied on intraday charts.
Trade Entry Condition:
A long position is initiated when:
The current price crosses above the Top CPR level (TC).
The previous close was below the Top CPR level, signaling a breakout above a key resistance level.
This condition aims to capture upward momentum as the price breaks above a significant level.
Exit Strategy:
Take Profit: The position is closed with a profit target set 50 points above the entry price.
Stop Loss: A stop loss is placed at the Pivot level to protect against unfavorable price movements.
Visual Reference:
The script plots the three CPR levels on the chart:
Pivot: Blue line.
Top CPR (TC): Green line.
Bottom CPR (BC): Red line.
These plotted levels provide visual guidance for identifying potential support and resistance zones.
Use Case:
The Pavan CPR Strategy is ideal for intraday traders who want to capitalize on price movements and breakouts above critical CPR levels. It provides clear entry and exit signals based on price action and is best used in conjunction with proper risk management.
Note: The strategy is written in Pine Script v5 for use on TradingView, and it is recommended to backtest and optimize it for the asset or market you are trading.
Advanced Bitcoin Trend Following StrategyTitle: Bitcoin Multi-Factor Trend Following Strategy
Description:
The Bitcoin Multi-Factor Trend Following Strategy is designed for traders seeking a robust, multi-factor approach to trend following in Bitcoin markets. This script combines technical indicators and statistical methods to identify trend directions, optimize entry and exit points, and manage position sizing based on volatility and leverage constraints. Key features of the strategy include:
Multi-Indicator Trend Forecasting:
This strategy employs three trend forecasting methods: range, exponential moving average (EMA), and Bollinger Bands. Each method can be independently enabled or disabled, giving traders flexibility in how trends are identified and followed.
Range Forecast : Calculates forecast based on the range (high and low) of recent prices, with optional smoothing via a Kalman filter to reduce noise.
EMA Spread Forecast : Utilizes the spread between fast and slow EMAs to gauge the trend’s strength, adjusted for volatility.
Bollinger Band Forecast : Measures the proximity of price to Bollinger Band levels to assess trend intensity.
Kalman Filter for Smoothing:
The Kalman filter is applied to price data for smoother trend estimation, particularly within the range forecast. This allows the strategy to reduce noise and focus on more reliable price signals.
Volatility-Adjusted Position Sizing:
The strategy incorporates volatility targeting to dynamically adjust position sizes based on current market conditions. Traders can set an annualized volatility target to control the risk level, with position size scaled accordingly to maintain consistent risk exposure. A maximum leverage cap ensures that position sizes do not exceed a user-defined threshold, offering an additional layer of risk control.
Dynamic Entry and Exit Points:
Entry and exit points are based on customizable thresholds that determine trend strength and are sensitive to market volatility. The script monitors changes in forecast values and automatically adjusts trades to capitalize on emerging trends or exit weakening ones. The strategy includes an option to close all open positions when trend forecasts fall below defined thresholds, ensuring an automated approach to risk management.
Backtesting and Performance Metrics:
To support strategy optimization, the script includes a backtest mode that calculates key performance metrics such as Sharpe Ratio, Buy & Hold profit, Strategy profit, Win rate, and other metrics. These metrics are displayed in a summary table directly on the chart, providing real-time insight into the strategy’s historical performance compared to a buy-and-hold approach.
Configurable Time and Date Range:
Users can specify start and end dates for the backtest period, allowing for focused backtesting over any desired timeframe. This feature enables in-depth analysis of performance across varying market conditions.
Use Case:
This strategy is best suited for experienced traders who wish to apply a structured trend-following approach in Bitcoin or other high-volatility assets. It is highly customizable, making it adaptable to various market conditions and trading styles. The combination of trend forecasting methods, volatility targeting, and automatic leverage control offers a balanced approach to capturing long-term trends while managing risk.
Parameters:
Entry Threshold: Adjusts the sensitivity of the entry point for trends. Lower values make the strategy more reactive.
Annual Volatility Target: Controls the risk level by targeting a specific annualized volatility percentage.
Max Leverage: Caps the allowable leverage for each trade.
Forecast Activations: Toggles to enable or disable the use of range, EMA, and Bollinger forecasts.
Date Range: Allows users to define the start and end dates for testing the strategy.
Notes:
This strategy is designed for educational purposes and requires thorough backtesting and optimization before live trading. Real-time performance may vary, and additional risk management practices are advised.
License:
This script is subject to the terms of the Mozilla Public License 2.0.
Fractional Accumulation Distribution Strategy🔹 INTRODUCTION:
As traders and investors, we often find ourselves searching for ways to maximize our market positioning—trying to capture the best price, manage risk, and adapt to ever-changing volatility. Through years of working with a variety of traders and investors, a common theme emerged: the most successful market participants were those who accumulated positions strategically over time, rather than relying on one-off, rigid entry points. However, even the best of them struggled to consistently time their entries and exits for optimal results.
That's why I created the Fractional Accumulation/Distribution Strategy (FADS)—an adaptable solution designed to dynamically adjust position sizing and entry points based on changing market conditions, enabling both passive and active market participants to optimize their approach.
The FADS trading strategy combines volatility-based trend detection and adaptive position scaling to maximize profitability across varied market conditions. By using the price ranges from higher timeframes, FADS pinpoints extreme demand and supply zones with a high statistical probability of reversal, making it effective in both high and low volatility environments. By applying adjustable threshold settings, users can focus on meaningful price movements to reduce unnecessary trades. Adaptive position scaling further enhances this approach by adjusting position sizes based on entry level distances, allowing for strategic position building that balances risk and reward in uncertain markets. This systematic scaling begins with smaller positions, expanding as the trend solidifies, creating a refined, robust trading experience.
🔹 FEATURES:
Multi-Timeframe Volatility-Based Trend Detection
Accumulation/Distribution Level Filter
Customizable Period for Highest/Lowest Prices Capture
Adjustable Sensitivity & Frequency in Positioning
Broad control settings of Strategy
Adaptive Position Scaling
🔹 SETTINGS:
Volatility : Determines trading range based on market volatility . Highest range value number of periods.
Factor : Adjusts the width of the Accumulation & Distribution bands separately. The Level Filter feature offers customizable triggering bands, allowing users to fine-tune the initiation point for the Accumulation/Distribution sequence. This flexibility enables traders to align entries more precisely with market conditions, setting optimal thresholds for initiating trade chains, whether in accumulating positions during uptrends or distributing in downtrends.
Lowest : Choose the price source (e.g., Close, Low). Number of bars considered when determining the lowest price level. Selecting the checkbox generate a signal when the price crosses below the previous lowest value for calculating the lowest value used for trade signals.
Highest : Choose the price source (e.g., Close, High). Number of bars considered when determining the highest price levels. Selecting the checkbox generate a signal when the price crosses above the previous highest value for calculating the highest value used for trade signals.
Accumulation Spread : Adjusts the buying frequency sensitivity by setting the distance between entries based on personal risk tolerance. Larger values for less frequent buys; smaller values for more frequent buys.
Distribution Spread : Adjusts the selling frequency sensitivity by setting the distance between exits based on reward preference. Larger values for less frequent sells; smaller values for more frequent sells.
Percentage of Capital Allocation : Sets the portion of total capital used for the initial trade in a strategy. It sets the scale for subsequent trades during accumulation phase.
🔹 APPLICATIONS:
❖ Accumulation and Distribution Phases
Early entries are avoided by initiating accumulation only after a trend reversal is confirmed and price breaks below long-term range.
Position sizes are determined by the distance between consecutive trades, smaller distance results in smaller position sizes and vice versa.
Average position cost is reduced by accumulating larger positions at the lower prices, potentially resulting in improved profitability.
Early exits are avoided by initiating distribution only after trend reversal is confirmed and price breaks above long-term range.
The pace of distribution can be tracked by the violet line that represents average positions during distribution phase
❖ Use Cases (Different than default setting input is used for illustration purposes)
If the starting point of accumulation starts too high for the risk preference, Accumulation Level Filter can be lowered by increasing the 🟢 threshold Factor.
If the starting point of distribution is too low for the reward preference, the Distribution Level Filter can be raised by increasing the 🔴 threshold Factor.
In lower timeframes, positions during the accumulation phase could be purchased at higher levels relative to prior entry positions. To optimize for this, consider extending the period used to capture the lowest prices. Similarly, during the distribution phase, increasing the period for identifying higher prices can improve accuracy.
🔹 Strategy Properties:
Adjusting properties within the script settings is recommended to align with specific accounts and trading platforms, ensuring realistic strategy results.
Balance (default): $100,000
Initial Order Size: 1% of the default balance
Commission: 0.1%
Slippage: 5 Ticks
Backtesting: Backtested using TradingView’s built-in strategy testing tool with default commission rates of 0.1% and slippage of 5 ticks. It reflects average market conditions for Apple Inc. (APPL) on 1-hour timeframe
Disclaimers: Commission and slippage varies with market conditions and brokerage policies. The assumed value may not represent all trading environments.
PAST PERFORMANCE DOESN’T GUARANTEE FUTURE RESULTS!
Disclaimer: Please remember that past performance may not be indicative of future results. Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting. This post and the script don’t provide any financial advice.
This invite-only script is being published as part of my commitment to developing tools that align with TradingView’s community standards. Access requests will be reviewed carefully after the script passes TradingView's moderation process.
Strategy without indicators v11. General Script Strategy
The objective of this strategy is to open buy or sell orders every new hour based on:
Whether the previous candle closed high (buy) or low (sell).
The presence of tops and bottoms to avoid opening orders at times of possible reversals.
The strategy also allows the user to set a date range (start date and end date) to calculate profit, loss, percentage of gain and percentage of loss only in that period.
2. Initial Settings and Parameters
Start Date and End Date: The start_date and end_date variables define the date range to account for profits and losses. These dates can be adjusted by the user to view results in specific periods.
3. Conditions for Order Entry
At each time change, the script checks the conditions for buying or selling, using the following variables and logic:
Detection of Bullish or Bearish Candle:
bullish_candle: True if the previous candle closed high.
bearish_candle: True if the previous candle closed lower.
Analysis of Tops and Bottoms:
To avoid opening orders close to tops and bottoms, the script uses the function find_top_and_bottom(period), which analyzes the last 500 candles and identifies the highest value (top) and the lowest value (bottom).
The variables current_top and current_bottom store these values.
next_top and next_bottom indicate whether the current candle is close to a top (prevents buying) or a bottom (prevents selling).
4. Opening Orders (Buy and Sell)
At each time change, the script checks the conditions to open buy or sell orders:
Condition for Sell:
The sell order is opened if the previous candle was bullish (bullish_candle) and is not close to a top (not next_top).
If there is an open buy order, it is closed before the new sell order.
Buy Condition:
The buy order is opened if the previous candle was bearish (bearish_candle) and is not near a bottom (not_near_bottom).
If there is an open sell order, it is closed before the new buy order.
5. Calculating Profit and Loss
The profit and loss calculation is only done within the configured date range (start_date and end_date):
Profit and Loss:
total_profit and total_loss accumulate the profit and loss values of all operations during the defined period.
percentage_gain and percentage_loss calculate the percentage of gain and loss in relation to the initial capital.
6. Displaying Results on the Chart
The script displays on the chart, next to the candles, the information on Total Profit, Total Loss, % Gain and % Loss:
Strategy Summary
Setting the Date Range: Allows you to set the period for calculating profit and loss.
Previous Candlestick Analysis: Decide whether to buy or sell based on the previous candlestick.
Preventing Entries at Tops and Bottoms: Avoids buying at tops and selling at bottoms to reduce false signals.
Result Calculation: Accumulates profits, losses and percentages within the configured date range.
Results Display on Chart: Displays the configured statistics directly on the chart, next to the candlesticks.
1. Estratégia Geral do Script
O objetivo dessa estratégia é abrir ordens de compra ou venda a cada nova hora com base em:
Se a vela anterior fechou em alta (compra) ou em baixa (venda).
A presença de topos e fundos para evitar abrir ordens em momentos de possíveis reversões.
A estratégia também permite que o usuário configure um intervalo de datas (data inicial e data final) para calcular o lucro, perda, percentual de ganho e percentual de perda apenas nesse período.
2. Configurações e Parâmetros Iniciais
Data Inicial e Data Final: As variáveis data_inicial e data_final definem o intervalo de datas para contabilizar os lucros e perdas. Essas datas podem ser ajustadas pelo usuário para visualizar resultados em períodos específicos.
3. Condições para Entrada de Ordens
A cada mudança de hora, o script verifica as condições de compra ou venda, usando as seguintes variáveis e lógicas:
Detecção de Vela de Alta ou Baixa:
vela_de_alta: Verdadeiro se a vela anterior fechou em alta.
vela_de_baixa: Verdadeiro se a vela anterior fechou em baixa.
Análise de Topos e Fundos:
Para evitar abrir ordens próximas de topos e fundos, o script utiliza a função find_top_and_bottom(periodo), que analisa as últimas 500 velas e identifica o valor mais alto (topo) e o valor mais baixo (fundo).
As variáveis topo_atual e fundo_atual armazenam esses valores.
topo_proximo e fundo_proximo indicam se a vela atual está perto de um topo (evita compra) ou de um fundo (evita venda).
4. Abertura de Ordens (Compra e Venda)
A cada mudança de hora, o script verifica as condições para abrir ordens de compra ou venda:
Condição para Venda:
A ordem de venda é aberta se a vela anterior foi de alta (vela_de_alta) e não está perto de um topo (not topo_proximo).
Se houver uma ordem de compra aberta, ela é fechada antes da nova ordem de venda.
Condição para Compra:
A ordem de compra é aberta se a vela anterior foi de baixa (vela_de_baixa) e não está perto de um fundo (not fundo_proximo).
Se houver uma ordem de venda aberta, ela é fechada antes da nova ordem de compra.
5. Cálculo de Lucros e Perdas
O cálculo de lucro e perda só é feito dentro do intervalo de datas configurado (data_inicial e data_final):
Lucro e Perda:
lucro_total e perca_total acumulam os valores de lucro e perda de todas as operações durante o período definido.
percentual_ganho e percentual_perca calculam o percentual de ganho e perda em relação ao capital inicial.
6. Exibição dos Resultados no Gráfico
O script exibe no gráfico, próximo das velas, as informações de Lucro Total, Perda Total, % de Ganho e % de Perda:
Resumo da Estratégia
Configuração de Intervalo de Datas: Permite configurar o período para cálculo do lucro e da perda.
Análise de Vela Anterior: Decide se a ordem é de compra ou venda com base na vela anterior.
Prevenção de Entradas em Topos e Fundos: Evita compras em topos e vendas em fundos para reduzir sinais falsos.
Cálculo de Resultados: Acumula lucros, perdas e percentuais dentro do período de datas configurado.
Exibição dos Resultados no Gráfico: Exibe as estatísticas configuradas diretamente no gráfico, próximo das velas.
Madhan_HMT_Ultimate_StrategyThis indicator is a trend-following strategy designed to identify buy and sell signals based on price action relative to dynamic channels and smoothing mechanisms. It uses two separate sets of parameters that adjust to market conditions, with each set of parameters acting as an independent trend filter. The indicator creates arrows on the chart to signal potential trade entries, with these arrows appearing when the price crosses certain thresholds established by the indicator's internal calculation.
The strategy can be customized with various parameters, including:
Stop loss and take profit levels based on multiple options: ATR (Average True Range), fixed points, or percentage-based values.
Trading mode options that allow the user to choose whether the strategy trades both long and short positions, or restricts trades to only one direction (long or short).
The indicator visually represents the entry levels, stop loss, and take profit levels, with backgrounds filling to highlight potential risk and reward areas. By adjusting the parameters, traders can tailor the indicator to suit different market conditions and their risk tolerance.
Zig Zag + Aroon StrategyBelow is a trading strategy that combines the Zig Zag indicator and the Aroon indicator. This combination can help identify trends and potential reversal points.
Zig Zag and Aroon Strategy Overview
Zig Zag Indicator:
The Zig Zag indicator helps to identify significant price movements and eliminates smaller fluctuations. It is useful for spotting trends and reversals.
Aroon Indicator:
The Aroon indicator consists of two lines: Aroon Up and Aroon Down. It measures the time since the highest high and the lowest low over a specified period, indicating the strength of a trend.
Strategy Conditions
Long Entry Conditions:
Aroon Up crosses above Aroon Down (indicating a bullish trend).
The Zig Zag indicator shows an upward movement (indicating a potential continuation).
Short Entry Conditions:
Aroon Down crosses above Aroon Up (indicating a bearish trend).
The Zig Zag indicator shows a downward movement (indicating a potential continuation).
Exit Conditions:
Exit long when Aroon Down crosses above Aroon Up.
Exit short when Aroon Up crosses above Aroon Down.