RSI Trend Following StrategyOverview
The RSI Trend Following Strategy utilizes Relative Strength Index (RSI) to enter the trade for the potential trend continuation. It uses Stochastic indicator to check is the price is not in overbought territory and the MACD to measure the current price momentum. Moreover, it uses the 200-period EMA to filter the counter trend trades with the higher probability. The strategy opens only long trades.
Unique Features
Dynamic stop-loss system: Instead of fixed stop-loss level strategy utilizes average true range (ATR) multiplied by user given number subtracted from the position entry price as a dynamic stop loss level.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Two layers trade filtering system: Strategy utilizes MACD and Stochastic indicators measure the current momentum and overbought condition and use 200-period EMA to filter trades against major trend.
Trailing take profit level: After reaching the trailing profit activation level script activates the trailing of long trade using EMA. More information in methodology.
Wide opportunities for strategy optimization: Flexible strategy settings allows users to optimize the strategy entries and exits for chosen trading pair and time frame.
Methodology
The strategy opens long trade when the following price met the conditions:
RSI is above 50 level.
MACD line shall be above the signal line
Both lines of Stochastic shall be not higher than 80 (overbought territory)
Candle’s low shall be above the 200 period EMA
When long trade is executed, strategy set the stop-loss level at the price ATR multiplied by user-given value below the entry price. This level is recalculated on every next candle close, adjusting to the current market volatility.
At the same time strategy set up the trailing stop validation level. When the price crosses the level equals entry price plus ATR multiplied by user-given value script starts to trail the price with trailing EMA(by default = 20 period). If price closes below EMA long trade is closed. When the trailing starts, script prints the label “Trailing Activated”.
Strategy settings
In the inputs window user can setup the following strategy settings:
ATR Stop Loss (by default = 1.75)
ATR Trailing Profit Activation Level (by default = 2.25)
MACD Fast Length (by default = 12, period of averaging fast MACD line)
MACD Fast Length (by default = 26, period of averaging slow MACD line)
MACD Signal Smoothing (by default = 9, period of smoothing MACD signal line)
Oscillator MA Type (by default = EMA, available options: SMA, EMA)
Signal Line MA Type (by default = EMA, available options: SMA, EMA)
RSI Length (by default = 14, period for RSI calculation)
Trailing EMA Length (by default = 20, period for EMA, which shall be broken close the trade after trailing profit activation)
Justification of Methodology
This trading strategy is designed to leverage a combination of technical indicators—Relative Strength Index (RSI), Moving Average Convergence Divergence (MACD), Stochastic Oscillator, and the 200-period Exponential Moving Average (EMA)—to determine optimal entry points for long trades. Additionally, the strategy uses the Average True Range (ATR) for dynamic risk management to adapt to varying market conditions. Let's look in details for which purpose each indicator is used for and why it is used in this combination.
Relative Strength Index (RSI) is a momentum indicator used in technical analysis to measure the speed and change of price movements in a financial market. It helps traders identify whether an asset is potentially overbought (overvalued) or oversold (undervalued), which can indicate a potential reversal or continuation of the current trend.
How RSI Works? RSI tracks the strength of recent price changes. It compares the average gains and losses over a specific period (usually 14 periods) to assess the momentum of an asset. Average gain is the average of all positive price changes over the chosen period. It reflects how much the price has typically increased during upward movements. Average loss is the average of all negative price changes over the same period. It reflects how much the price has typically decreased during downward movements.
RSI calculates these average gains and losses and compares them to create a value between 0 and 100. If the RSI value is above 70, the asset is generally considered overbought, meaning it might be due for a price correction or reversal downward. Conversely, if the RSI value is below 30, the asset is considered oversold, suggesting it could be poised for an upward reversal or recovery. RSI is a useful tool for traders to determine market conditions and make informed decisions about entering or exiting trades based on the perceived strength or weakness of an asset's price movements.
This strategy uses RSI as a short-term trend approximation. If RSI crosses over 50 it means that there is a high probability of short-term trend change from downtrend to uptrend. Therefore RSI above 50 is our first trend filter to look for a long position.
The MACD (Moving Average Convergence Divergence) is a popular momentum and trend-following indicator used in technical analysis. It helps traders identify changes in the strength, direction, momentum, and duration of a trend in an asset's price.
The MACD consists of three components:
MACD Line: This is the difference between a short-term Exponential Moving Average (EMA) and a long-term EMA, typically calculated as: MACD Line = 12 period EMA − 26 period EMA
Signal Line: This is a 9-period EMA of the MACD Line, which helps to identify buy or sell signals. When the MACD Line crosses above the Signal Line, it can be a bullish signal (suggesting a buy); when it crosses below, it can be a bearish signal (suggesting a sell).
Histogram: The histogram shows the difference between the MACD Line and the Signal Line, visually representing the momentum of the trend. Positive histogram values indicate increasing bullish momentum, while negative values indicate increasing bearish momentum.
This strategy uses MACD as a second short-term trend filter. When MACD line crossed over the signal line there is a high probability that uptrend has been started. Therefore MACD line above signal line is our additional short-term trend filter. In conjunction with RSI it decreases probability of following false trend change signals.
The Stochastic Indicator is a momentum oscillator that compares a security's closing price to its price range over a specific period. It's used to identify overbought and oversold conditions. The indicator ranges from 0 to 100, with readings above 80 indicating overbought conditions and readings below 20 indicating oversold conditions.
It consists of two lines:
%K: The main line, calculated using the formula (CurrentClose−LowestLow)/(HighestHigh−LowestLow)×100 . Highest and lowest price taken for 14 periods.
%D: A smoothed moving average of %K, often used as a signal line.
This strategy uses stochastic to define the overbought conditions. The logic here is the following: we want to avoid long trades in the overbought territory, because when indicator reaches it there is a high probability that the potential move is gonna be restricted.
The 200-period EMA is a widely recognized indicator for identifying the long-term trend direction. The strategy only trades in the direction of this primary trend to increase the probability of successful trades. For instance, when the price is above the 200 EMA, only long trades are considered, aligning with the overarching trend direction.
Therefore, strategy uses combination of RSI and MACD to increase the probability that price now is in short-term uptrend, Stochastic helps to avoid the trades in the overbought (>80) territory. To increase the probability of opening long trades in the direction of a main trend and avoid local bounces we use 200 period EMA.
ATR is used to adjust the strategy risk management to the current market volatility. If volatility is low, we don’t need the large stop loss to understand the there is a high probability that we made a mistake opening the trade. User can setup the settings ATR Stop Loss and ATR Trailing Profit Activation Level to realize his own risk to reward preferences, but the unique feature of a strategy is that after reaching trailing profit activation level strategy is trying to follow the trend until it is likely to be finished instead of using fixed risk management settings. It allows sometimes to be involved in the large movements.
Backtest Results
Operating window: Date range of backtests is 2023.01.01 - 2024.08.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: -3.94%
Maximum Single Profit: +15.78%
Net Profit: +1359.21 USDT (+13.59%)
Total Trades: 111 (36.04% win rate)
Profit Factor: 1.413
Maximum Accumulated Loss: 625.02 USDT (-5.85%)
Average Profit per Trade: 12.25 USDT (+0.40%)
Average Trade Duration: 40 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 2h 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
Stochastic Oscillator
MACD with 1D Stochastic Confirmation Reversal StrategyOverview
The MACD with 1D Stochastic Confirmation Reversal Strategy utilizes MACD indicator in conjunction with 1 day timeframe Stochastic indicators to obtain the high probability short-term trend reversal signals. The main idea is to wait until MACD line crosses up it’s signal line, at the same time Stochastic indicator on 1D time frame shall show the uptrend (will be discussed in methodology) and not to be in the oversold territory. Strategy works on time frames from 30 min to 4 hours and opens only long trades.
Unique Features
Dynamic stop-loss system: Instead of fixed stop-loss level strategy utilizes average true range (ATR) multiplied by user given number subtracted from the position entry price as a dynamic stop loss level.
Configurable Trading Periods: Users can tailor the strategy to specific market windows, adapting to different market conditions.
Higher time frame confirmation: Strategy utilizes 1D Stochastic to establish the major trend and confirm the local reversals with the higher probability.
Trailing take profit level: After reaching the trailing profit activation level scrip activate the trailing of long trade using EMA. More information in methodology.
Methodology
The strategy opens long trade when the following price met the conditions:
MACD line of MACD indicator shall cross over the signal line of MACD indicator.
1D time frame Stochastic’s K line shall be above the D line.
1D time frame Stochastic’s K line value shall be below 80 (not overbought)
When long trade is executed, strategy set the stop-loss level at the price ATR multiplied by user-given value below the entry price. This level is recalculated on every next candle close, adjusting to the current market volatility.
At the same time strategy set up the trailing stop validation level. When the price crosses the level equals entry price plus ATR multiplied by user-given value script starts to trail the price with EMA. If price closes below EMA long trade is closed. When the trailing starts, script prints the label “Trailing Activated”.
Strategy settings
In the inputs window user can setup the following strategy settings:
ATR Stop Loss (by default = 3.25, value multiplied by ATR to be subtracted from position entry price to setup stop loss)
ATR Trailing Profit Activation Level (by default = 4.25, value multiplied by ATR to be added to position entry price to setup trailing profit activation level)
Trailing EMA Length (by default = 20, period for EMA, when price reached trailing profit activation level EMA will stop out of position if price closes below it)
User can choose the optimal parameters during backtesting on certain price chart, in our example we use default settings.
Justification of Methodology
This strategy leverages 2 time frames analysis to have the high probability reversal setups on lower time frame in the direction of the 1D time frame trend. That’s why it’s recommended to use this strategy on 30 min – 4 hours time frames.
To have an approximation of 1D time frame trend strategy utilizes classical Stochastic indicator. The Stochastic Indicator is a momentum oscillator that compares a security's closing price to its price range over a specific period. It's used to identify overbought and oversold conditions. The indicator ranges from 0 to 100, with readings above 80 indicating overbought conditions and readings below 20 indicating oversold conditions.
It consists of two lines:
%K: The main line, calculated using the formula (CurrentClose−LowestLow)/(HighestHigh−LowestLow)×100 . Highest and lowest price taken for 14 periods.
%D: A smoothed moving average of %K, often used as a signal line.
Strategy logic assumes that on 1D time frame it’s uptrend in %K line is above the %D line. Moreover, we can consider long trade only in %K line is below 80. It means that in overbought state the long trade will not be opened due to higher probability of pullback or even major trend reversal. If these conditions are met we are going to our working (lower) time frame.
On the chosen time frame, we remind you that for correct work of this strategy you shall use 30min – 4h time frames, MACD line shall cross over it’s signal line. The MACD (Moving Average Convergence Divergence) is a popular momentum and trend-following indicator used in technical analysis. It helps traders identify changes in the strength, direction, momentum, and duration of a trend in a stock's price.
The MACD consists of three components:
MACD Line: This is the difference between a short-term Exponential Moving Average (EMA) and a long-term EMA, typically calculated as: MACD Line=12-period EMA−26-period
Signal Line: This is a 9-period EMA of the MACD Line, which helps to identify buy or sell signals. When the MACD Line crosses above the Signal Line, it can be a bullish signal (suggesting a buy); when it crosses below, it can be a bearish signal (suggesting a sell).
Histogram: The histogram shows the difference between the MACD Line and the Signal Line, visually representing the momentum of the trend. Positive histogram values indicate increasing bullish momentum, while negative values indicate increasing bearish momentum.
In our script we are interested in only MACD and signal lines. When MACD line crosses signal line there is a high chance that short-term trend reversed to the upside. We use this strategy on 45 min time frame.
ATR is used to adjust the strategy risk management to the current market volatility. If volatility is low, we don’t need the large stop loss to understand the there is a high probability that we made a mistake opening the trade. User can setup the settings ATR Stop Loss and ATR Trailing Profit Activation Level to realize his own risk to reward preferences, but the unique feature of a strategy is that after reaching trailing profit activation level strategy is trying to follow the trend until it is likely to be finished instead of using fixed risk management settings. It allows sometimes to be involved in the large movements.
Backtest Results
Operating window: Date range of backtests is 2023.01.01 - 2024.08.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: -4.79%
Maximum Single Profit: +20.14%
Net Profit: +2361.33 USDT (+44.72%)
Total Trades: 123 (44.72% win rate)
Profit Factor: 1.623
Maximum Accumulated Loss: 695.80 USDT (-5.48%)
Average Profit per Trade: 19.20 USDT (+0.59%)
Average Trade Duration: 30 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 between 30 min and 4 hours and chart (optimal performance observed on 45 min 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
Stochastic Z-Score Oscillator Strategy [TradeDots]The "Stochastic Z-Score Oscillator Strategy" represents an enhanced approach to the original "Buy Sell Strategy With Z-Score" trading strategy. Our upgraded Stochastic model incorporates an additional Stochastic Oscillator layer on top of the Z-Score statistical metrics, which bolsters the affirmation of potential price reversals.
We also revised our exit strategy to when the Z-Score revert to a level of zero. This amendment gives a much smaller drawdown, resulting in a better win-rate compared to the original version.
HOW DOES IT WORK
The strategy operates by calculating the Z-Score of the closing price for each candlestick. This allows us to evaluate how significantly the current price deviates from its typical volatility level.
The strategy first takes the scope of a rolling window, adjusted to the user's preference. This window is used to compute both the standard deviation and mean value. With these values, the strategic model finalizes the Z-Score. This determination is accomplished by subtracting the mean from the closing price and dividing the resulting value by the standard deviation.
Following this, the Stochastic Oscillator is utilized to affirm the Z-Score overbought and oversold indicators. This indicator operates within a 0 to 100 range, so a base adjustment to match the Z-Score scale is required. Post Stochastic Oscillator calculation, we recalibrate the figure to lie within the -4 to 4 range.
Finally, we compute the average of both the Stochastic Oscillator and Z-Score, signaling overpriced or underpriced conditions when the set threshold of positive or negative is breached.
APPLICATION
Firstly, it is better to identify a stable trading pair for this technique, such as two stocks with considerable correlation. This is to ensure conformance with the statistical model's assumption of a normal Gaussian distribution model. The ideal performance is theoretically situated within a sideways market devoid of skewness.
Following pair selection, the user should refine the span of the rolling window. A broader window smoothens the mean, more accurately capturing long-term market trends, while potentially enhancing volatility. This refinement results in fewer, yet precise trading signals.
Finally, the user must settle on an optimal Z-Score threshold, which essentially dictates the timing for buy/sell actions when the Z-Score exceeds with thresholds. A positive threshold signifies the price veering away from its mean, triggering a sell signal. Conversely, a negative threshold denotes the price falling below its mean, illustrating an underpriced condition that prompts a buy signal.
Within a normal distribution, a Z-Score of 1 records about 68% of occurrences centered at the mean, while a Z-Score of 2 captures approximately 95% of occurrences.
The 'cool down period' is essentially the number of bars that await before the next signal generation. This feature is employed to dodge the occurrence of multiple signals in a short period.
DEFAULT SETUP
The following is the default setup on EURAUD 1h timeframe
Rolling Window: 80
Z-Score Threshold: 2.8
Signal Cool Down Period: 5
Stochastic Length: 14
Stochastic Smooth Period: 7
Commission: 0.01%
Initial Capital: $10,000
Equity per Trade: 40%
FURTHER IMPLICATION
The Stochastic Oscillator imparts minimal impact on the current strategy. As such, it may be beneficial to adjust the weightings between the Z-Score and Stochastic Oscillator values or the scale of Stochastic Oscillator to test different performance outcomes.
Alternative momentum indicators such as Keltner Channels or RSI could also serve as robust confirmations of overbought and oversold signals when used for verification.
RISK DISCLAIMER
Trading entails substantial risk, and most day traders incur losses. All content, tools, scripts, articles, and education provided by TradeDots serve purely informational and educational purposes. Past performances are not definitive predictors of future results.
How to force strategies fire exit alerts not reversalsPineScript has gone a long way, from very simple and little-capable scripting language to a robust coding platform with reliable execution endpoints. However, this one small intuitivity glitch is still there and is likely to stay, because it is traditionally justified and quite intuitive for significant group of traders. I'm sharing this workaround in response to frequent inquiries about it.
What's the glitch? When setting alerts on strategies to be synchronized with TradingView's Strategy Tester events, using simple alert messages such as "buy" or "sell" based on entry direction seems straightforward by inserting {{strategy.order.action}} into the Create Alert's "Message" field. Because "buy" or "sell" are exactly the strings produced by {{strategy.order.action}} placeholder. However, complications arise when attempting to EXIT positions without reversing, whether triggered by price levels like Stop Loss or Take Profit, or logical conditions to close trades. Those bricks fall apart, because on such events {{strategy.order.action}} sends the same "sell" for exiting buy positions and "buy" for exiting sell positions, instead of something more differentiating like "closebuy" or "closesell". As a result reversal trades are opened, instead of simply closing the open ones.
This convention harkens back to traditional stock market practices, where traders either bought shares to enter positions or sold them to exit. However, modern trading encompasses diverse instruments like CFDs, indices, and Forex, alongside advanced features such as Stop Loss, reshaping the landscape. Despite these advancements, the traditional nomenclature persists.
And is poised to stay on TradingView as well, so we need a workaround to get a simple strategy going. Luckily it is here and is called alert_message . It is a parameter, which needs to be added into each strategy.entry() / strategy.exit() / strategy.close() function call - each call, which causes Strategy Tester to produce entry or exit orders. As in this example script:
line 12: strategy.entry(... alert_message ="buy")
line 14: strategy.entry(... alert_message ="sell")
line 19: strategy.exit(... alert_message ="closebuy")
line 20: strategy.exit(... alert_message ="closesell")
line 24: strategy.close(... alert_message ="closebuy")
line 26: strategy.close(... alert_message ="closesell")
These alert messages are compatible with the Alerts Syntax of TradingConnector - a tool facilitating auto-execution of TradingView alerts in MetaTrader 4 or 5. Yes, simple alert messages like "buy" / "sell" / "closebuy" / "closesell" suffice to carry the execution of simple strategy, without complex JSON files with multiple ids and such. Other parameters can be added (actually plenty), but they are only option and that's not a part of this story :)
Last thing left to do is to replace "Message" in Create Alert popup with {{strategy.order.alert_message}} . This placeholder transmits the string defined in the PineScript alert_message= parameter, as outlined in this publication. With this workaround, executing closing alerts becomes seamless within PineScript strategies on TradingView.
Disclaimer: this content is purely educational, especially please don't pay attention to backtest results on any timeframe/ticker.
Bollinger and Stochastic with Trailing Stop - D.M.P.This trading strategy combines Bollinger Bands and the Stochastic indicator to identify entry opportunities in oversold and overbought conditions in the market. The aim is to capitalize on price rebounds from the extremes defined by the Bollinger Bands, with the confirmation of the Stochastic to maximize the probability of success of the operations.
Indicators Used
- Bollinger Bands Used to measure volatility and define oversold and overbought levels. When the price touches or breaks through the lower band, it indicates a possible oversold condition. Similarly, when it touches or breaks through the upper band, it indicates a possible overbought condition.
- Stochastic: A momentum oscillator that compares the closing price of an asset with its price range over a certain period. Values below 20 indicate oversold, while values above 80 indicate overbought.
Strategy Logic
- Long Entry (Buy): A purchase operation is executed when the price closes below the lower Bollinger band (indicating oversold) and the Stochastic is also in the oversold zone.
- Short Entry (Sell): A sell operation is executed when the price closes above the upper Bollinger band (indicating overbought) and the Stochastic is in the overbought zone.
Stochastic StrategyThis strategy is designed to make trading decisions based on the Stochastic Oscillator (Stoch) indicator with settings of (7,2,2). The strategy opens a long (buy) position when the Stoch indicator crosses above the 50 level from below. Conversely, it opens a short (sell) position when the Stoch indicator crosses below the 50 level from above. Additionally, when a long position is opened, any existing short position is closed, and vice versa.
Key Parameters:
Stochastic Oscillator Settings: Length = 7, SmoothK = 2, SmoothD = 2.
Overbought Level: 80.
Oversold Level: 20.
Strategy Description:
The Stochastic Oscillator (Stoch) is calculated based on the closing price, high price, and low price with a period of 7, and both the %K and %D lines are smoothed with periods of 2.
When the %K line crosses above the oversold level (20), it generates a long (buy) signal.
When the %K line crosses below the overbought level (80), it generates a short (sell) signal.
The strategy visually marks long and short signals on the chart using upward and downward triangles, respectively.
The strategy automatically enters long or short positions when the respective conditions are met.
If a long position is opened, any existing short position is closed, and vice versa.
Please note that this is a basic example of a trading strategy and does not take into account all possible risk factors or optimizations. Before using this strategy in live trading, it's essential to thoroughly test and customize it to suit your specific needs, and carefully analyze the results. Trading carries risks, and it's important to use proper risk management techniques when implementing any trading strategy.
Strategy Creator5 indicators. Backtesting available. Uses ADX, RSI, Stochastic, MACD, and crossing EMAs (1,2, or 3). This strategy creator allows you to turn on or off these indicators and adjust the parameters for each indicator. It allows you to make one trade at a time e.g the next trade doesn't open until the last one closes. (You are also able to enter how many trades in one direction you want for example if you want only 2 long trades in a row, then the strategy waits for the next short position without making anymore long trades. Once there are 2 short positions in a row, it waits for a long position). The code can be edited to for automated trading by editing the comment in the source code for the strategy parameters. This took many hours to finish. ENJOY.
LowFinder_PyraMider_V2This strategy is a result of an exploration to experiment with other ways to detect lows / dips in the price movement, to try out alternative ways to exit and stop positions and a dive into risk management. It uses a combination of different indicators to detect and filter the potential lows and opens multiple positions to spread the risk and opportunities for unrealized losses or profits. This script combines code developed by fellow Tradingview community_members.
LowFinder
The lows in the price movement are detected by the Low finder script by RafaelZioni . It finds the potential lows based on the difference between RSI and EMA RSI. The MTF RSI formula is part of the MTFindicators library developed by Peter_O and is integrated in the Low finder code to give the option to use the RSI of higher timeframes. The sensitivity of the LowFinder is controlled by the MA length. When potential lows are detected, a Moving Average, a MTF Stochastic (based the the MTFindiicators by Peter_O) and the average price level filter out the weak lows. In the settings the minimal percentage needed for a low to be detected below the average price can be specified.
Order Sizing and Pyramiding
Pyramiding, or spreading multiple positions, is at the heart of this strategy and what makes it so powerful. The order size is calculated based on the max number of orders and portfolio percentage specified in the input settings. There are two order size modes. The ‘base’ mode uses the same base quantity for each order it opens, the ‘multiply’ mode multiplies the quantity with each order number. For example, when Long 3 is opened, the quantity is multiplied by 3. So, the more orders the bigger the consecutive order sizes. When using ‘multiply’ mode the sizes of the first orders are considerably lower to make up for the later bigger order sizes. There is an option to manually set a fixed order size but use this with caution as it bypasses all the risk calculations.
Stop Level, Take Profit, Trailing Stop
The one indicator that controls the exits is the Stop Level. When close crosses over the Stop Level, the complete position is closed and all orders are exited. The Stop Level is calculated based on the highest high given a specified candle lookback (settings). There is an option to deviate above this level with a specified percentage to tweak for better results. You can activate a Take Profit / Trailing Stop. When activated and close crosses the specified percentage, the Stop Level logic changes to a trailing stop to gain more profits. Another option is to use the percentage as a take profit, either when the stop level crosses over the take profit or close. With this option active, you can make this strategy more conservative. It is active by default.
And finally there is an option to Take Profit per open order. If hit, the separate orders close. In the current settings this option is not used as the percentage is 10%.
Stop Loss
I published an earlier version of this script a couple of weeks ago, but it got hidden by the moderators. Looking back, it makes sense because I didn’t pay any attention to risk management and save order sizing. This resulted in unrealistic results. So, in this script update I added a Stop Loss option. There are two modes. The ‘average price’ mode calculates the stop loss level based on a given percentage below the average price of the total position. The ‘equity’ mode calculates the stop loss level based on a given percentage of your equity you want to lose. By default, the ‘equity’ mode is active. By tweaking the percentage of the portfolio size and the stop loss equity mode, you can achieve a quite low risk strategy set up.
Variables in comments
To sent alerts to my exchange I use a webhook server. This works with a sending the information in the form of a comment. To be able to send messages with different quantities, a variable is added to the comment. This makes it possible to open different positions on the exchange with increasing quantities. To test this the quantities are printed in the comment and the quantities are switched off in the style settings.
This code is a result of a study and not intended for use as a worked out and full functioning strategy. Use it at your own risk. To make the code understandable for users that are not so much introduced into pine script (like me), every step in the code is commented to explain what it does. Hopefully it helps.
Enjoy!
Exponential Stochastic Strategywhat is Exponential Stochastic?
it is a modified version of the stochastic indicator. This strategy does not include pyramiding, repaint, trailing stop or take profit.
what it does?
It contains an extra input in addition to the stochastic indicator. Thanks to this input, different exponential weights can be given to the outputs and the indicator can be made more sensitive or insensitive. The strategy buys when the indicator leaves the overbought zone, sells when it leaves the oversold zone and always stays in the trade.
how it does it?
it uses this formula: i.hizliresim.com
Thanks to this formula, even if the weights given to the outputs change, the indicator always continues to take a value between 0 and 100.
how to use it ?
With the input named "exp", you can change the sensitivity of the indicator and develop different strategies. other inputs are the same as the stochastic indicator. Increasing the exp value causes the indicator to signal less, decreasing it makes it much more sensitive.
Strategy Myth-Busting #5 - POKI+GTREND+ADX - [MYN]This is part of a new series we are calling "Strategy Myth-Busting" where we take open public manual trading strategies and automate them. The goal is to not only validate the authenticity of the claims but to provide an automated version for traders who wish to trade autonomously.
Our fifth one we are automating is one of the strategies from "The Best 3 Buy And Sell Indicators on Tradingview + Confirmation Indicators ( The Golden Ones ))" from "Online Trading Signals (Scalping Channel)". No formal backtesting was done by them and resuructo messaged me asking if we could validate their claims.
Originally, we mimic verbatim the settings Online Trading Signals was using however weren't getting promising results. So before we stopped there we thought we might want to see if this could be improved on. So we adjusted the Renko Assignment modifier from ATR to Traditional and adjusted the value to be higher from 30 to 47. We also decided to try adding another signal confirmation to eliminate some of the ranged market conditions so we choose our favorite, ADX . Also, given we are using this on a higher time-frame we adjusted the G-Channel Trend detection source from close to OHLC4 to get better average price action indication and more accurate trend direction.
This strategy uses a combination of 2 open-source public indicators:
poki buy and sell Take profit and stop loss by RafaelZioni
G-Channel Trend Detection by jaggedsoft
Trading Rules
15m - 4h timeframe. We saw best results at the recommended 1 hour timeframe.
Long Entry:
When POKI triggers a buy signal
When G-Channel Trend Detection is in an upward trend (Green)
ADX Is above 25
Short Entry:
When POKI triggers a sell signal
When G-Channel Trend Detection is in an downward trend (red)
ADX Is above 25
If you know of or have a strategy you want to see myth-busted or just have an idea for one, please feel free to message me.
Rob Booker Reversal Tabs StrategyRob Booker Reversal Tabs Strategy is an updated version of Rob Bookers Reversal Tab study: Rob Booker Reversal Tabs
While the original is a Pinescript study, this version can be switched between strategy and indicator mode.
Rob Bookers script generates reversal signal based on MACD and Stochastics, it is not a true reversal system, default pyramiding value is set to 5.
Inputs determine MACD and Stochastics settings. The only additional input is the "Strategy Mode" checkbox.
This script works well on its own for some tickers, but like any reversal pattern generating scripts, traders will profit from looking at overall price action and trend strength before making a trade.
From the original:
A simple reversal pattern indicator that uses MACD and Stochastics.
Created by Rob Booker and programmed by Andrew Palladino.
Please note that I only updated the original to V5 and edited it to be a strategy, which was a grand total of 5 minutes of work. I updated it because I wanted to see how the script performs as a strategy and I'm publishing it in case others would like to use it. I take no credit whatsoever for the original and WILL take this version down if Rob Booker or his Team ask me to or decide to release their own strategy version of the original.
Check out Rob Bookers scripts and ideas on his Tradingview account: robbooker
Estocastoco Lento - DTOperacional criado pelo Jean Lira - Trader.
Basicamente busca uma situação de confirmação de exaustão com o indicador estocastico.
Na primeira barra de reversão do movimento, e com o sinal forte do estocastico Lento, no periodo de 5.
Gerenciamento de risco com e sem parcial.
Morning Scalp StrategyThe Morning Scalp Strategy combines the 50EMA with the Stochastic Momentum Index. The morning period is when penny stocks usually have the highest volatility, so the strategy works between 10:00 AM and 12:10 PM.
***It opens only long positions. The ideal timeframe for this scalping strategy is 5 minutes on low-price stocks. The stock should spike in the morning with momentum and Volume.
***Look for a daily or intraday support area, close to the open position, to increase the confidence in the play
The components are:
- EMA50: Exponential Moving Average (EMA50)
- Stochastic Momentum Index (SMI)
Rules:
- Period: 10:00 AM and 12:10 PM
- if SMI Crossover and SMI < 0, open a position
- If close < EMA50, close the position
- Profit target: To be decided by the user, default value = 10% above the entry price
If you have any questions, let me know!
Stochastic Moving AverageHi all,
This Strategy script combines the power of EMAs along with the Stochastic Oscillator in a trend following / continuation manner, along with some cool functionalities.
I designed this script especially for trading altcoins, but it works just as good on Bitcoin itself and on some Forex pairs.
______ SIGNALS ______
The script has 4 mandatory conditions to unlock a trading signal. Find these conditions for a long trade below (works the exact other way round for shorts)
- Fast EMA must be higher than Slow EMA
- Stochastic K% line must be in oversold territory
- Stochastic K% line must cross over Stochastic D% line
- Price as to close between slow EMA and fast EMA
Once all the conditions are true, a trade will start at the opening of the next
______ SETTINGS ______
- Trade Setup:
Here you can choose to trade only longs or shorts and change your Risk:Reward.
You can also decide to adjust your volume per position according to your risk tolerance. With “% of Equity” your stop loss will always be equal to a fixed percentage of your initial capital (will “compound” overtime) and with “$ Amount” your stop loss will always be 'x' amount of the base currency (ex: USD, will not compound)
Stop Loss:
The ATR is used to create a stop loss that matches current volatility. The multiplier corresponds to how many times the ATR stop losses and take profits will be away from closing price.
- Stochastic:
Here you can find the usual K% & D% length and overbought (OB) and oversold (OS) levels.
The “Stochastic OB/OS lookback” increase the tolerance towards OB/OS territories. It allows to look 'x' bars back for a value of the Stochastic K line to be overbought or oversold when detecting an entry signal.
The “All must be OB/OS” refers to the previous “Stochastic OB/OS lookback” parameter. If this option is ticked, instead of needing only 1 OB/OS value within the lookback period to get a valid signal, now, all bars looked back must be OB/OS.
The color gradient drawn between the fast and slow EMAs is a representation of the Stochastic K% line position. With default setting colors, when fast EMA > slow EMA, gradient will become solid blue when Stochastic is oversold and when slow EMA > fast EMA, gradient will become solid blue when Stochastic is overbought
- EMAs:
Just pick your favorite ones
- Reference Market:
An additional filter to be certain to stay aligned with the current a market index trend (in our case: Bitcoin). If selected reference market (and timeframe) is trading above selected EMA, this strategy will only take long trades (vice-versa for shorts) Because, let’s face it… even if this filter isn’t bulletproof, you know for sure that when Bitcoin tanks, there won’t be many Alts going north simultaneously. Once again, this is a trend following strategy.
A few tips for increased performance: fast EMA and D% Line can be real fast… 😉
As always, my scripts evolve greatly with your ideas and suggestions, keep them coming! I will gladly incorporate more functionalities as I go.
All my script are tradable when published but remain work in progress, looking for further improvements.
Hope you like it!
OTT-Stoch-TP/SLThis strategy combines stochastic oscillator and OTT (OTT is originally owned by Anıl Özekşi).
The strategy is triggered at fast OTT and slow OTT crossing points. User can select the "Evaluate Stoch OTT" option which is validate the crossing points through stochastic oscillator.
In the same way, user can select "take profit", "stop loss" and position direction(long, short or both) via interface.
By the way, Stoch OTT is not classic Stochastic oscillator. Actually, it is also combined classic stochastic oscillator and OTT for long term validation to base strategy.
Stochastic & MAThis trading system comes from the experience of having a "fast" signal for entry at low prices (such as the stoscastic) and then "following" the stock with a "slower" indicator such as the exponential moving average. Both the input and output signals are filtered.
The use of the trading system only carries out long operations and has been tested on shares and ETFs, including indices, on daily bases (End Of Day).
ENTRY CONDITION: when stochastic's k is higher than d (on the default value of 21 periods) we enter the lower part of the oversold, to which we apply a filter or the confirmation that the closing of the day of the crossing is higher than that of the n -th previous bar (the 2nd previous bar recommended).
Other default settings are k = 6 and d = 4; the oversold level is also customizable (recommended = 25).
EXIT CONDITIONS: once the entry has "gone well", we follow the upward trend of the stock not with a stochastic oscillator - which tends to exit too soon, especially in case of strong trends - but with a simple moving average exponential (by default at 38 periods). Also in this case a filter is added, that is, k must be> to a filter threshold (recommended = 65) which is used to distinguish the decline between a "physiological" tracking. "(k drops" slowly "together with the approach of prices to the moving average) from a more" violent "tracking (prices are below the moving average and k consequently fall" suddenly ", in a few bars).
MONEY MANAGEMENT: 13% stop loss inserted (the physiological level of tracking of the shares is generally max 8-12% so we also consider a 1% margin due to trading). For more volatile stocks, the level can be extended to 20%.
LEVERAGE: the default value is equal to 1, but it is advisable, for simulations on shares, to use higher levers (x2, x3, ...) if you trade the relative CFD or on the index in case of buying and selling of Leveraged ETFs (e.g. LEVMIB which is 2x leveraged ETFs on Italian index).
AVG Stochastic Strategy [M30 Backtesting]1. AVG Stochastic Calculate
1.1 AVG %K is calculated by apply EMA with smooth K period on Average of Original Stochastic %k & %d
+ avg_k=ema((%k+%d)/2,smoothK)
1.2 AVG %D is calculated by apply EMA with %d period on AVG %K
+ avg_d=ema(avg_k,periodD)
2. Parameter
+ %K Length: 21
+ %K Smoothing: 3
+ %D Smoothing: 3
+ Symbol: BTC/USDT
+ Timeframe: M30
+ Pyramiding: Maximum 3 orders at the same direction.
3. Signal
3.1 Buy Signal
+ Entry: AVG %K crossover AVG %D and AVG %D < 20
+ Exit: AVG %D > 80
3.2 Sell Signal
+ Entry: AVG %K crossunder AVG %D and AVG %D > 80
+ Exit: AVG %D < 20
KDJ Strategy @ionvolutionBuys if there is crossover in J and D and the crossover is above an SMA defined as an input parameter
Sells if the close is below the SMA or there is a crossunder in J and D
The KDJ calculation is done using ll21LAMBOS21 script. I added start date, end date, stop loss margin and stop profit margin to ease the simulation on diferent conditions of the market.
Tested on BTCBUSD pair. Gives good results in 30m candles with K period = 7 and D period = 3, but also works fine with K period = 14 and D period = 8. It works fine when market is bullish and gives false signals in flat markets. I just developed long strategy, as it is developed to operate in SPOT trading.
Contrarian Scalping Counter Trend Bb Envelope Adx and StochasticContrarian Scalping is an trading strategy designed to take advanted of a counter-trend.
The advantage of these strrategies types is that they have a good profitability but with do not great gain (in relation at the time frame).
Indicators used:
Bollinger
Envelope
ADX
Stochastic
Rules for entry
For short: close of the price is above upper band from bb and envelope, adx is below 30 and stochastic is above 50
For long: close of the price is below lower band from bb and envelope, adx is below 30 and stochastic is below 50
Rules for exit
For short: either close of the candle is below lower band of bb or enveloper or stochastic is below 50
For long: either close o the candle is above upper band of bb or envelope or stochastic is above 50
If there are any questions let me know !
Simple EMA20 Strategy + StochasticThis is a Trend Following Strategy.
The intent of this strategy is to catchthe price as it trends higher than the 20-period EMA and sell immediately after the price closes below it.
I have implemented calculations from Stochastic to make sure the price is coming from an oversold area.
There is also a check to see if the 20-period EMA is trending higher than before.
Kifier's MFI/STOCH Hidden Divergence/Trend BeaterMFI/STOCH Hidden Divergence/Trend Beater
General Idea:
My premise around this strategy was to make a general strategy for crypto that would help out with finding entry positions for when you’re bullish on a crypto and want to hold on for a while, and at the same time avoiding massive drops. Essentially a way to mix long term/ swing trading; I somewhat achieved my goal however it still requires a lot of logic tuning of the trend averages.
I’m a huge proponent of volume indicators and coupled with average closing price, I think this gives a really good idea of what is happening with the market. It gives an idea on the market and retail investor sentiment. This generally gives you logical entry positions (Although I don’t know how amazing that will work with all cryptos, there’s a fine line between a good strategy and one that just rides bubble market conditions, some would argue that’s still a success and others not)
How it works:
There are many components to the strategy that try to do different things:
First of all there are two types of entries, a MFI hidden divergence with a STOCH check, essentially it will only fire when a divergence is detected while STOCH is above 50%, however this might be changed in the future as due to the volatile nature of cryptos, the STOCH is not too effective. The second entry is a simple MFI/STOCH trend, if STOCH is above 50% and the trend is detected to be in a trending long, once a MFI crossover over the 50% line is detected an entry is placed, this is designed to get out profit where the divergence would otherwise be less accurate during strongly trending conditions.
-MFI is a great indicator, as a volume weighted momentum indicator I find it the most accurate of all, the STOCH however is a great indicator to get a general picture of simple market conditions and can filter out the emotional noise of retail investors.
-VWMA and an SMA (The bottom oscillator) gives an idea of the trend tacking into account of the volume, this serves as a more short term filter of the trend for filters.
-OBV checks are done between the OBV and an EMA of the OBV, to get the idea of a volume weighted long trend, which is important for crypto as there are massive rallies to go up due to retail greed, it’s great to jump onto it at the beginning, and get off before the stack of cards fall apart.
-ATR is used to detect when the market is relatively just ranging or moving sideways, which is where the hidden divergence entries are done, during predictable and profitable market conditions.
- Stop loss is based on the closest support of the entry, this is a nice medium of room to breath but also an actual stop loss.
Future plans and improvements:
Currently there’s a lot I want to improve, mostly the divergence detection and the overall sharpe ratio could be much better, but the current value of 0.5 gives me hope that the strategy is onto something. I also want to change TP from a percentage stop to something more dynamic but that might be too optimistic. The current plan is to paper trade test this either by manual or by a python bot, to see how it performs with some user input as well.
Alert(), alertcondition() or strategy alerts?Variety of possibilities offered by PineScript, especially thanks to recent additions, created some confusion. Especially one question repeats quite often - which method to use to trigger alerts?
I'm posting this to clarify and give some syntax examples. I'll discuss these 3 methods in chronological order, meaning - in the order they were introduced to PineScript.
ALERTCONDITION() - it is a function call, which can be used only in study-type script. Since years ago, you could create 2 types of a script: strategy and study. First one enables creating a backtest of a strategy. Second was to develop scripts which didn't require backtesting and could trigger alerts. alertcondition() calls in strategy-type scripts were rejected by Pine compiler. On the other hand compiling study-type scripts rejected all strategy...() calls. That created difficulties, because once you had a nice and backtested strategy, you had to rip it off from all strategy...() function calls to convert your script to study-type so you could produce alerts. Maintenance of two versions of each script was necessary and it was painful.
"STRATEGY ALERTS" were introduced because of alertcondition() pains. To create strategy alert, you need to click "Add alert" button inside Strategy Tester (backtester) and only there. Alerts set-up this way are bound with the backtester - whenever backtester triggers an order, which is visible on the chart, alert is also fired. And you can customize alert message using some placeholders like {{strategy.order.contracts}} or {{ticker}}.
ALERT() was added last. This is an alerts-triggering function call, which can be run from strategy-type script. Finally it is doable! You can connect it to any event coded in PineScript and generate any alert message you want, thanks to concatenation of strings and wrapping variables into tostring() function.
Out of these three alertcondition() is obviously archaic and probably will be discontinued. There is a chance this makes strategy/study distinction not making sense anymore, so I wouldn't be surprised if "studies" are deprecated at some point.
But what are the differences between "Strategy alerts" and alert()? "Strategy alerts" seem easier to set-up with just a few clicks and probably easier to understand and verify, because they go in sync with the backtester and on-chart trade markers. It is especially important to understand how they work if you're building strategy based on pending orders (stop and limit) - events in your code might trigger placing pending order, but alert will be triggered only (and when) such order is executed.
But "Strategy Alerts" have some limitations - not every variable you'd like to include in alert message is available from PineScript. And maybe you don't need the alert fired when the trade hit a stop-loss or take-profit, because you have already forwarded info about closing conditions in entry alert to your broker/exchange.
Alert() was added to PineScript to fill all these gaps. Is allows concatenating any alert message you want, with any variable you want inside it and you can attach alert() function at any event in your PineScript code. For example - when placing orders, crossing variables, exiting trades, but not explicitly at pending orders execution.
The Verdict
"Strategy Alerts" might seem a better fit - easier to set-up and verify, flexible and they fire only when a trade really happens, not producing unnecessary mess when each pending order is placed. But these advantages are illusionary, because they don't give you the full-control which is needed when trading with real money. Especially when using pending orders. If an alert is fired when price actually hit a stop-order or limit-order level, and even if you are executing such alert within 1 second thanks to a tool like TradingConnector, you might already be late and you are making entry at a market price. Slippage will play a great role here. You need to send ordering alert when logical conditions are met - then it will be executed at the price you want. Even if you need to cancel all the pending orders which were not executed. Because of that I strongly recommend sticking to ALERT() when building your alerts system.
Below is an example strategy, showing syntax to manage placing the orders and cancelling them. Yes, this is another spin-off from my TradingView Alerts to MT4 MT5 . As usual, please don't pay attention to backtest results, as this is educational script only.
P.S. For the last time - farewell alertcondition(). You served us well.