Dynamic RSI Mean Reversion StrategyDynamic RSI Mean Reversion Strategy
Overview:
This strategy uses an RSI with ATR-Adjusted OB/OS levels in order to enhance the quality of it's mean reversion trades. It also incorporates a form of trend filtering in an effort to minimize downside and maximize upside. The backtest has fewer trades, as it uses substantial filtering to enhance trade quality. As you can see, I didn't cherry pick the results, so the results aren't the most beautiful thing you'll see in your life. I did this to ensure nobody gets misled. If you need a higher frequency of trades, consider removing the trend filter or increasing the length of the EMAs used for trend detection.
Features:
Dynamic OB/OS Levels: Uses ATR to adjust overbought and oversold thresholds dynamically, making the RSI more responsive in varying volatility conditions. This approach enhances signal strength by expanding the RSI range in high volatility and tightening it in low volatility.
Mean Reversion Focus: Designed for mean reversion but incorporates a trend-following filter to reduce countertrend trades. When the RSI is high, it often indicates an uptrend, so a trend filter prevents shorting in these cases and the same goes for downtrends and longing.
Trend Filtering: A moving average cross trend filter checks for the trend direction, with the RSI signal line color-coded to reflect trend shifts. Entries occur when the RSI crosses above or below the dynamic thresholds and is not a countertrend trade.
Stop Losses: Stop losses are set based on ATR distance from the entry price, providing volatility-adjusted protection.
Note:
If you're using this strategy on assets with a higher price, remember to increase the initial capital in the strategy settings. Otherwise, the strategy won't generate any (or many) trades and you'll end up with some inaccurate results.
Recommended Use:
Test it on different assets and timeframes. I’ve found the best results with standard RSI inputs, a relatively slow ATR, and a slower MA cross for trend filtering. Thus, the defaults are set that way. If the trend metrics are too slow, you’ll filter out too many good trades while allowing crummy ones; if too fast, most trades may be filtered out. As always, this has a lot of configurability so experiment to find the balance that works for your trading style.
Meanreversion
Z-Score RSI StrategyOverview
The Z-Score RSI Indicator is an experimental take on momentum analysis. By applying the Relative Strength Index (RSI) to a Z-score of price data, it measures how far prices deviate from their mean, scaled by standard deviation. This isn’t your traditional use of RSI, which is typically based on price data alone. Nevertheless, this unconventional approach can yield unique insights into market trends and potential reversals.
Theory and Interpretation
The RSI calculates the balance between average gains and losses over a set period, outputting values from 0 to 100. Typically, people look at the overbought or oversold levels to identify momentum extremes that might be likely to lead to a reversal. However, I’ve often found that RSI can be effective for trend-following when observing the crossover of its moving average with the midline or the crossover of the RSI with its own moving average. These crossovers can provide useful trend signals in various market conditions.
By combining RSI with a Z-score of price, this indicator estimates the relative strength of the price’s distance from its mean. Positive Z-score trends may signal a potential for higher-than-average prices in the near future (scaled by the standard deviation), while negative trends suggest the opposite. Essentially, when the Z-Score RSI indicates a trend, it reflects that the Z-score (the distance between the average and current price) is likely to continue moving in the trend’s direction. Generally, this signals a potential price movement, though it’s important to note that this could also occur if there’s a shift in the mean or standard deviation, rather than a meaningful change in price itself.
While the Z-Score RSI could be an insightful addition to a comprehensive trading system, it should be interpreted carefully. Mean shifts may validate the indicator’s predictions without necessarily indicating any notable price change, meaning it’s best used in tandem with other indicators or strategies.
Recommendations
Before putting this indicator to use, conduct thorough backtesting and avoid overfitting. The added parameters allow fine-tuning to fit various assets, but be careful not to optimize purely for the highest historical returns. Doing so may create an overly tailored strategy that performs well in backtests but fails in live markets. Keep it balanced and look for robust performance across multiple scenarios, as overfitting is likely to lead to disappointing real-world results.
Intramarket Difference Index StrategyHi Traders !!
The IDI Strategy:
In layman’s terms this strategy compares two indicators across markets and exploits their differences.
note: it is best the two markets are correlated as then we know we are trading a short to long term deviation from both markets' general trend with the assumption both markets will trend again sometime in the future thereby exhausting our trading opportunity.
📍 Import Notes:
This Strategy calculates trade position size independently (i.e. risk per trade is controlled in the user inputs tab), this means that the ‘Order size’ input in the ‘Properties’ tab will have no effect on the strategy. Why ? because this allows us to define custom position size algorithms which we can use to improve our risk management and equity growth over time. Here we have the option to have fixed quantity or fixed percentage of equity ATR (Average True Range) based stops in addition to the turtle trading position size algorithm.
‘Pyramiding’ does not work for this strategy’, similar to the order size input togeling this input will have no effect on the strategy as the strategy explicitly defines the maximum order size to be 1.
This strategy is not perfect, and as of writing of this post I have not traded this algo.
Always take your time to backtests and debug the strategy.
🔷 The IDI Strategy:
By default this strategy pulls data from your current TV chart and then compares it to the base market, be default BINANCE:BTCUSD . The strategy pulls SMA and RSI data from either market (we call this the difference data), standardizes the data (solving the different unit problem across markets) such that it is comparable and then differentiates the data, calling the result of this transformation and difference the Intramarket Difference (ID). The formula for the the ID is
ID = market1_diff_data - market2_diff_data (1)
Where
market(i)_diff_data = diff_data / ATR(j)_market(i)^0.5,
where i = {1, 2} and j = the natural numbers excluding 0
Formula (1) interpretation is the following
When ID > 0: this means the current market outperforms the base market
When ID = 0: Markets are at long run equilibrium
When ID < 0: this means the current market underperforms the base market
To form the strategy we define one of two strategy type’s which are Trend and Mean Revesion respectively.
🔸 Trend Case:
Given the ‘‘Strategy Type’’ is equal to TREND we define a threshold for which if the ID crosses over we go long and if the ID crosses under the negative of the threshold we go short.
The motivating idea is that the ID is an indicator of the two symbols being out of sync, and given we know volatility clustering, momentum and mean reversion of anomalies to be a stylised fact of financial data we can construct a trading premise. Let's first talk more about this premise.
For some markets (cryptocurrency markets - synthetic symbols in TV) the stylised fact of momentum is true, this means that higher momentum is followed by higher momentum, and given we know momentum to be a vector quantity (with magnitude and direction) this momentum can be both positive and negative i.e. when the ID crosses above some threshold we make an assumption it will continue in that direction for some time before executing back to its long run equilibrium of 0 which is a reasonable assumption to make if the market are correlated. For example for the BTCUSD - ETHUSD pair, if the ID > +threshold (inputs for MA and RSI based ID thresholds are found under the ‘‘INTRAMARKET DIFFERENCE INDEX’’ group’), ETHUSD outperforms BTCUSD, we assume the momentum to continue so we go long ETHUSD.
In the standard case we would exit the market when the IDI returns to its long run equilibrium of 0 (for the positive case the ID may return to 0 because ETH’s difference data may have decreased or BTC’s difference data may have increased). However in this strategy we will not define this as our exit condition, why ?
This is because we want to ‘‘let our winners run’’, to achieve this we define a trailing Donchian Channel stop loss (along with a fixed ATR based stop as our volatility proxy). If we were too use the 0 exit the strategy may print a buy signal (ID > +threshold in the simple case, market regimes may be used), return to 0 and then print another buy signal, and this process can loop may times, this high trade frequency means we fail capture the entire market move lowering our profit, furthermore on lower time frames this high trade frequencies mean we pay more transaction costs (due to price slippage, commission and big-ask spread) which means less profit.
By capturing the sum of many momentum moves we are essentially following the trend hence the trend following strategy type.
Here we also print the IDI (with default strategy settings with the MA difference type), we can see that by letting our winners run we may catch many valid momentum moves, that results in a larger final pnl that if we would otherwise exit based on the equilibrium condition(Valid trades are denoted by solid green and red arrows respectively and all other valid trades which occur within the original signal are light green and red small arrows).
another example...
Note: if you would like to plot the IDI separately copy and paste the following code in a new Pine Script indicator template.
indicator("IDI")
// INTRAMARKET INDEX
var string g_idi = "intramarket diffirence index"
ui_index_1 = input.symbol("BINANCE:BTCUSD", title = "Base market", group = g_idi)
// ui_index_2 = input.symbol("BINANCE:ETHUSD", title = "Quote Market", group = g_idi)
type = input.string("MA", title = "Differrencing Series", options = , group = g_idi)
ui_ma_lkb = input.int(24, title = "lookback of ma and volatility scaling constant", group = g_idi)
ui_rsi_lkb = input.int(14, title = "Lookback of RSI", group = g_idi)
ui_atr_lkb = input.int(300, title = "ATR lookback - Normalising value", group = g_idi)
ui_ma_threshold = input.float(5, title = "Threshold of Upward/Downward Trend (MA)", group = g_idi)
ui_rsi_threshold = input.float(20, title = "Threshold of Upward/Downward Trend (RSI)", group = g_idi)
//>>+----------------------------------------------------------------+}
// CUSTOM FUNCTIONS |
//<<+----------------------------------------------------------------+{
// construct UDT (User defined type) containing the IDI (Intramarket Difference Index) source values
// UDT will hold many variables / functions grouped under the UDT
type functions
float Close // close price
float ma // ma of symbol
float rsi // rsi of the asset
float atr // atr of the asset
// the security data
getUDTdata(symbol, malookback, rsilookback, atrlookback) =>
indexHighTF = barstate.isrealtime ? 1 : 0
= request.security(symbol, timeframe = timeframe.period,
expression = [close , // Instentiate UDT variables
ta.sma(close, malookback) ,
ta.rsi(close, rsilookback) ,
ta.atr(atrlookback) ])
data = functions.new(close_, ma_, rsi_, atr_)
data
// Intramerket Difference Index
idi(type, symbol1, malookback, rsilookback, atrlookback, mathreshold, rsithreshold) =>
threshold = float(na)
index1 = getUDTdata(symbol1, malookback, rsilookback, atrlookback)
index2 = getUDTdata(syminfo.tickerid, malookback, rsilookback, atrlookback)
// declare difference variables for both base and quote symbols, conditional on which difference type is selected
var diffindex1 = 0.0, var diffindex2 = 0.0,
// declare Intramarket Difference Index based on series type, note
// if > 0, index 2 outpreforms index 1, buy index 2 (momentum based) until equalibrium
// if < 0, index 2 underpreforms index 1, sell index 1 (momentum based) until equalibrium
// for idi to be valid both series must be stationary and normalised so both series hae he same scale
intramarket_difference = 0.0
if type == "MA"
threshold := mathreshold
diffindex1 := (index1.Close - index1.ma) / math.pow(index1.atr*malookback, 0.5)
diffindex2 := (index2.Close - index2.ma) / math.pow(index2.atr*malookback, 0.5)
intramarket_difference := diffindex2 - diffindex1
else if type == "RSI"
threshold := rsilookback
diffindex1 := index1.rsi
diffindex2 := index2.rsi
intramarket_difference := diffindex2 - diffindex1
//>>+----------------------------------------------------------------+}
// STRATEGY FUNCTIONS CALLS |
//<<+----------------------------------------------------------------+{
// plot the intramarket difference
= idi(type,
ui_index_1,
ui_ma_lkb,
ui_rsi_lkb,
ui_atr_lkb,
ui_ma_threshold,
ui_rsi_threshold)
//>>+----------------------------------------------------------------+}
plot(intramarket_difference, color = color.orange)
hline(type == "MA" ? ui_ma_threshold : ui_rsi_threshold, color = color.green)
hline(type == "MA" ? -ui_ma_threshold : -ui_rsi_threshold, color = color.red)
hline(0)
Note it is possible that after printing a buy the strategy then prints many sell signals before returning to a buy, which again has the same implication (less profit. Potentially because we exit early only for price to continue upwards hence missing the larger "trend"). The image below showcases this cenario and again, by allowing our winner to run we may capture more profit (theoretically).
This should be clear...
🔸 Mean Reversion Case:
We stated prior that mean reversion of anomalies is an standerdies fact of financial data, how can we exploit this ?
We exploit this by normalizing the ID by applying the Ehlers fisher transformation. The transformed data is then assumed to be approximately normally distributed. To form the strategy we employ the same logic as for the z score, if the FT normalized ID > 2.5 (< -2.5) we buy (short). Our exit conditions remain unchanged (fixed ATR stop and trailing Donchian Trailing stop)
🔷 Position Sizing:
If ‘‘Fixed Risk From Initial Balance’’ is toggled true this means we risk a fixed percentage of our initial balance, if false we risk a fixed percentage of our equity (current balance).
Note we also employ a volatility adjusted position sizing formula, the turtle training method which is defined as follows.
Turtle position size = (1/ r * ATR * DV) * C
Where,
r = risk factor coefficient (default is 20)
ATR(j) = risk proxy, over j times steps
DV = Dollar Volatility, where DV = (1/Asset Price) * Capital at Risk
🔷 Risk Management:
Correct money management means we can limit risk and increase reward (theoretically). Here we employ
Max loss and gain per day
Max loss per trade
Max number of consecutive losing trades until trade skip
To read more see the tooltips (info circle).
🔷 Take Profit:
By defualt the script uses a Donchain Channel as a trailing stop and take profit, In addition to this the script defines a fixed ATR stop losses (by defualt, this covers cases where the DC range may be to wide making a fixed ATR stop usefull), ATR take profits however are defined but optional.
ATR SL and TP defined for all trades
🔷 Hurst Regime (Regime Filter):
The Hurst Exponent (H) aims to segment the market into three different states, Trending (H > 0.5), Random Geometric Brownian Motion (H = 0.5) and Mean Reverting / Contrarian (H < 0.5). In my interpretation this can be used as a trend filter that eliminates market noise.
We utilize the trending and mean reverting based states, as extra conditions required for valid trades for both strategy types respectively, in the process increasing our trade entry quality.
🔷 Example model Architecture:
Here is an example of one configuration of this strategy, combining all aspects discussed in this post.
Future Updates
- Automation integration (next update)
Bollinger Bands Enhanced StrategyOverview
The common practice of using Bollinger bands is to use it for building mean reversion or squeeze momentum strategies. In the current script Bollinger Bands Enhanced Strategy we are trying to combine the strengths of both strategies types. It utilizes Bollinger Bands indicator to buy the local dip and activates trailing profit system after reaching the user given number of Average True Ranges (ATR). Also it uses 200 period EMA to filter trades only in the direction of a trend. Strategy can execute only long trades.
Unique Features
Trailing Profit System: Strategy uses user given number of ATR to activate trailing take profit. If price has already reached the trailing profit activation level, scrip will close long trade if price closes below Bollinger Bands middle line.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Major Trend Filter: Strategy utilizes 100 period EMA to take trades only in the direction of a trend.
Flexible Risk Management: Users can choose number of ATR as a stop loss (by default = 1.75) for trades. This is flexible approach because ATR is recalculated on every candle, therefore stop-loss readjusted to the current volatility.
Methodology
First of all, script checks if currently price is above the 200-period exponential moving average EMA. EMA is used to establish the current trend. Script will take long trades on if this filtering system showing us the uptrend. Then the strategy executes the long trade if candle’s low below the lower Bollinger band. To calculate the middle Bollinger line, we use the standard 20-period simple moving average (SMA), lower band is calculated by the substruction from middle line the standard deviation multiplied by user given value (by default = 2).
When long trade executed, script places stop-loss at the price level below the entry price by user defined number of ATR (by default = 1.75). This stop-loss level recalculates at every candle while trade is open according to the current candle ATR value. Also strategy set the trailing profit activation level at the price above the position average price by user given number of ATR (by default = 2.25). It is also recalculated every candle according to ATR value. When price hit this level script plotted the triangle with the label “Strong Uptrend” and start trail the price at the middle Bollinger line. It also started to be plotted as a green line.
When price close below this trailing level script closes the long trade and search for the next trade opportunity.
Risk Management
The strategy employs a combined and flexible approach to risk management:
It allows positions to ride the trend as long as the price continues to move favorably, aiming to capture significant price movements. It features a user-defined ATR stop loss parameter to mitigate risks based on individual risk tolerance. By default, this stop-loss is set to a 1.75*ATR drop from the entry point, but it can be adjusted according to the trader's preferences.
There is no fixed take profit, but strategy allows user to define user the ATR trailing profit activation parameter. By default, this stop-loss is set to a 2.25*ATR growth from the entry point, but it can be adjusted according to the trader's preferences.
Justification of Methodology
This strategy leverages Bollinger bangs indicator to open long trades in the local dips. If price reached the lower band there is a high probability of bounce. Here is an issue: during the strong downtrend price can constantly goes down without any significant correction. That’s why we decided to use 200-period EMA as a trend filter to increase the probability of opening long trades during major uptrend only.
Usually, Bollinger Bands indicator is using for mean reversion or breakout strategies. Both of them have the disadvantages. The mean reversion buys the dip, but closes on the return to some mean value. Therefore, it usually misses the major trend moves. The breakout strategies usually have the issue with too high buy price because to have the breakout confirmation price shall break some price level. Therefore, in such strategies traders need to set the large stop-loss, which decreases potential reward to risk ratio.
In this strategy we are trying to combine the best features of both types of strategies. Script utilizes ate ATR to setup the stop-loss and trailing profit activation levels. ATR takes into account the current volatility. Therefore, when we setup stop-loss with the user-given number of ATR we increase the probability to decrease the number of false stop outs. The trailing profit concept is trying to add the beat feature from breakout strategies and increase probability to stay in trade while uptrend is developing. When price hit the trailing profit activation level, script started to trail the price with middle line if Bollinger bands indicator. Only when candle closes below the middle line script closes the long trade.
Backtest Results
Operating window: Date range of backtests is 2020.10.01 - 2024.07.01. It is chosen to let the strategy to close all opened positions.
Commission and Slippage: Includes a standard Binance commission of 0.1% and accounts for possible slippage over 5 ticks.
Initial capital: 10000 USDT
Percent of capital used in every trade: 30%
Maximum Single Position Loss: -9.78%
Maximum Single Profit: +25.62%
Net Profit: +6778.11 USDT (+67.78%)
Total Trades: 111 (48.65% win rate)
Profit Factor: 2.065
Maximum Accumulated Loss: 853.56 USDT (-6.60%)
Average Profit per Trade: 61.06 USDT (+1.62%)
Average Trade Duration: 76 hours
These results are obtained with realistic parameters representing trading conditions observed at major exchanges such as Binance and with realistic trading portfolio usage parameters.
How to Use
Add the script to favorites for easy access.
Apply to the desired timeframe and chart (optimal performance observed on 4h BTC/USDT).
Configure settings using the dropdown choice list in the built-in menu.
Set up alerts to automate strategy positions through web hook with the text: {{strategy.order.alert_message}}
Disclaimer:
Educational and informational tool reflecting Skyrex commitment to informed trading. Past performance does not guarantee future results. Test strategies in a simulated environment before live implementation
AlgoBuilder [Mean-Reversion] | FractalystWhat's the strategy's purpose and functionality?
This strategy is designed for both traders and investors looking to rely and trade based on historical and backtested data using automation.
The main goal is to build profitable mean-reversion strategies that outperform the underlying asset in terms of returns while minimizing drawdown.
For example, as for a benchmark, if the S&P 500 (SPX) has achieved an estimated 10% annual return with a maximum drawdown of -57% over the past 20 years, using this strategy with different entry and exit techniques, users can potentially seek ways to achieve a higher Compound Annual Growth Rate (CAGR) while maintaining a lower maximum drawdown.
Although the strategy can be applied to all markets and timeframes, it is most effective on stocks, indices, future markets, cryptocurrencies, and commodities and JPY currency pairs given their trending behaviors.
In trending market conditions, the strategy employs a combination of moving averages and diverse entry models to identify and capitalize on upward market movements. It integrates market structure-based moving averages and bands mechanisms across different timeframes and provides exit techniques, including percentage-based and risk-reward (RR) based take profit levels.
Additionally, the strategy has also a feature that includes a built-in probability function for traders who want to implement probabilities right into their trading strategies.
Performance summary, weekly, and monthly tables enable quick visualization of performance metrics like net profit, maximum drawdown, profit factor, average trade, average risk-reward ratio (RR), and more.
This aids optimization to meet specific goals and risk tolerance levels effectively.
-----
How does the strategy perform for both investors and traders?
The strategy has two main modes, tailored for different market participants: Traders and Investors.
Trading:
1. Trading:
- Designed for traders looking to capitalize on bullish trending markets.
- Utilizes a percentage risk per trade to manage risk and optimize returns.
- Suitable for active trading with a focus on mean-reversion and risk per trade approach.
◓: Mode | %: Risk percentage per trade
3. Investing:
- Geared towards investors who aim to capitalize on bullish trending markets without using leverage while mitigating the asset's maximum drawdown.
- Utilizes pre-define percentage of the equity to buy, hold, and manage the asset.
- Focuses on long-term growth and capital appreciation by fully investing in the asset during bullish conditions.
- ◓: Mode | %: Risk not applied (In investing mode, the strategy uses 10% of equity to buy the asset)
-----
What's is FRMA? How does the triple bands work? What are the underlying calculations?
Middle Band (FRMA):
The middle band is the core of the FRMA system. It represents the Fractalyst Moving Average, calculated by identifying the most recent external swing highs and lows in the market structure.
By determining these external swing pivot points, which act as significant highs and lows within the market range, the FRMA provides a unique moving average that adapts to market structure changes.
Upper Band:
The upper band shows the average price of the most recent external swing highs.
External swing highs are identified as the highest points between pivot points in the market structure.
This band helps traders identify potential overbought conditions when prices approach or exceed this upper band.
Lower Band:
The lower band shows the average price of the most recent external swing lows.
External swing lows are identified as the lowest points between pivot points in the market structure.
The script utilizes this band to identify potential oversold conditions, triggering entry signals as prices approach or drop below the lower band.
Adjustments Based on User Inputs:
Users can adjust how the upper and lower bands are calculated based on their preferences:
Upper/Lower: This method calculates the average bands using the prices of external swing highs and lows identified in the market.
Percentage Deviation from FRMA: Alternatively, users can opt to calculate the bands based on a percentage deviation from the middle FRMA. This approach provides flexibility to adjust the width of the bands relative to market conditions and volatility.
-----
What's the purpose of using moving averages in this strategy? What are the underlying calculations?
Using moving averages is a widely-used technique to trade with the trend.
The main purpose of using moving averages in this strategy is to filter out bearish price action and to only take trades when the price is trading ABOVE specified moving averages.
The script uses different types of moving averages with user-adjustable timeframes and periods/lengths, allowing traders to try out different variations to maximize strategy performance and minimize drawdowns.
By applying these calculations, the strategy effectively identifies bullish trends and avoids market conditions that are not conducive to profitable trades.
The MA filter allows traders to choose whether they want a specific moving average above or below another one as their entry condition.
This comparison filter can be turned on (>) or off.
For example, you can set the filter so that MA#1 > MA#2, meaning the first moving average must be above the second one before the script looks for entry conditions. This adds an extra layer of trend confirmation, ensuring that trades are only taken in more favorable market conditions.
⍺: MA Period | Σ: MA Timeframe
-----
What entry modes are used in this strategy? What are the underlying calculations?
The strategy by default uses two different techniques for the entry criteria with user-adjustable left and right bars: Breakout and Fractal.
1. Breakout Entries :
- The strategy looks for pivot high points with a default period of 3.
- It stores the most recent high level in a variable.
- When the price crosses above this most recent level, the strategy checks if all conditions are met and the bar is closed before taking the buy entry.
◧: Pivot high left bars period | ◨: Pivot high right bars period
2. Fractal Entries :
- The strategy looks for pivot low points with a default period of 3.
- When a pivot low is detected, the strategy checks if all conditions are met and the bar is closed before taking the buy entry.
◧: Pivot low left bars period | ◨: Pivot low right bars period
2. Hunt Entries :
- The strategy identifies a candle that wicks through the lower FRMA band.
- It waits for the next candle to close above the low of the wick candle.
- When this condition is met and the bar is closed, the strategy takes the buy entry.
By utilizing these entry modes, the strategy aims to capitalize on bullish price movements while ensuring that the necessary conditions are met to validate the entry points.
-----
What type of stop-loss identification method are used in this strategy? What are the underlying calculations?
Initial Stop-Loss:
1. ATR Based:
The Average True Range (ATR) is a method used in technical analysis to measure volatility. It is not used to indicate the direction of price but to measure volatility, especially volatility caused by price gaps or limit moves.
Calculation:
- To calculate the ATR, the True Range (TR) first needs to be identified. The TR takes into account the most current period high/low range as well as the previous period close.
The True Range is the largest of the following:
- Current Period High minus Current Period Low
- Absolute Value of Current Period High minus Previous Period Close
- Absolute Value of Current Period Low minus Previous Period Close
- The ATR is then calculated as the moving average of the TR over a specified period. (The default period is 14).
Example - ATR (14) * 2
⍺: ATR period | Σ: ATR Multiplier
2. ADR Based:
The Average Day Range (ADR) is an indicator that measures the volatility of an asset by showing the average movement of the price between the high and the low over the last several days.
Calculation:
- To calculate the ADR for a particular day:
- Calculate the average of the high prices over a specified number of days.
- Calculate the average of the low prices over the same number of days.
- Find the difference between these average values.
- The default period for calculating the ADR is 14 days. A shorter period may introduce more noise, while a longer period may be slower to react to new market movements.
Example - ADR (20) * 2
⍺: ADR period | Σ: ADR Multiplier
3. PL Based:
This method places the stop-loss at the low of the previous candle.
If the current entry is based on the hunt entry strategy, the stop-loss will be placed at the low of the candle that wicks through the lower FRMA band.
Example:
If the previous candle's low is 100, then the stop-loss will be set at 100.
This method ensures the stop-loss is placed just below the most recent significant low, providing a logical and immediate level for risk management.
Application in Strategy (ATR/ADR):
- The strategy calculates the current bar's ADR/ATR with a user-defined period.
- It then multiplies the ADR/ATR by a user-defined multiplier to determine the initial stop-loss level.
By using these methods, the strategy dynamically adjusts the initial stop-loss based on market volatility, helping to protect against adverse price movements while allowing for enough room for trades to develop.
Each market behaves differently across various timeframes, and it is essential to test different parameters and optimizations to find out which trailing stop-loss method gives you the desired results and performance.
-----
What type of break-even and take profit identification methods are used in this strategy? What are the underlying calculations?
For Break-Even:
Percentage (%) Based:
Moves the initial stop-loss to the entry price when the price reaches a certain percentage above the entry.
Calculation:
Break-even level = Entry Price * (1 + Percentage / 100)
Example:
If the entry price is $100 and the break-even percentage is 5%, the break-even level is $100 * 1.05 = $105.
Risk-to-Reward (RR) Based:
Moves the initial stop-loss to the entry price when the price reaches a certain RR ratio.
Calculation:
Break-even level = Entry Price + (Initial Risk * RR Ratio)
Example:
If the entry price is $100, the initial risk is $10, and the RR ratio is 2, the break-even level is $100 + ($10 * 2) = $120.
FRMA Based:
Moves the stop-loss to break-even when the price hits the FRMA level at which the entry was taken.
Calculation:
Break-even level = FRMA level at the entry
Example:
If the FRMA level at entry is $102, the break-even level is set to $102 when the price reaches $102.
For TP1 (Take Profit 1):
- You can choose to set a take profit level at which your position gets fully closed or 50% if the TP2 boolean is enabled.
- Similar to break-even, you can select either a percentage (%) or risk-to-reward (RR) based take profit level, allowing you to set your TP1 level as a percentage amount above the entry price or based on RR.
For TP2 (Take Profit 2):
- You can choose to set a take profit level at which your position gets fully closed.
- As with break-even and TP1, you can select either a percentage (%) or risk-to-reward (RR) based take profit level, allowing you to set your TP2 level as a percentage amount above the entry price or based on RR.
When Both Percentage (%) Based and RR Based Take Profit Levels Are Off:
The script will adjust the take profit level to the higher FRMA band set within user inputs.
Calculation:
Take profit level = Higher FRMA band length/timeframe specified by the user.
This ensures that when neither percentage-based nor risk-to-reward-based take profit methods are enabled, the strategy defaults to using the higher FRMA band as the take profit level, providing a consistent and structured approach to profit-taking.
For TP1 and TP2, it's specifying the price levels at which the position is partially or fully closed based on the chosen method (percentage or RR) above the entry price.
These calculations are crucial for managing risk and optimizing profitability in the strategy.
⍺: BE/TP type (%/RR) | Σ: how many RR/% above the current price
-----
What's the ADR filter? What does it do? What are the underlying calculations?
The Average Day Range (ADR) measures the volatility of an asset by showing the average movement of the price between the high and the low over the last several days.
The period of the ADR filter used in this strategy is tied to the same period you've used for your initial stop-loss.
Users can define the minimum ADR they want to be met before the script looks for entry conditions.
ADR Bias Filter:
- Compares the current bar ADR with the ADR (Defined by user):
- If the current ADR is higher, it indicates that volatility has increased compared to ADR (DbU).(⬆)
- If the current ADR is lower, it indicates that volatility has decreased compared to ADR (DbU).(⬇)
Calculations:
1. Calculate ADR:
- Average the high prices over the specified period.
- Average the low prices over the same period.
- Find the difference between these average values in %.
2. Current ADR vs. ADR (DbU):
- Calculate the ADR for the current bar.
- Calculate the ADR (DbU).
- Compare the two values to determine if volatility has increased or decreased.
By using the ADR filter, the strategy ensures that trades are only taken in favorable market conditions where volatility meets the user's defined threshold, thus optimizing entry conditions and potentially improving the overall performance of the strategy.
>: Minimum required ADR for entry | %: Current ADR comparison to ADR of 14 days ago.
-----
What's the probability filter? What are the underlying calculations?
The probability filter is designed to enhance trade entries by using buyside liquidity and probability analysis to filter out unfavorable conditions.
This filter helps in identifying optimal entry points where the likelihood of a profitable trade is higher.
Calculations:
1. Understanding Swing highs and Swing Lows
Swing High: A Swing High is formed when there is a high with 2 lower highs to the left and right.
Swing Low: A Swing Low is formed when there is a low with 2 higher lows to the left and right.
2. Understanding the purpose and the underlying calculations behind Buyside, Sellside and Equilibrium levels.
3. Understanding probability calculations
1. Upon the formation of a new range, the script waits for the price to reach and tap into equilibrium or the 50% level. Status: "⏸" - Inactive
2. Once equilibrium is tapped into, the equilibrium status becomes activated and it waits for either liquidity side to be hit. Status: "▶" - Active
3. If the buyside liquidity is hit, the script adds to the count of successful buyside liquidity occurrences. Similarly, if the sellside is tapped, it records successful sellside liquidity occurrences.
5. Finally, the number of successful occurrences for each side is divided by the overall count individually to calculate the range probabilities.
Note: The calculations are performed independently for each directional range. A range is considered bearish if the previous breakout was through a sellside liquidity. Conversely, a range is considered bullish if the most recent breakout was through a buyside liquidity.
Example - BSL > 55%
-----
What's the range length Filter? What are the underlying calculations?
The range length filter identifies the price distance between buyside and sellside liquidity levels in percentage terms. When enabled, the script only looks for entries when the minimum range length is met. This helps ensure that trades are taken in markets with sufficient price movement.
Calculations:
Range Length (%) = ( ( Buyside Level − Sellside Level ) / Current Price ) ×100
Range Bias Identification:
Bullish Bias: The current range price has broken above the previous external swing high.
Bearish Bias: The current range price has broken below the previous external swing low.
Example - Range length filter is enabled | Range must be above 1%
>: Minimum required range length for entry | %: Current range length percentage in a (Bullish/Bearish) range
-----
What's the day filter Filter, what does it do?
The day filter allows users to customize the session time and choose the specific days they want to include in the strategy session. This helps traders tailor their strategies to particular trading sessions or days of the week when they believe the market conditions are more favorable for their trading style.
Customize Session Time:
Users can define the start and end times for the trading session.
This allows the strategy to only consider trades within the specified time window, focusing on periods of higher market activity or preferred trading hours.
Select Days:
Users can select which days of the week to include in the strategy.
This feature is useful for excluding days with historically lower volatility or unfavorable trading conditions (e.g., Mondays or Fridays).
Benefits:
Focus on Optimal Trading Periods:
By customizing session times and days, traders can focus on periods when the market is more likely to present profitable opportunities.
Avoid Unfavorable Conditions:
Excluding specific days or times can help avoid trading during periods of low liquidity or high unpredictability, such as major news events or holidays.
Increased Flexibility: The filter provides increased flexibility, allowing traders to adapt the strategy to their specific needs and preferences.
Example - Day filter | Session Filter
θ: Session time | Exchange time-zone
-----
What tables are available in this script?
Table Type:
- Summary: Provides a general overview, displaying key performance parameters such as Net Profit, Profit Factor, Max Drawdown, Average Trade, Closed Trades and more.
Avg Trade: The sum of money gained or lost by the average trade generated by a strategy. Calculated by dividing the Net Profit by the overall number of closed trades. An important value since it must be large enough to cover the commission and slippage costs of trading the strategy and still bring a profit.
MaxDD: Displays the largest drawdown of losses, i.e., the maximum possible loss that the strategy could have incurred among all of the trades it has made. This value is calculated separately for every bar that the strategy spends with an open position.
Profit Factor: The amount of money a trading strategy made for every unit of money it lost (in the selected currency). This value is calculated by dividing gross profits by gross losses.
Avg RR: This is calculated by dividing the average winning trade by the average losing trade. This field is not a very meaningful value by itself because it does not take into account the ratio of the number of winning vs losing trades, and strategies can have different approaches to profitability. A strategy may trade at every possibility in order to capture many small profits, yet have an average losing trade greater than the average winning trade. The higher this value is, the better, but it should be considered together with the percentage of winning trades and the net profit.
Winrate: The percentage of winning trades generated by a strategy. Calculated by dividing the number of winning trades by the total number of closed trades generated by a strategy. Percent profitable is not a very reliable measure by itself. A strategy could have many small winning trades, making the percent profitable high with a small average winning trade, or a few big winning trades accounting for a low percent profitable and a big average winning trade. Most mean-reversion successful strategies have a percent profitability of 40-80% but are profitable due to risk management control.
BE Trades: Number of break-even trades, excluding commission/slippage.
Losing Trades: The total number of losing trades generated by the strategy.
Winning Trades: The total number of winning trades generated by the strategy.
Total Trades: Total number of taken traders visible your charts.
Net Profit: The overall profit or loss (in the selected currency) achieved by the trading strategy in the test period. The value is the sum of all values from the Profit column (on the List of Trades tab), taking into account the sign.
- Monthly: Displays performance data on a month-by-month basis, allowing users to analyze performance trends over each month.
- Weekly: Displays performance data on a week-by-week basis, helping users to understand weekly performance variations.
- OFF: Hides the performance table.
Profit Color:
- Allows users to set the color for representing profit in the performance table, helping to quickly distinguish profitable periods.
Loss Color:
- Allows users to set the color for representing loss in the performance table, helping to quickly identify loss-making periods.
These customizable tables provide traders with flexible and detailed performance analysis, aiding in better strategy evaluation and optimization.
-----
User-input styles and customizations:
To facilitate studying historical data, all conditions and rules can be applied to your charts. By plotting background colors on your charts, you'll be able to identify what worked and what didn't in certain market conditions.
Please note that all background colors in the style are disabled by default to enhance visualization.
-----
How to Use This Algobuilder to Create a Profitable Edge and System:
Choose Your Strategy mode:
- Decide whether you are creating an investing strategy or a trading strategy.
Select a Market:
- Choose a one-sided market such as stocks, indices, or cryptocurrencies.
Historical Data:
- Ensure the historical data covers at least 10 years of price action for robust backtesting.
Timeframe Selection:
- Choose the timeframe you are comfortable trading with. It is strongly recommended to use a timeframe above 15 minutes to minimize the impact of commissions/slippage on your profits.
Set Commission and Slippage:
- Properly set the commission and slippage in the strategy properties according to your broker or prop firm specifications.
Parameter Optimization:
- Use trial and error to test different parameters until you find the performance results you are looking for in the summary table or, preferably, through deep backtesting using the strategy tester.
Trade Count:
- Ensure the number of trades is 100 or more; the higher, the better for statistical significance.
Positive Average Trade:
- Make sure the average trade value is above zero.
(An important value since it must be large enough to cover the commission and slippage costs of trading the strategy and still bring a profit.)
Performance Metrics:
- Look for a high profit factor, and net profit with minimum drawdown.
- Ideally, aim for a drawdown under 20-30%, depending on your risk tolerance.
Refinement and Optimization:
- Try out different markets and timeframes.
- Continue working on refining your edge using the available filters and components to further optimize your strategy.
Automation:
- Once you’re confident in your strategy, you can use the automation section to connect the algorithm to your broker or prop firm.
- Trade a fully automated and backtested trading strategy, allowing for hands-free execution and management.
-----
What makes this strategy original?
1. Incorporating direct integration of probabilities into the strategy.
2. Utilizing built-in market structure-based moving averages across various timeframes.
4. Offering both investing and trading strategies, facilitating optimization from different perspectives.
5. Automation for efficient execution.
6. Providing a summary table for instant access to key parameters of the strategy.
-----
How to use automation?
For Traders:
1. Ensure the strategy parameters are properly set based on your optimized parameters.
2. Enter your PineConnector License ID in the designated field.
3. Specify the desired risk level.
4. Provide the Metatrader symbol.
5. Check for chart updates to ensure the automation table appears on the top right corner, displaying your License ID, risk, and symbol.
6. Set up an alert with the strategy selected as Condition and the Message as {{strategy.order.alert_message}}.
7. Activate the Webhook URL in the Notifications section, setting it as the official PineConnector webhook address.
8. Double-check all settings on PineConnector to ensure the connection is successful.
9. Create the alert for entry/exit automation.
For Investors:
1. Ensure the strategy parameters are properly set based on your optimized parameters.
2. Choose "Investing" in the user-input settings.
3. Create an alert with a specified name.
4. Customize the notifications tab to receive alerts via email.
5. Buying/selling alerts will be triggered instantly upon entry or exit order execution.
-----
Terms and Conditions | Disclaimer
Our charting tools are provided for informational and educational purposes only and should not be construed as financial, investment, or trading advice. They are not intended to forecast market movements or offer specific recommendations. Users should understand that past performance does not guarantee future results and should not base financial decisions solely on historical data.
Built-in components, features, and functionalities of our charting tools are the intellectual property of @Fractalyst Unauthorized use, reproduction, or distribution of these proprietary elements is prohibited.
By continuing to use our charting tools, the user acknowledges and accepts the Terms and Conditions outlined in this legal disclaimer and agrees to respect our intellectual property rights and comply with all applicable laws and regulations.
PRICE CHANNEL MEAN REVERSIONThis script is a Fully Automated trading script meant to be used with "Oanda" broker and the plug-ins for algorithmic trading automation.( FOREX ONLY)
This script is meant to capture "MEAN REVERSION " for intraday charts (1hour) preferably and will hold for days / weeks .trading on forex markets.
(The combination of indicators includes a high and low price channel along with a fast moving average)
This script is original in the description of Alan Hulls moving average combined with the high and low closing of price action.
The concept of this mean reversion strategy is to try and capture price exhaustive moves . The moving average is fast and most times remains in the channel. when the moving average overshoots the channel the average price of the instrument is thought to be rising or falling faster then average, indicating a possibility that the instrument may revert (pull back) this strategy aims to capture that pull back.
This strategy uses a higher risk than reward profile to jump in front of market moves (4 risk to 1 reward)
in the likelihood the instrument will revert back (example) 25 pips before it continues 100 pips in the current direction.
This strategy should only be used in markets that you believe are mean reverting at the time of trading otherwise you will be jumping Infront of a possible trend and the price can continue in the trending direction for an unknown specified amount of time.
This script uses a (user defined period) fast moving average ( green/red color) and (user defined period) price channel (White/Blue) chosen in the indicator settings menu.
The default parameters are 55 with a (minimum of 1 and maximum of 10000) for the moving average and 50 with a (minimum of 1 and maximum of 10000) for the price channel , the default parameters = roughly 2 days of price action on the (1 hour) chart.
"The default parameters should be kept unless you fully understand the complete strategy"
the upper band (white line) is the highest close of the specified period and the lower band (blue line) is the lowest close of the same period.
When the fast moving average over shoots the price channel (exits) then crosses back into the price channel (enters) it will trigger a long or short trade.
The long signal is given when the the moving average crosses below the low band then crosses back above the low band . The trade long trade will be entered and the trade will exit if the stop loss or profit targets are hit or if the short signal is given the trade will close then reverse.
The short trade will be entered if the fast moving average crosses above the upper band (white line) then crosses back down through the upper band (white line) The trade short trade will be entered and the trade will exit if the stop loss or profit targets are hit or if the long signal is given the trade will close then reverse.
When the trade is entered a red , a blue and green horizontal dotted line will appear on the chart.
the blue line is the strategy entry price , the red line is the stop loss price , and the green line is the take profit price . the colors will invert if the trade is long or short.
(Setting alerts should be done in the indicator settings menu, and the parameters you chose will determine the stop loss/target and the amount of "units = (position size)" you wish to trade for the (forex only) markets. using "alert() function calls only" is the only alert that should be used with this strategy.
(note : when "alert() function calls only" is set two messages will be sent, one closing any open position in the opposite direction and one placing the new order regardless if you are currently in a trade or not)
Trade targets , stoploss and trade position size are a user defined variables entered in the indicator settings menu. (target pips minimum 0 and a maximum of 1000)(stop pips minimum of 0 and maximum of 1000)
Back test date range is included in the script for back testing different data periods.
the back ground will be colored a transparent navy blue if the period you are looking trading is with in the date range( note: to place live trades the end date will need to be in the future)
this is also adjustable in the settings menu
The avoid spread filter is a user defined time in which the spread is typically higher than average, applying this filter avoids trades in the specified time. When this filter is applied there will be a transparent red back ground color in the specified time.
Back test default setting are equivocal to OANDA:NZDUSD
at the time of this publication placing trades with the "Oanda" broker are as follows , NZD units = 3250 equal 2000 USD position size . "Oanda" current leverage is 33.3 to 1 for this particular pair and commission is paid in spread (1.7) pips = 0.55 USD per trade , Margin required for the trade is 60.50 USD , Position sizing = 6.5% of a 1000 USD account. OANDA:NZDUSD
HTF star - trailingDescription:
The HTF - Stars (Highertimeframe Stars) Strategy Script is designed to explore the behavior of a strategy using multiple timeframes. This experimental script focuses on identifying star candle patterns on a chosen higher timeframe and capturing subsequent price movements on a lower timeframe. By leveraging the power of star candle patterns forming on a higher timeframe, this strategy aims to capture potential trading opportunities on a shorter timeframe.
Key Features:
Multiple Timeframe Analysis: The strategy script allows you to be on a lower timeframe while searching for star candle patterns on a higher timeframe using the security function. This approach enables you to take advantage of higher timeframe insights and potentially capture favorable price movements on a shorter timeframe.
Star Candle Pattern Detection: The script identifies star candle patterns on the chosen higher timeframe. After the candle closes, a buy or sell order is executed on the lower timeframe, signaling a potential trading opportunity based on the detected pattern.
Trailing Stop: The strategy utilizes a trailing stop feature to manage trades. The trailing stop is set at a specified ATR (Average True Range) distance above or below the candle closes. This mechanism allows you to capture potential profits if the price moves in the anticipated direction and then reverses.
Mean Reversion Potential: During backtesting, it was observed that shorting stars above the 360 MA (Moving Average) and taking long positions on stars below the 360 MA yielded the most profitable results in the current market conditions. This suggests that star candle patterns in this context may serve as potential mean reversion signals. However, user inputs allow for customization, enabling you to experiment with different trading approaches when a star candle is detected.
Backtesting Feature: The script includes a backtesting feature that uses a percentage of equity, with 1% of equity set as the default. It displays a table presenting various statistics about the strategy's performance, providing valuable insights into its historical results.
Adjustable User Inputs: The script offers multiple adjustable settings, each accompanied by tooltips explaining their functionality. This flexibility allows you to fine-tune the strategy according to your preferences and experiment with different parameters to optimize its performance.
Disclaimer:
The HTF - Stars Strategy Script is provided for experimental and educational purposes only. Trading in the financial markets involves risk, and you should only trade with funds that you can afford to lose. The information presented in this script does not constitute financial advice or investment recommendations. Always conduct your own research and due diligence before making any investment decisions. The creator of this script shall not be held responsible for any losses or damages incurred from the use of this script. Historical performance is not indicative of future results.
Please note that past performance is not necessarily indicative of future results. Trading the markets involves risk, and there is no guarantee that the strategy described will be profitable for you. It is important to thoroughly test the strategy, adapt it to your trading style, and use proper risk management techniques.
BBPullback1.0.2This is a simple strategy script based on Bollinger Bands pullbacks.
The strategy is simple, as follows:
For LONGS: At the close of any candle, it check to see if this candle is an UP candle where the low broke below the lower Bollinger Band. If so, we call this the trigger candle. For the next bar, we issue a BUY signal if the price breaks above the high of the trigger candle. The stoploss is the low of the trigger candle. We take profit when the price goes above the middle Bollinger Band (the mean/average line).
For SHORTS: At the close of any candle, it check to see if this candle is an DOWN candle where the high broke above the upper Bollinger Band. If so, we call this the trigger candle. For the next bar, we issue a SELL signal if the price breaks below the low of the trigger candle. The stoploss is the high of the trigger candle. We take profit when the price goes below the middle Bollinger Band (the mean/average line).
I11L - Reversal Trading Ideas by Larry ConnorsThis is my own Twist on Larry Connors Simple Tradingideas.
It Combines the RSI, Averaging In and the Lowest Bars in a Single System.
The current Configuration is designed for the Daily Timeframe.
Feel free to play with the Parameters and keep in mind that Larry Intended to buy fear and sell the greed!
The Rules are the following:
---Buy---
Buy, if the lowest Bar of your Configuration has been hit (default is set to 7).
---Average Down--
Buy, if the lowest Bar of your Configuration * Your open trades has been hit AND only if the buyin is atleast 1% cheaper.
---Close---
Close, if the RSI closes above a certain level (default is set to 70).
---TP---
There is no TP
---SL---
There is no SL, so be cautions of your tail Risk!
Quantitative mean reversion v4The code uses the concept of mean reversion. Mean reversion suggests that price over a period of time reverts back to its statistical mean. In simple terms, it means if a price has drifted apart from the statistical mean, after a certain amount of time, it will revert back to its statistical mean. This drift is measured via z-score. When the z-score value is high, the price is expected to revert. Besides, the higher the time frame you use, the lesser the drift is, so reduce the z-score in the tabs if you use higher time frames, else, vice-versa.
Based on the parameters, the code will provide a trade signal - both long and short, and entry and exit. You can use notifications for alerts. Please use the parameters in the options to find the best combinations for your stocks.
In the properties, you can use your own brokers commission, capital, to see if the strategy is profitable for your ticker in the long run or not. This code has been tested for profits for various assets in both crypto - Bitcoin futures , Ethereum futures -, and stocks - AMD , Apple , MSFT , etc.
This is not get rich quick scheme, and you have to be patient with it for the long run.
If you have any query, please feel free to ask in the comments sections.
If you want some new changes, please feel free to suggest
Currently, I am optimising the maximum time for holding a trade. Till that's completed, use this and please feel free to leave a feedback to make it better
tvbot Trend Following with Mean Reversion algoDefault settings are for the ETHUSDT 5 min Binance Chart regular candles.
Back test Default settings are 10,000 usd to start, Commission 0.075%, capital deployment per position is 10%, slippage value of 1.
This algo uses the EMA to set the trend line . You are also able to turn the trend line into a range instead of just a static line. The algo uses the VWMA to set the base entry parameters. When a candle closes above or below the VWMA it will record that price and then wait for the VWMA to meet the candle close price. When that happens the Base entry condition is met. (it causes the vwma to create a hook like structure. essentially tell you that the momentum has changed directions.)
The algo will always check to see if the trend line has either breached or has been tested and held. If this condition has been met it will then go to the base entry condition to check to see if the momentum has changed.
There is a mean reversion component in this algo as well. When the price has moved away from the mean(set by user) by a certain amount the algo will start to look for a top or bottom. Once that condition has been met it will then use the base entry condition to look for a change in momentum, but the mean reversion base entry condition uses the HMA to check for a change in momentum.
This algo effectively looks like a hamburger. Mean reversion being the tops and bottoms(bun) and the trend following(beef patty)
Mean reversionSimple mean reversion strategy.
Strategy aims to find three bullish or bearish candle pattern which ends with strong move. Position will be open until we get close above previous highs.
Strategy uses also simple moving average to filter short positions.
This strategy works well with QQQ and daily time frame but it seems to do fairly well intraday also.
User can modify moving average length and how strong is the move of the last candle.
This strategy is inspired a strategy by hackertrader. The original idea by QuantpT.
Steven Primo's bollinger bands strategyHi, this strategy is taken from a video made by Steven Primo. You can look it up on YouTube if you want to know about it.
It is a mean-reversion strategy based on the Bollinger Bands, in which we wait for 5 consecutive closes above the upper band, and for a short-term top. Once it happens, we place an entry order on this top, with a stop at the nearest bottom before the movement started, and use the difference from the stop and entry point to determine the target. For shorting, it's the same process, but for the downside. From my testing, only long orders were profitable, but you can configure whichever you want.
It works well for directional markets with a low level of noise, as you can see with the BTCUSD chart. One of its caveats is the short number of occurrences, and the long stop loss and target. You can enable a trailing stop, but from my testings, it just made the results worse.
I made some modifications, like removing the MA requirement, since the entry point was above it almost all the time, and I forced the BB to use a log version of the prices, so that discrepancies are eliminated. You'll also notice that you can't select an extension that is lower than 100, and that is intentional, since you're not supposed to enter a trade in which you can lose more than what you can earn.
I chose not to implement any kind of risk management, but I might do that in the future. You can leave your suggestions in the comments.
R3 ETF StrategyThis strategy is a modification of the “R3 Strategy” from the book "High Probability ETF Trading" by Larry Connors and Cesar Alvarez. This RSI strategy is for a 1-day time-frame and has these 3 simple rules:
Criteria:
The price must be above the 200 day moving average.
The 2-period (day) RSI drops 3 days in a row.
The 2-period RSI must have been below 60 3 days ago and below 10 today.
Entry and Exit:
If the 3 rules above are true, then buy on the close of the current day.
Exit on the day's close when the RSI crosses above 70.
How it works :
The Strategy will buy when the buy conditions above are true. The strategy will sell when the RSI crosses above 70. The RSI period/length, and RSI entry/exit criteria thresholds have all been coded to be adjustable with inputs.
Plots :
Blue line = 200 Day EMA (Used as Entry Criteria)
Disclaimer: Open-source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. If you would like to implement a version of any script, I would recommend making significant additions/modifications to the strategy & risk management functions. If you don’t know how to program in Pine, then hire a Pine-coder. We can help!
Outside DayThis strategy is taken from Perry Kaufman's book "Trading System and Methods".
You can enter on the direction of the candle, or opposite to it. I find that the opposite tends to yield better results in volatile assets, allowing a better reward to risk ratio. There is no stop loss in this strategy, only a fixed take profit and a time limitation.
Low-High-Trend StrategyWhen asked what the key to successful investing was, Warren Buffet famously said “buy low, sell high.” Was he onto something? Today I am sharing with the community a simple “buy low, sell high” strategy with an optional trend filter and take-profit target. I’ve found that this strategy works well in a variety of markets but has a higher tendency to out-perform buy & hold in markets that are ranging sideways.
How it works:
The strategy tracks the highest and lowest price over the last X number of bars (you select the look-back period). The highest price line is plotted in green and the lowest price line is potted in red. If the price crosses over the lowest price in the last X number of bars, then a buy signal is generated. Exit options include a take-profit % or selling when the price crosses over the highest price in the last X amount of bars. I.e. “Buy low, sell high.” An EMA is also plotted as a blue trend line, and there is an option to only trade if the price is above the EMA trend line.
Disclaimer: Open source scripts I publish in the community are largely meant to spark ideas that can be used as building blocks for part of a more robust trade management strategy. Even though this example script beats buy and hold over the back-test time-frame, I wouldn't advise using it as a stand-alone strategy without significant additions/modifications to the strategy and risk management functions. In this example the script is being used as a medium-term strategy with just 10% leverage over account equity, a $25k start balance, and back-testing 10+ years. Modifiable slippage and commissions are included in the model.
Green line = Highest price in the look-back period
Red line = Lowest price in the look-back period
Blue line = EMA Trend
Mean Reversion Strategy v2 [KL]Description :
This strategy will enter a position when the following conditions are met:
a) Main signal: When source data (ATR) diverts from its moving average value, and
b) Confirmation: If predicted direction of trend is favorable.
Assumptions :
During periods of high price volatility, ATR diverts from its moving average value. Eventually, ATR should revert. But since just knowing the magnitude of increase/decrease of ATR does not indicate a trend signal, we need to introduce a model to predict the current trend.
In short:
• Trend Prediction : This strategy calculates the expected logarithmic return of the security (the "Drift") and considers prices to be moving in uptrend if the drift curve is upward sloping.
• Assessment of ATR diversion : To determine "yes/no" regarding whether ATR at a given point in time has diverted, this script conducts a two-tailed hypothesis test at each candlestick period. The null hypothesis (H0) is that the fast moving average value should equal the slow moving average value (say, denoted as H0: atr14 == atr28; it is assumed that atr28 is more meaningful for the purpose of describing the current trend because it has a larger sample size). Investopedia has an article summarizing this topic .
Exit Condition :
When trailing stop loss hits.
Previous version :
This strategy is based on Version 1 published back in September . This older version considers +/- one standard deviation to be the critical values relative to average ATR when testing whether ATR has diverted from the mean. This does not take Standard Error ("SE") into account. As a result, the threshold is often too wide and it generates too many entry signals.
[KL] Mean Reversion (ATR) StrategyThis strategy will enter into a position when price volatility is relative high, betting that price will subsequently trend in a favourable direction.
Hypothesis : During periods of high price volatility, ATR will divert from its moving average by at least +/- one standard deviation. Eventually, ATR will revert back to the mean. However, just knowing the magnitude of increase/decrease of ATR does not give a trend signal, so we need to introduce a model in this script to predict whether the next bars will be up/down.
Trend Prediction : This strategy calculates the expected logarithmic return of the security (the "Drift") and considers prices to be moving in uptrend if the drift curve is upward sloping or if the drift value is positive.
Entry Conditions : Long position is entered when:
(a) ATR has diverted from mean by one standard deviation, and
(b) trend is predicted to move in our favor.
Exit Condition : When trailing stop loss is hit.
Results from backtesting against VOO (1H timeframe):
- approx 46% win rate over 491 trades, on average holding for 20 hours per trade
- price at the beginning of backtest (Jan. 2015) was $187.52, giving holding period return of ~120% had we not sold in between ("HPR of HODL'ing")
- this strategy gained ~159%, exceeding ~120% HPR of HODL'ing
HYE Combo Market [Strategy] (Vwap Mean Reversion + Trend Hunter)In this strategy, I used a combination of trend hunter and vwap mean reversion strategies that I published before.
Trend Hunter Strategy:
Mean Reversion Vwap Strategy:
The results are quite impressive, especially for bitcoin.
While the hodl return for bitcoin was 13419%, the strategy's return in the same period was about 5 times (65000%) of this.
s3.tradingview.com
In this combo strategy, I made some changes to the original settings of the strategies used together and added some more new features.
Trend Hunter Strategy Settings: (Original / Combo)
- Slow Tenkansen Period : 9 / 9
- Slow Kijunsen Period : 26 / 13
- Fast Tenkansen Period : 5 / 3
- Fast Kijunsen Period : 13 / 7
- BB Length : 20 / 20
- BB Stdev : 2 / 2
- TSV Length : 13 / 20
- TSV Ema Length : 7 / 7
* I also added a "vidya moving average" to be used as a confirmation tool to open a long position. (Candle close must be above the vidya line.)
Vwap Mean Reversion Strategy Settings: (Original / Combo)
- Small Vwap : 2 / 8
- Big Vwap : 5 / 10
- Percent Below to Buy : 3 / 2
- RSI Period : 2 / 2
- RSI Ema Period : 5 / 5
- Maximum RSI Level for Buy : 30
* I also added a "mean vwap line" to be used for exits in this part of the strategy. In the original version, when small vwap crossovers big vwap, we close the position, but in this strategy we will wait for the close above the mean vwap.
TIPS AND WARNINGS
1-) The standard settings of this combo strategy is designed and tested with daily timeframe. For lower timeframes, you should change the strategy settings and find the best value for yourself.
2-) Only the mean vwap line is displayed on the graph. For a detailed view, you can delete the "//" marks from the plot codes in the strategy code.
3-) This is a strategy for educational and experimental purposes. It cannot be considered as investment advice. You should be careful and make your own risk assessment when opening real market trades using this strategy.
________________________________________________________
Bu stratejide, daha önce yayınladığım trend avcısı ve vwap ortalamaya geri dönüş stratejilerinin bir kombinasyonunu kullandım.
Sonuçlar özellikle bitcoin için oldukça etkileyici.
Bitcoin için hodl getirisi %13419 iken, stratejinin aynı dönemdeki getirisi bunun yaklaşık 5 katı (%65000) idi.
Bu kombo stratejide, birlikte kullanılan stratejilerin orijinal ayarlarında bazı değişiklikler yaptım ve bazı yeni özellikler ekledim.
Trend Avcısı Strateji Ayarları: (Orijinal / Combo)
- Yavaş Tenkansen Periyodu : 9 / 9
- Yavaş Kijunsen Periyodu : 26 / 13
- Hızlı Tenkansen Periyodu : 5 / 3
- Hızlı Kijunsen Periyodu : 13 / 7
- BB Uzunluğu : 20 / 20
- BB Standart Sapması : 2 / 2
- TSV Uzunluğu : 13 / 20
- TSV Ema Uzunluğu : 7 / 7
* Ayrıca long pozisyon açmak için onay aracı olarak kullanılmak üzere "vidya hareketli ortalama" ekledim. (Mum kapanışı vidya çizgisinin üzerinde olmalıdır.)
Vwap Ortalamaya Dönüş Stratejisi Ayarları: (Orijinal / Combo)
- Küçük Vwap : 2 / 8
- Büyük Vwap : 5 / 10
- Alış İçin Gerekli Fark Oranı : 3 / 2
- RSI Periyodu : 2 / 2
- RSI Ema Periyodu: 5 / 5
- Alış için gerekli maksimum RSI seviyesi : 30
* Stratejinin bu bölümünde pozisyondan çıkışlar için kullanılacak bir "ortalama vwap çizgisi" de ekledim. Orijinal versiyonda, küçük vwap, büyük vwap'ı yukarı kestiğinde pozisyonu kapatıyoruz, ancak bu stratejide, ortalama vwap'ın üzerindeki kapanışı bekleyeceğiz.
İPUÇLARI VE UYARILAR
1-) Bu birleşik stratejinin standart ayarları, günlük zaman dilimi ile tasarlanmış ve test edilmiştir. Daha düşük zaman dilimleri için strateji ayarlarını değiştirmeli ve kendiniz için en iyi değeri bulmalısınız.
2-) Grafikte sadece ortalama vwap çizgisi görüntülenir. Ayrıntılı bir görünüm için strateji kodundaki "plot" ile başlayan satırlarda grafikte görünmesini istediğiniz özelliğin önündeki "//" işaretlerini silebilirsiniz.
3-) Eğitim ve deneysel amaçlı bir stratejidir. Yatırım tavsiyesi olarak değerlendirilemez. Bu stratejiyi kullanarak gerçek piyasa işlem açarken dikkatli olmalı ve kendi risk değerlendirmenizi yapmalısınız.
Mean Reversion Strategy (Double EMA) w Stop LossOne of the strategy inspired by John F. Carter in his book - Mastering the trade. The idea is simple, once the price cross the fast MA (open trade), it will most likely approach the slow MA (close trade). I added an optional filter, which you can turn on to only open position when the distance between the 2 MA is higher or equal than a minimum % that you indicate. Suitable for volatile stocks/markets. Best use when the market is ranging, like any other mean reversion strategy.
Stop Loss feature is also added, with the option to choose from Percentage Stop Loss, Percentage Trailing Stop Loss, ATR Stop Loss or ATR Trailing Stop Loss.
dirt cheap yet elegant RSI StrategyFor Educational Purposes. Results can differ on different markets and can fail at any time. Profit is not guaranteed.
This only works in a few markets and in certain situations. Changing the settings can give better or worse results for other markets. This is a good way to show off a good looking strategy, atleast in paper, with minimal effort involved in the making and usage. It can be made with the most minimal lines of code if needed to bring shame unto others. It only works in a few markets and who knows if it will actually rebound from the overbought or oversold levels but in case it doesn't I put in a time-based stop to exit in case of that worst case scenario. There's not much to it, good for trolling others, or serious business, you decide.
Bollinger Bands Strategy with Intraday Intensity IndexFor Educational Purposes. Results can differ on different markets and can fail at any time. Profit is not guaranteed.
This only works in a few markets and in certain situations. Changing the settings can give better or worse results for other markets.
This is a mean reversion strategy based on Bollinger Bands and the Intraday Intensity Index (a volume indicator). John Bollinger mentions that the Intraday Intensity Index can be used with Bollinger Bands and is one of the top indicators he recommends in his book. It seems he prefers it over the other volume indicators that he compares to for some reason. III looks a lot like Chaikin Money Flow but without the denominator in that calculation. On the default settings of the BBs, the III helps give off better entry signals. John Bollinger however is vague on how to use the BBs and it's hard to say if one should enter when it is below/above the bands or when the price crosses them. I find that with many indicators and strategies it's best to wait for a confirmation of some sort, in this case by waiting for some crossover of a band. Like most mean reversion strategies, the exit is very loose if using BBs alone. Usually the plan to exit is when the price finally reverts back to the mean or in this case the middle band. This can potentially lead to huge drawdowns and/or losses. Mean reversion strategies can have high win/loss ratios but can still end up unprofitable because of the huge losses that can occur. These drawdowns/losses that mean reversion strategies suffer from can potentially eat away at a large chunk of all that was previously made or perhaps up to all of it in the worst cases, can occur weeks or perhaps up to months after being profitable trading such a strategy, and will take a while and several trades to make it all back or keep a profitable track record. It is important to have a stop loss, trailing stop, or some sort of stop plan with these types of strategies. For this one, in addition to exiting the trade when price reverts to the middle band, I included a time-based stop plan that exits with a gain or with a loss to avoid potentially large losses, and to exit after only a few periods after taking the trade if in profit instead of waiting for the price to revert back to the mean.
GMS: Mean Reversion StrategyThis is based on my GMS: Mean Reversion Indicator ()
Features:
- % Based Profit Target and Stop Loss
- SMA Trend Filter
- Can choose trade exit based off a moving average or linear regression curve
- Filter for long only trades, short only trades, or both at the same time.
Source code is open, so feel free to take a look!
I hope it helps,
Andre