IU Range Trading StrategyIU Range Trading Strategy
The IU Range Trading Strategy is designed to identify range-bound markets and take trades based on defined price ranges. This strategy uses a combination of price ranges and ATR (Average True Range) to filter entry conditions and incorporates a trailing stop-loss mechanism for better trade management.
User Inputs:
- Range Length: Defines the number of bars to calculate the highest and lowest price range (default: 10).
- ATR Length: Sets the length of the ATR calculation (default: 14).
- ATR Stop-Loss Factor: Determines the multiplier for the ATR-based stop-loss (default: 2.00).
Entry Conditions:
1. A range is identified when the difference between the highest and lowest prices over the selected range is less than or equal to 1.75 times the ATR.
2. Once a valid range is formed:
- A long trade is triggered at the range high.
- A short trade is triggered at the range low.
Exit Conditions:
1. Trailing Stop-Loss:
- The stop-loss adjusts dynamically using ATR targets.
- The strategy locks in profits as the trade moves in your favor.
2. The stop-loss and take-profit levels are visually plotted for transparency and easier decision-making.
Features:
- Automated box creation to visualize the trading range.
- Supports one position at a time, canceling opposite-side entries.
- ATR-based trailing stop-loss for effective risk management.
- Clear visual representation of stop-loss and take-profit levels with colored bands.
This strategy works best in markets with defined ranges and can help traders identify breakout opportunities when the price exits the range.
Educational
BTC/USD Gaussian Channel 1 Day Chart - Foneysmiles v1.0 Cryptocurrency trading strategy specifically designed for BTC/USD on a daily timeframe.
Strategy Framework:
Initial capital: $10,000
Position size: 60% of equity per trade
Commission: 0.1%
Slippage: 4 points
Time range: From January 2018 to end of 2069 (effectively no end date)
Gaussian Channel: The primary technical indicator that creates an adaptive channel around price
Uses a complex Gaussian filter with customizable poles (default 4)
Sampling period of 144 days
True Range multiplier of 1.414
Options for reduced lag and fast response modes
Price source defaults to HLC3 (High + Low + Close / 3)
Stochastic RSI with:
RSI length: 21 periods
Stochastic length: 200 periods
K smoothing: 1 period
D smoothing: 4 periods
Entry Conditions:
A long position is entered when ALL of these conditions are met:
The Gaussian filter is trending up (finalFilter > finalFilter )
Price is above the upper Gaussian channel band (close > hband)
Stochastic RSI is in extreme territory (k > 80 or k < 20)
Within the specified date range
Exit Conditions:
Positions are closed when price crosses below the upper band of the Gaussian channel
The visualization includes:
A color-coded Gaussian filter line (green when rising, red when falling)
Upper and lower bands forming a channel
The channel is filled with a semi-transparent version of the same color
This is a trend-following strategy that aims to catch strong upward moves in Bitcoin while using the Stochastic RSI as an additional filter. The strategy only takes long positions and doesn't include any short trades.
foneysmiles@gmail.com if you have any questions or have other use cases
My strategy 1 - Haisree (supertrend+ema)My strategy 1 - Haisree (supertrend+ema)
this strategy created mix of super trend and exponential moving averages 25,50,100
Supertrend & EMA Pure Strategy with Sideways Detection - HaisreeSupertrend & EMA Pure Strategy with Sideways Detection
bigprofitcosmosUltimate Scalping Strategy for the 1-Minute Timeframe
If you're a scalper aiming to seize every market movement, precision is key. Here’s the ideal setup:
Key Value : Set to 8 for short-term trend identification.
ATR (Average True Range): Adjust to 1000 to gauge volatility effectively.
Important Reminder :
Your lot size can either make or break your trading journey. Always prioritize proper risk management:
Risk only what you can afford to lose.
Avoid over-leveraging, and stick to a consistent position-sizing plan.
By following this approach, you'll increase your chances of capturing quick opportunities while minimizing unnecessary risks.
Adaptive Trend SignalsTry to give accurate signals for buying and selling using FAV and price movement
DCA_Swing Strategy_YARІнструкція з використання DCA-Based Swing Strategy
Таймфрейм: Рекомендовано 4H або 1D.
Сигнали:
"BUY" – зелена мітка під свічкою (вхід при RSI < 30).
"SELL" – червона мітка над свічкою (тейк-профіт 3 ATR).
Лінії на графіку:
Синя – середня ціна входу.
Зелена пунктирна – тейк-профіт.
Ліміти:
До 4 покупок (Max Entries).
Загальний ризик – $200.
RSI 5min Cross StrategyA short-term mean-reversion strategy that capitalizes on RSI oscillations in volatile markets.
Core Logic:
Entry Signal:
Triggers LONG position when 14-period RSI crosses above 35 on 5-minute charts
Indicates emerging momentum from oversold territory
Exit Signal:
Closes position when 14-period RSI crosses below 65
Captures profit before potential overbought reversal
Key Features:
Designed for high-liquidity markets (FX, crypto, large-cap stocks)
Optimized for ranging/sideways markets
Default 0.1% transaction cost included
Non-repainting signals for reliable backtesting
Rationale:
Uses wider RSI thresholds (35/65 vs standard 30/70) to avoid false signals
Exploits short-term price mean-reversion in 5-minute timeframes
Automated exit prevents emotional decision-making
Ideal For:
Day traders seeking frequent opportunities (6-12 trades/day)
Markets with clear oscillation patterns (e.g., indices, major currency pairs)
Risk Management:
⚠️ Requires strict stop-loss (not included in base script)
⚠️ Performs best when combined with:
Volume confirmation
Support/resistance alignment
Volatility filters (ATR/BB Width)
Strengths ➔ Quick turnaround trades, simple ruleset
Limitations ➔ Choppy markets cause whipsaws, needs trend confirmation
DCA (ASAP) V0 PTTScript Name: DCA (ASAP) V0 PTT
Detailed Description:
This script implements the Dollar-Cost Averaging (DCA) strategy, allowing you to automatically manage buy/sell orders safely and efficiently. Below are the key features of this script:
1. Purpose and Operation:
o Supports both Long and Short trading modes.
o Designed to optimize profitability using the DCA method, where Safety Orders are triggered when the price moves against the predicted direction.
o Helps users maintain their Target Profit in various market conditions.
2. Main Features:
o Automatic Order Placement: The initial Base Order is opened as soon as no active order exists.
o Safety Order Management: Safety Orders are automatically placed when the price moves against the initial order. The volume and distance of these orders are customizable.
o Order Closing: Orders are closed upon reaching the Target Profit, accounting for transaction fees.
o Detailed Information Display: Displays open orders, trading statistics, and performance metrics directly on the chart.
3. Customizable Parameters:
o Base Order Size: The size of the initial order.
o Target Profit (%): Target profit as a percentage of the total order volume.
o Safety Order Size: The size of each Safety Order.
o Price Deviation (%): The percentage distance between consecutive Safety Orders.
o Safety Order Volume Scale: The scaling factor for increasing the volume of subsequent Safety Orders.
o Max Safety Orders: The maximum number of Safety Orders allowed per deal.
4. Unique Features:
o Backtest Range Support: Enables you to limit backtesting to a specific time range of interest.
o Comprehensive Statistics: Displays detailed tables including open trades, pending orders, ROI, trading days, and realized profit.
o Integrated Trading Fees: Includes transaction fees in profit calculations for precise results.
5. Usage Instructions:
o Select the trading mode (Long or Short) from the "Strategy" input.
o Customize parameters such as Base Order, Safety Order, and Target Profit according to your requirements and the asset being traded.
o Monitor the performance of the strategy through the displayed information tables.
Notes:
• This script does not disclose detailed calculation logic but provides an overview of the concepts and usage.
• Designed for trading on exchanges that support margin or spot trading.
Dynamic Ticks Oscillator Model (DTOM)The Dynamic Ticks Oscillator Model (DTOM) is a systematic trading approach grounded in momentum and volatility analysis, designed to exploit behavioral inefficiencies in the equity markets. It focuses on the NYSE Down Ticks, a metric reflecting the cumulative number of stocks trading at a lower price than their previous trade. As a proxy for market sentiment and selling pressure, this indicator is particularly useful in identifying shifts in investor behavior during periods of heightened uncertainty or volatility (Jegadeesh & Titman, 1993).
Theoretical Basis
The DTOM builds on established principles of momentum and mean reversion in financial markets. Momentum strategies, which seek to capitalize on the persistence of price trends, have been shown to deliver significant returns in various asset classes (Carhart, 1997). However, these strategies are also susceptible to periods of drawdown due to sudden reversals. By incorporating volatility as a dynamic component, DTOM adapts to changing market conditions, addressing one of the primary challenges of traditional momentum models (Barroso & Santa-Clara, 2015).
Sentiment and Volatility as Core Drivers
The NYSE Down Ticks serve as a proxy for short-term negative sentiment. Sudden increases in Down Ticks often signal panic-driven selling, creating potential opportunities for mean reversion. Behavioral finance studies suggest that investor overreaction to negative news can lead to temporary mispricings, which systematic strategies can exploit (De Bondt & Thaler, 1985). By incorporating a rate-of-change (ROC) oscillator into the model, DTOM tracks the momentum of Down Ticks over a specified lookback period, identifying periods of extreme sentiment.
In addition, the strategy dynamically adjusts entry and exit thresholds based on recent volatility. Research indicates that incorporating volatility into momentum strategies can enhance risk-adjusted returns by improving adaptability to market conditions (Moskowitz, Ooi, & Pedersen, 2012). DTOM uses standard deviations of the ROC as a measure of volatility, allowing thresholds to contract during calm markets and expand during turbulent ones. This approach helps mitigate false signals and aligns with findings that volatility scaling can improve strategy robustness (Barroso & Santa-Clara, 2015).
Practical Implications
The DTOM framework is particularly well-suited for systematic traders seeking to exploit behavioral inefficiencies while maintaining adaptability to varying market environments. By leveraging sentiment metrics such as the NYSE Down Ticks and combining them with a volatility-adjusted momentum oscillator, the strategy addresses key limitations of traditional trend-following models, such as their lagging nature and susceptibility to reversals in volatile conditions.
References
• Barroso, P., & Santa-Clara, P. (2015). Momentum Has Its Moments. Journal of Financial Economics, 116(1), 111–120.
• Carhart, M. M. (1997). On Persistence in Mutual Fund Performance. The Journal of Finance, 52(1), 57–82.
• De Bondt, W. F., & Thaler, R. (1985). Does the Stock Market Overreact? The Journal of Finance, 40(3), 793–805.
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65–91.
• Moskowitz, T. J., Ooi, Y. H., & Pedersen, L. H. (2012). Time Series Momentum. Journal of Financial Economics, 104(2), 228–250.
EMA RSI Strategy krit test1This script implements strategy with the specified conditions. Key features include:
EMA Crossover Signals:
Buy signal: EMA (6) crosses above EMA (82).
Sell signal: EMA (6) crosses below EMA (82).
RSI Conditions:
Buy signals are restricted when RSI > 70 (overbought zone).
Sell signals are restricted when RSI < 22 (oversold zone).
Candle Conditions:
Buy signal: Current candle closes at a higher high.
Sell signal: Current candle closes at a lower low.
RSI Overbought/Oversold Strategy - Haisreeit should be work 4hrs 100% this 80 over bought and 20 over sold straregy.
Demand and Supply Zones Intraday Strategy(SAMARESH PANDA)Explanation:
Input Parameters:
length: Determines the number of bars to look back for identifying the highest and lowest prices to mark demand and supply zones.
zoneBuffer: A buffer in pips to place the stop and limit orders near the identified demand and supply zones.
Demand and Supply Zones:
The script identifies demand zones as the lowest low over the past length bars and supply zones as the highest high over the same period.
Buy (Long) Condition:
A buy signal is generated when the price crosses above the demand zone from below and the price closes above the demand zone.
Sell (Short) Condition:
A sell signal is generated when the price crosses below the supply zone from above and the price closes below the supply zone.
Stop and Limit Orders:
For long trades, the stop is placed just below the demand zone (zoneBuffer), and the limit is placed just above the demand zone.
For short trades, the stop is placed just above the supply zone (zoneBuffer), and the limit is placed just below the supply zone.
Exit Conditions:
The long position is closed when the price moves above the supply zone.
The short position is closed when the price moves below the demand zone.
Additional Notes:
Customization: You can modify the length and zoneBuffer values to adjust how sensitive the strategy is to price action and the zone buffers.
Risk Management: You may want to add additional filters for volume, indicators like RSI/MACD, or other market conditions to filter out false signals.
Testing & Optimization: As with any strategy, it's important to backtest and optimize it according to your preferred market conditions and risk tolerance.
Using the Strategy:
Apply the script to a 1-hour or 30-minute chart for identifying the demand and supply zones.
For better precision in entry, you can switch to a lower timeframe (like 5-minute or 15-minute) to execute your trades more accurately when the price reaches a demand or supply zone.
The buy and sell signals will appear on the chart as green (BUY) and red (SELL) labels.
Example of Execution:
Long Entry: The price closes above the demand zone and crosses up. A long position is opened with a stop below the demand zone and a limit near it.
Short Entry: The price closes below the supply zone and crosses down. A short position is opened with a stop above the supply zone and a limit near it.
This strategy works best in trending markets where price tends to respect these zones. Make sure to monitor the strategy closely and adjust it based on market volatility or changes in the broader trend.
You said:
create a pine script pivot point standard for buy sell
ChatGPT said:
ChatGPT
Sure! Below is a Pine Script that implements the Pivot Point Standard for intraday trading, with buy and sell signals based on the pivot point strategy.
Pivot points are calculated based on the previous day’s high, low, and close prices, and they are widely used in intraday trading to determine potential support and resistance levels.
00 Averaging Down Backtest Strategy by RPAlawyer v21FOR EDUCATIONAL PURPOSES ONLY! THE CODE IS NOT YET FULLY DEVELOPED, BUT IT CAN PROVIDE INTERESTING DATA AND INSIGHTS IN ITS CURRENT STATE.
This strategy is an 'averaging down' backtester strategy. The goal of averaging/doubling down is to buy more of an asset at a lower price to reduce your average entry price.
This backtester code proves why you shouldn't do averaging down, but the code can be developed (and will be developed) further, and there might be settings even in its current form that prove that averaging down can be done effectively.
Different averaging down strategies exist:
- Linear/Fixed Amount: buy $1000 every time price drops 5%
- Grid Trading: Placing orders at price levels, often with increasing size, like $1000 at -5%, $2000 at -10%
- Martingale: doubling the position size with each new entry
- Reverse Martingale: decreasing position size as price falls: $4000, then $2000, then $1000
- Percentage-Based: position size based on % of remaining capital, like 10% of available funds at each level
- Dynamic/Adaptive: larger entries during high volatility, smaller during low
- Logarithmic: position sizes increase logarithmically as price drops
Unlike the above average costing strategies, it applies averaging down (I use DCA as a synonym) at a very strong trend reversal. So not at a certain predetermined percentage negative PNL % but at a trend reversal signaled by an indicator - hence it most closely resembles a dynamically moving grid DCA strategy.
Both entering the trade and averaging down assume a strong trend. The signals for trend detection are provided by an indicator that I published under the name '00 Parabolic SAR Trend Following Signals by RPAlawyer', but any indicator that generates numeric signals of 1 and -1 for buy and sell signals can be used.
The indicator must be connected to the strategy: in the strategy settings under 'External Source' you need to select '00 Parabolic SAR Trend Following Signals by RPAlawyer: Connector'. From this point, the strategy detects when the indicator generates buy and sell signals.
The strategy considers a strong trend when a buy signal appears above a very conservative ATR band, or a sell signal below the ATR band. The conservative ATR is chosen to filter ranging markets. This very conservative ATR setting has a default multiplier of 8 and length of 40. The multiplier can be increased up to 10, but there will be very few buy and sell signals at that level and DCA requirements will be very high. Trade entry and DCA occur at these strong trends. In the settings, the 'ATR Filter' setting determines the entry condition (e.g., ATR Filter multiplier of 9), and the 'DCA ATR' determines when DCA will happen (e.g., DCA ATR multiplier of 6).
The DCA levels and DCA amounts are determined as follows:
The first DCA occurs below the DCA Base Deviation% level (see settings, default 3%) which acts as a threshold. The thick green line indicates the long position avg price, and the thin red line below the green line indicates the 3% DCA threshold for long positions. The thick red line indicates the short position avg price, and the thin red line above the thick red line indicates the short position 3% DCA threshold. DCA size multiplier defines the DCA amount invested.
If the loss exceeds 3% AND a buy signal arrives below the lower ATR band for longs, or a sell signal arrives above the upper ATR band for shorts, then the first DCA will be executed. So the first DCA won't happen at 3%, rather 3% is a threshold where the additional condition is that the price must close above or below the ATR band (let's say the first DCA occured at 8%) – this is why the code resembles a dynamic grid strategy, where the grid moves such that alongside the first 3% threshold, a strong trend must also appear for DCA. At this point, the thick green/red line moves because the avg price is modified as a result of the DCA, and the thin red line indicating the next DCA level also moves. The next DCA level is determined by the first DCA level, meaning modified avg price plus an additional +8% + (3% * the Step Scale Multiplier in the settings). This next DCA level will be indicated by the modified thin red line, and the price must break through this level and again break through the ATR band for the second DCA to occur.
Since all this wasn't complicated enough, and I was always obsessed by the idea that when we're sitting in an underwater position for days, doing DCA and waiting for the price to correct, we can actually enter a short position on the other side, on which we can realize profit (if the broker allows taking hedge positions, Binance allows this in Europe).
This opposite position in this strategy can open from the point AFTER THE FIRST DCA OF THE BASE POSITION OCCURS. This base position first DCA actually indicates that the price has already moved against us significantly so time to earn some money on the other side. Breaking through the ATR band is also a condition for entry here, so the hedge position entry is not automatic, and the condition for further DCA is breaking through the DCA Base Deviation (default 3%) and breaking through the ATR band. So for the 'hedge' or rather opposite position, the entry and further DCA conditions are the same as for the base position. The hedge position avg price is indicated by a thick black line and the Next Hedge DCA Level is indicated by a thin black line.
The TPs are indicated by green labels for base positions and red labels for hedge positions.
No SL built into the strategy at this point but you are free to do your coding.
Summary data can be found in the upper right corner.
The fantastic trend reversal indicator Machine learning: Lorentzian Classification by jdehorty can be used as an external indicator, choose 'backtest stream' for the external source. The ATR Band multiplicators need to be reduced to 5-6 when using Lorentz.
The code can be further developed in several aspects, and as I write this, I already have a few ideas 😊
Dynamic Volatility Differential Model (DVDM)The Dynamic Volatility Differential Model (DVDM) is a quantitative trading strategy designed to exploit the spread between implied volatility (IV) and historical (realized) volatility (HV). This strategy identifies trading opportunities by dynamically adjusting thresholds based on the standard deviation of the volatility spread. The DVDM is versatile and applicable across various markets, including equity indices, commodities, and derivatives such as the FDAX (DAX Futures).
Key Components of the DVDM:
1. Implied Volatility (IV):
The IV is derived from options markets and reflects the market’s expectation of future price volatility. For instance, the strategy uses volatility indices such as the VIX (S&P 500), VXN (Nasdaq 100), or RVX (Russell 2000), depending on the target market. These indices serve as proxies for market sentiment and risk perception (Whaley, 2000).
2. Historical Volatility (HV):
The HV is computed from the log returns of the underlying asset’s price. It represents the actual volatility observed in the market over a defined lookback period, adjusted to annualized levels using a multiplier of \sqrt{252} for daily data (Hull, 2012).
3. Volatility Spread:
The difference between IV and HV forms the volatility spread, which is a measure of divergence between market expectations and actual market behavior.
4. Dynamic Thresholds:
Unlike static thresholds, the DVDM employs dynamic thresholds derived from the standard deviation of the volatility spread. The thresholds are scaled by a user-defined multiplier, ensuring adaptability to market conditions and volatility regimes (Christoffersen & Jacobs, 2004).
Trading Logic:
1. Long Entry:
A long position is initiated when the volatility spread exceeds the upper dynamic threshold, signaling that implied volatility is significantly higher than realized volatility. This condition suggests potential mean reversion, as markets may correct inflated risk premiums.
2. Short Entry:
A short position is initiated when the volatility spread falls below the lower dynamic threshold, indicating that implied volatility is significantly undervalued relative to realized volatility. This signals the possibility of increased market uncertainty.
3. Exit Conditions:
Positions are closed when the volatility spread crosses the zero line, signifying a normalization of the divergence.
Advantages of the DVDM:
1. Adaptability:
Dynamic thresholds allow the strategy to adjust to changing market conditions, making it suitable for both low-volatility and high-volatility environments.
2. Quantitative Precision:
The use of standard deviation-based thresholds enhances statistical reliability and reduces subjectivity in decision-making.
3. Market Versatility:
The strategy’s reliance on volatility metrics makes it universally applicable across asset classes and markets, ensuring robust performance.
Scientific Relevance:
The strategy builds on empirical research into the predictive power of implied volatility over realized volatility (Poon & Granger, 2003). By leveraging the divergence between these measures, the DVDM aligns with findings that IV often overestimates future volatility, creating opportunities for mean-reversion trades. Furthermore, the inclusion of dynamic thresholds aligns with risk management best practices by adapting to volatility clustering, a well-documented phenomenon in financial markets (Engle, 1982).
References:
1. Christoffersen, P., & Jacobs, K. (2004). The importance of the volatility risk premium for volatility forecasting. Journal of Financial and Quantitative Analysis, 39(2), 375-397.
2. Engle, R. F. (1982). Autoregressive conditional heteroskedasticity with estimates of the variance of United Kingdom inflation. Econometrica, 50(4), 987-1007.
3. Hull, J. C. (2012). Options, Futures, and Other Derivatives. Pearson Education.
4. Poon, S. H., & Granger, C. W. J. (2003). Forecasting volatility in financial markets: A review. Journal of Economic Literature, 41(2), 478-539.
5. Whaley, R. E. (2000). The investor fear gauge. Journal of Portfolio Management, 26(3), 12-17.
This strategy leverages quantitative techniques and statistical rigor to provide a systematic approach to volatility trading, making it a valuable tool for professional traders and quantitative analysts.
Fibonacci Trend - Aynet1. Inputs
lookbackPeriod: Defines the number of bars to consider for calculating swing highs and lows. Default is 20.
fibLevel1 to fibLevel5: Fibonacci retracement levels to calculate price levels (23.6%, 38.2%, 50%, 61.8%, 78.6%).
useTime: Enables or disables time-based Fibonacci projections.
riskPercent: Defines the percentage of risk for trading purposes (currently not used in calculations).
2. Functions
isSwingHigh(index): Identifies a swing high at the given index, where the high of that candle is higher than both its previous and subsequent candles.
isSwingLow(index): Identifies a swing low at the given index, where the low of that candle is lower than both its previous and subsequent candles.
3. Variables
swingHigh and swingLow: Store the most recent swing high and swing low prices.
swingHighTime and swingLowTime: Store the timestamps of the swing high and swing low.
fib1 to fib5: Fibonacci levels based on the difference between swingHigh and swingLow.
4. Swing Point Detection
The script checks if the last bar is a swing high or swing low using the isSwingHigh() and isSwingLow() functions.
If a swing high is detected:
The high price is stored in swingHigh.
The timestamp of the swing high is stored in swingHighTime.
If a swing low is detected:
The low price is stored in swingLow.
The timestamp of the swing low is stored in swingLowTime.
5. Fibonacci Levels Calculation
If both swingHigh and swingLow are defined, the script calculates the Fibonacci retracement levels (fib1 to fib5) based on the price difference (priceDiff = swingHigh - swingLow).
6. Plotting Fibonacci Levels
Fibonacci levels (fib1 to fib5) are plotted as horizontal lines using the line.new() function.
Labels (e.g., "23.6%") are added near the lines to indicate the level.
Lines and labels are color-coded:
23.6% → Blue
38.2% → Green
50.0% → Yellow
61.8% → Orange
78.6% → Red
7. Filling Between Fibonacci Levels
The plot() function creates lines for each Fibonacci level.
The fill() function is used to fill the space between two levels with semi-transparent colors:
Blue → Between fib1 and fib2
Green → Between fib2 and fib3
Yellow → Between fib3 and fib4
Orange → Between fib4 and fib5
8. Time-Based Fibonacci Projections
If useTime is enabled:
The time difference (timeDiff) between the swing high and swing low is calculated.
Fibonacci time projections are added based on multiples of 23.6%.
If the current time reaches a projected time, a label (e.g., "T1", "T2") is displayed near the high price.
9. Trading Logic
Two placeholder variables are defined for trading logic:
longCondition: Tracks whether a condition for a long trade is met (currently not implemented).
shortCondition: Tracks whether a condition for a short trade is met (currently not implemented).
These variables can be extended to define entry/exit signals based on Fibonacci levels.
How It Works
Detect Swing Points: It identifies recent swing high and swing low points on the chart.
Calculate Fibonacci Levels: Based on the swing points, it computes retracement levels.
Visualize Levels: Plots the levels on the chart with labels and fills between them.
Time Projections: Optionally calculates time-based projections for future price movements.
Trading Opportunities: The framework provides tools for detecting potential reversal or breakout zones using Fibonacci levels.
Forex Hammer and Hanging Man StrategyThe strategy is based on two key candlestick chart patterns: Hammer and Hanging Man. These chart patterns are widely used in technical analysis to identify potential reversal points in the market. Their relevance in the Forex market, known for its high liquidity and volatile price movements, is particularly pronounced. Both patterns provide insights into market sentiment and trader psychology, which are critical in currency trading, where short-term volatility plays a significant role.
1. Hammer:
• Typically occurs after a downtrend.
• Signals a potential trend reversal to the upside.
• A Hammer has:
• A small body (close and open are close to each other).
• A long lower shadow, at least twice as long as the body.
• No or a very short upper shadow.
2. Hanging Man:
• Typically occurs after an uptrend.
• Signals a potential reversal to the downside.
• A Hanging Man has:
• A small body, similar to the Hammer.
• A long lower shadow, at least twice as long as the body.
• A small or no upper shadow.
These patterns are a manifestation of market psychology, specifically the tug-of-war between buyers and sellers. The Hammer reflects a situation where sellers tried to push the price down but were overpowered by buyers, while the Hanging Man shows that buyers failed to maintain the upward movement, and sellers could take control.
Relevance of Chart Patterns in Forex
In the Forex market, chart patterns are vital tools because they offer insights into price action and market sentiment. Since Forex trading often involves large volumes of trades, chart patterns like the Hammer and Hanging Man are important for recognizing potential shifts in market momentum. These patterns are a part of technical analysis, which aims to forecast future price movements based on historical data, relying on the psychology of market participants.
Scientific Literature on the Relevance of Candlestick Patterns
1. Behavioral Finance and Candlestick Patterns:
Research on behavioral finance supports the idea that candlestick patterns, such as the Hammer and Hanging Man, are relevant because they reflect shifts in trader psychology and sentiment. According to Lo, Mamaysky, and Wang (2000), patterns like these could be seen as representations of collective investor behavior, influenced by overreaction, optimism, or pessimism, and can often signal reversals in market trends.
2. Statistical Validation of Chart Patterns:
Studies by Brock, Lakonishok, and LeBaron (1992) explored the profitability of technical analysis strategies, including candlestick patterns, and found evidence that certain patterns, such as the Hammer, can have predictive value in financial markets. While their study primarily focused on stock markets, their findings are generally applicable to the Forex market as well.
3. Market Efficiency and Candlestick Patterns:
The efficient market hypothesis (EMH) posits that all available information is reflected in asset prices, but some studies suggest that markets may not always be perfectly efficient, allowing for profitable exploitation of certain chart patterns. For instance, Jegadeesh and Titman (1993) found that momentum strategies, which often rely on price patterns and trends, could generate significant returns, suggesting that patterns like the Hammer or Hanging Man may provide a slight edge, particularly in short-term Forex trading.
Testing the Strategy in Forex Using the Provided Script
The provided script allows traders to test and evaluate the Hammer and Hanging Man patterns in Forex trading by entering positions when these patterns appear and holding the position for a specified number of periods. This strategy can be tested to assess its performance across different currency pairs and timeframes.
1. Testing on Different Timeframes:
• The effectiveness of candlestick patterns can vary across different timeframes, as market dynamics change with the level of detail in each timeframe. Shorter timeframes may provide more frequent signals, but with higher noise, while longer timeframes may produce more reliable signals, but with fewer opportunities. This multi-timeframe analysis could be an area to explore to enhance the strategy’s robustness.
2. Exit Strategies:
• The script incorporates an exit strategy where positions are closed after holding them for a specified number of periods. This is useful for testing how long the reversal patterns typically take to play out and when the optimal exit occurs for maximum profitability. It can also help to adjust the exit logic based on real-time market behavior.
Conclusion
The Hammer and Hanging Man patterns are widely recognized in technical analysis as potential reversal signals, and their application in Forex trading is valuable due to the market’s high volatility and liquidity. This strategy leverages these candlestick patterns to enter and exit trades based on shifts in market sentiment and psychology. Testing and optimization, as offered by the script, can help refine the strategy and improve its effectiveness.
For further refinement, it could be valuable to consider combining candlestick patterns with other technical indicators or using multi-timeframe analysis to confirm patterns and increase the probability of successful trades.
References:
• Lo, A. W., Mamaysky, H., & Wang, J. (2000). Foundations of Technical Analysis: Computational Algorithms, Statistical Inference, and Empirical Implementation. The Journal of Finance, 55(4), 1705-1770.
• Brock, W., Lakonishok, J., & LeBaron, B. (1992). Simple Technical Trading Rules and the Stochastic Properties of Stock Returns. The Journal of Finance, 47(5), 1731-1764.
• Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. The Journal of Finance, 48(1), 65-91.
This provides a theoretical basis for the use of candlestick patterns in trading, supported by academic literature and research on market psychology and efficiency.
Adaptive Momentum Reversion StrategyThe Adaptive Momentum Reversion Strategy: An Empirical Approach to Market Behavior
The Adaptive Momentum Reversion Strategy seeks to capitalize on market price dynamics by combining concepts from momentum and mean reversion theories. This hybrid approach leverages a Rate of Change (ROC) indicator along with Bollinger Bands to identify overbought and oversold conditions, triggering trades based on the crossing of specific thresholds. The strategy aims to detect momentum shifts and exploit price reversions to their mean.
Theoretical Framework
Momentum and Mean Reversion: Momentum trading assumes that assets with a recent history of strong performance will continue in that direction, while mean reversion suggests that assets tend to return to their historical average over time (Fama & French, 1988; Poterba & Summers, 1988). This strategy incorporates elements of both, looking for periods when momentum is either overextended (and likely to revert) or when the asset’s price is temporarily underpriced relative to its historical trend.
Rate of Change (ROC): The ROC is a straightforward momentum indicator that measures the percentage change in price over a specified period (Wilder, 1978). The strategy calculates the ROC over a 2-period window, making it responsive to short-term price changes. By using ROC, the strategy aims to detect price acceleration and deceleration.
Bollinger Bands: Bollinger Bands are used to identify volatility and potential price extremes, often signaling overbought or oversold conditions. The bands consist of a moving average and two standard deviation bounds that adjust dynamically with price volatility (Bollinger, 2002).
The strategy employs two sets of Bollinger Bands: one for short-term volatility (lower band) and another for longer-term trends (upper band), with different lengths and standard deviation multipliers.
Strategy Construction
Indicator Inputs:
ROC Period: The rate of change is computed over a 2-period window, which provides sensitivity to short-term price fluctuations.
Bollinger Bands:
Lower Band: Calculated with a 18-period length and a standard deviation of 1.7.
Upper Band: Calculated with a 21-period length and a standard deviation of 2.1.
Calculations:
ROC Calculation: The ROC is computed by comparing the current close price to the close price from rocPeriod days ago, expressing it as a percentage.
Bollinger Bands: The strategy calculates both upper and lower Bollinger Bands around the ROC, using a simple moving average as the central basis. The lower Bollinger Band is used as a reference for identifying potential long entry points when the ROC crosses above it, while the upper Bollinger Band serves as a reference for exits, when the ROC crosses below it.
Trading Conditions:
Long Entry: A long position is initiated when the ROC crosses above the lower Bollinger Band, signaling a potential shift from a period of low momentum to an increase in price movement.
Exit Condition: A position is closed when the ROC crosses under the upper Bollinger Band, or when the ROC drops below the lower band again, indicating a reversal or weakening of momentum.
Visual Indicators:
ROC Plot: The ROC is plotted as a line to visualize the momentum direction.
Bollinger Bands: The upper and lower bands, along with their basis (simple moving averages), are plotted to delineate the expected range for the ROC.
Background Color: To enhance decision-making, the strategy colors the background when extreme conditions are detected—green for oversold (ROC below the lower band) and red for overbought (ROC above the upper band), indicating potential reversal zones.
Strategy Performance Considerations
The use of Bollinger Bands in this strategy provides an adaptive framework that adjusts to changing market volatility. When volatility increases, the bands widen, allowing for larger price movements, while during quieter periods, the bands contract, reducing trade signals. This adaptiveness is critical in maintaining strategy effectiveness across different market conditions.
The strategy’s pyramiding setting is disabled (pyramiding=0), ensuring that only one position is taken at a time, which is a conservative risk management approach. Additionally, the strategy includes transaction costs and slippage parameters to account for real-world trading conditions.
Empirical Evidence and Relevance
The combination of momentum and mean reversion has been widely studied and shown to provide profitable opportunities under certain market conditions. Studies such as Jegadeesh and Titman (1993) confirm that momentum strategies tend to work well in trending markets, while mean reversion strategies have been effective during periods of high volatility or after sharp price movements (De Bondt & Thaler, 1985). By integrating both strategies into one system, the Adaptive Momentum Reversion Strategy may be able to capitalize on both trending and reverting market behavior.
Furthermore, research by Chan (1996) on momentum-based trading systems demonstrates that adaptive strategies, which adjust to changes in market volatility, often outperform static strategies, providing a compelling rationale for the use of Bollinger Bands in this context.
Conclusion
The Adaptive Momentum Reversion Strategy provides a robust framework for trading based on the dual concepts of momentum and mean reversion. By using ROC in combination with Bollinger Bands, the strategy is capable of identifying overbought and oversold conditions while adapting to changing market conditions. The use of adaptive indicators ensures that the strategy remains flexible and can perform across different market environments, potentially offering a competitive edge for traders who seek to balance risk and reward in their trading approaches.
References
Bollinger, J. (2002). Bollinger on Bollinger Bands. McGraw-Hill Professional.
Chan, L. K. C. (1996). Momentum, Mean Reversion, and the Cross-Section of Stock Returns. Journal of Finance, 51(5), 1681-1713.
De Bondt, W. F., & Thaler, R. H. (1985). Does the Stock Market Overreact? Journal of Finance, 40(3), 793-805.
Fama, E. F., & French, K. R. (1988). Permanent and Temporary Components of Stock Prices. Journal of Political Economy, 96(2), 246-273.
Jegadeesh, N., & Titman, S. (1993). Returns to Buying Winners and Selling Losers: Implications for Stock Market Efficiency. Journal of Finance, 48(1), 65-91.
Poterba, J. M., & Summers, L. H. (1988). Mean Reversion in Stock Prices: Evidence and Implications. Journal of Financial Economics, 22(1), 27-59.
Wilder, J. W. (1978). New Concepts in Technical Trading Systems. Trend Research.
EMA Crossover Strategy with Take Profit and Candle HighlightingStrategy Overview:
This strategy is based on the Exponential Moving Averages (EMA), specifically the EMA 20 and EMA 50. It takes advantage of EMA crossovers to identify potential trend reversals and uses multiple take-profit levels and a stop-loss for risk management.
Key Components:
EMA Crossover Signals:
Buy Signal (Uptrend): A buy signal is generated when the EMA 20 crosses above the EMA 50, signaling the start of a potential uptrend.
Sell Signal (Downtrend): A sell signal is generated when the EMA 20 crosses below the EMA 50, signaling the start of a potential downtrend.
Take Profit Levels:
Once a buy or sell signal is triggered, the strategy calculates multiple take-profit levels based on the range of the previous candle. The user can define multipliers for each take-profit level.
Take Profit 1 (TP1): 50% of the previous candle's range above or below the entry price.
Take Profit 2 (TP2): 100% of the previous candle's range above or below the entry price.
Take Profit 3 (TP3): 150% of the previous candle's range above or below the entry price.
Take Profit 4 (TP4): 200% of the previous candle's range above or below the entry price.
These levels are adjusted dynamically based on the previous candle's high and low, so they adapt to changing market conditions.
Stop Loss:
A stop-loss is set to manage risk. The default stop-loss is 3% from the entry price, but this can be adjusted in the settings. The stop-loss is triggered if the price moves against the position by this amount.
Trend Direction Highlighting:
The strategy highlights the bars (candles) with colors:
Green bars indicate an uptrend (when EMA 20 crosses above EMA 50).
Red bars indicate a downtrend (when EMA 20 crosses below EMA 50).
These visual cues help users easily identify the market direction.
Strategy Entries and Exits:
Entries: The strategy enters a long (buy) position when the EMA 20 crosses above the EMA 50 and a short (sell) position when the EMA 20 crosses below the EMA 50.
Exits: The strategy exits the positions at any of the defined take-profit levels or the stop-loss. Multiple exit levels provide opportunities to take profit progressively as the price moves in the favorable direction.
Entry and Exit Conditions in Detail:
Buy Entry Condition (Uptrend):
A buy position is opened when EMA 20 crosses above EMA 50, signaling the start of an uptrend.
The strategy calculates take-profit levels above the entry price based on the previous bar's range (high-low) and the multipliers for TP1, TP2, TP3, and TP4.
Sell Entry Condition (Downtrend):
A sell position is opened when EMA 20 crosses below EMA 50, signaling the start of a downtrend.
The strategy calculates take-profit levels below the entry price, similarly based on the previous bar's range.
Exit Conditions:
Take Profit: The strategy attempts to exit the position at one of the take-profit levels (TP1, TP2, TP3, or TP4). If the price reaches any of these levels, the position is closed.
Stop Loss: The strategy also has a stop-loss set at a default value (3% below the entry for long trades, and 3% above for short trades). The stop-loss helps to protect the position from significant losses.
Backtesting and Performance Metrics:
The strategy can be backtested using TradingView's Strategy Tester. The results will show how the strategy would have performed historically, including key metrics like:
Net Profit
Max Drawdown
Win Rate
Profit Factor
Average Trade Duration
These performance metrics can help users assess the strategy's effectiveness over historical periods and optimize the input parameters (e.g., multipliers, stop-loss level).
Customization:
The strategy allows for the adjustment of several key input values via the settings panel:
Take Profit Multipliers: Users can customize the multipliers for each take-profit level (TP1, TP2, TP3, TP4).
Stop Loss Percentage: The user can also adjust the stop-loss percentage to a custom value.
EMA Periods: The default periods for the EMA 50 and EMA 20 are fixed, but they can be adjusted for different market conditions.
Pros of the Strategy:
EMA Crossover Strategy: A classic and well-known strategy used by traders to identify the start of new trends.
Multiple Take Profit Levels: By taking profits progressively at different levels, the strategy locks in gains as the price moves in favor of the position.
Clear Trend Identification: The use of green and red bars makes it visually easier to follow the market's direction.
Risk Management: The stop-loss and take-profit features help to manage risk and optimize profit-taking.
Cons of the Strategy:
Lagging Indicators: The strategy relies on EMAs, which are lagging indicators. This means that the strategy might enter trades after the trend has already started, leading to missed opportunities or less-than-ideal entry prices.
No Confirmation Indicators: The strategy purely depends on the crossover of two EMAs and does not use other confirming indicators (e.g., RSI, MACD), which might lead to false signals in volatile markets.
How to Use in Real-Time Trading:
Use for Backtesting: Initially, use this strategy in backtest mode to understand how it would have performed historically with your preferred settings.
Paper Trading: Once comfortable, you can use paper trading to test the strategy in real-time market conditions without risking real money.
Live Trading: After testing and optimizing the strategy, you can consider using it for live trading with proper risk management in place (e.g., starting with a small position size and adjusting parameters as needed).
Summary:
This strategy is designed to identify trend reversals using EMA crossovers, with customizable take-profit levels and a stop-loss to manage risk. It's well-suited for traders looking for a systematic way to enter and exit trades based on clear market signals, while also providing flexibility to adjust for different risk profiles and trading styles.
DCA Buy v1Key Features
1. Selective Entry Filters
Trend Filter
Enabled through "Enable Trend Filter?" using the "EMA Length" setting to ensure entries align with prevailing trends.
Momentum Filter
Configured using "Enable Momentum Filter?" combined with "RSI Length" and "RSI Source" to detect oversold conditions.
Bollinger Filter
Activated via "Enable Bollinger Filter?" along with "BB Length" and "BB Multiplier" to focus entries on deeper price dips below Bollinger Bands.
2. DCA Configuration
Base Order Settings
Choose between a percentage ("Base Order % of Equity/Initial Capital") or fixed value ("Base Order Value ($)").
Safety Order Settings
Fine-tune "Initial Deviation (%)" and "Price Deviation Multiplier" to control the spacing of safety orders.
Use "Volume Scaling Factor (Qty)" to scale the size of each subsequent safety order.
Customize the "First Safety Order Type" as either value-based or a multiplier of the base order using "1st Safety Order Value ($)" or "1st Safety Order Multiplier (Qty)".
Set the maximum number of safety orders through "Max Safety Orders".
3. Profit and Risk Management
Take Profit Settings
"Take Profit (%)" triggers a sell when a specific profit percentage above the average entry is reached.
Use "Trailing Take Profit (%)" to lock in profits while capturing additional upside if prices continue to rise.
Stop Loss Settings
Configure "Stop Loss (%)" to prevent excessive drawdowns by closing all positions when prices drop below a defined percentage.
4. Time Control & Visualization
Time Filters
Define trading windows with "Start Time" and "End Time".
Use "Cooldown (Seconds)" to avoid frequent entries during rapid price movements.
Visualization
Enable "Show Average Entry Price", "Show Take Profit Level", and "Show Stop Loss Level" to plot key levels on the chart for better monitoring.
5. Performance Metrics
Built-in performance tracking includes:
Net Profit (%): Measures overall profitability.
Win Rate (%): Displays the ratio of winning trades.
Max Drawdown (%): Tracks the largest equity decline.
Trading Days: Calculates the duration of active trades.
Profit/Day (%): Evaluates daily returns.
The performance table also shows average cycle duration and utilization of available capital.