Risk Management Strategy TemplateThis strategy is intended to be used as a base template for building new strategies.
It incorporates the following features:
Risk management:
Configurable X% loss per stop loss
Configurable R:R ratio
Trade entry:
Calculated position size based on risk tolerance
Trade exit:
Stop Loss currently configurable ATR multiplier but can be replaced based on strategy
Take Profit calculated from Stop Loss using R:R ratio
Backtesting:
Configurable backtesting range by date
Trade drawings:
TP/SL boxes drawn for all trades. Can be turned on and off
Trade exit information labels. Can be turned on and off
NOTE: Trade drawings will only be applicable when using overlay strategies
Debugging:
Includes section with useful debugging techniques
Strategy conditions
Trade entry:
LONG
C1: Price is above EMA line
C2: RSI is crossing out of oversold area
SHORT
C1: Price is below EMA line
C2: RSI is crossing out of overbought area
Trade exit:
Stop Loss: Stop Loss ATR multiplier is hit
Take Profit: R:R multiplier * Stop Loss is hit
The idea is to use RSI to catch pullbacks within the main trend.
Note that this strategy is intended to be a simple base strategy for building upon. It was not designed to be traded in its current form.
Backtest
X48 - Strategy | MA Type Cross + TPSL | Future&Spot | V.2Thank You For Open Source Code, This Strategy Ref. By 1.Simple Strategy Like MA Crossover For Long/Short or Spot Trade, 2. CDC Action Zone V.2 for BarPaint
This Strategy Mixing With MA Crossover Strategy and BarPaint By CDC Action Zone and TP/SL by Varbara
### How To Use Strategy : Setting EMA/SMA Crossover EMA/SMA, Any Value If You Want
For Long Position : Cross Up
For Short Position : Cross Down
Can Use With Spot Trade : Cross Up = Buy, Cross Down = Sell
TP/SL When Your OrderSize Change From any % Of Your TP/SL Value
### In Strategy Setting
Intitial Capital = Ex. 200
Order Size = Should Be Money Management Not Use 100% of Capital Ex. 10% of Capital (200$) = Order Size 20$
StopLoss and Take Profit = If You Run Trend TF 4H+ or 1D+ You Can Change TP% = 1,000% for nonlimit and Stop Loss 5 - 20% from your order size
Ex. Stoploss 15% = OrderSize / 100 x %SL = 20$/100 x 15% = 3$ Loss from order size 20$ (if you not set stop loss.)
Base Currency = (Your Currency) # Ex. USD
Commission = (Your Trading Fee) # Ex. Future Fee Can Check At Binance Fee Rate > www.binance.com > Choose Your Fee Type, Ex. USD M Future (Regular User) = 0.02 (Maker), 0.04 (Taker)
Commission Symbol Type = % # (Ref. By Binance Fee Rate)
### Notice ####
Default Setting It's Realistic From Normal Life Ex. Capital 200$ / Ordersize 20$ (10%)/ Commission 0.1% (Buy+Sell) / Slippage = 2 / TP = 1000% (nonlimit) / SL = 15%/OrderSize
Low Risk But High Return, Good Luck
### Bot Auto Trade by X4815162342 ###
if you wanna try my bot auto trade X48-3in1-bot : Contact My Line ID : x4815x
Full Command Alert For This Strategy If You Wanna See It's
'{"ex":"'+markettype+'","side": "'+longcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
'{"ex":"'+markettype+'","side": "'+shortcommand+'", "amount": "@{{strategy.order.contracts}}", "symbol": "{{ticker}}", "passphrase": "'+passphrase+'","leverage":"'+str.tostring(leveragex)+'"}'
But Easy Than Full Command Just Use Thisssssss !! Strategy Be Manage Auto Long and Short or TPSL Position
You Don't Do Anything Just Use This Message to Alerts Message
{{strategy.order.alert_message}}
### If you don't use bot but just looking for strategy test ####
Just Pass Bot Setting Function It's Nothing Effect For Strategy !!!!!!
Let's Enjoy With Your Strategy BackTest 😁
Remember Beware Max drawdown%. I'm Recommend Lower Than 10% It's Very Good.
EMA Cross (data chaining template)Hello Traders! This is the source code for a simple EMA Cross indicator that can be chained to other indicators or another instance of itself as a filter.
The code is fully commented to guide you in building your own chain of indicators based on your ideas and trading plans.
All the best,
Val - Protervus Trading
Breakout Probability (Expo)█ Overview
Breakout Probability is a valuable indicator that calculates the probability of a new high or low and displays it as a level with its percentage. The probability of a new high and low is backtested, and the results are shown in a table— a simple way to understand the next candle's likelihood of a new high or low. In addition, the indicator displays an additional four levels above and under the candle with the probability of hitting these levels.
The indicator helps traders to understand the likelihood of the next candle's direction, which can be used to set your trading bias.
█ Calculations
The algorithm calculates all the green and red candles separately depending on whether the previous candle was red or green and assigns scores if one or more lines were reached. The algorithm then calculates how many candles reached those levels in history and displays it as a percentage value on each line.
█ Example
In this example, the previous candlestick was green; we can see that a new high has been hit 72.82% of the time and the low only 28.29%. In this case, a new high was made.
█ Settings
Percentage Step
The space between the levels can be adjusted with a percentage step. 1% means that each level is located 1% above/under the previous one.
Disable 0.00% values
If a level got a 0% likelihood of being hit, the level is not displayed as default. Enable the option if you want to see all levels regardless of their values.
Number of Lines
Set the number of levels you want to display.
Show Statistic Panel
Enable this option if you want to display the backtest statistics for that a new high or low is made. (Only if the first levels have been reached or not)
█ Any Alert function call
An alert is sent on candle open, and you can select what should be included in the alert. You can enable the following options:
Ticker ID
Bias
Probability percentage
The first level high and low price
█ How to use
This indicator is a perfect tool for anyone that wants to understand the probability of a breakout and the likelihood that set levels are hit.
The indicator can be used for setting a stop loss based on where the price is most likely not to reach.
The indicator can help traders to set their bias based on probability. For example, look at the daily or a higher timeframe to get your trading bias, then go to a lower timeframe and look for setups in that direction.
-----------------
Disclaimer
The information contained in my Scripts/Indicators/Ideas/Algos/Systems does not constitute financial advice or a solicitation to buy or sell any securities of any type. I will not accept liability for any loss or damage, including without limitation any loss of profit, which may arise directly or indirectly from the use of or reliance on such information.
All investments involve risk, and the past performance of a security, industry, sector, market, financial product, trading strategy, backtest, or individual's trading does not guarantee future results or returns. Investors are fully responsible for any investment decisions they make. Such decisions should be based solely on an evaluation of their financial circumstances, investment objectives, risk tolerance, and liquidity needs.
My Scripts/Indicators/Ideas/Algos/Systems are only for educational purposes!
Strategy BackTest Display Statistics - TraderHalaiThis script was born out of my quest to be able to display strategy back test statistics on charts to allow for easier backtesting on devices that do not natively support backtest engine (such as mobile phones, when I am backtesting from away from my computer). There are already a few good ones on TradingView, but most / many are too complicated for my needs.
Found an excellent display backtest engine by 'The Art of Trading'. This script is a snippet of his hard work, with some very minor tweaks and changes. Much respect to the original author.
Full credit to the original author of this script. It can be found here: www.tradingview.com
I decided to modify the script by simplifying it down and make it easier to integrate into existing strategies, using simple copy and paste, by relying on existing tradingview strategy backtester inputs. I have also added 3 additional performance metrics:
- Max Run Up
- Average Win per trade
- Average Loss per trade
As this is a work in progress, I will look to add in more performance metrics in future, as I further develop this script.
Feel free to use this display panel in your scripts and strategies.
Thanks and enjoy :)
Smoothed Heikin Ashi Trend on Chart - TraderHalai BACKTESTSmoothed Heikin Ashi Trend on chart - Backtest
This is a backtest of the Smoothed Heikin Ashi Trend indicator, which computes the reverse candle close price required to flip a Heikin Ashi trend from red to green and vice versa. The original indicator can be found in the scripts section of my profile.
This particular back test uses this indicator with a Trend following paradigm with a percentage-based stop loss.
Note, that backtesting performance is not always indicative of future performance, but it does provide some basis for further development and walk-forward / live testing.
Testing was performed on Bitcoin , as this is a primary target market for me to use this kind of strategy.
Sample Backtesting results as of 10th June 2022:
Backtesting parameters:
Position size: 10% of equity
Long stop: 1% below entry
Short stop: 1% above entry
Repainting: Off
Smoothing: SMA
Period: 10
8 Hour:
Number of Trades: 1046
Gross Return: 249.27 %
CAGR Return: 14.04 %
Max Drawdown: 7.9 %
Win percentage: 28.01 %
Profit Factor (Expectancy): 2.019
Average Loss: 0.33 %
Average Win: 1.69 %
Average Time for Loss: 1 day
Average Time for Win: 5.33 days
1 Day:
Number of Trades: 429
Gross Return: 458.4 %
CAGR Return: 15.76 %
Max Drawdown: 6.37 %
Profit Factor (Expectancy): 2.804
Average Loss: 0.8 %
Average Win: 7.2 %
Average Time for Loss: 3 days
Average Time for Win: 16 days
5 Day:
Number of Trades: 69
Gross Return: 1614.9 %
CAGR Return: 26.7 %
Max Drawdown: 5.7 %
Profit Factor (Expectancy): 10.451
Average Loss: 3.64 %
Average Win: 81.17 %
Average Time for Loss: 15 days
Average Time for Win: 85 days
Analysis:
The strategy is typical amongst trend following strategies with a less regular win rate, but where profits are more significant than losses. Most of the losses are in sideways, low volatility markets. This strategy performs better on higher timeframes, where it shows a positive expectancy of the strategy.
The average win was positively impacted by Bitcoin’s earlier smaller market cap, as the percentage wins earlier were higher.
Overall the strategy shows potential for further development and may be suitable for walk-forward testing and out of sample analysis to be considered for a demo trading account.
Note in an actual trading setup, you may wish to use this with volatility filters, combined with support resistance zones for a better setup.
As always, this post/indicator/strategy is not financial advice, and please do your due diligence before trading this live.
Original indicator links:
On chart version -
Oscillator version -
Update - 27/06/2022
Unfortunately, It appears that the original script had been taken down due to auto-moderation because of concerns with no slippage / commission. I have since adjusted the backtest, and re-uploaded to include the following to address these concerns, and show that I am genuinely trying to give back to the community and not mislead anyone:
1) Include commission of 0.1% - to match Binance's maker fees prior to moving to a fee-less model.
2) Include slippage of 10 ticks (This is a realistic slippage figure from searching online for most crypto exchanges)
3) Adjust account balance to 10,000 - since most of us are not millionaires.
The rest of the backtesting parameters are comparable to previous results:
Backtesting parameters:
Initial capital: 10000 dollars
Position size: 10% of equity
Long stop: 2% below entry
Short stop: 2% above entry
Repainting: Off
Smoothing: SMA
Period: 10
Slippage: 10 ticks
Commission: 0.1%
This script still remains to shows viability / profitablity on higher term timeframes (with slightly higher drawdown), and I have included the backtest report below to document my findings:
8 Hour:
Number of Trades: 1082
Gross Return: 233.02%
CAGR Return: 14.04 %
Max Drawdown: 7.9 %
Win percentage: 25.6%
Profit Factor (Expectancy): 1.627
Average Loss: 0.46 %
Average Win: 2.18 %
Average Time for Loss: 1.33 day
Average Time for Win: 7.33 days
Once again, please do your own research and due dillegence before trading this live. This post is for education and information purposes only, and should not be taken as financial advice.
Boom Hunter + Hull Suite + Volatility Oscillator StrategyTRADE CONDITIONS
Long entry:
Boom Hunter (leading indicator): Trigger line crosses over Quotient 2 line (white cross over red)
Hull Suite (trend confirmation): Price closed above hull suite line and hull suite is green (represented by horizontal line at -10 in strategy pane)
Volatility Oscillator (volatility confirmation): Volatility spike trigger line is above upper band (represented by horizontal line at -30 in strategy pane)
Short entry:
Boom Hunter (leading indicator): Trigger line crosses under Quotient 2 line (white cross under red)
Hull Suite (trend confirmation): Price closed below hull suite line and hull suite is red (represented by horizontal line at -10 in strategy pane)
Volatility Oscillator (volatility confirmation): Volatility spike trigger line is below lower band (represented by horizontal line at -30 in strategy pane)
Risk management:
Each trade risks 3% of account (configurable in settings)
SL size determined by swing low/high of previous X candles (configurable in settings) or 1 ATR if swing is less than 1 ATR
TP is calculated by Risk:Reward ratio (configurable in settings)
TIPS
Timeframe: I have found good results running on BTC/USDT 5M chart
Note: To help visual identification of trade entries and exits you may wish to add the Hull Suite and Volatility Oscillator to the chart separately. It was not possible to display them in a clear way within a single panel for the strategy. Make sure you set the settings of the auxiliary indicators to match what is in the settings of this indicator if you do decide to add them.
CREDITS
Boom Hunter Pro by veryfid
Hull Suite by InSilico
Volatility Oscillator by veryfid
Backtesting- IndicatorFor anyone interested, Here is an example of how to put backtesting results into an Indicator. This calculates the same values as you find in the Summary Screen of the built in Strategy backtester. This will use the same result size as the standard backtester i.e. 5 minute chart grabs roughly 1 month of data, 1 minute chart grabs 1 week of data, etc... I tried to keep this as self-contained as possible so I put most of the code for the results in the bottom of the Indicator. The results stop at the last completed trade signal i.e. a Buy has a Sell to it. This is the same indicator I posted earlier with the PCT Trailing StopLoss so you will see that code in here as well. As said in my previous posting, the indicator is just a simple EMA crossover to give it something to do and I would not recommend using this indicator on its own, but instead copy the code to your own indicator if you find it useful. I also left the code in so that you can switch back to a Strategy if you want to verify the results.
Additional Notes:
- The results are within an acceptable margin of error due to the fact that the Indicator is having to calculate based on when the Buy and Sell Signal occur as opposed to when actual trades occur like in the Strategy Backtester
- I was trying to find a way to set the number of Buy Signals to use i.e. show me the results from the past 100 trades but couldn't sort out the logic. I am open to suggestions. Also keep in mind I am not a coder by profession so if you have any ideas on that front, please explain it to me as though I am a 5 year old child and provide code examples if possible :)
- I included the Strategy results in the Screen Shots so that you can see where the results line up.
Additional Additional Note:
This is not financial advice. Use at your own risk.
Template Trailing Strategy (Backtester)💭 Overview
💢 What is the "Template Trailing Strategy” ❓
The "Template Trailing Strategy" (TTS) is a back-tester orchestration framework. It supercharges the implementation-test-evaluation lifecycle of new trading strategies, by making it possible to plug in your own trading idea.
While TTS offers a vast number of configuration settings, it primarily allows the trader to:
Test and evaluate your own trading logic that is described in terms of entry, exit, and cancellation conditions.
Define the entry and exit order types as well as their target prices when the limit, stop, or stop-limit order types are used.
Utilize a variety of options regarding the placement of the stop-loss and take-profit target(s) prices and support for well-known techniques like moving to breakeven and trailing.
Provide well-known quantity calculation methods to properly handle risk management and easily evaluate trading strategies and compare them.
Alert on each trading event or any related change through a robust and fully customizable messaging system.
All the above, build a robust tool that, once learned, significant and repetitive work that strategy developers often implement individually on every strategy script is eliminated. Taking advantage of TradingView’s built-in backtesting engine the evaluation of the trading ideas feels natural.
By utilizing the TTS one can easily swap “trading logic” by testing, evaluating, and comparing each trading idea and/or individual component of a strategy.
Finally, TTS, through its per-event alert management (and debugging) system, provides a fully automated solution that supports automated trading with real brokers via webhooks.
NOTE: The “Template Trailing Strategy” does not dictate the way you can combine different (types of) indicators or how you should combine them. Thus, it should not be confused as a “Trading System”, because it gives its user full flexibility on that end (for better or worse).
💢 What is a “Signal Indicator” ❓
“Signal Indicator” (SI) is an indicator that can output a “signal” that follows a specific convention so that the “Template Trailing Strategy” can “understand” and execute the orders accordingly. The SI realizes the core trading logic signaling to the TTS when to enter, exit, or cancel an order. A SI instructs the TTS “when” to enter or exit, and the TTS determines “how” to enter and exit the position once the Signal Indicator generates a signal.
A very simple example of a Signal Indicator might be a 200-day Simple Moving Average Signal. When the price of the security closes above the 200-day SMA, a SI would provide TTS with a “long entry signal”. Once TTS receives the “long entry signal”, the TTS will open a long position and send an alert or automated trade message via webhook to a broker, based on the Entry settings defined in TTS. If the TTS Entry settings specify a “Market” order type, then the open long position will be executed by TTS immediately. But if the TTS Entry settings specify a “Stop” order type with a 1% Stop Distance, then when the price of the security rises by 1% after the “long entry signal” occurs, the TTS will open a long position and the Long Entry alert or webhook to the broker will be sent.
🤔 How to Guide
💢 How to connect a “signal” from a “Signal Indicator” ❓
The “Template Trailing Strategy” was designed to receive external signals from a “Signal Indicator”. In this way, a “new trading idea” can be developed, configured, and evaluated separately from the TTS. Similarly, the SI can be held constant, and the trading mechanics can change in the TTS settings and back-tested to answer questions such as, “Am I better with a different stop loss placement method, what if I used a limit order instead of a stop order to enter, what if I used 25% margin instead of trading spot market?”
To make that possible by connecting an external signal indicator to TTS, you should:
Add in the same chart, the “Signal Indicator” of your choice (e.g. “Two MA Signal Indicator” , “Click Signal Indicator” , “Signal Adapter” , “Signal Composer” ) and the “Template Trailing Strategy”.
Go to the “Settings/Inputs” tab in the “🛠️ STRATEGY” group of the TTS and change the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" to “🔨External”
Go to the “🔨 STRATEGY – EXTERNAL” group settings of the TTS and change the “🔌𝐒𝐢𝐠𝐧𝐚𝐥 🛈➡” to the output signal of the “Signal Indicator” you want to connect. The selected combo box option should look like “:🔌Signal to TTS” where should correspond to the short title of your “Signal Indicator”
💢 How to create a Custom Trading logic ❓
The “Template Trailing Strategy” provides two ways to plug in your custom trading logic. Both of them have their advantages and disadvantages.
✍️ Develop your own Customized “Signal Indicator” 💥
The first approach is meant to be used for relatively more complex trading logic. The advantages of this approach are the full control and customization you have over the trading logic and the relatively simple configuration setup by having two scripts only. The downsides are that you have to have some experience with pinescript or you are willing to learn and experiment. You should also know the exact formula for every indicator you will use since you have to write it by yourself. Copy-pasting from existing open-source indicators will get you started quite fast though.
The idea here is either to create a new indicator script from scratch or to copy an existing non-signal indicator and make it a “Signal Indicator”. To create a new script, press the “Pine Editor” button below the chart to open the “Pine Editor” and then press the “Open” button to open the drop-down menu with the templates. Select the “New Indicator” option. Add it to your chart to copy an existing indicator and press the source code {} button. Its source code will be shown in the “Pine Editor” with a warning on top stating that this is a read-only script. Press the “create a working copy”. Now you can give a descriptive title and a short title to your script, and you can work on (or copy-paste) the (other) indicators of your interest. Having all the information needed to make your decision the only thing you should do is define a DealConditions object and plot it like this:
import jason5480/tts_convention/4 as conv
// Calculate the start, end, cancel start, cancel end conditions
dealConditions = conv.DealConditions.new(
startLongDeal = ,
startShortDeal = ,
endLongDeal = ,
endShortDeal = ,
cnlStartLongDeal = ,
cnlStartShortDeal = ,
cnlEndLongDeal = ,
cnlEndShortDeal = )
// Use this signal in scripts like "Template Trailing Strategy" and "Signal Composer" that can use its value
// Emit the current signal value according to the "two channels mod div" convention
plot(series = conv.getSignal(dealConditions), title = '🔌Signal to TTS', color = color.olive, display = display.data_window + display.status_line, precision = 0)
You should write your deal conditions appropriately based on your trading logic and put them in the code section shown above by replacing the “…” part after “=”. You can omit the conditions that are not relevant to your logic. For example, if you use only market orders for entering and exiting your positions the cnlStartLongDeal, cnlStartShortDeal, cnlEndLongDeal, and cnlEndShortDeal are irrelevant to your case and can be safely omitted from the DealConditions object. After successfully compiling your new custom SI script add it to the same chart with the TTS by pressing the “Add to chart” button. If all goes well, you will be able to connect your “signal” to the TTS as described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
🧩 Adapt and Combine existing non-signal indicators 💥
The second approach is meant to be used for relatively simple trading logic. The advantages of this approach are the lack of pine script and coding experience needed and the fact that it can be used with closed-source indicators as long as the decision-making part is displayed as a line in the chart. The drawback is that you have to have a subscription that supports the “indicator on indicator” feature so you can connect the output of one indicator as an input to another indicator. Please check if your plan supports that feature here
To plug in your own logic that way you have to add your indicator(s) of preference in the chart and then add the “Signal Adapter” script in the same chart as well. This script is a “Signal Indicator” that can be used as a proxy to define your custom logic in the CONDITIONS group of the “Settings/Inputs” tab after defining your inputs from your preferred indicators in the VARIABLES group. Then a “signal” will be produced, if your logic is simple enough it can be directly connected to the TTS that is also added to the same chart for execution. Check the “How to connect a “signal” from a “Signal Indicator”?” in the “🤔 How to Guide“ for more information.
If your logic is slightly more complicated, you can add a second “Signal Adapter” in your chart. Then you should add the “Signal Composer” in the same chart, go to the SIGNALS group of the “Settings/Inputs” tab, and connect the “signals” from the “Signal Adapters”. “Signal Composer” is also a SI so its composed “signal” can be connected to the TTS the same way it is described in the “How to connect a “signal” from a “Signal Indicator”?” guide.
At this point, due to the composability of the framework, you can add an arbitrary number (bounded by your subscription of course) of “Signal Adapters” and “Signal Composers” before connecting the final “signal” to the TTS.
💢 How to set up ⏰Alerts ❓
The “Template Trailing Strategy” provides a fully customizable per-even alert mechanism. This means that you may have an entirely different message for entering and exiting into a position, hitting a stop-loss or a take-profit target, changing trailing targets, etc. There are no restrictions, and this gives you great flexibility.
First of all, you have to enable the alerts of the events that interest you. Go to the “🔔 ALERT MESSAGES” module of the TTS settings and check the “Enable…” checkbox of the events you are interested in. For each specific event, you will find a text area where you can type the exact message you want to receive when the event occurs. What’s more, there are placeholders you can use that will be replaced by the TTS with the actual values before the message is sent. The placeholder categories are the following and the placeholder names are self-explanatory.
Chart info: {{ticker}}, {{base_currency}}, {{quote_currency}}
Quantities and percentages: {{base_quantity}}, {{quote_quantity}}, {{quote_quantity_perc}},
{{take_profit_base_quantity}}, {{remaining_quantity_perc}}, {{remaining_base_quantity}}, {{risk_perc}}
Target prices: {{stop_loss_price}}, {{entry_price}}, {{entry+_price}}, {{entry-_price}},
{{exit_price}}, {{exit+_price}}, {{exit-_price}}, {{take_profit_price_1}},
{{take_profit_price_2}}, {{take_profit_price_3}}, {{take_profit_price_4}}, {{take_profit_price_5}}
❗ To get the message on the other side you have to set a strategy alert as described here and use the {{strategy.order.alert_message}} placeholder as text in the “Message Box” that contains the message that came from the TTS.
💢 How to execute my orders in a broker ❓
To execute your orders in a broker that supports webhook integration, you should enable the appropriate alerts in the “Template Trailing Strategy” first (see the “How to set up Alerts?” guide above). Then you should go to the “Create Alert/Notifications” tab check the “Webhook URL” and paste the URL provided by your broker. You have to read the documentation of your broker for more information on what messages are expected.
Keep in mind that some brokers have deep integration with TradingView so a per-event alert approach might be overkill.
📑 Definitions
This section tries to give some definitions in terms that appear in the “Settings/Inputs" tab of the “Template Trailing Strategy”
💢 What is Trailing ❓
Trailing is a technique where a price target follows another “barrier” price (usually high or low) by trying to keep a maximum distance from the “barrier” when it moves in only one direction (up or down). When the “barrier” moves in the other direction the price target will not change. There are as many types of trailing as price targets, which means that there are entry trailing, exit trailing, stop-loss trailing, and take-profit trailing techniques.
💢 What is a Moonbag ❓
A Moonbag in a trade is the quantity of the position that is reserved and will not be exited even if all take-profit targets defined in the strategy are hit, the quantity will be exited only if the stop-loss is hit or a close signal is received. This makes the stop-loss trailing technique in a trend-following strategy a good candidate to take advantage of a Moonbag.
💢 What is Distance ❓
Distance is the difference between two prices.
💢 What is Bias ❓
Bias is a psychological phenomenon where you make decisions based on market sentiment. For example, when you want to enter a long position you have a long bias, and when you want to exit from the long position you have a short bias. It is the other way around for the short position.
💢 What is the Margin Distance of a price target ❓
The Margin Distance of a price target is the distance that the target will deviate from its initial price. The direction of this deviation depends on the bias of the market. For example, suppose you are in a long position, and you set a take-profit target to the local high (HHLL). In that case, adding a margin of five ticks will place your take-profit target 5 ticks below this local high because you have a short bias when exiting a long position. When the bias is long the margin will be added resulting in a higher target price and when you have a short bias the margin will be subtracted.
⚙️ Settings
In the “Settings/Inputs” tab of the “Template Trailing Strategy”, you can find all the customizable settings that are provided by the framework. The variety of those settings is vast; hence we will only scratch the surface here. However, for every setting, there is an information icon 🛈 where you can learn more if you mouse over it. The “Settings/Inputs” tab is divided into ten main groups. Each one of them is responsible for one module of the framework. Every setting is part of a group that is named after the module it represents. So, to spot the module of a setting find the title that appears above it comes with an emoji and uppercase letters. Some settings might have the same name but belong to different modules e.g. “Distance Method”. Some settings are indented, which means that are closely related to the non-indented setting above. Usually, intended settings provide further configuration for one or more options of the non-intended setting. The groups that correspond to each module of the framework are the following:
📆 FILTERS
In this module time filters are implemented. You can define a DateTime window for your strategy to run. You can also specify a session by selecting the days of the week and the time range you want to operate.
🛠️ STRATEGY
This module contains the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" that defines if the “Template Trailing Strategy” will operate using the Internal or the External (“Signal Indicator”) conditions. Some general settings can be applied regardless of the mode.
🔨 STRATEGY – EXTERNAL
This sub-module makes the connection between the external signal of the “Signal Indicator” and the “Template Trailing Strategy”. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔨External”.
🔧 STRATEGY – INTERNAL
This sub-module defines the internal strategy logic and it's used as an example to demonstrate this framework. It should produce the same results as if the “Two MA Signal Indicator” was used as a “signal” in external mode. It takes effect only if the "𝐃𝐞𝐚𝐥 𝐂𝐨𝐧𝐝𝐢𝐭𝐢𝐨𝐧𝐬 𝐌𝐨𝐝𝐞" is set to “🔧Internal”.
🎢 VOLATILITY
This module defines the volatility parameters that are used in various other settings like average true range and standard deviation. It also makes it clear whether their values are updated during a trade (DYNAMIC) or not (STATIC).
🔷 ENTRY
This module defines how the start deal conditions will be executed by defining the order type of your entry and all necessary parameters to execute them.
🎯 TAKE PROFIT
This module defines the take-profit targets placement logic. The number of the take-profit targets to use, their distance from the entry price, and the distance from each other are only some of the features that can be configured.
🛑 STOP LOSS
This module defines the stop-loss target placement logic. The distance from the entry price, move to break even, and start trailing after a take-profit target is hit are only some of the features that can be configured.
🟪 EXIT
This module defines how the end deal conditions will be executed by defining the order type of your exit and all necessary parameters to execute them.
💰 QUANTITY/RISK MANAGEMENT
This module defines the method that calculates the amount of money you will put into each trade. Also, the percentage of the Moonbag quantity can be configured.
📊 ANALYTICS
This module can visualize some extra analytics of the strategy in the chart and calculate some metrics to measure the overall performance.
🔔 ALERT MESSAGES
This module defines all the messages that can be emitted per event during the strategy execution.
😲 Caveats
💢 Does “Template Trailing Strategy” has a repainting behavior ❓
The answer is that the “Template Trailing Strategy” does not repaint as long as the “Signal Indicator” that is connected also does not repaint. If you developed your own SI make sure that you understand and know how to prevent this behavior. The publication by @PineCoders here will give you a good idea on how to avoid most of the repainting cases.
⚠️There is an exception though, when the “Enable Trail⚠️💹” checkbox is checked, the Take Profit trailing feature is enabled, and a tick-based approach is used, meaning that after a while, when the TradingView discards all the real-time data, assumptions will be made by the backtesting engine that will cause a form of repainting. To avoid making false assumptions please disable this feature in the early stages and evaluate its usefulness in your strategy later on, after first confirming the success of the logic without this feature. In this case, consider turning on the bar magnifier feature. This way you will get more accurate backtest results when the Take Profit trailing feature is enabled.
💢 Can “Template Trailing Strategy” satisfy all my trading strategies ❓
While this framework can satisfy quite a large number of trading strategies there are cases where it cannot do so. For example, if you have a custom logic for your stop-loss or take-profit placement, or if you want to dollar cost average, then it might be better to start a new strategy script from scratch.
⚠️ It is not recommended to copy the official TTS code and start developing unless you are a pine wizard! Even in that case, there is a stiff learning curve that might not be worth your time. Last, you must consider that I do not offer support for customized versions of the TTS script and if something goes wrong in the process you are all alone.
🤗 Thanks
Special thanks to @upslidedown and @metadimensional, who regularly gave feedback all those years and helped me to shape the framework as it is today! Thanks to @EltAlt, @PlusUltraTrading, and everyone else who contributed by either filing a “defect report” or asking questions that helped me to understand what improvements were necessary.
Enjoy!
Jason
Manual Backtest - Flat the ChartThis script is an utility tool for manual backtesting.
The main problem in backtesting a discretionary strategy is the bias of knowing the future result of the market, in this way all the market will be crushed into a flat line, this way you can avoid bias.
The way to use this indicator is easy and made by 4 step:
Step 1 : add to an asset you won't backtest and put the auto scale on
Step 2 : go to the asset you will backtest and scroll left until the date you want to start
Step 3 : use the replay function of tradingview (15 min chart won't go back more than 18 month)
Step 4: toggle off the indicator or remove from the chart (untill next asset to backtest)
That's not a complex indicator but is what you need to do a fair backtesting
WhaleCrew BacktesterBacktesting indicators is easy , just add the following line of code to your script:
plot(longEntry ? 1 : shortEntry ? -1 : longTP ? 0.5 : shortTP ? -0.5 : 0, color=na, editable=false, title='Backtest')
These numbers are defined as constants in the backtester source-code.
After adding this indicator to your chart:
1. Open Settings
2. Select supported indicator to backtest
3. Select if you want to enter Longs and/or Shorts
4. Open the 'Strategy Tester' at the bottom to check the performance
Remember:
past performance is not indicative of future results
repainting indicators will create wrong/unrealistic results
Zendog SHORT DCA Trigger RSI+StochRSIThis is a script that generates a SELL signal by combining RSI and Stochastic RSI into the same script and that can easily be integrated into an external Backtester like the one I published.
The script uses default values for RSI and Stochastic RSI overbought conditions.
They should be adjusted for specific assets and timeframes so they better match the current trend. Please beware you might overfit settings to match a short timeframe trend (like a few days or hours). If this is the case once the trend changes the signals will not be accurate.
The purpose of this script is to provide some pine code that can be used to further combine multiple indicators into a SHORT Deal Start signal.
Integration with the Zendog Backtster:
- add the backtester on the chart
- add this script on the chart
- in the Zendog backtester Deal start type select "External indicator"
- in the Zendog backtester Indicator source and value select "Zendog SHORT DCA Trigger RSI+StochRSI: SIGNAL"
Zendog LONG DCA Trigger RSI+StochRSIThis is a script that generates a BUY signal by combining RSI and Stochastic RSI into the same script and that can easily be integrated into an external Backtester like the one I published.
The script uses default values for RSI and Stochastic RSI oversold conditions.
They should be adjusted for specific assets and timeframes so they better match the current trend. Please beware you might overfit settings to match a short timeframe trend (like a few days or hours). If this is the case once the trend changes the signals will not be accurate.
The purpose of this script is to provide some pine code that can be used to further combine multiple indicators into a LONG Deal Start signal.
Integration with the Zendog Backtster:
- add the backtester on the chart
- add this script on the chart
- in the Zendog backtester Deal start type select "External indicator"
- in the Zendog backtester Indicator source and value select "Zendog LONG DCA Trigger RSI+StochRSI: SIGNAL"
Dual MACD StrategyThis strategy Multi Time Frame Macd Indicator
We take the first long position when we have a buy signal in Weekly Macd (Macd line crosses above Signal line). This open a trading window, showed with green background color
We close the first position when either Weekly or Daily Macd give us a sell signal ((Macd line crosses below Signal line))
Enable Profit and Stop in strategy settings with different percentage to backtest the strategy. Also if it is better to use a Traditional Stop Loss or a Trailing Stop Loss based on a percentage from low prices
Change macd resolution in settings for other time frames to test the strategy
This Strategy was tested on Crypto Market with good results in assets as BTC, ETH, BNB, ADA, LTC, XLM, BCH, among others
Zendog V2 backtest DCA bot 3commasHi everyone,
After a few iterations and additional implemented features this version of the Backtester is now open source.
The Strategy is a Backtester for 3commas DCA bots. The main usage scenario is to plugin your external indicator, and backtest it using different DCA settings.
Before using this script please make sure you read these explanations and make sure you understand how it works.
Features:
- Because of Tradingview limitations on how orders are grouped into Trades, this Strategy statistics are calculated by the script, so please ignore the Strategy Tester statistics completely
Statistics Table explained:
- Status: either all deals are closed or there is a deal still running, in which case additional info
is provided below, as when the deal started, current PnL, current SO
- Finished deals: Total number of closed deals both Winning and Losing.
A deal is comprised as the Base Order (BO) + all Safety Orders (SO) related to that deal, so this number
will be different than the Strategy Tester List of Trades
- Winning Deals: Deal ended in profit
- Losing deals: Deals ended with loss due to Stop Loss. In the future I might add a Deal Stop condition to
the script, so that will count towards this number as well.
- Total days ( Max / Avg days in Deal ):
Total Days in the Backtest given by either Tradingview limitation on the number of candles or by the
config of the script regarding "Limit Date Range".
Max Days spent in a deal + which period this happened.
Avg days spent in a deal.
- Required capital: This is the total capital required to run the Backtester and it is automatically calculated by
the script taking into consideration BO size, SO size, SO volume scale. This should be the same as 3commas.
This number overwrites strategy.initial_capital and is used to calculate Profit and other stats, so you don't need
to update strategy.initial_capital every time you change BO/SO settings
- Profit after commission
- Buy and Hold return: The PnL that could have been obtained by buying at the close of the first candle of the
backtester and selling at the last.
- Covered deviation: The % of price move from initial BO order covered by SO settings
- Max Deviation: Biggest market % price move vs BO price, in the other direction (for long
is down, for short it is up)
- Max Drawdown: Biggest market % price move vs Avg price of the whole Trade (BO + any SO), in the other
direction (for long price goes down, for short it goes up)
This is calculated for the whole Trade so it is different than List of Trades
- Max / Avg bars in deal
- Total volume / Commission calculated by the strategy. For correct commission please set Commission in the
Inputs Tab and you may ignore Properties Tab
- Close stats for deals: This is a list of how many Trades were closed at each step, including Stop Loss (if
configured), together with covered deviation for that step, the number of deals, and the percentage of this
number from all the deals
TODO: Might add deal avg value for each step
- Settings Table that can be enabled / disabled just to have an overview of your configs on the chart, this is a
drawn on bottom left
- Steps Table similar to 3commas, this is also drawn on bottom left, so please disable Settings table if you want
to see this one
TODO: Might add extra stats here
- Deal start condition: built in RSI-7 or plugin any external indicator and compare with any value the indicator plots
(main purpose of this strategy is to connect your own studies, so using external indicator is recommended)
- Base order and safety orders configs similar to 3commas (order size, percent deviation, safety orders,
percent scale and volume scale)
- Long and Short
- Stop Loss
- Support for Take profit from base order or from Total volume of the deal
- Configs help (besides self explanatory):
- Chart theme: Adjust according to the theme you run on. There is no way to detect theme at the moment.
This adjust different colors
- Deal Start Type: Either a builtin RSI7 or "External indicator"
- Indicator Source an value: If using External Indicator then select source, comparison and value.
For example you could start a deal when Volume is greater than xxxx, or code a custom indicator that plots
different values based on your conditions and test those values
- Visuals / Decimals for display: Adjust according to your symbol
- BO Entry Price for steps table: This is the BO start deal price used to calculate the steps in the table
Hull Crossover Strategy no TP or SLWhat is it?
A simple yet effective strategy ran on the 30m chart.
This is a basic idea that can be expanded on using different indicator to either add signals or filter out certain bad signals!
The strategy consists of 1 fast moving average and 1 slow moving average.
Both of these moving averages are the Hull Moving Average
What is the Hull Moving Average?
The Hull Moving Average ( HMA ) is a directional trend indicator.
It captures the current market conditions and uses recent price action to determine if conditions are bullish or bearish relative to historical data.
The Hull is different from traditional trend indicators like the EMA and the SMA .
It is designed to reduce the lag often associated with other MAs by providing a faster signal on a smoother visual plane.
How it works?
When the fast HMA crosses over the slow HMA , we initiate a long signal, and
when the fast HMA crosses under the slow HMA , we initiate a short signal.
Conclusion
The power of simplicity is what makes this such a great core to use to build onto making something even better!
The results were optimised to suit the most common market conditions seen today.
******** Not financial advice! ********
QFL bull bypassThis bypass indicator triggers plots 1 when the price is above the QFL base.
This can be used as a "bypass" by a consumer indicator that can skip trades when the bypass is triggering.
You can use it for long and short strategies, to prevent using buy or sell signals in areas were the price is either overextended.
QFL works better in 1, 2 or 4 hours timeframes.
Inverse Fisher Transform on RSI for backtest w/alertsThis version of the Inverse Fisher Transform on RSI comes with support for
1) Backtesting with Gavin's backtest script
2) Bypass, you can use another indicator to pause buy signals from this indicator. Just create another indicator that plots "1" whenever you want to activate the bypass on the IFTRSI signal.
3) Independent buy and sell level thresholds. Some tokens perform better with a higher sell level, even levels as high as 0.996, sometimes the buy level can also be relaxed to even 0.6 and get incredible results on the 5 minute chart.
4) alerts for Buy and Sell signals
Make sure you add Gavin's backtest and select external signal and this indicator as the source.
TV signal for DCA backtestThis script allows you to backtest Trading View's "Technical Ratings" (Buy, Strong buy, Sell, Strong Sell) using Gavin's backtest script.
To use it add the backtest script to the chart together with this script and then from the back test settings connect the external indicator. You should select "TV Signal" as the source.
Backtesting works best on the 5m chart, but you can still change this script from its settings to higher timeframes.
Encoding
Buy is 1
Strong Buy is 2
Sell is -1
Strong Sell is -2
In the backtest script you can decide which rating you want to use for open deal and which one for close deal.
For example, if you were backtesting a long bot you could enter a long position when TV signal is Buy (1) and close the deal when TV signal is Sell (-1).
You have the full flexibility to decide which technical rating to use for your backtesting.
Enjoy!
Smart AlertsThis indicator provides back-tested signals and alerts from multiple technical indicators.
No more guessing whether or not you should trust an indicator. See your indicators' past performance at a glance.
No more false alarms. Disable re-painting of signals.
When multiple indicators overlap, a Confluence indicator will print (large triangle). With your settings properly tuned, this will show a HIGH probability of a move.
Current Signal/Alert Options (more to come):
RSI Oversold
RSI Overbought
EMA Crossing Up
EMA Crossing Down
Buy Signal Confluence
Sell Signal Confluence
Instructions:
-Enable/disable individual indicators so you can fine tune one at a time
-Adjust the indicator's settings
-Adjust your trade parameters (Max Wait, Take Profit %). Signals that would have given the desired profit in the time allowed will be painted orange.
-Repeat this process with each indicator until you're satisfied
-Set-up alerts
Smart EMA SignalsThis indicator starts by plotting each time the price action crosses above or below the EMA, of which you can tune the timeframe and duration.
It then takes it a step further and plots whether or not that indicator would have given you a profitable trade, of which you can also tune the parameters (Max wait time, and % Profit).
Once you have your EMA tuned to your liking, set up alerts to notify you of a golden opportunity.
QFL single TF with alertsBacktesting compatible QFL pine script w/alerts
This version of QFL was made based on this one:
From author:
www.tradingview.com
I made the following additions according to my requirements:
- I need to use pine script 4
- I needed to avoid repainting issues so I'm not calling directly security, I'm using the wrapper function.
- There might be still repainting issues when you use "max base age" which uses the function "barssince" so be careful, you can disable it by setting its value to zero.
- Alerts so I can use it for automated trading and bots
- In order to make this signal compatible with the backtest script there's an option provided in the settings. If you enable this option this indicator will plot 1 whenever there's a BUY signal. This will allow the backtest to pick the "QFL Buy" from external indicator so it can perform the backtest.
I recommend some of these settings to start playing with the chart in 15 min / QFL in 1, 2 or 4 hours.
The higher the TF the more conservative.
QFL with 3.5% is pretty popular but you can try higher QFL percentage settings for a more conservative approach.
Rainbow Strategy BacktestingRainbow Strategy Backtesting base on "Rainbow Moving Average" Strategy as below:
1.Rainbow Moving Average setup
- Source: source of 1st MA
- Type: SMA/EMA
- Period: period of 1st MA
- Displacement: period of 2nd MA to 7th MA with source is previous MA
2.Trend Define
- Up Trend: Main MA moving at the top of Rainbow
- Down Trend: Main MA moving at the bottom of Rainbow
- Sideway: Main MA moving between the top and the bottom of Rainbow
3.Signal
- Buy Signal: When Rainbow change to Up Trend.
- Sell Signal: When Rainbow change to Down Trend.
- Exit: When Rainbow change to Sideway.
4.RSI Filter
- "Enable": Only signals have 1st RSI moving between Overbought and Oversold and 2nd RSI moving outside Middle Channel are accepted.
- The filter may help trader avoid bull trap, bear trap and choppy market.
5.Backtesting Infomation
- Ticker: BTCUSDT
- Timeframe: H1
- Rainbow parameter:
+ Source: hlc3
+ Type: SMA
+ Period: 12
+ Displacement: 3
- RSI Filter parameter:
+ Enable
+ 1st RSI filter: period 12, overbought 65, oversold 35
+ 2nd RSI filter: period 9, upper middle 56, lower middle 44