Backtesting ModuleDo you often find yourself creating new 'strategy()' scripts for each trading system? Are you unable to focus on generating new systems due to fatigue and time loss incurred in the process? Here's a potential solution: the 'Backtesting Module' :)
INTRODUCTION
Every trading system is based on four basic conditions: long entry, long exit, short entry and short exit (which are typically defined as boolean series in Pine Script).
If you can define the conditions generated by your trading system as a series of integers, it becomes possible to use these variables in different scripts in efficient ways. (Pine Script is a convenient language that allows you to use the integer output of one indicator as a source in another.)
The 'Backtesting Module' is a dynamic strategy script designed to adapt to your signals. It boasts two notable features:
⮞ It produces a backtest report using the entry and exit variables you define.
⮞ It not only serves for system testing but also to combine independent signals into a single system. (This functionality enables to create complex strategies and report on their success!)
The module tests Golden and Death cross signals by default, when you enter your own conditions the default signals will be neutralized. The methodology is described below.
PREPARATION
There are three simple steps to connect your own indicator to the Module.
STEP 1
Firstly, you must define entry and exit variables in your own script. Let's elucidate it with a straightforward example. Consider a system generating long and short signals based on the intersections of two moving averages. Consequently, our conditions would be as follows:
// Signals
long = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
short = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
Now, the question is: How can we convert boolean variables into integer variables? The answer is conditional ternary block, defined as follows:
// Entry & Exit
long_entry = long ? 1 : 0
long_exit = short ? 1 : 0
short_entry = short ? 1 : 0
short_exit = long ? 1 : 0
The mechanics of the Entry & Exit variables are simple. The variable takes on a value of 1 when your trading system generates the signal and if your system does not produce any signal, variable returns 0. In this example, you see how exit signals can be generated in a trading system that only contains entry signals. If you have a system with original exit signals, you can also use them directly. (Please mind the NOTES section below).
STEP 2
To utilize the Entry & Exit variables as source in another script, they must be plotted on the chart. Therefore, the final detail to include in the script containing your trading system would be as follows:
// Plot The Output
plot(long_entry, "Long Entry", display=display.data_window, editable=false)
plot(long_exit, "Long Exit", display=display.data_window, editable=false)
plot(short_entry, "Short Entry", display=display.data_window, editable=false)
plot(short_exit, "Short Exit", display=display.data_window, editable=false)
STEP 3
Now, we are ready to test the system! Load the Backtesting Module indicator onto the chart along with your trading system/indicator. Then set the outputs of your system (Long Entry, Long Exit, Short Entry, Short Exit) as source in the module. That's it.
FEATURES & ORIGINALITY
⮞ Primarily, this script has been created to provide you with an easy and practical method when testing your trading system.
⮞ I thought it might be nice to visualize a few useful results. The Backtesting Module provides insights into the outcomes of both long and short trades by computing the number of trades and the success percentage.
⮞ Through the 'Trade' parameter, users can specify the market direction in which the indicator is permitted to initiate positions.
⮞ Users have the flexibility to define the date range for the test.
⮞ There are optional features allowing users to plot entry prices on the chart and customize bar colors.
⮞ The report and the test date range are presented in a table on the chart screen. The entry price can be monitored in the data window.
⮞ Note that results are based on realized returns, and the open trade is not included in the displayed results. (The only exception is the 'Unrealized PNL' result in the table.)
STRATEGY SETTINGS
The default parameters are as follows:
⮞ Initial Balance : 10000 (in units of currency)
⮞ Quantity : 10% of equity
⮞ Commission : 0.04%
⮞ Slippage : 0
⮞ Dataset : All bars in the chart
For a realistic backtest result, you should size trades to only risk sustainable amounts of equity. Do not risk more than 5-10% on a trade. And ALWAYS configure your commission and slippage parameters according to pessimistic scenarios!
NOTES
⮞ This script is intended solely for development purposes. And it'll will be available for all the indicators I publish.
⮞ In this version of the module, all order types are designed as market orders. The exit size is the sum of the entry size.
⮞ As your trading conditions grow more intricate, you might need to define the outputs of your system in alternative ways. The method outlined in this description is tailored for straightforward signal structures.
⮞ Additionally, depending on the structure of your trading system, the backtest module may require further development. This encompasses stop-loss, take-profit, specific exit orders, quantity, margin and risk management calculations. I am considering releasing improvements that consider these options in future versions.
⮞ An example of how complex trading signals can be generated is the OTT Collection. If you're interested in seeing how the signals are constructed, you can use the link below.
THANKS
Special thanks to PineCoders for their valuable moderation efforts.
I hope this will be a useful example for the TradingView community...
DISCLAIMER
This is just an indicator, nothing more. It is provided for informational and educational purposes exclusively. The utilization of this script does not constitute professional or financial advice. The user solely bears the responsibility for risks associated with script usage. Do not forget to manage your risk. And trade as safely as possible. Best of luck!
Indicadores e estratégias
Contrarian DC Strategy - w Entry SL Pause and TrailingStopDonchian Channel Setup:
The strategy uses a tool called the Donchian Channel. Imagine this as two lines (bands) on a chart that show the highest and lowest prices over a certain number of past trading days (default is 20 days).
There's also a centerline, which is the average of these two bands.
Entry Conditions for Trades:
Buying (Going Long): The strategy considers buying when the price touches or falls below the lower band of the Donchian Channel. However, this only happens if there has been a pause after a previous losing trade. This pause is a number of candles where no new trades are taken.
Selling (Going Short): Similarly, the strategy considers selling when price reaches or exceeds the upper band of the Donchian Channel. Again, this is subject to a pause after a losing trade.
Stop Loss and Take Profit:
Each trade has a "Stop Loss" and "Take Profit" set. The Stop Loss is a preset price level where the trade will close to prevent further losses if the market moves against your position. The Take Profit does the same but locks in profit if the market moves in your favor.
The Stop Loss is set based on a percentage of the price at which you entered the trade.
The Take Profit is determined by the Risk/Reward Ratio. This ratio helps balance how much you're willing to risk versus the potential reward.
Trailing Stop Loss:
When a trade is profitable, the strategy should involve a "Trailing Stop Loss." This means the Stop Loss level moves (or trails) the price movement to lock in profits as the market moves in your favor.
For a buy trade, if the price moves above the centerline of the Donchian Channel, the Trailing Stop Loss should be adjusted in the middle between the entry price and the centerline. Viceversa for a sell trade, it should be adjusted in the same way if the price goes below the centerline.
IMPORTANT: There's no allert for the trailing stop at the moment.
Post-Stop Loss Pause:
If a trade hits the Stop Loss (i.e., it's a losing trade), the strategy takes a break before opening another trade in the same direction. This pause helps to avoid entering another trade immediately in a potentially unfavorable market.
In summary, this strategy is designed to make trades based on the Donchian Channel, with specific rules for when to enter and exit trades, and mechanisms to manage risk and protect profits. It's contrarian because it tends to buy when the price is low and sell when the price is high, which is opposite to what many traders might do.
COSTAR Strategy [SS]A little late posting this but here it is, as promised!
This is the companion to the COSTAR indicator.
What it does:
It creates a co-integration paired relationship with a separate, cointegrated ticker. It then plots out the expected range based on the value of the cointegrated pair. When the current ticker is below the value of its co-integrated partner, it becomes a "Buy" and should be longed. When it becomes overvalued in comparison, it becomes a "Sell" and should be shorted.
The example above is with BA and USO, which have a strong inverse relationship.
How it works:
I made the strategy version a bit more intuitive. Instead of you selecting the parameters for your model, it will autoselect the ideal parameters based on your desired co-integrated pair. You simply enter the ticker you want to compare against, and it will sort through the values at various lags to find significance and stationarity. It will then create a model and plot the model out for you on your chart, as you can see above.
The premise of the strategy:
The premise of the strategy is as stated before. You long when the ticker is undervalued in comparison to its co-integrated pair, and short when it is overvalued. The conditions for entry are simply a co-integrated pair being over the expected range (short) or below the expected range (long).
The condition to exit is a "re-integration", or a crossover of the expected value of the ticker (the centreline).
What if it can't find a relationship?
In some instances, the indicator will not be able to determine a co-integrated relationship, owning to a lack of stationarity between the data. When this happens, you will get the following error:
The indicator provides you with prompts, such as switching the timeframe or trying an alternative ticker. In the case displayed above, if we simply switch to the 1 hour timeframe, we have a viable model with great backtest results:
You can toggle in the settings menu the various parameters, such as timeframe, fills and displays.
And that is the strategy in a nutshell, be sure to check out its partner indicator, COSTAR, for more information on the premise of using co-integrated models for trading. And let me know your questions below!
Safe trades everyone!
Donchian Quest Research// =================================
Trend following strategy.
// =================================
Strategy uses two channels. One channel - for opening trades. Second channel - for closing.
Channel is similar to Donchian channel, but uses Close prices (not High/Low). That helps don't react to wicks of volatile candles (“stop hunting”). In most cases openings occur earlier than in Donchian channel. Closings occur only for real breakout.
// =================================
Strategy waits for beginning of trend - when price breakout of channel. Default length of both channels = 50 candles.
Conditions of trading:
- Open Long: If last Close = max Close for 50 closes.
- Close Long: If last Close = min Close for 50 closes.
- Open Short: If last Close = min Close for 50 closes.
- Close Short: If last Close = max Close for 50 closes.
// =================================
Color of lines:
- black - channel for opening trade.
- red - channel for closing trade.
- yellow - entry price.
- fuchsia - stoploss and breakeven.
- vertical green - go Long.
- vertical red - go Short.
- vertical gray - close in end, don't trade anymore.
// =================================
Order size calculated with ATR and volatility.
You can't trade 1 contract in BTC and 1 contract in XRP - for example. They have different price and volatility, so 1 contract BTC not equal 1 contract XRP.
Script uses universal calculation for every market. It is based on:
- Risk - USD sum you ready to loss in one trade. It calculated as percent of Equity.
- ATR indicator - measurement of volatility.
With default setting your stoploss = 0.5 percent of equity:
- If initial capital is 1000 USD and used parameter "Permit stop" - loss will be 5 USD (0.5 % of equity).
- If your Equity rises to 2000 USD and used parameter "Permit stop"- loss will be 10 USD (0.5 % of Equity).
// =================================
This Risk works only if you enable “Permit stop” parameter in Settings.
If this parameter disabled - strategy works as reversal strategy:
⁃ If close Long - channel border works as stoploss and momentarily go Short.
⁃ If close Short - channel border works as stoploss and momentarily go Long.
Channel borders changed dynamically. So sometime your loss will be greater than ‘Risk %’. Sometime - less than ‘Risk %’.
If this parameter enabled - maximum loss always equal to 'Risk %'. This parameter also include breakeven: if profit % = Risk %, then move stoploss to entry price.
// =================================
Like all trend following strategies - it works only in trend conditions. If no trend - slowly bleeding. There is no special additional indicator to filter trend/notrend. You need to trade every signal of strategy.
Strategy gives many losses:
⁃ 30 % of trades will close with profit.
⁃ 70 % of trades will close with loss.
⁃ But profit from 30% will be much greater than loss from 70 %.
Your task - patiently wait for it and don't use risky setting for position sizing.
// =================================
Recommended timeframe - Daily.
// =================================
Trend can vary in lengths. Selecting length of channels determine which trend you will be hunting:
⁃ 20/10 - from several days to several weeks.
⁃ 20/20 or 50/20 - from several weeks to several months.
⁃ 50/50 or 100/50 or 100/100 - from several months to several years.
// =================================
Inputs (Settings):
- Length: length of channel for trade opening/closing. You can choose 20/10, 20/20, 50/20, 50/50, 100/50, 100/100. Default value: 50/50.
- Permit Long / Permit short: Longs are most profitable for this strategy. You can disable Shorts and enable Longs only. Default value: permit all directions.
- Risk % of Equity: for position sizing used Equity percent. Don't use values greater than 5 % - it's risky. Default value: 0.5%.
⁃ ATR multiplier: this multiplier moves stoploss up or down. Big multiplier = small size of order, small profit, stoploss far from entry, low chance of stoploss. Small multiplier = big size of order, big profit, stop near entry, high chance of stoploss. Default value: 2.
- ATR length: number of candles to calculate ATR indicator. It used for order size and stoploss. Default value: 20.
- Close in end - to close active trade in the end (and don't trade anymore) or leave it open. You can see difference in Strategy Tester. Default value: don’t close.
- Permit stop: use stop or go reversal. Default value: without stop, reversal strategy.
// =================================
Properties (Settings):
- Initial capital - 1000 USD.
- Script don't uses 'Order size' - you need to change 'Risk %' in Inputs instead.
- Script don't uses 'Pyramiding'.
- 'Commission' 0.055 % and 'Slippage' 0 - this parameters are for crypto exchanges with perpetual contracts (for example Bybit). If use on other markets - set it accordingly to your exchange parameters.
// =================================
Big dataset used for chart - 'BITCOIN ALL TIME HISTORY INDEX'. It gives enough trades to understand logic of script. It have several good trends.
// =================================
London BreakOut ClassicHey there, this is my first time publishing a strategy. The strategy is based on the London Breakout Idea, an incredibly popular concept with abundant information available online.
Let me summarize the London Breakout Strategy in a nutshell: It involves identifying key price levels based on the Tokyo Session before the London Session starts. Typically, these key levels are the high and low of the previous Tokyo session. If a breakout occurs during the London session, you simply follow the trend.
The purpose of this code
After conducting my research, I came across numerous posts, videos, and articles discussing the London Breakout Strategy. I aimed to automatically test it myself to verify whether the claims made by these so-called trading gurus are accurate or not. Consequently, I wrote this script to gain an understanding of how this strategy would perform if I were to follow its basic settings blindly.
Explanation of drawings on the chart:
Red or Green Box: A box is drawn on our chart displaying the exact range of the Tokyo trading session. This box is colored red if the trend during the session was downward and green if it was upward. The box is always drawn between the high and the low between 0:00 AM and 7:00 AM UTC. You can change the settings via the Inputs "Session time Tokyo" & "Session time zone".
Green Background: The green background represents the London trading session. My code allows us to make entries only during this time. If we haven't entered a trade, any pending orders are canceled. I've also programmed a timeout at 11 pm to ensure every trade is closed before the new Tokyo session begins.
Red Line: The red line is automatically placed in the middle of our previous Tokyo range. This line acts as our stop loss. If we cross this line after entering a trade but before reaching our take profit, we'll be stopped out.
When do we enter a trade?
We wait for a candle body to close outside of the previous Tokyo range to enter a trade with the opening of the next candle. We only enter one trade per day.
Where do we put our Take Profit?
The code calculates the exact distance between our entry point and the stop loss. We are trading a risk-reward ratio of 1:1 by default, meaning our take profit is always the same number of pips away from our entry as the stop loss. The Stop Loss is always defined by the red line on the chart. You can change the risk-reward ratio via the inputs setting "CRV", to see how the result changes.
What is the purpose of this script?
I wanted to backtest the London breakout strategy to see how it actually works. Therefore, I wrote this code so that everybody can test it for themselves. You can change the settings and see how the result changes. Typically, you should test this strategy on forex markets and on either 1Min, 5 Min, or 15 Min timeframe.
What are the results?
Over the last 3-6 months (over 100 trades), trading the strategy with my default settings hasn't proven to be very successful. Consequently, I do not recommend trading this strategy blindly. The purpose of this code is to provide you with a foundation for the London Breakout Strategy, allowing you to modify and enhance it according to your preferences. If you're contemplating whether to give it a try, you can assess the results from the past months by using this code as a starting point.
MACD of Relative Strenght StrategyMACD Relative Strenght Strategy :
INTRODUCTION :
This strategy is based on two well-known indicators: MACD and Relative Strenght (RS). By coupling them, we obtain powerful buy signals. In fact, the special feature of this strategy is that it creates an indicator from an indicator. Thus, we construct a MACD whose source is the value of the RS. The strategy only takes buy signals, ignoring SHORT signals as they are mostly losers. There's also a money management method enabling us to reinvest part of the profits or reduce the size of orders in the event of substantial losses.
RELATIVE STRENGHT :
RS is an indicator that measures the anomaly between momentum and the assumption of market efficiency. It is used by professionals and is one of the most robust indicators. The idea is to own assets that do better than average, based on their past performance. We calculate RS using this formula :
RS = close/highest_high(RS_Length)
Where highest_high(RS_Length) = highest value of the high over a user-defined time period (which is the RS_Length).
We can thus situate the current price in relation to its highest price over this user-defined period.
MACD (Moving Average Convergence - Divergence) :
This is one of the best-known indicators, measuring the distance between two exponential moving averages : one fast and one slower. A wide distance indicates fast momentum and vice versa. We'll plot the value of this distance and call this line macdline. The MACD uses a third moving average with a lower period than the first two. This last moving average will give a signal when it crosses the macdline. It is therefore constructed using the values of the macdline as its source.
It's important to note that the first two MAs are constructed using RS values as their source. So we've just built an indicator of an indicator. This kind of method is very powerful because it is rarely used and brings value to the strategy.
PARAMETERS :
RS Length : Relative Strength length i.e. the number of candles back to find the highest high and compare the current price with this high. Default is 300.
MACD Fast Length : Relative Strength fast EMA length used to plot the MACD. Default is 14.
MACD Slow Length : Relative Strength slow EMA length used to plot the MACD. Default is 26.
MACD Signal Smoothing : Macdline SMA length used to plot the MACD. Default is 10.
Max risk per trade (in %) : The maximum loss a trade can incur (in percentage of the trade value). Default is 8%.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. Default is 400, meaning that for each $400 gain or loss, the order size is increased or decreased by a user-selected amount.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot has been used to test the different parameters and determine which ones maximize return while limiting drawdown. This strategy is the most optimal on BITSTAMP:ETHUSD in 8h timeframe with the parameters set by default.
ENTER RULES :
The entry rules are very simple : we open a long position when the MACD value turns positive. You are therefore LONG when the MACD is green.
EXIT RULES :
We exit a position (whether losing or winning) when the MACD becomes negative, i.e. turns red.
RISK MANAGEMENT :
This strategy can incur losses, so it's important to manage our risks well. If the position is losing and has incurred a loss of -8%, our stop loss is activated to limit losses.
MONEY MANAGEMENT :
The fixed ratio method was used to manage our gains and losses. For each gain of an amount equal to the value of the fixed ratio, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy increases both performance and drawdown.
Enjoy the strategy and don't forget to take the trade :)
Trend-based Price Action StrategyThis is a strategy script that combines trend-based price action analysis with the Relative Strength Index (RSI) and Exponential Moving Averages (EMA) as trend filters. Here's a summary of the key components and logic:
Price Action Candlestick Patterns:
Bullish patterns: Engulfing candle and Morning Star.
Bearish patterns: Engulfing candle and Evening Star.
RSI Integration:
RSI is used to identify overbought and oversold conditions.
EMA Trend Filter:
Three EMAs with different periods: Fast , Medium and Slow.
Long trend condition occur when the fast EMA is above the medium and the medium is above the slow EMA.
Short trend condition occur when the slow EMA is above the medium and the medium is above the fast EMA.
Long entry conditions: RSI is oversold, RSI is decreasing, bullish candlestick pattern, and EMA trend filter conditions are met.
Short entry conditions: RSI is overbought, RSI is decreasing, bearish candlestick pattern, and EMA trend filter conditions are met.
Exit conditions:
Take profit or stop loss is reached.
Plotting:
Signals are plotted on the chart when entry conditions are met.
EMAs are plotted when the EMA trend filter is enabled.
This script aims to capture potential trend reversal points based on a combination of candlestick patterns, RSI, and EMA trend analysis.
Traders can use this script as a starting point for further customization or as a reference for developing their own trading strategies. It's important to note that past performance is not indicative of future results, and thorough testing and validation are recommended before deploying any trading strategy.
simple pull back TJlv26This is a very simple strategy for swing trade in stock indexes.
this strategy only trade long position, recommend to use this in day chart of sp500 or nas100.
SPX
NDX
Buy condition:
close price above long term SMA(default period 200),close price under short term SMA(default period 10), RSI is under 30(default period 3)
Sell condition:
1:if close price is above short period SMA and current close price is lower than low price of previous bar
2:hit the take profit target(default value 10%)
3:hit the stop loss target(default value 5%)
from author:
As you can see, it's a very simple logic. You only start trading when the price is above long-term moving average, so you can avoid risk by taking positions only in the uptrend. You also use stop-loss, so even in situations where there is a significant downturn, you can minimize losses.
However, it's important to note that this strategy performs well only in markets where long-term (approximately 10 years) upward movements are expected. It often yields disappointing results during prolonged bear markets. This is where each user's fundamental analysis comes into play, as there is no such thing as a perfect trading logic.
Another noteworthy point is that, as seen in the results of back testing, this strategy tends to underperform buy-and-hold in most cases. As mentioned earlier, it's a strategy focused on risk mitigation and starting trades at the most advantageous prices, so I believe that using leverage of 2-4 times can maximize profits. However, trading with leverage is highly risky, so it should be assessed based on each individual's risk tolerance.
Supertrend Advance Pullback StrategyHandbook for the Supertrend Advance Strategy
1. Introduction
Purpose of the Handbook:
The main purpose of this handbook is to serve as a comprehensive guide for traders and investors who are looking to explore and harness the potential of the Supertrend Advance Strategy. In the rapidly changing financial market, having the right tools and strategies at one's disposal is crucial. Whether you're a beginner hoping to dive into the world of trading or a seasoned investor aiming to optimize and diversify your portfolio, this handbook offers the insights and methodologies you need. By the end of this guide, readers should have a clear understanding of how the Supertrend Advance Strategy works, its benefits, potential pitfalls, and practical application in various trading scenarios.
Overview of the Supertrend Advance Pullback Strategy:
At its core, the Supertrend Advance Strategy is an evolution of the popular Supertrend Indicator. Designed to generate buy and sell signals in trending markets, the Supertrend Indicator has been a favorite tool for many traders around the world. The Advance Strategy, however, builds upon this foundation by introducing enhanced mechanisms, filters, and methodologies to increase precision and reduce false signals.
1. Basic Concept:
The Supertrend Advance Strategy relies on a combination of price action and volatility to determine the potential trend direction. By assessing the average true range (ATR) in conjunction with specific price points, this strategy aims to highlight the potential starting and ending points of market trends.
2. Methodology:
Unlike the traditional Supertrend Indicator, which primarily focuses on closing prices and ATR, the Advance Strategy integrates other critical market variables, such as volume, momentum oscillators, and perhaps even fundamental data, to validate its signals. This multidimensional approach ensures that the generated signals are more reliable and are less prone to market noise.
3. Benefits:
One of the main benefits of the Supertrend Advance Strategy is its ability to filter out false breakouts and minor price fluctuations, which can often lead to premature exits or entries in the market. By waiting for a confluence of factors to align, traders using this advanced strategy can increase their chances of entering or exiting trades at optimal points.
4. Practical Applications:
The Supertrend Advance Strategy can be applied across various timeframes, from intraday trading to swing trading and even long-term investment scenarios. Furthermore, its flexible nature allows it to be tailored to different asset classes, be it stocks, commodities, forex, or cryptocurrencies.
In the subsequent sections of this handbook, we will delve deeper into the intricacies of this strategy, offering step-by-step guidelines on its application, case studies, and tips for maximizing its efficacy in the volatile world of trading.
As you journey through this handbook, we encourage you to approach the Supertrend Advance Strategy with an open mind, testing and tweaking it as per your personal trading style and risk appetite. The ultimate goal is not just to provide you with a new tool but to empower you with a holistic strategy that can enhance your trading endeavors.
2. Getting Started
Navigating the financial markets can be a daunting task without the right tools. This section is dedicated to helping you set up the Supertrend Advance Strategy on one of the most popular charting platforms, TradingView. By following the steps below, you'll be able to integrate this strategy into your charts and start leveraging its insights in no time.
Setting up on TradingView:
TradingView is a web-based platform that offers a wide range of charting tools, social networking, and market data. Before you can apply the Supertrend Advance Strategy, you'll first need a TradingView account. If you haven't set one up yet, here's how:
1. Account Creation:
• Visit TradingView's official website.
• Click on the "Join for free" or "Sign up" button.
• Follow the registration process, providing the necessary details and setting up your login credentials.
2. Navigating the Dashboard:
• Once logged in, you'll be taken to your dashboard. Here, you'll see a variety of tools, including watchlists, alerts, and the main charting window.
• To begin charting, type in the name or ticker of the asset you're interested in the search bar at the top.
3. Configuring Chart Settings:
• Before integrating the Supertrend Advance Strategy, familiarize yourself with the chart settings. This can be accessed by clicking the 'gear' icon on the top right of the chart window.
• Adjust the chart type, time intervals, and other display settings to your preference.
Integrating the Strategy into a Chart:
Now that you're set up on TradingView, it's time to integrate the Supertrend Advance Strategy.
1. Accessing the Pine Script Editor:
• Located at the top-center of your screen, you'll find the "Pine Editor" tab. Click on it.
• This is where custom strategies and indicators are scripted or imported.
2. Loading the Supertrend Advance Strategy Script:
• Depending on whether you have the script or need to find it, there are two paths:
• If you have the script: Copy the Supertrend Advance Strategy script, and then paste it into the Pine Editor.
• If searching for the script: Click on the “Indicators” icon (looks like a flame) at the top of your screen, and then type “Supertrend Advance Strategy” in the search bar. If available, it will show up in the list. Simply click to add it to your chart.
3. Applying the Strategy:
• After pasting or selecting the Supertrend Advance Strategy in the Pine Editor, click on the “Add to Chart” button located at the top of the editor. This will overlay the strategy onto your main chart window.
4. Configuring Strategy Settings:
• Once the strategy is on your chart, you'll notice a small settings ('gear') icon next to its name in the top-left of the chart window. Click on this to access settings.
• Here, you can adjust various parameters of the Supertrend Advance Strategy to better fit your trading style or the specific asset you're analyzing.
5. Interpreting Signals:
• With the strategy applied, you'll now see buy/sell signals represented on your chart. Take time to familiarize yourself with how these look and behave over various timeframes and market conditions.
3. Strategy Overview
What is the Supertrend Advance Strategy?
The Supertrend Advance Strategy is a refined version of the classic Supertrend Indicator, which was developed to aid traders in spotting market trends. The strategy utilizes a combination of data points, including average true range (ATR) and price momentum, to generate buy and sell signals.
In essence, the Supertrend Advance Strategy can be visualized as a line that moves with the price. When the price is above the Supertrend line, it indicates an uptrend and suggests a potential buy position. Conversely, when the price is below the Supertrend line, it hints at a downtrend, suggesting a potential selling point.
Strategy Goals and Objectives:
1. Trend Identification: At the core of the Supertrend Advance Strategy is the goal to efficiently and consistently identify prevailing market trends. By recognizing these trends, traders can position themselves to capitalize on price movements in their favor.
2. Reducing Noise: Financial markets are often inundated with 'noise' - short-term price fluctuations that can mislead traders. The Supertrend Advance Strategy aims to filter out this noise, allowing for clearer decision-making.
3. Enhancing Risk Management: With clear buy and sell signals, traders can set more precise stop-loss and take-profit points. This leads to better risk management and potentially improved profitability.
4. Versatility: While primarily used for trend identification, the strategy can be integrated with other technical tools and indicators to create a comprehensive trading system.
Type of Assets/Markets to Apply the Strategy:
1. Equities: The Supertrend Advance Strategy is highly popular among stock traders. Its ability to capture long-term trends makes it particularly useful for those trading individual stocks or equity indices.
2. Forex: Given the 24-hour nature of the Forex market and its propensity for trends, the Supertrend Advance Strategy is a valuable tool for currency traders.
3. Commodities: Whether it's gold, oil, or agricultural products, commodities often move in extended trends. The strategy can help in identifying and capitalizing on these movements.
4. Cryptocurrencies: The volatile nature of cryptocurrencies means they can have pronounced trends. The Supertrend Advance Strategy can aid crypto traders in navigating these often tumultuous waters.
5. Futures & Options: Traders and investors in derivative markets can utilize the strategy to make more informed decisions about contract entries and exits.
It's important to note that while the Supertrend Advance Strategy can be applied across various assets and markets, its effectiveness might vary based on market conditions, timeframe, and the specific characteristics of the asset in question. As always, it's recommended to use the strategy in conjunction with other analytical tools and to backtest its effectiveness in specific scenarios before committing to trades.
4. Input Settings
Understanding and correctly configuring input settings is crucial for optimizing the Supertrend Advance Strategy for any specific market or asset. These settings, when tweaked correctly, can drastically impact the strategy's performance.
Grouping Inputs:
Before diving into individual input settings, it's important to group similar inputs. Grouping can simplify the user interface, making it easier to adjust settings related to a specific function or indicator.
Strategy Choice:
This input allows traders to select from various strategies that incorporate the Supertrend indicator. Options might include "Supertrend with RSI," "Supertrend with MACD," etc. By choosing a strategy, the associated input settings for that strategy become available.
Supertrend Settings:
1. Multiplier: Typically, a default value of 3 is used. This multiplier is used in the ATR calculation. Increasing it makes the Supertrend line further from prices, while decreasing it brings the line closer.
2. Period: The number of bars used in the ATR calculation. A common default is 7.
EMA Settings (Exponential Moving Average):
1. Period: Defines the number of previous bars used to calculate the EMA. Common periods are 9, 21, 50, and 200.
2. Source: Allows traders to choose which price (Open, Close, High, Low) to use in the EMA calculation.
RSI Settings (Relative Strength Index):
1. Length: Determines how many periods are used for RSI calculation. The standard setting is 14.
2. Overbought Level: The threshold at which the asset is considered overbought, typically set at 70.
3. Oversold Level: The threshold at which the asset is considered oversold, often at 30.
MACD Settings (Moving Average Convergence Divergence):
1. Short Period: The shorter EMA, usually set to 12.
2. Long Period: The longer EMA, commonly set to 26.
3. Signal Period: Defines the EMA of the MACD line, typically set at 9.
CCI Settings (Commodity Channel Index):
1. Period: The number of bars used in the CCI calculation, often set to 20.
2. Overbought Level: Typically set at +100, denoting overbought conditions.
3. Oversold Level: Usually set at -100, indicating oversold conditions.
SL/TP Settings (Stop Loss/Take Profit):
1. SL Multiplier: Defines the multiplier for the average true range (ATR) to set the stop loss.
2. TP Multiplier: Defines the multiplier for the average true range (ATR) to set the take profit.
Filtering Conditions:
This section allows traders to set conditions to filter out certain signals. For example, one might only want to take buy signals when the RSI is below 30, ensuring they buy during oversold conditions.
Trade Direction and Backtest Period:
1. Trade Direction: Allows traders to specify whether they want to take long trades, short trades, or both.
2. Backtest Period: Specifies the time range for backtesting the strategy. Traders can choose from options like 'Last 6 months,' 'Last 1 year,' etc.
It's essential to remember that while default settings are provided for many of these tools, optimal settings can vary based on the market, timeframe, and trading style. Always backtest new settings on historical data to gauge their potential efficacy.
5. Understanding Strategy Conditions
Developing an understanding of the conditions set within a trading strategy is essential for traders to maximize its potential. Here, we delve deep into the logic behind these conditions, using the Supertrend Advance Strategy as our focal point.
Basic Logic Behind Conditions:
Every strategy is built around a set of conditions that provide buy or sell signals. The conditions are based on mathematical or statistical methods and are rooted in the study of historical price data. The fundamental idea is to recognize patterns or behaviors that have been profitable in the past and might be profitable in the future.
Buy and Sell Conditions:
1. Buy Conditions: Usually formulated around bullish signals or indicators suggesting upward price momentum.
2. Sell Conditions: Centered on bearish signals or indicators indicating downward price momentum.
Simple Strategy:
The simple strategy could involve using just the Supertrend indicator. Here:
• Buy: When price closes above the Supertrend line.
• Sell: When price closes below the Supertrend line.
Pullback Strategy:
This strategy capitalizes on price retracements:
• Buy: When the price retraces to the Supertrend line after a bullish signal and is supported by another bullish indicator.
• Sell: When the price retraces to the Supertrend line after a bearish signal and is confirmed by another bearish indicator.
Indicators Used:
EMA (Exponential Moving Average):
• Logic: EMA gives more weight to recent prices, making it more responsive to current price movements. A shorter-period EMA crossing above a longer-period EMA can be a bullish sign, while the opposite is bearish.
RSI (Relative Strength Index):
• Logic: RSI measures the magnitude of recent price changes to analyze overbought or oversold conditions. Values above 70 are typically considered overbought, and values below 30 are considered oversold.
MACD (Moving Average Convergence Divergence):
• Logic: MACD assesses the relationship between two EMAs of a security’s price. The MACD line crossing above the signal line can be a bullish signal, while crossing below can be bearish.
CCI (Commodity Channel Index):
• Logic: CCI compares a security's average price change with its average price variation. A CCI value above +100 may mean the price is overbought, while below -100 might signify an oversold condition.
And others...
As the strategy expands or contracts, more indicators might be added or removed. The crucial point is to understand the core logic behind each, ensuring they align with the strategy's objectives.
Logic Behind Each Indicator:
1. EMA: Emphasizes recent price movements; provides dynamic support and resistance levels.
2. RSI: Indicates overbought and oversold conditions based on recent price changes.
3. MACD: Showcases momentum and direction of a trend by comparing two EMAs.
4. CCI: Measures the difference between a security's price change and its average price change.
Understanding strategy conditions is not just about knowing when to buy or sell but also about comprehending the underlying market dynamics that those conditions represent. As you familiarize yourself with each condition and indicator, you'll be better prepared to adapt and evolve with the ever-changing financial markets.
6. Trade Execution and Management
Trade execution and management are crucial aspects of any trading strategy. Efficient execution can significantly impact profitability, while effective management can preserve capital during adverse market conditions. In this section, we'll explore the nuances of position entry, exit strategies, and various Stop Loss (SL) and Take Profit (TP) methodologies within the Supertrend Advance Strategy.
Position Entry:
Effective trade entry revolves around:
1. Timing: Enter at a point where the risk-reward ratio is favorable. This often corresponds to confirmatory signals from multiple indicators.
2. Volume Analysis: Ensure there's adequate volume to support the movement. Volume can validate the strength of a signal.
3. Confirmation: Use multiple indicators or chart patterns to confirm the entry point. For instance, a buy signal from the Supertrend indicator can be confirmed with a bullish MACD crossover.
Position Exit Strategies:
A successful exit strategy will lock in profits and minimize losses. Here are some strategies:
1. Fixed Time Exit: Exiting after a predetermined period.
2. Percentage-based Profit Target: Exiting after a certain percentage gain.
3. Indicator-based Exit: Exiting when an indicator gives an opposing signal.
Percentage-based SL/TP:
• Stop Loss (SL): Set a fixed percentage below the entry price to limit potential losses.
• Example: A 2% SL on an entry at $100 would trigger a sell at $98.
• Take Profit (TP): Set a fixed percentage above the entry price to lock in gains.
• Example: A 5% TP on an entry at $100 would trigger a sell at $105.
Supertrend-based SL/TP:
• Stop Loss (SL): Position the SL at the Supertrend line. If the price breaches this line, it could indicate a trend reversal.
• Take Profit (TP): One could set the TP at a point where the Supertrend line flattens or turns, indicating a possible slowdown in momentum.
Swing high/low-based SL/TP:
• Stop Loss (SL): For a long position, set the SL just below the recent swing low. For a short position, set it just above the recent swing high.
• Take Profit (TP): For a long position, set the TP near a recent swing high or resistance. For a short position, near a swing low or support.
And other methods...
1. Trailing Stop Loss: This dynamic SL adjusts with the price movement, locking in profits as the trade moves in your favor.
2. Multiple Take Profits: Divide the position into segments and set multiple TP levels, securing profits in stages.
3. Opposite Signal Exit: Exit when another reliable indicator gives an opposite signal.
Trade execution and management are as much an art as they are a science. They require a blend of analytical skill, discipline, and intuition. Regularly reviewing and refining your strategies, especially in light of changing market conditions, is crucial to maintaining consistent trading performance.
7. Visual Representations
Visual tools are essential for traders, as they simplify complex data into an easily interpretable format. Properly analyzing and understanding the plots on a chart can provide actionable insights and a more intuitive grasp of market conditions. In this section, we’ll delve into various visual representations used in the Supertrend Advance Strategy and their significance.
Understanding Plots on the Chart:
Charts are the primary visual aids for traders. The arrangement of data points, lines, and colors on them tell a story about the market's past, present, and potential future moves.
1. Data Points: These represent individual price actions over a specific timeframe. For instance, a daily chart will have data points showing the opening, closing, high, and low prices for each day.
2. Colors: Used to indicate the nature of price movement. Commonly, green is used for bullish (upward) moves and red for bearish (downward) moves.
Trend Lines:
Trend lines are straight lines drawn on a chart that connect a series of price points. Their significance:
1. Uptrend Line: Drawn along the lows, representing support. A break below might indicate a trend reversal.
2. Downtrend Line: Drawn along the highs, indicating resistance. A break above might suggest the start of a bullish trend.
Filled Areas:
These represent a range between two values on a chart, usually shaded or colored. For instance:
1. Bollinger Bands: The area between the upper and lower band is filled, giving a visual representation of volatility.
2. Volume Profile: Can show a filled area representing the amount of trading activity at different price levels.
Stop Loss and Take Profit Lines:
These are horizontal lines representing pre-determined exit points for trades.
1. Stop Loss Line: Indicates the level at which a trade will be automatically closed to limit losses. Positioned according to the trader's risk tolerance.
2. Take Profit Line: Denotes the target level to lock in profits. Set according to potential resistance (for long trades) or support (for short trades) or other technical factors.
Trailing Stop Lines:
A trailing stop is a dynamic form of stop loss that moves with the price. On a chart:
1. For Long Trades: Starts below the entry price and moves up with the price but remains static if the price falls, ensuring profits are locked in.
2. For Short Trades: Starts above the entry price and moves down with the price but remains static if the price rises.
Visual representations offer traders a clear, organized view of market dynamics. Familiarity with these tools ensures that traders can quickly and accurately interpret chart data, leading to more informed decision-making. Always ensure that the visual aids used resonate with your trading style and strategy for the best results.
8. Backtesting
Backtesting is a fundamental process in strategy development, enabling traders to evaluate the efficacy of their strategy using historical data. It provides a snapshot of how the strategy would have performed in past market conditions, offering insights into its potential strengths and vulnerabilities. In this section, we'll explore the intricacies of setting up and analyzing backtest results and the caveats one must be aware of.
Setting Up Backtest Period:
1. Duration: Determine the timeframe for the backtest. It should be long enough to capture various market conditions (bullish, bearish, sideways). For instance, if you're testing a daily strategy, consider a period of several years.
2. Data Quality: Ensure the data source is reliable, offering high-resolution and clean data. This is vital to get accurate backtest results.
3. Segmentation: Instead of a continuous period, sometimes it's helpful to backtest over distinct market phases, like a particular bear or bull market, to see how the strategy holds up in different environments.
Analyzing Backtest Results:
1. Performance Metrics: Examine metrics like the total return, annualized return, maximum drawdown, Sharpe ratio, and others to gauge the strategy's efficiency.
2. Win Rate: It's the ratio of winning trades to total trades. A high win rate doesn't always signify a good strategy; it should be evaluated in conjunction with other metrics.
3. Risk/Reward: Understand the average profit versus the average loss per trade. A strategy might have a low win rate but still be profitable if the average gain far exceeds the average loss.
4. Drawdown Analysis: Review the periods of losses the strategy could incur and how long it takes, on average, to recover.
9. Tips and Best Practices
Successful trading requires more than just knowing how a strategy works. It necessitates an understanding of when to apply it, how to adjust it to varying market conditions, and the wisdom to recognize and avoid common pitfalls. This section offers insightful tips and best practices to enhance the application of the Supertrend Advance Strategy.
When to Use the Strategy:
1. Market Conditions: Ideally, employ the Supertrend Advance Strategy during trending market conditions. This strategy thrives when there are clear upward or downward trends. It might be less effective during consolidative or sideways markets.
2. News Events: Be cautious around significant news events, as they can cause extreme volatility. It might be wise to avoid trading immediately before and after high-impact news.
3. Liquidity: Ensure you are trading in assets/markets with sufficient liquidity. High liquidity ensures that the price movements are more reflective of genuine market sentiment and not due to thin volume.
Adjusting Settings for Different Markets/Timeframes:
1. Markets: Each market (stocks, forex, commodities) has its own characteristics. It's essential to adjust the strategy's parameters to align with the market's volatility and liquidity.
2. Timeframes: Shorter timeframes (like 1-minute or 5-minute charts) tend to have more noise. You might need to adjust the settings to filter out false signals. Conversely, for longer timeframes (like daily or weekly charts), you might need to be more responsive to genuine trend changes.
3. Customization: Regularly review and tweak the strategy's settings. Periodic adjustments can ensure the strategy remains optimized for the current market conditions.
10. Frequently Asked Questions (FAQs)
Given the complexities and nuances of the Supertrend Advance Strategy, it's only natural for traders, both new and seasoned, to have questions. This section addresses some of the most commonly asked questions regarding the strategy.
1. What exactly is the Supertrend Advance Strategy?
The Supertrend Advance Strategy is an evolved version of the traditional Supertrend indicator. It's designed to provide clearer buy and sell signals by incorporating additional indicators like EMA, RSI, MACD, CCI, etc. The strategy aims to capitalize on market trends while minimizing false signals.
2. Can I use the Supertrend Advance Strategy for all asset types?
Yes, the strategy can be applied to various asset types like stocks, forex, commodities, and cryptocurrencies. However, it's crucial to adjust the settings accordingly to suit the specific characteristics and volatility of each asset type.
3. Is this strategy suitable for day trading?
Absolutely! The Supertrend Advance Strategy can be adjusted to suit various timeframes, making it versatile for both day trading and long-term trading. Remember to fine-tune the settings to align with the timeframe you're trading on.
4. How do I deal with false signals?
No strategy is immune to false signals. However, by combining the Supertrend with other indicators and adhering to strict risk management protocols, you can minimize the impact of false signals. Always use stop-loss orders and consider filtering trades with additional confirmation signals.
5. Do I need any prior trading experience to use this strategy?
While the Supertrend Advance Strategy is designed to be user-friendly, having a foundational understanding of trading and market analysis can greatly enhance your ability to employ the strategy effectively. If you're a beginner, consider pairing the strategy with further education and practice on demo accounts.
6. How often should I review and adjust the strategy settings?
There's no one-size-fits-all answer. Some traders adjust settings weekly, while others might do it monthly. The key is to remain responsive to changing market conditions. Regular backtesting can give insights into potential required adjustments.
7. Can the Supertrend Advance Strategy be automated?
Yes, many traders use algorithmic trading platforms to automate their strategies, including the Supertrend Advance Strategy. However, always monitor automated systems regularly to ensure they're operating as intended.
8. Are there any markets or conditions where the strategy shouldn't be used?
The strategy might generate more false signals in markets that are consolidative or range-bound. During significant news events or times of unexpected high volatility, it's advisable to tread with caution or stay out of the market.
9. How important is backtesting with this strategy?
Backtesting is crucial as it allows traders to understand how the strategy would have performed in the past, offering insights into potential profitability and areas of improvement. Always backtest any new setting or tweak before applying it to live trades.
10. What if the strategy isn't working for me?
No strategy guarantees consistent profits. If it's not working for you, consider reviewing your settings, seeking expert advice, or complementing the Supertrend Advance Strategy with other analysis methods. Remember, continuous learning and adaptation are the keys to trading success.
Other comments
Value of combining several indicators in this script and how they work together
Diversification of Signals: Just as diversifying an investment portfolio can reduce risk, using multiple indicators can offer varied perspectives on potential price movements. Each indicator can capture a different facet of the market, ensuring that traders are not overly reliant on a single data point.
Confirmation & Reduced False Signals: A common challenge with many indicators is the potential for false signals. By requiring confirmation from multiple indicators before acting, the chances of acting on a false signal can be significantly reduced.
Flexibility Across Market Conditions: Different indicators might perform better under different market conditions. For example, while moving averages might excel in trending markets, oscillators like RSI might be more useful during sideways or range-bound conditions. A mashup strategy can potentially adapt better to varying market scenarios.
Comprehensive Analysis: With multiple indicators, traders can gauge trend strength, momentum, volatility, and potential market reversals all at once, providing a holistic view of the market.
How do the different indicators in the Supertrend Advance Strategy work together?
Supertrend: This is primarily a trend-following indicator. It provides traders with buy and sell signals based on the volatility of the price. When combined with other indicators, it can filter out noise and give more weight to strong, confirmed trends.
EMA (Exponential Moving Average): EMA gives more weight to recent price data. It can be used to identify the direction and strength of a trend. When the price is above the EMA, it's generally considered bullish, and vice versa.
RSI (Relative Strength Index): An oscillator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions. By cross-referencing with other indicators like EMA or MACD, traders can spot potential reversals or confirmations of a trend.
MACD (Moving Average Convergence Divergence): This indicator identifies changes in the strength, direction, momentum, and duration of a trend in a stock's price. When the MACD line crosses above the signal line, it can be a bullish sign, and when it crosses below, it can be bearish. Pairing MACD with Supertrend can provide dual confirmation of a trend.
CCI (Commodity Channel Index): Initially developed for commodities, CCI can indicate overbought or oversold conditions. It can be used in conjunction with other indicators to determine entry and exit points.
In essence, the synergy of these indicators provides a balanced, comprehensive approach to trading. Each indicator offers its unique lens into market conditions, and when they align, it can be a powerful indication of a trading opportunity. This combination not only reduces the potential drawbacks of each individual indicator but leverages their strengths, aiming for more consistent and informed trading decisions.
Backtesting and Default Settings
• This indicator has been optimized to be applied for 1 hour-charts. However, the underlying principles of this strategy are supply and demand in the financial markets and the strategy can be applied to all timeframes. Daytraders can use the 1min- or 5min charts, swing-traders can use the daily charts.
• This strategy has been designed to identify the most promising, highest probability entries and trades for each stock or other financial security.
• The combination of the qualifiers results in a highly selective strategy which only considers the most promising swing-trading entries. As a result, you will normally only find a low number of trades for each stock or other financial security per year in case you apply this strategy for the daily charts. Shorter timeframes will result in a higher number of trades / year.
• Consequently, traders need to apply this strategy for a full watchlist rather than just one financial security.
• Default properties: RSI on (length 14, RSI buy level 50, sell level 50), EMA, RSI, MACD on, type of strategy pullback, SL/TP type: ATR (length 10, factor 3), trade direction both, quantity 5, take profit swing hl 5.1, highest / lowest lookback 2, enable ATR trail (ATR length 10, SL ATR multiplier 1.4, TP multiplier 2.1, lookback = 4, trade direction = both).
Monthly Performance Table by Dr. MauryaWhat is this ?
This Strategy script is not aim to produce strategy results but It aim to produce monthly PnL performance Calendar table which is useful for TradingView community to generate a monthly performance table for Own strategy.
So make sure to read the disclaimer below.
Why it is required to publish?:
I am not satisfied with the monthly performance available on TV community script. Sometimes it is very lengthy in code and sometimes it showing the wrong PNL for current month.
So I have decided to develop new Monthly performance or return in value as well as in percentage with highly flexible to adjust row automatically.
Features :
Accuracy increased for current month PnL.
There are 14 columns and automatically adjusted rows according to available trade years/month.
First Column reflect the YEAR, from second column to 13 column reflect the month and 14 column reflect the yearly PnL.
In tabulated data reflects the monthly PnL (value and (%)) in month column and Yearly PnL (value and (%)) in Yearly column.
Various color input also added to change the table look like background color, text color, heading text color, border color.
In tabulated data, background color turn green for profit and red for loss.
Copy from line 54 to last line as it is in your strategy script.
Credit: This code is modified and top up of the open-source code originally written by QuantNomad. Thanks for their contribution towards to give base and lead to other developers. I have changed the way of determining past PnL to array form and keep separated current month and year PnL from array. Which avoid the false pnl in current month.
Strategy description:
As in first line I said This strategy is aim to provide monthly performance table not focused on the strategy. But it is necessary to explain strategy which I have used here. Strategy is simply based on ADX available on TV community script. Long entry is based on when the difference between DIPlus and ADX is reached on certain value (Set value in Long difference in Input Tab) while Short entry is based on when the difference between DIMinus and ADX is reached on certain value (Set value in Short difference in Input Tab).
Default Strategy Properties used on chart(Important)
This script backtest is done on 1 hour timeframe of NSE:Reliance Inds Future cahrt, using the following backtesting properties:
Balance (default): 500 000 (default base currency)
Order Size: 1 contract
Comission: 20 INR per Order
Slippage: 5 tick
Default setting in Input tab
Len (ADX length) : 14
Th (ADX Threshhold): 20
Long Difference (DIPlus - ADX) = 5
Short Difference (DIMinus - ADX) = 5
We use these properties to ensure a realistic preview of the backtesting system, do note that default properties can be different for various reasons described below:
Order Size: 1 contract by default, this is to allow the strategy to run properly on most instruments such as futures.
Comission: Comission can vary depending on the market and instrument, there is no default value that might return realistic results.
We strongly recommend all users to ensure they adjust the Properties within the script settings to be in line with their accounts & trading platforms of choice to ensure results from the strategies built are realistic.
Disclaimer:
This script not provide indicative of any future results.
This script don’t provide any financial advice.
This strategy is only for the readymade snippet code for monthly PnL performance calender table for any own strategy.
RMI Trend Sync - Strategy [presentTrading]█ Introduction and How It Is Different
The "RMI Trend Sync - Strategy " combines the strength of the Relative Momentum Index (RMI) with the dynamic nature of the Supertrend indicator. This strategy diverges from traditional methodologies by incorporating a dual analytical framework, leveraging both momentum and trend indicators to offer a more holistic market perspective. The integration of the RMI provides an enhanced understanding of market momentum, while the Super Trend indicator offers clear insights into the end of market trends, making this strategy particularly effective in diverse market conditions.
BTC 4h long/short performance
█ Strategy: How It Works - Detailed Explanation
- Understanding the Relative Momentum Index (RMI)
The Relative Momentum Index (RMI) is an adaptation of the traditional Relative Strength Index (RSI), designed to measure the momentum of price movements over a specified period. While RSI focuses on the speed and change of price movements, RMI incorporates the direction and magnitude of those movements, offering a more nuanced view of market momentum.
- Principle of RMI
Calculation Method: RMI is calculated by first determining the average gain and average loss over a given period (Length). It differs from RSI in that it uses the price change (close-to-close) rather than absolute gains or losses. The average gain is divided by the average loss, and this ratio is then normalized to fit within a 0-100 scale.
- Momentum Analysis in the Strategy
Thresholds for Decision Making: The strategy uses predetermined thresholds (pmom for positive momentum and nmom for negative momentum) to trigger trading decisions. When RMI crosses above the positive threshold and other conditions align (e.g., a bullish trend), it signals a potential long entry. Similarly, crossing below the negative threshold in a bearish trend may trigger a short entry.
- Super Trend and Trend Analysis
The Super Trend indicator is calculated based on a higher time frame, providing a broader view of the market trend. This indicator uses the Average True Range (ATR) to adapt to market volatility, making it an effective tool for identifying trend reversals.
The strategy employs a Volume Weighted Moving Average (VWMA) alongside the Super Trend, enhancing its capability to identify significant trend shifts.
ETH 4hr long/short performance
█ Trade Direction
The strategy offers flexibility in selecting the trading direction: long, short, or both. This versatility allows traders to adapt to their market outlook and risk tolerance, whether looking to capitalize on bullish trends, bearish trends, or a combination of both.
█ Usage
To effectively use the "RMI Trend Sync" strategy, traders should first set their preferred trading direction and adjust the RMI and Super Trend parameters according to their risk appetite and trading goals.
The strategy is designed to adapt to various market conditions, making it suitable for different asset classes and time frames.
█ Default Settings
RMI Settings: Length: 21, Positive Momentum Threshold: 70, Negative Momentum Threshold: 30
Super Trend Settings: Length: 10, Higher Time Frame: 480 minutes, Super Trend Factor: 3.5, MA Source: WMA
Visual Settings: Display Range MA: True, Bullish Color: #00bcd4, Bearish Color: #ff5252
Additional Settings: Band Length: 30, RWMA Length: 20
Captain Backtest Model [TFO]Created by @imjesstwoone and @mickey1984, this trade model attempts to capture the expansion from the 10:00-14:00 EST 4h candle using just 3 simple steps. All of the information presented in this description has been outlined by its creators, all I did was translate it to Pine Script. All core settings of the trade model may be edited so that users can test several variations, however this description will cover its default, intended behavior using NQ 5m as an example.
Step 1 is to identify our Price Range. In this case, we are concerned with the highest high and the lowest low created from 6:00-10:00 EST.
Step 2 is to wait for either the high or low of said range to be taken out. Whichever side gets taken first determines the long/short bias for the remainder of the Trade Window (i.e. if price takes the range high, bias is long, and vice versa). Bias must be determined by 11:15 EST, otherwise no trades will be taken. This filter is intended to weed out "choppy" trading days.
Step 3 is to wait for a retracement and enter with a close through the previous candle's high (if long biased) or low (if short biased). There are a couple toggleable criteria that we use to define a retracement; one is checking for opposite close candles that indicate a pullback; another is checking if price took the previous candle's low (if long biased) or high (if short biased).
This trade model was initially tested for index futures, particularly ES and NQ, using a 5m chart, however this indicator allows us to backtest any symbol on any timeframe. Creators @imjesstwoone and @mickey1984 specified a 5 point stop loss on ES and a 25 point stop loss on NQ with their testing.
I've personally found some success in backtesting NQ 5m using a 25 point stop loss and 75 point profit target (3:1 R). Enabling the Use Fixed R:R parameter will ensure that these stops and targets are utilized, otherwise it will enter and hold the position until the close of the Trade Window.
Bollinger Bands StrategyBollinger Bands Strategy :
INTRODUCTION :
This strategy is based on the famous Bollinger Bands. These are constructed using a standard moving average (SMA) and the standard deviation of past prices. The theory goes that 90% of the time, the price is contained between these two bands. If it were to break out, this would mean either a reversal or a continuation. However, when a reversal occurs, the movement is weak, whereas when a continuation occurs, the movement is substantial and profits can be interesting. We're going to use BB to take advantage of this strong upcoming movement, while managing our risks reasonably. There's also a money management method for reinvesting part of the profits or reducing the size of orders in the event of substantial losses.
BOLLINGER BANDS :
The construction of Bollinger bands is straightforward. First, plot the SMA of the price, with a length specified by the user. Then calculate the standard deviation to measure price dispersion in relation to the mean, using this formula :
stdv = (((P1 - avg)^2 + (P2 - avg)^2 + ... + (Pn - avg)^2) / n)^1/2
To plot the two Bollinger bands, we then add a user-defined number of standard deviations to the initial SMA. The default is to add 2. The result is :
Upper_band = SMA + 2*stdv
Lower_band = SMA - 2*stdv
When the price leaves this channel defined by the bands, we obtain buy and sell signals.
PARAMETERS :
BB Length : This is the length of the Bollinger Bands, i.e. the length of the SMA used to plot the bands, and the length of the price series used to calculate the standard deviation. The default is 120.
Standard Deviation Multipler : adds or subtracts this number of times the standard deviation from the initial SMA. Default is 2.
SMA Exit Signal Length : Exit signals for winning and losing trades are triggered by another SMA. This parameter defines the length of this SMA. The default is 110.
Max Risk per trade (in %) : It's the maximum percentage the user can lose in one trade. The default is 6%.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. The default is 400, meaning that for each $400 gain or loss, the order size is increased or decreased by a user-selected amount.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot has been used to test the different parameters and determine which ones maximize return while limiting drawdown. This strategy is the most optimal on BITSTAMP:BTCUSD in 8h timeframe with the following parameters :
BB Length = 120
Standard Deviation Multipler = 2
SMA Exit Signal Length = 110
Max Risk per trade (in %) = 6%
ENTER RULES :
The entry rules are simple:
If close > Upper_band it's a LONG signal
If close < Lower_band it's a SHORT signal
EXIT RULES :
If we are LONG and close < SMA_EXIT, position is closed
If we are SHORT and close > SMA_EXIT, the position is closed
Positions close automatically if they lose more than 6% to limit risk
RISK MANAGEMENT :
This strategy is subject to losses. We manage our risk using the exit SMA or using a SL sets to 6%. This SMA gives us exit signals when the price closes below or above, thus limiting losses. If the signal arrives too late, the position is closed after a loss of 6%.
MONEY MANAGEMENT :
The fixed ratio method was used to manage our gains and losses. For each gain of an amount equal to the fixed ratio value, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy increases both performance and drawdown.
NOTE :
Please note that the strategy is backtested from 2017-01-01. As the timeframe is 8h, this strategy is a medium/long-term strategy. That's why only 51 trades were closed. Be careful, as the test sample is small and performance may not necessarily reflect what may happen in the future.
Enjoy the strategy and don't forget to take the trade :)
Rate of Change StrategyRate of Change Strategy :
INTRODUCTION :
This strategy is based on the Rate of Change indicator. It compares the current price with that of a user-defined period of time ago. This makes it easy to spot trends and even speculative bubbles. The strategy is long term and very risky, which is why we've added a Stop Loss. There's also a money management method that allows you to reinvest part of your profits or reduce the size of your orders in the event of substantial losses.
RATE OF CHANGE (ROC) :
As explained above, the ROC is used to situate the current price compared to that of a certain period of time ago. The formula for calculating ROC in relation to the previous year is as follows :
ROC (365) = (close/close (365) - 1) * 100
With this formula we can find out how many percent the change in the current price is compared with 365 days ago, and thus assess the trend.
PARAMETERS :
ROC Length : Length of the ROC to be calculated. The current price is compared with that of the selected length ago.
ROC Bubble Signal : ROC value indicating that we are in a bubble. This value varies enormously depending on the financial product. For example, in the equity market, a bubble exists when ROC = 40, whereas in cryptocurrencies, a bubble exists when ROC = 150.
Stop Loss (in %) : Stop Loss value in percentage. This is the maximum trade value percentage that can be lost in a single trade.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. The default is 400, which means that for each $400 gain or loss, the order size is increased or decreased by an amount chosen by the user.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot has been used to test the different parameters and determine which ones maximize return while limiting drawdown. This strategy is the most optimal on BITSTAMP:BTCUSD in 1D timeframe with the following parameters :
ROC Length = 365
ROC Bubble Signal = 180
Stop Loss (in %) = 6
LONG CONDITION :
We are in a LONG position if ROC (365) > 0 for at least two days. This allows us to limit noise and irrelevant signals to ensure that the ROC remains positive.
SHORT CONDITION :
We are in a SHORT position if ROC (365) < 0 for at least two days. We also open a SHORT position when the speculative bubble is about to burst. If ROC (365) > 180, we're in a bubble. If the bubble has been in existence for at least a week and the ROC falls back below this threshold, we can expect the asset to return to reasonable prices, and thus a downward trend. So we're opening a SHORT position to take advantage of this upcoming decline.
EXIT RULES FOR WINNING TRADE :
The strategy is self-regulating. We don't exit a LONG trade until a SHORT signal has arrived, and vice versa. So, to exit a winning position, you have to wait for the entry signal of the opposite position.
RISK MANAGEMENT :
This strategy is very risky, and we can easily end up on the wrong side of the trade. That's why we're going to manage our risk with a Stop Loss, limiting our losses as a percentage of the trade's value. By default, this percentage is set at 6%. Each trade will therefore take a maximum loss of 6%.
If the SL has been triggered, it probably means we were on the wrong side. This is why we change the direction of the trade when a SL is triggered. For example, if we were SHORT and lost 6% of the trade value, the strategy will close this losing trade and open a long position without taking into account the ROC value. This allows us to be in position all the time and not miss the best opportunities.
MONEY MANAGEMENT :
The fixed ratio method was used to manage our gains and losses. For each gain of an amount equal to the value of the fixed ratio, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy increases both performance and drawdown.
NOTE :
Please note that the strategy is backtested from 2017-01-01. As the timeframe is 1D, this strategy is a medium/long-term strategy. That's why only 34 trades were closed. Be careful, as the test sample is small and performance may not necessarily reflect what may happen in the future.
Enjoy the strategy and don't forget to take the trade :)
RSI & Backed-Weighted MA StrategyRSI & MA Strategy :
INTRODUCTION :
This strategy is based on two well-known indicators that work best together: the Relative Strength Index (RSI) and the Moving Average (MA). We're going to use the RSI as a trend-follower indicator, rather than a reversal indicator as most are used to. To the signals sent by the RSI, we'll add a condition on the chart's MA, filtering out irrelevant signals and considerably increasing our winning rate. This is a medium/long-term strategy. There's also a money management method enabling us to reinvest part of the profits or reduce the size of orders in the event of substantial losses.
RSI :
The RSI is one of the best-known and most widely used indicators in trading. Its purpose is to warn traders when an asset is overbought or oversold. It was designed to send reversal signals, but we're going to use it as a trend indicator by increasing its length to 20. The RSI formula is as follows :
RSI (n) = 100 - (100 / (1 + (H (n)/L (n))))
With n the length of the RSI, H(n) the average of days closing above the open and L(n) the average of days closing below the open.
MA :
The Moving Average is also widely used in technical analysis, to smooth out variations in an asset. The SMA formula is as follows :
SMA (n) = (P1 + P2 + ... + Pn) / n
where n is the length of the MA.
However, an SMA does not weight any of its terms, which means that the price 10 days ago has the same importance as the price 2 days ago or today's price... That's why in this strategy we use a RWMA, i.e. a back-weighted moving average. It weights old prices more heavily than new ones. This will enable us to limit the impact of short-term variations and focus on the trend that was dominating. The RWMA used weights :
The 4 most recent terms by : 100 / (4+(n-4)*1.30)
The other oldest terms by : weight_4_first_term*1.30
So the older terms are weighted 1.30 more than the more recent ones. The moving average thus traces a trend that accentuates past values and limits the noise of short-term variations.
PARAMETERS :
RSI Length : Lenght of RSI. Default is 20.
MA Type : Choice between a SMA or a RWMA which permits to minimize the impact of short term reversal. Default is RWMA.
MA Length : Length of the selected MA. Default is 19.
RSI Long Signal : Minimum value of RSI to send a LONG signal. Default is 60.
RSI Short signal : Maximum value of RSI to send a SHORT signal. Default is 40.
ROC MA Long Signal : Maximum value of Rate of Change MA to send a LONG signal. Default is 0.
ROC MA Short signal : Minimum value of Rate of Change MA to send a SHORT signal. Default is 0.
TP activation in multiple of ATR : Threshold value to trigger trailing stop Take Profit. This threshold is calculated as multiple of the ATR (Average True Range). Default value is 5 meaning that to trigger the trailing TP the price need to move 5*ATR in the right direction.
Trailing TP in percentage : Percentage value of trailing Take Profit. This Trailing TP follows the profit if it increases, remaining selected percentage below it, but stops if the profit decreases. Default is 3%.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. Default is 400, which means that for each $400 gain or loss, the order size is increased or decreased by a user-selected amount.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot has been used to test the different parameters and determine which ones maximize return while limiting drawdown. This strategy is the most optimal on BITSTAMP:ETHUSD with a timeframe set to 6h. Parameters are set as follows :
MA type: RWMA
MA Length: 19
RSI Long Signal: >60
RSI Short Signal : <40
ROC MA Long Signal : <0
ROC MA Short Signal : >0
TP Activation in multiple ATR : 5
Trailing TP in percentage : 3
ENTER RULES :
The principle is very simple:
If the asset is overbought after a bear market, we are LONG.
If the asset is oversold after a bull market, we are SHORT.
We have defined a bear market as follows : Rate of Change (20) RWMA < 0
We have defined a bull market as follows : Rate of Change (20) RWMA > 0
The Rate of Change is calculated using this formula : (RWMA/RWMA(20) - 1)*100
Overbought is defined as follows : RSI > 60
Oversold is defined as follows : RSI < 40
LONG CONDITION :
RSI > 60 and (RWMA/RWMA(20) - 1)*100 < -1
SHORT CONDITION :
RSI < 40 and (RWMA/RWMA(20) - 1)*100 > 1
EXIT RULES FOR WINNING TRADE :
We have a trailing TP allowing us to exit once the price has reached the "TP Activation in multiple ATR" parameter, i.e. 5*ATR by default in the profit direction. TP trailing is triggered at this point, not limiting our gains, and securing our profits at 3% below this trigger threshold.
Remember that the True Range is : maximum(H-L, H-C(1), C-L(1))
with C : Close, H : High, L : Low
The Average True Range is therefore the average of these TRs over a length defined by default in the strategy, i.e. 20.
RISK MANAGEMENT :
This strategy may incur losses. The method for limiting losses is to set a Stop Loss equal to 3*ATR. This means that if the price moves against our position and reaches three times the ATR, we exit with a loss.
Sometimes the ATR can result in a SL set below 10% of the trade value, which is not acceptable. In this case, we set the SL at 10%, limiting losses to a maximum of 10%.
MONEY MANAGEMENT :
The fixed ratio method was used to manage our gains and losses. For each gain of an amount equal to the value of the fixed ratio, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy increases both performance and drawdown.
Enjoy the strategy and don't forget to take the trade :)
Narrow Range StrategyNarrow Range Strategy :
INTRODUCTION :
This strategy is based on the Narrow Range Day concept, implying that low volatility will generate higher volatility in the days ahead. The strategy sends us buy and sell signals with well-defined profit targets. It's a medium/long-term strategy. There's also a money management method that allows us to reinvest part of the profits or reduce the size of orders in the event of substantial losses.
NARROW RANGE (NR) DAY :
A Narrow Range Day is a day in which price variations are included in those of a specific day some time before. The high and low of this specific day form the "reference range". In general, we compare these variations with those of 4 or 7 days ago. The mathematical formula for finding an NR4 is :
If low > low(4) and high < high(4) :
nr = true
This implies that the current low is greater than the low of 4 days ago, and the current high is smaller than the high of 4 days ago. So today's volatility is lower than that of 4 days ago, and may be a sign of high volatility to come.
PARAMETERS :
Narrow Range Length : Corresponds to the number of candles back to compare current volatility. The default is 4, allowing comparison of current volatility with that of 4 candles ago.
Stop Loss : Percentage of the reference range on which to set an exit order to limit losses. The minimum value is 0.001, while the maximum is 1. The default value is 0.35.
Fixed Ratio : This is the amount of gain or loss at which the order quantity is changed. The default is 400, which means that for each $400 gain or loss, the order size is increased or decreased by an amount chosen by the user.
Increasing Order Amount : This is the amount to be added to or subtracted from orders when the fixed ratio is reached. The default is $200, which means that for every $400 gain, $200 is reinvested in the strategy. On the other hand, for every $400 loss, the order size is reduced by $200.
Initial capital : $1000
Fees : Interactive Broker fees apply to this strategy. They are set at 0.18% of the trade value.
Slippage : 3 ticks or $0.03 per trade. Corresponds to the latency time between the moment the signal is received and the moment the order is executed by the broker.
Important : A bot was used to test NR4 and NR7 with all possible Stop Losses in order to find out which combination generates the highest return on BITSTAMP:ETHUSD while limiting the drawdown. This strategy is the most optimal with an NR4 and a SL of 35% of the reference range size in 5D timeframe.
BUY AND SHORT SIGNALS :
When an NR is spotted, we create two stop orders on the high and low of the reference range. As soon as there's a breakout from this reference range (shown in blue on the chart), we open a position. We're LONG if there's a breakout on the high and SHORT if there's a breakout on the low. Executing a stop order cancels the second stop order.
RISK MANAGEMENT :
This strategy is subject to losses. We manage our risk with Stop Losses. The user is free to enter a SL as a percentage of the reference range. The maximum amount risked per trade therefore depends on the size of the range. The larger the range, the greater the risk. That's why we have set a maximum Stop Loss to 10% to limiting risks per trade.
The special feature of this strategy is that it targets a precise profit objective. This corresponds to the size of the reference range at the top of the high if you're LONG, or at the bottom of the low if you're short. In the same way, the larger the reference range, the greater the potential profits.
The risk reward remains the same for all trades and amounts to : 100/35 = 2.86. If the reference range is too high, we have set a SL to 10% of the trade value to limit losses. In that case, the risk reward is less than 2.86.
MONEY MANAGEMENT :
The fixed ratio method was used to manage our gains and losses. For each gain of an amount equal to the value of the fixed ratio, we increase the order size by a value defined by the user in the "Increasing order amount" parameter. Similarly, each time we lose an amount equal to the value of the fixed ratio, we decrease the order size by the same user-defined value. This strategy increases both performance and drawdown.
NOTE :
Please note that the strategy is backtested from 2017-01-01. As the timeframe is 5D, this strategy is a medium/long-term strategy. That's why only 37 trades were closed. Be careful, as the test sample is small and performance may not necessarily reflect what may happen in the future.
Enjoy the strategy and don't forget to take the trade :)
Stx Monthly Trades ProfitMonthly profit displays profits in a grid and allows you to know the gain related to the investment during each month.
The profit could be computed in terms of gain/trade_cost or as percentage of equity update.
Settings:
- Profit: Monthly profit percentage or percentage of equity
- Table position
This strategy is intended only as a container for the code and for testing the script of the profit table.
Setting of strategy allows to select the test case for this snippet (percentage grid).
Money management: not relevant as strategy is a test case.
This script stand out as take in account the gain of each trade in relation to the capital invested in each trade. For example consider the following scenario:
Capital of 1000$ and we invest a fixed amount of 1000$ (I know is too risky but is a good example), we gain 10% every month.
After 10 months our capital is of 2000$ and our strategy is perfect as we have the same performance every month.
Instead, evaluating the percentage of equity we have 10% the first month, 9.9% the second (1200$/1100$ - 1) and 5.26% the tenth month. So seems that strategy degrade with times but this is not true.
For this reason, to evaluate my strategy I prefer to see the montly return of investment.
WARNING: The strategy provided with this script is only a test case and allows to see the behavior with different "trades" management, for these reason commision are set to zero.
At the moment only the provided test cases are handled:
test 1 - single entry and single exit;
test 2 - single entry and multiple exits;
test 3 - single entry and switch position;
hamster-bot MRS 2 (simplified version) MRS - Mean Reversion Strategy (Countertrend) (Envelope strategy)
This script does not claim to be unique and does not mislead anyone. Even the unattractive backtest result is attached. The source code is open. The idea has been described many times in various sources. But at the same time, their collection in one place provides unique opportunities.
Published by popular demand and for ease of use. so that users can track the development of the script and can offer their ideas in the comments. Otherwise, you have to communicate in several telegram chats.
Representative of the family of counter-trend strategies. The basis of the strategy is Mean reversion . You can also read about the Envelope strategy .
Mean reversion , or reversion to the mean, is a theory used in finance that suggests that asset price volatility and historical returns eventually will revert to the long-run mean or average level of the entire dataset.
The strategy is very simple. Has very few settings. Good for beginners to get acquainted with algorithmic trading. A simple adjustment will help avoid overfitting. There are many variations of this strategy, but for understanding it is better to start with this implementation.
Principle of operation.
1)
A conventional MA is being built. (fuchsia line). A limit order is placed on this line to close the position.
2)
(green line) A limit order is placed on this line to open a long position
3)
(red line) A limit order is placed on this line to open a short position
Attention!
Please note that a limit order is used. Conclude that the strategy has a limited capacity. And the results obtained on low-liquid instruments will be too high in the tester. On real auctions there will be a different result.
Note for testing the strategy in the spot market:
When testing in the spot market, do not include both long and short at the same time. It is recommended to test only the long mode on the spot. Short mode for more advanced users.
Settings:
Available types of moving averages:
SMA
EMA
TEMA - triple exponential moving average
DEMA - Double Exponential Moving Average
ZLEMA - Zero lag exponential moving average
WMA - weighted moving average
Hma - Hull Moving Average
Thma - Triple Exponential Hull Moving Average
Ehma - Exponential Hull Moving Average
H - MA built based on highs for n candles | ta.highest(len)
L - MA built based on lows for n candles | ta.lowest(len)
DMA - Donchian Moving Average
A Kalman filter can be applied to all MA
The peculiarity of the strategy is a large selection of MA and the possibility of shifting lines. You can set up a reverse trending strategy on the Donchian channel for example.
Use Long - enable/disable opening a Long position
Use Short - enable/disable opening a Short position
Lot Long, % - % allocated from the deposit for opening a Long position. In the spot market, do not use % greater than 100%
Lot Short, % - allocated % of the deposit for opening a Short position
Start date - the beginning of the testing period
End date - the end of the testing period (Example: only August 2020 can be tested)
Mul - multiplier. Used to offset lines. Example:
Mul = 0.99 is shift -1%
Mul = 1.01 is shift +1%
Non-strict recommendations:
1) Test the SPOT market on crypto exchanges. (The countertrend strategy has liquidation risk on futures)
2) Symbols altcoin/bitcoin or altcoin/altcoin. Example: ETH/BTC or DOGE/ETH
3) Timeframe is usually 1 hour
If the script passes moderation, I will supplement it by adding separate settings for closing long and short positions according to their MA
EUR/USD 45 MIN Strategy - FinexBOTThis strategy uses three indicators:
RSI (Relative Strength Index) - It indicates if a stock is potentially overbought or oversold.
CCI (Commodity Channel Index) - It measures the current price level relative to an average price level over a certain period of time.
Williams %R - It is a momentum indicator that shows whether a stock is at the high or low end of its trading range.
Long (Buy) Trades Open:
When all three indicators suggest that the stock is oversold (RSI is below 25, CCI is below -130, and Williams %R is below -85), the strategy will open a buy position, assuming there is no current open trade.
Short (Sell) Trades Open:
When all three indicators suggest the stock is overbought (RSI is above 75, CCI is above 130, and Williams %R is above -15), the strategy will open a sell position, assuming there is no current open trade.
SL (Stop Loss) and TP (Take Profit):
SL (Stop Loss) is 0.45%.
TP (Take Profit) is 1.2%.
The strategy automatically sets these exit points as a percentage of the entry price for both long and short positions to manage risks and secure profits. You can easily adopt these inputs according to your strategy. However, default settings are recommended.
[blackcat] L2 Fibonacci BandsThe concept of the Fibonacci Bands indicator was described by Suri Dudella in his book "Trade Chart Patterns Like the Pros" (Section 8.3, page 149). These bands are derived from Fibonacci expansions based on a fixed moving average, and they display potential areas of support and resistance. Traders can utilize the Fibonacci Bands indicator to identify key price levels and anticipate potential reversals in the market.
To calculate the Fibonacci Bands indicator, three Keltner Channels are applied. These channels help in determining the upper and lower boundaries of the bands. The default Fibonacci expansion levels used are 1.618, 2.618, and 4.236. These levels act as reference points for traders to identify significant areas of support and resistance.
When analyzing the price action, traders can focus on the extreme Fibonacci Bands, which are the upper and lower boundaries of the bands. If prices trade outside of the bands for a few bars and then return inside, it may indicate a potential reversal. This pattern suggests that the price has temporarily deviated from its usual range and could be due for a correction.
To enhance the accuracy of the Fibonacci Bands indicator, traders often use multiple time frames. By aligning short-term signals with the larger time frame scenario, traders can gain a better understanding of the overall market trend. It is generally advised to trade in the direction of the larger time frame to increase the probability of success.
In addition to identifying potential reversals, traders can also use the Fibonacci Bands indicator to determine entry and exit points. Short-term support and resistance levels can be derived from the bands, providing valuable insights for trade decision-making. These levels act as reference points for placing stop-loss orders or taking profits.
Another useful tool for analyzing the trend is the slope of the midband, which is the middle line of the Fibonacci Bands indicator. The midband's slope can indicate the strength and direction of the trend. Traders can monitor the slope to gain insights into the market's momentum and make informed trading decisions.
The Fibonacci Bands indicator is based on the concept of Fibonacci levels, which are support or resistance levels calculated using the Fibonacci sequence. The Fibonacci sequence is a mathematical pattern that follows a specific formula. A central concept within the Fibonacci sequence is the Golden Ratio, represented by the numbers 1.618 and its inverse 0.618. These ratios have been found to occur frequently in nature, architecture, and art.
The Italian mathematician Leonardo Fibonacci (1170-1250) is credited with introducing the Fibonacci sequence to the Western world. Fibonacci noticed that certain ratios could be calculated and that these ratios correspond to "divine ratios" found in various aspects of life. Traders have adopted these ratios in technical analysis to identify potential areas of support and resistance in financial markets.
In conclusion, the Fibonacci Bands indicator is a powerful tool for traders to identify potential reversals, determine entry and exit points, and analyze the overall trend. By combining the Fibonacci Bands with other technical indicators and using multiple time frames, traders can enhance their trading strategies and make more informed decisions in the market.
Multi-TF AI SuperTrend with ADX - Strategy [PresentTrading]
## █ Introduction and How it is Different
The trading strategy in question is an enhanced version of the SuperTrend indicator, combined with AI elements and an ADX filter. It's a multi-timeframe strategy that incorporates two SuperTrends from different timeframes and utilizes a k-nearest neighbors (KNN) algorithm for trend prediction. It's different from traditional SuperTrend indicators because of its AI-based predictive capabilities and the addition of the ADX filter for trend strength.
BTC 8hr Performance
ETH 8hr Performance
## █ Strategy, How it Works: Detailed Explanation (Revised)
### Multi-Timeframe Approach
The strategy leverages the power of multiple timeframes by incorporating two SuperTrend indicators, each calculated on a different timeframe. This multi-timeframe approach provides a holistic view of the market's trend. For example, a 8-hour timeframe might capture the medium-term trend, while a daily timeframe could capture the longer-term trend. When both SuperTrends align, the strategy confirms a more robust trend.
### K-Nearest Neighbors (KNN)
The KNN algorithm is used to classify the direction of the trend based on historical SuperTrend values. It uses weighted voting of the 'k' nearest data points. For each point, it looks at its 'k' closest neighbors and takes a weighted average of their labels to predict the current label. The KNN algorithm is applied separately to each timeframe's SuperTrend data.
### SuperTrend Indicators
Two SuperTrend indicators are used, each from a different timeframe. They are calculated using different moving averages and ATR lengths as per user settings. The SuperTrend values are then smoothed to make them suitable for KNN-based prediction.
### ADX and DMI Filters
The ADX filter is used to eliminate weak trends. Only when the ADX is above 20 and the directional movement index (DMI) confirms the trend direction, does the strategy signal a buy or sell.
### Combining Elements
A trade signal is generated only when both SuperTrends and the ADX filter confirm the trend direction. This multi-timeframe, multi-indicator approach reduces false positives and increases the robustness of the strategy.
By considering multiple timeframes and using machine learning for trend classification, the strategy aims to provide more accurate and reliable trade signals.
BTC 8hr Performance (Zoom-in)
## █ Trade Direction
The strategy allows users to specify the trade direction as 'Long', 'Short', or 'Both'. This is useful for traders who have a specific market bias. For instance, in a bullish market, one might choose to only take 'Long' trades.
## █ Usage
Parameters: Adjust the number of neighbors, data points, and moving averages according to the asset and market conditions.
Trade Direction: Choose your preferred trading direction based on your market outlook.
ADX Filter: Optionally, enable the ADX filter to avoid trading in a sideways market.
Risk Management: Use the trailing stop-loss feature to manage risks.
## █ Default Settings
Neighbors (K): 3
Data points for KNN: 12
SuperTrend Length: 10 and 5 for the two different SuperTrends
ATR Multiplier: 3.0 for both
ADX Length: 21
ADX Time Frame: 240
Default trading direction: Both
By customizing these settings, traders can tailor the strategy to fit various trading styles and assets.
MACD Strategy_baskerMACD Strategy_basker, which will see the macd cross over and update buy sell. then do trailing sl
2 Moving Averages | Trend FollowingThe trading system is a trend-following strategy based on two moving averages (MA) and Parabolic SAR (PSAR) indicators.
How it works:
The strategy uses two moving averages: a fast MA and a slow MA.
It checks for a bullish trend when the fast MA is above the slow MA and the current price is above the fast MA.
It checks for a bearish trend when the fast MA is below the slow MA and the current price is below the fast MA.
The Parabolic SAR (PSAR) indicator is used for additional trend confirmation.
Long and short positions can be turned on or off based on user input.
The strategy incorporates risk management with stop-loss orders based on the Average True Range (ATR).
Users can filter the backtest date range and display various indicators.
The strategy is designed to work with the date range filter, risk management, and user-defined positions.
Features:
Trend-following strategy.
Two customizable moving averages.
Parabolic SAR for trend confirmation.
User-defined risk management with stop-loss based on ATR.
Backtest date range filter.
Flexibility to enable or disable long and short positions.
This trading system provides a comprehensive approach to trend-following and risk management, making it suitable for traders looking to capture trends with controlled risk.