Bjorgum Double Tap█ OVERVIEW
Double Tap is a pattern recognition script aimed at detecting Double Tops and Double Bottoms. Double Tap can be applied to the broker emulator to observe historical results, run as a trading bot for live trade alerts in real time with entry signals, take profit, and stop orders, or to simply detect patterns.
█ CONCEPTS
How Is A Pattern Defined?
Doubles are technical formations that are both reversal patterns and breakout patterns. These formations typically have a distinctive “M” or a “W” shape with price action breaking beyond the neckline formed by the center of the pattern. They can be recognized when a pivot fails to break when tested for a second time and the retracement that follows breaks beyond the key level opposite. This can trap entrants that were playing in the direction of the prior trend. Entries are made on the breakout with a target projected beyond the neckline equal to the height of the pattern.
Pattern Recognition
Patterns are recognized through the use of zig-zag; a method of filtering price action by connecting swing highs and lows in an alternating fashion to establish trend, support and resistance, or derive shapes from price action. The script looks for the highest or lowest point in a given number of bars and updates a list with the values as they form. If the levels are exceeded, the values are updated. If the direction changes and a new significant point is made, a new point is added to the list and the process starts again. Meanwhile, we scan the list of values looking for the distinctive shape to form as previously described.
█ STRATEGY RESULTS
Back Testing
Historical back testing is the most common method to test a strategy due in part to the general ease of gathering quick results. The underlying theory is that any strategy that worked well in the past is likely to work well in the future, and conversely, any strategy that performed poorly in the past is likely to perform poorly in the future. It is easy to poke holes in this theory, however, as for one to accept it as gospel, one would have to assume that future results will match what has come to pass. The randomness of markets may see to it otherwise, so it is important to scrutinize results. Some commonly used methods are to compare to other markets or benchmarks, perform statistical analysis on the results over many iterations and on differing datasets, walk-forward testing, out-of-sample analysis, or a variety of other techniques. There are many ways to interpret the results, so it is important to do research and gain knowledge in the field prior to taking meaningful conclusions from them.
👉 In short, it would be naive to place trust in one good backtest and expect positive results to continue. For this reason, results have been omitted from this publication.
Repainting
Repainting is simply the difference in behaviour of a strategy in real time vs the results calculated on the historical dataset. The strategy, by default, will wait for confirmed signals and is thus designed to not repaint. Waiting for bar close for entires aligns results in the real time data feed to those calculated on historical bars, which contain far less data. By doing this we align the behaviour of the strategy on the 2 data types, which brings significance to the calculated results. To override this behaviour and introduce repainting one can select "Recalculate on every tick" from the properties tab. It is important to note that by doing this alerts may not align with results seen in the strategy tester when the chart is reloaded, and thus to do so is to forgo backtesting and restricts a strategy to forward testing only.
👉 It is possible to use this script as an indicator as opposed to a full strategy by disabling "Use Strategy" in the "Inputs" tab. Basic alerts for detection will be sent when patterns are detected as opposed to complex order syntax. For alerts mid-bar enable "Recalculate on every tick" , and for confirmed signals ensure it is disabled.
█ EXIT ORDERS
Limit and Stop Orders
By default, the strategy will place a stop loss at the invalidation point of the pattern. This point is beyond the pattern high in the case of Double Tops, or beneath the pattern low in the case of Double Bottoms. The target or take profit point is an equal-legs measurement, or 100% of the pattern height in the direction of the pattern bias. Both the stop and the limit level can be adjusted from the user menu as a percentage of the pattern height.
Trailing Stops
Optional from the menu is the implementation of an ATR based trailing stop. The trailing stop is designed to begin when the target projection is reached. From there, the script looks back a user-defined number of bars for the highest or lowest point +/- the ATR value. For tighter stops the user can look back a lesser number of bars, or decrease the ATR multiple. When using either Alertatron or Trading Connector, each change in the trail value will trigger an alert to update the stop order on the exchange to reflect the new trail price. This reduces latency and slippage that can occur when relying on alerts only as real exchange orders fill faster and remain in place in the event of a disruption in communication between your strategy and the exchange, which ensures a higher level of safety.
👉 It is important to note that in the case the trailing stop is enabled, limit orders are excluded from the exit criteria. Rather, the point in time that the limit value is exceeded is the point that the trail begins. As such, this method will exit by stop loss only.
█ ALERTS
Five Built-in 3rd Party Destinations
The following are five options for delivering alerts from Double Tap to live trade execution via third party API solutions or chat bots to share your trades on social media. These destinations can be selected from the input menu and alert syntax will automatically configure in alerts appropriately to manage trades.
Custom JSON
JSON, or JavaScript Object Notation, is a readable format for structuring data. It is used primarily to transmit data between a server and a web application. In regards to this script, this may be a custom intermediary web application designed to catch alerts and interface with an exchange API. The JSON message is a trade map for an application to read equipped with where its been, where its going, targets, stops, quantity; a full diagnostic of the current state and its previous state. A web application could be configured to follow the messages sent in this format and conduct trades in sync with alerts running on the TV server.
Below is an example of a rendered JSON alert:
{
"passphrase": "1234",
"time": "2022-05-01T17:50:05Z",
"ticker": "ETHUSDTPERP",
"plot": {
"stop_price": 2600.15,
"limit_price": 3100.45
},
"strategy": {
"position_size": 0.1,
"order_action": "buy",
"market_position": "long",
"market_position_size": 0,
"prev_market_position": "flat",
"prev_market_position_size": 0
}
}
Trading Connector
Trading Connector is a third party fully autonomous Chrome extension designed to catch alert webhooks from TradingView and interface with MT4/MT5 to execute live trades from your machine. Alerts to Trading Connector are simple; just select the destination from the input drop down menu, set your ticker in the "TC Ticker" box in the "Alert Strings" section and enter your URL in the alert window when configuring your alert.
Alertatron
Alertatron is an automated algo platform for cryptocurrency trading that is designed to automate your trading strategies. Although the platform is currently restricted to crypto, it offers a versatile interface with high flexibility syntax for complex market orders and conditions. To direct alerts to Alertatron, select the platform from the 3rd party drop down, configure your API key in the ”Alertatron Key” box and add your URL in the alert message box when making alerts.
3 Commas
3 Commas is an easy and quick to use click-and-go third party crypto API solution. Alerts are simple without overly complex syntax. Messages are simply pasted into alerts and executed as alerts are triggered. There are 4 boxes at the bottom of the "Inputs" tab where the appropriate messages to be placed. These messages can be copied from 3 Commas after the bots are set up and pasted directly into the settings menu. Remember to select 3 Commas as a destination from the third party drop down and place the appropriate URL in the alert message window.
Discord
Some may wish to share their trades with their friends in a Discord chat via webhook chat bot. Messages are configured to notify of the pattern type with targets and stop values. A bot can be configured through the integration menu in a Discord chat to which you have appropriate access. Select Discord from the 3rd party drop down menu and place your chat bot URL in the alert message window when configuring alerts.
👉 For further information regarding alert setup, refer to the platform specific instructions given by the chosen third party provider.
█ IMPORTANT NOTES
Setting Alerts
For alert messages to be properly delivered on order fills it is necessary to place the following placeholder in the alert message box when creating an alert.
{{strategy.order.alert_message}}
This placeholder will auto-populate the alert message with the appropriate syntax that is designated for the 3rd party selected in the user menu.
Order Sizing and Commissions
The values that are sent in alert messages are populated from live metrics calculated by the strategy. This means that the actual values in the "Properties" tab are used and must be set by the user. The initial capital, order size, commission, etc. are all used in the calculations, so it is important to set these prior to executing live trades. Be sure to set the commission to the values used by the exchange as well.
👉 It is important to understand that the calculations on the account size take place from the beginning of the price history of the strategy. This means that if historical results have inflated or depleted the account size from the beginning of trade history until now, the values sent in alerts will reflect the calculated size based on the inputs in the "Properties" tab. To start fresh, the user must set the date in the "Inputs" tab to the current date as to remove trades from the trade history. Failure to follow this instruction can result in an unexpected order size being sent in the alert.
█ FOR PINECODERS
• With the recent introduction of matrices in Pine, the script utilizes a matrix to track pivot points with the bars they occurred on, while tracking if that pivot has been traded against to prevent duplicate detections after a trade is exited.
• Alert messages are populated with placeholders ; capability that previously was only possible in alertcondition() , but has recently been extended to `strategy.*()` functions for use in the `alert_message` argument. This allows delivery of live trade values to populate in strategy alert messages.
• New arguments have been added to strategy.exit() , which allow differentiated messages to be sent based on whether the exit occurred at the stop or the limit. The new arguments used in this script are `alert_profit` and `alert_loss` to send messages to Discord
Indicators and strategies
Traling.SL.TargetTrailing SL and Target
I have seen few requests in PineScripters telegram group asking questions about implementation of trailing stop-loss (SL) and targets. This script is one of the way to implement the same.
This script is developed based on dark color theme and is best viewed using dark color theme.
How and where can this script be used:
The script is built to demonstrate how one can implement the trailing SL and target, so by referring the script one can mimic the approach and add trailing SL and target implementation in their own strategy.
How it works:
To demonstrate the SL and target implementation, i have considered simple EMA crossover strategy.
Key Input Parameters
Method to use for SL/Target trailing:
1. % Based Target and SL - Used to calculate trailing based on parameters defined under group '% Based Target SL'
2. Fixed point Based Target and SL - Used to calculate trailing based on parameters defined under group 'Fixed point Based Target and SL'
% Based Target and SL:
Initial profit % - This is used to calculate target when trade is initiated
Initial SL % - This is used to calculate SL when trade is initiated
Initiate trailing % - This parameter determines, when to start trailing SL and target.
Trail profit by % - Target would be trailed by % specified as this parameter
Trail SL by % - SL would be trailed by % specified as this parameter
e.g.
Trade type: - Long
Trade price: 10000
initial profit %: 1
Initial SL %: 1
Initiate trailing %: 0.5
Trail profit by %: 0.3
Trail SL by %: 0.4
Calculations based on above:
initial profit %: 10100 (trade price + 1%)
Initial SL %: 9900 (trade price - 1%)
Initiate trailing %: 10049.5 (initial profit - 0.5%)
Trail profit by %: 10130 (initial profit + 0.3%)
Trail SL by %: 9939.6 (initial SL + 0.4%)
For next iteration of Trailing SL and target above calculated values will be taken as a base and next set of values will be calculated. these calculations will continue till the trade is exited either on price reaching profit or SL point.
Fixed point Based Target and SL:
Initial profit target points - To derive initial target, parameter value is added to trade price in case of long trade.
Initial SL points - To derive SL point, parameter value is subtracted from trade price
Initiate trailing points - To derive start of trailing logic, parameter value is subtracted from initial profit point.
Trail profit by points - In case of long trade, parameter value is added to the profit target to derive new trailed profit target.
Trail SL by % - In case of long trade, parameter value is added to the SL initial point to derive new trailed SL.
Calculation of Trailing SL and target will continue till the trade is exited either on price reaching profit or SL point.
Plots displayed on the chart:
Apart from default trade markings i have added 3 shapes on the chart to describe working of Trailing SL and targets.
Diamond shape marks - These are added on the chart when trade is initiated. These shapes gives additional trade information by way of 'tooltip'. This information can be viewed by placing mouse pointer on the shape.
Circle shape marks - These are added on the chart whenever Trailing SL and targets are calculated. These shapes gives additional trade information by way of 'tooltip'. This information can be viewed by placing mouse pointer on the shape. You will also notice a number displayed just above or below circle denoting Trailing iteration.
Labels up and label down shapes - These are dynamically placed on the chart whenever trade is in progress. These labels will display ongoing trades, Target and SL points.
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
3Commas BotBjorgum 3Commas Bot
A strategy in a box to get you started today
With 3rd party API providers growing in popularity, many are turning to automating their strategies on their favorite assets. With so many options and layers of customization possible, TradingView offers a place no better for young or even experienced coders to build a platform from to meet these needs. 3Commas has offered easy access with straight forward TradingView compatibility. Before long many have their brokers hooked up and are ready to send their alerts (or perhaps they have been trying with mixed success for some time now) only they realize there might just be a little bit more to building a strategy that they are comfortable letting out of their sight to trade their money while they eat, sleep, etc. Many may have ideas for entry criteria they are excited to try, but further questions arise... "What about risk mitigation?" "How can I set stop or limit orders?" "Is there not some basic shell of a strategy that has laid some of this out for me to get me going?"
Well now there is just that. This strategy is meant for those that have begun to delve into the world of algorithmic trading providing a template that offers risk defined positions complete with stops, limit orders, and even trailing stops should one so choose to employ any of these criteria. It provides a framework that is easily manipulated (with some basic working knowledge of pine coding) to encompass ones own ideas and entry criteria, while also providing an already functioning strategy.
The default settings have a basic 1:1 risk to reward ratio, which sets a limit and a stop equal distance from the entry. The entry is a simple MA cross (up for long, down for short). There a variety of MA's to choose from and the user can define the lengths of the averages. The ratio can be adjusted from the menu along with a volatility based adder (ATR) that helps to distance a stop from support or resistance. These values are calculated off the swing low/high of the user defined lookback period. Risk is calculated from position entry to stop, and projected upwards to the limit as a function of the desired risk to reward ratio. Of note: the default settings include 0.05% commissions. Competitive commissions of the leading cryptocurrency exchanges are .1% round trip (one buy and one sell) for market orders. There is also some slippage to allow time for alerts to be sent and orders to fill giving the back test results a more accurate representation of real time conditions. Its recommended to research the going rates for your exchange and set them to default for the strategy you use or build.
To get started a user would:
1) Make a copy of the code and paste in their bot keys in the area provided under the "3Comma Keys" section
- eg. Long bot "start deal" copied from 3commas in to define "Long" etc. (code is commented)
2) Place alert on desired asset with desired settings ensuring to select "Order fills and alert() function calls"
3) Paste webhook into the webhook box and select webhook URL alerts (3rd party provided webhook)
3) Delete contents of alert message box and replace with {{strategy.order.alert_message}} and nothing else
- the codes will be sent to the webhook appropriately as the strategy enters and exits positions. Only 1 alert is needed
settings used for the display image:
1hr chart on BTCUSD
-ATR stop
-Risk adjustment 1.2
-ATR multiplier 1.3
-RnR 0.6
-MAs HEMA/SMA
-MA Length 50/100
-Order size percent of equity
-Trail trigger 60% of target
Experiment with your own settings on your crypto of choice or implement your own code!
Implementing your trailing stop (optional)
Among the options for possible settings is a trailing stop. This stop will ratchet higher once triggered as a function of the Average True Range (ATR). There is a variable level to choose where the user would like to begin trailing the stop during the trade. The level can be assigned with a decimal between 0 and 1 (eg. 0.5 = 50% of the distance between entry and the target which must be exceeded before the trail triggers to begin). This can allow for some dips to occur during the trade possibly keeping you in the trade for longer, while potentially reducing risk of drawdown over time. The default for this setting is 0 meaning unless adjusted, the trail will trigger on entry if the trailing stop exit method is selected. An example can be seen below:
Again, optional as well is the choice to implement a limit order. If one were to select a trailing stop they could choose not to set a limit, which could allow a trail to run further until hit. Drawdowns of this strategy would be foregoing locking gains at highs on target on other trades. This is a trade-off the user can decide on and test. An example of this working in favor can be observed below:
Conclusion
Although a simple strategy is implemented here, the benefits of this script allow a user a starting platform to build their strategies from with built in risk mitigation. This allows the user to sidestep some of the potential difficulties' that can arise while learning Pine and taking on the endeavor of automating their trading strategies. It is meant as an aid, a structure, and an educational piece that can be seen as a "pick-up-and-go" strategy with easy 3Commas compatibility. Additionally, this can help users become more comfortable with strategy alert messages and sending strings in the form of alerts from Pine. As well, FAQs are often littered with questions regarding "strategy.exit" calls, how to implement stops. how to properly set a trailing stop based on ATR, and more. The time this can save an individual to get started is likely of the best "take-aways" here.
Happy trading
Monthly Returns in PineScript StrategiesI'm not 100% satisfied with the strategy performance output I receive from TradingView. Quite often I want to see something that is not available by default. I usually export raw trades/metrics from TradingView and then do additional analysis manually.
But with tables, you can build additional metrics and tools for your strategies quite easily.
This script will just show a table with monthly/yearly performance of your script. Quite a lot of traders/investors used to look at returns like that. Also, it might help you to identify periods of time when your strategy performed good/bad than expected and try to analyze that better.
The script is very simple and I believe you can easily apply it to your own strategies.
Disclaimer
Please remember that past performance may not be indicative of future results.
Due to various factors, including changing market conditions, the strategy may no longer perform as well as in historical backtesting.
This post and the script don’t provide any financial advice.
How to use Leverage and Margin in PineScriptEn route to being absolutely the best and most complete trading platform out there, TradingView has just closed 2 gaps in their PineScript language.
It is now possible to create and backtest a strategy for trading with leverage.
Backtester now produces Margin Calls - so recognizes mid-trade drawdown and if it is too big for the broker to maintain your trade, some part of if will be instantly closed.
New additions were announced in official blogpost , but it lacked code examples, so I have decided to publish this script. Having said that - this is purely educational stuff.
█ LEVERAGE
Let's start with the Leverage. I will discuss this assuming we are always entering trades with some percentage of our equity balance (default_qty_type = strategy.percent_of_equity), not fixed order quantity.
If you want to trade with 1:1 leverage (so no leverage) and enter a trade with all money in your trading account, then first line of your strategy script must include this parameter:
default_qty_value = 100 // which stands for 100%
Now, if you want to trade with 30:1 leverage, you need to multipy the quantity by 30x, so you'd get 30 x 100 = 3000:
default_qty_value = 3000 // which stands for 3000%
And you can play around with this value as you wish, so if you want to enter each trade with 10% equity on 15:1 leverage you'd get default_qty_value = 150.
That's easy. Of course you can modify this quantity value not only in the script, but also afterwards in Script Settings popup, "Properties" tab.
█ MARGIN
Second newly released feature is Margin calculation together with Margin Calls. If the market goes against your trades and your trading account cannot maintain mid-trade drawdown - those trades will be closed in full or partly. Also, if your trading account cannot afford to open more trades (pyramiding those trades), Margin mechanism will prevent them from being entered.
I will not go into details about how Margin calculation works, it was all explainged in above mentioned blogpost and documentation .
All you need to do is to add two parameters to the opening line of your script:
margin_long = 1./30*50, margin_short = 1./30*50
Whereas "30" is a leverage scale as in 30:1, and "50" stands for 50% of Margin required by your broker. Personally the Required Margin number I've met most often is 50%, so I'm using value 50 here, but there are literally 1000+ brokers in this world and this is individual decision by each of them, so you'd better ask yourself.
--------------------
Please note, that if you ever encounter a strategy which triggers Margin Call at least once, then it is probably a very bad strategy. Margin Call is a last resort, last security measure - all the risks should be calculated by the strategy algorithm before it is ever hit. So if you see a Margin Call being triggred, then something is wrong with risk management of the strategy. Therefore - don't use it!
Oscillator Evaluator (Analysis tool)Oscillator Evaluator (Analysis tool)
The oscillator evaluator is a tool that will help you analyse and compare the oscillator of your choice to another 2 oscillators.
By selecting the strategy with which you will analyze the oscillators, you will be able to see the behaviour of the oscillators in different aspects.
First there is a moving average increase or decrease strategy, that will give you a good idea of the correlation of the oscillator with the price.
The second is a commom 2 MA crossover strategy, that will give you and idea of the validaty of that oscillator as a strategy or as a trend filter.
The third strategy is a cross over 0 signal, that will go long on a crossover of 0 and short on a crossunder 0. This helps you see how good is the oscillator at evaluating suport and resistance areas and give you an idea of its balance.
The forth strategy is a Buy/Sell on extremes of the oscillator and will let you know how good is your strategy at spotting good places to buy and sell.
The fith strategy is to evaluate how goood the oscillator is as a mean reversion filter or how good it is at spotting small price changes.
The sixth strategy is similar to the last but is focused on how good is the oscillator spotting good places to take profits on trending strategies.
The 6 strategies in the script produce signals from the oscillator and from the oscillator only.
In conclusion this tool can be used to measure your oscillator and see if it really is as good as you think in comparison to others.
This script is not intended to be used as a full strategy but as a tool.
Built-in Kelly ratio for dynamic position sizingThis is the defaut keltners channel strategy with a few additions.
The main purpose is to show how we include the Kelly ratio into our scripts for dynamic position sizing based on the performance of the strategy on a per trade basis.
We've also included the usual take-profit and stop-loss parameters in the event you want to play a little :)
We hope this helps you advance your personal system.
Happy Trading!
Ultimate Strategy TemplateHello Traders
As most of you know, I'm a member of the PineCoders community and I sometimes take freelance pine coding jobs for TradingView users.
Off the top of my head, users often want to:
- convert an indicator into a strategy, so as to get the backtesting statistics from TradingView
- add alerts to their indicator/strategy
- develop a generic strategy template which can be plugged into (almost) any indicator
My gift for the community today is my Ultimate Strategy Template
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
For doing so:
1) Find in your indicator where are the conditions printing the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, ZigZag, Pivots, higher-highs, lower-lows or whatever indicator with clear buy and sell conditions
//@version=4
study(title='Moving Average Cross', shorttitle='Moving Average Cross', overlay=true, precision=6, max_labels_count=500, max_lines_count=500)
type_ma1 = input(title="MA1 type", defval="SMA", options= )
length_ma1 = input(10, title = " MA1 length", type=input.integer)
type_ma2 = input(title="MA2 type", defval="SMA", options= )
length_ma2 = input(100, title = " MA2 length", type=input.integer)
// MA
f_ma(smoothing, src, length) =>
iff(smoothing == "RMA", rma(src, length),
iff(smoothing == "SMA", sma(src, length),
iff(smoothing == "EMA", ema(src, length), src)))
MA1 = f_ma(type_ma1, close, length_ma1)
MA2 = f_ma(type_ma2, close, length_ma2)
// buy and sell conditions
buy = crossover(MA1, MA2)
sell = crossunder(MA1, MA2)
plot(MA1, color=color_ma1, title="Plot MA1", linewidth=3)
plot(MA2, color=color_ma2, title="Plot MA2", linewidth=3)
plotshape(buy, title='LONG SIGNAL', style=shape.circle, location=location.belowbar, color=color_ma1, size=size.normal)
plotshape(sell, title='SHORT SIGNAL', style=shape.circle, location=location.abovebar, color=color_ma2, size=size.normal)
/////////////////////////// SIGNAL FOR STRATEGY /////////////////////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Basically, I identified my buy, sell conditions in the code and added this at the bottom of my indicator code
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title="🔌Connector🔌", transp=100)
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal , and -1 for the bearish signal
Now you can connect your indicator to the Strategy Template using the method below or that one
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings and in the Data Source field select your 🔌Connector🔌 (which comes from your indicator)
From then, you should start seeing the signals and plenty of other stuff on your chart
🔥 Note that whenever you'll update your indicator values, the strategy statistics and visual on your chart will update in real-time
Settings
- Color Candles : Color the candles based on the trade state (bullish, bearish, neutral)
- Close positions at market at the end of each session : useful for everything but cryptocurrencies
- Session time ranges : Take the signals from a starting time to an ending time
- Close Direction : Choose to close only the longs, shorts, or both
- Date Filter : Take the signals from a starting date to an ending date
- Set the maximum losing streak length with an input
- Set the maximum winning streak length with an input
- Set the maximum consecutive days with a loss
- Set the maximum drawdown (in % of strategy equity)
- Set the maximum intraday loss in percentage
- Limit the number of trades per day
- Limit the number of trades per week
- Stop-loss: None or Percentage or Trailing Stop Percentage or ATR
- Take-Profit: None or Percentage or ATR
- Risk-Reward based on ATR multiple for the Stop-Loss and Take-Profit
This script is open-source so feel free to use it, and optimize it as you want
Alerts
Maybe you didn't know it but alerts are available on strategy scripts.
I added them in this template - that's cool because:
- if you don't know how to code, now you can connect your indicator and get alerts
- you have now a cool template showing you how to create alerts for strategy scripts
Source: www.tradingview.com
I hope you'll like it, use it, optimize it and most importantly....make some optimizations to your indicators thanks to this Strategy template
Special Thanks
Special thanks to @JosKodify as I borrowed a few risk management snippets from his website: kodify.net
Additional features
I thought of plenty of extra filters that I'll add later on this week on this strategy template
Best
Dave
Stepped trailing strategy exampleThis is a stepped trailing exit example for educational purpose .
Short brief.
There are 1 stop loss and 3 profit levels.
When first tp is reached we move stop loss to break-even.
When second tp is reached we move stop loss to first tp.
When third tp is reached we exit by profit.
PMax Explorer STRATEGY & SCREENERProfit Maximizer - PMax Explorer STRATEGY & SCREENER screens the BUY and SELL signals (trend reversals) for 20 user defined different tickers in Tradingview charts.
Simply input the name of the ticker in Tradingview that you want to screen.
Terminology explanation:
Confirmed Reversal: PMax reversal that happened in the last bar and cannot be repainted.
Potential Reversal: PMax reversal that might happen in the current bar but can also not happen depending upon the timeframe closing price.
Downtrend: Tickers that are currently in the sell zone
Uptrend: Tickers that are currently in the buy zone
Screener has also got a built in PMax indicator which users can confirm the reversals on graphs.
Screener explores the 20 tickers in current graph's time frame and also in desired parameters of the SuperTrend indicator.
Also you can optimize the parameters manually with the built in STRATEGY version.
PMax indicator :
Profit Maximizer - PMax is a brand new indicator developed by me.
It's a combination of two trailing stop loss indicators;
One is Anıl Özekşi's MOST (Moving Stop Loss) Indicator
and the other one is well known ATR based SuperTrend
Profit Maximizer - PMax tries to solve this problem. PMax combines the powerful sides of MOST (Moving Average Trend Changer) and SuperTrend (ATR price detection) in one indicator.
Backtest and optimization results of PMax are far better when compared to its ancestors MOST and SuperTrend. It reduces the number of false signals in sideways and give more reliable trade signals.
PMax is easy to determine the trend and can be used in any type of markets and instruments. It does not repaint.
The first parameter in the PMax indicator set by the three parameters is the period/length of ATR.
The second Parameter is the Multiplier of ATR which would be useful to set the value of distance from the built in Moving Average.
I personally think the most important parameter is the Moving Average Length and type.
PMax will be much sensitive to trend movements if Moving Average Length is smaller. And vice versa, will be less sensitive when it is longer.
As the period increases it will become less sensitive to little trends and price actions.
In this way, your choice of period, will be closely related to which of the sort of trends you are interested in.
We are under the effect of the uptrend in cases where the Moving Average is above PMax;
conversely under the influence of a downward trend, when the Moving Average is below PMax.
Built in Moving Average type defaultly set as EMA but users can choose from 8 different Moving Average types like:
SMA : Simple Moving Average
EMA : Exponential Movin Average
WMA : Weighted Moving Average
TMA : Triangular Moving Average
VAR : Variable Index Dynamic Moving Average aka VIDYA
WWMA : Welles Wilder's Moving Average
ZLEMA : Zero Lag Exponential Moving Average
TSF : True Strength Force
Tip: In sideways VAR would be a good choice
You can use PMax default alarms and Buy Sell signals like:
1-
BUY when Moving Average crosses above PMax
SELL when Moving Average crosses under PMax
2-
BUY when prices jumps over PMax line.
SELL when prices go under PMax line.
Grid Like StrategyIt is possible to use progressive position sizing in order to recover from past losses, a well-known position sizing system being the "martingale", which consists of doubling your position size after a loss, this allows you to recover any previous losses in a losing streak + winning an extra. This system has seen a lot of attention from the trading community (mostly from beginners), and many strategies have been designed around the martingale, one of them being "grid trading strategies".
While such strategies often shows promising results on paper, they are often subjects to many frictions during live trading that makes them totally unusable and dangerous to the trader. The motivations behind posting such a strategy isn't to glorify such systems, but rather to present the problems behind them, many users come to me with their ideas and glorious ways to make money, sometimes they present strategies using the martingale, and it is important to present the flaws of this methodology rather than blindly saying "you shouldn't use it".
Strategy Settings
Point determines the "grid" size and should be adjusted accordingly to the scale of the symbol you are applying the strategy to. Higher value would require larger price movements in order to trigger a trade, as such higher values will generate fewer trades.
The order size determines the number of contracts/shares to purchase.
The martingale multiplier determines the factor by which the position size is multiplied after a loss, using values higher to 2 will "squarify" your balance, while a value of 1 would use a constant position sizing.
Finally, the anti-martingale parameter determines whether the strategy uses a reverse martingale or not, if set to true then the position size is multiplied after any wins.
The Grid
Grid strategies are commons and do not present huge problems until we use certain position sizing methods such as the martingale. A martingale is extremely sensitive to any kind of friction (frictional costs, slippage...etc), the grid strategy aims to provide a stable and simple environment where a martingale might possibly behave well.
The goal of a simple grid strategy is to go long once the price crossover a certain level, a take profit is set at the level above the current one and stop loss is placed at the level below the current one, in a winning scenario the price reach the take profit, the position is closed and a new one is opened with the same setup. In a losing scenario, the price reaches the stop loss level, the position is closed and a short one is opened, the take profit is set at the level below the current one, and a stop loss is set at the level above the current one. Note that all levels are equally spaced.
It follows from this strategy that wins and losses should be constant over time, as such our balance would evolve in a linear fashion. This is a great setup for a martingale, as we are theoretically assured to recover all the looses in a losing streak.
Martingale - Exponential Decays - Risk/Reward
By using a martingale we double our position size (exposure) each time we lose a trade, if we look at our balance when using a martingale we see significant drawdowns, with our balance peaking down significantly. The martingale sequence is subject to exponential growth, as such using a martingale makes our balance exposed to exponential decays, that's really bad, we could basically lose all the initially invested capital in a short amount of time, it follows from this that the theoretical success of a martingale is determined by what is the maximum losing streak you can endure
Now consider how a martingale affects our risk-reward ratio, assuming unity position sizing our martingale sequence can be described by 2^(x-1) , using this formula we would get the amount of shares/contracts we need to purchase at the x trade of a losing streak, we would need to purchase 256 contracts in order to recover from a losing streak of size 9, this is enormous when you take into account that your wins are way smaller, the risk-reward ratio is totally unfair.
Of course, some users might think that a losing streak of size 9 is pretty unlikely, if the probability of winning and losing are both equal to 0.5, then the probability of 9 consecutive losses is equal to 0.5^9 , there are approximately 0.2% of chance of having such large losing streak, note however that under a ranging market such case scenario could happen, but we will see later that the length of a losing streak is not the only problem.
Other Problems
Having a capital large enough to tank 9any number of consecutive losses is not the only thing one should focus on, as we have to take into account market prices and trading dynamics, that's where the ugly part start.
Our first problem is frictional costs, one example being the spread, but this is a common problem for any strategy, however here a martingale is extra sensitive to it, if the strategy does not account for it then we will still double our positions costs but we might not recover all the losses of a losing streak, instead we would be recovering only a proportion of it, under such scenario you would be certain to lose over time.
Another problem are gaps, market price might open under a stop-loss without triggering it, and this is a big no-no.
Equity of the strategy on AMD, in a desired scenario the equity at the second arrow should have been at a higher position than the equity at the first arrow.
In order for the strategy to be more effective, we would need to trade a market that does not close, such as the cryptocurrency market. Finally, we might be affected by slippage, altho only extreme values might drastically affect our balance.
The Anti Martingale
The strategy lets you use an anti-martingale, which double the position size after a win instead of a loss, the goal here is not to recover from a losing strike but instead to profit from a potential winning streak.
Here we are exposing your balance to exponential gross but you might also lose a trade at the end a winning streak, you will generally want to reinitialize your position size after a few wins instead of waiting for the end of a streak.
Alternative
You can use other-kind of progressions for position sizing, such as a linear one, increasing your position size by a constant number each time you lose. More gentle progressions will recover a proportion of your losses in a losing streak.
You can also simulate the effect of a martingale without doubling your position size by doubling your target profit, if for example you have a 10$ profit-target/stop-loss and lose a trade, you can use a 20$ profit target to recover from the lost trade + gain a profit of 10$. While this approach does not introduce exponential decay in your balance, you are betting on the market reaching your take profits, considering the fact that you are doubling their size you are expecting market volatility to increase drastically over time, as such this approach would not be extremely effective for high losing streak.
Conclusion
You will see a lot of auto-trading strategies that are based on a grid approach, they might even use a martingale. While the backtests will look appealing, you should think twice before using such kind of strategy, remember that frictional costs will be a huge challenge for the strategy, and that it assumes that the trader has an important initial capital. We have also seen that the risk/reward ratio is theoretically the worst you can have on a strategy, having a low reward and a high risk. This does not mean that progressive position sizing is bad, but it should not be pushed to the extreme.
It is nice to note that the martingale is originally a betting system designed for casino games, which unlike trading are not subject to frictional costs, but even casino players don't use it, so why would you?
Thx for reading
Gap Filling Strategy Gaps are market prices structures that appear frequently in the stock market, and can be detected when the opening price is different from the previous closing price, this is why gaps are also called "opening price jumps". While gaps can occur frequently, some of them are more significant than others, and can be observed when looking at a long term chart.
The following strategy is based on the exploitation of significant gaps occurring during a new session, and posses various options that can return a wide variety of results.
Type Of Gaps And Occurence
I'am not a professional when it comes to gaps, but as you know the stock market close for the day, however it is still possible to place orders, your broker will hold them until the market open back. Once the market reopen the broker execute the pending orders, and when many orders where pending the market register really high volume and the price might differ from the precedent close.
Gaps are generally broken down into four types:
Common : Gaps occurring within a certain price range, mostly occurs during ranging markets.
Break Away : Gaps breaking a support and resistance, making a new higher high/lower low.
Runaway : Gaps occurring within a trend, followed by a continuation of the trend.
Exhaustion : Gaps occurring at the end of a trend, followed by a reversal.
As said before, some gaps are more significant than others, the significance of a gap can be determined by comparing the opening price with the previous high/low price and by looking at volume. Significant up gaps will have an opening price greater than the previous high, while significant down gap will have an opening price lower than the previous low with both high volume accompanying them.
After a gap, when the price go back to the point previous to the gap we say that it has been "filled", this characteristic is what will be exploited in this strategy.
Strategy Rules & Logic
In this strategy, the significance of a gap is determined by the position of the opening price relative to the previous high/low and make sure the bar following the gap don't fill it.
When the setting invert is set to false the strategy interpret the detected gaps as being exhaustion gaps, therefore when an up gap occur a short position is opened, when a down gap occur a long position is opened. When invert is set to true gaps are considered to be runaway or break away gaps, therefore the contrary positions are opened. Positions are exited when the gap has been filled, which in the chart is show'n when the price cross the red level who act as either a take profit (invert = false) or as a stop loss (invert = true).
There are various closing conditions available that the user can select from the "close when" setting.
New Session : This option close all previous positions when the market is in a new session.
New Gap : This option close all previous position when a new gap has been detected.
Reverse Position : This option close all previous position when a contrary position to the current one is opened. This option would reduce the number of trades.
Testing On Some Stocks
The analysis will be tested in different tech stocks with a main TF of 15 minutes with no spread and commissions applied. Default settings will be used. We'll be making our first analysis using AMD, who has recently formed a full reverse HS pattern, where the neckline has been crossed by the price. (by the way i have a bad feeling about it, hey ! feeling filling ! Lame jokes!)
Profit: $ -12.22
Trades: 272
Profitability: 65.07 %
We can see negative results, with an heavily decreasing balance. Using invert would return positive results.
We will now test the strategy on NVDA, the company is one of the biggest when it comes to the Gpu market.
Profit: $ -215.54
Trades: 297
Profitability: 60.27 %
Not better, using invert would of course create better results. Like AMD the balance is heavily decreasing.
Finally we will test the strategy on Seagate technology, a company mostly known for their mechanical hard drives.
Profit: $ -4.32
Trades: 261
Profitability: 65.9 %
Here the balance does not appear so heavily decreasing and even managed to reach back the initial balance before going down again.
Summary
A strategy based on gap filling has been briefly introduced and tested with 3 tech stocks. The results show that using invert option might be better. The advantage of this strategy against ones using technical indicators is that this one does not heavily depend on user settings, which make it way more efficient, this a big advantage of patterns based strategies.
Thx to LucF for helping with the "process_orders_on_close" element, since i had to use closing price i had to remove it tho, was afraid results would differ even more from a more realistic backtest. And thx for those who continuously support me, more cool stuff is coming up.
Thx for reading and i hope you'll have learned something new today !
inwCoin Martingale Strategy ( for Bitcoin )** Same as my previous martingale script but this version = opensource **
inwCoin Martingale Strategy is the proof of concept strategy that in the end, anyone who using martingale strategy will kaboom their portfolio.
For those who don't know what is "martingale".. it's a simple double down strategy in the hope to cover the loss in previous entry.
Example
In the game that if you win, you'll get 100% of your bet money back.
1st loss = 1$
2nd loss = bet 2$ : if win, get 2$ / real profit = 1$ ( 2-1 )
3rd loss = bet 4$ : if win, get 4$ / real profit = 1$ ( 4 - ( 2+1) )
4th loss = bet 8$ : if win, get 8$ / real profit = 1$ ( 8 - ( 4+2+1 ) )
...
...
10th loss = bet 512$ : if win, get 512$ / real profit = 1$ ( 512 - ( 256+128+64+32+16+8+4+2+1) )
as you can see, the next bet will be first bet x 2^(n-1)
and the profit will equal to your first bet.
==================
In trading and forex EA ( Expert Advisor or bot ) people use this strategy to fool newbies that their martingale system will generate steady income for eternity.
But in reality, this strategy will destroy your whole portfolio eventually some time in the future. Because there will be some "Blackswan event" in market at some point in time. And one who ignore this fact, will lose everything.
But, if you using low risk strategy and generate some profit from your low-risk portfolio. You can take small chunk of that profit and put it in riskier strategy like this martingale, to accerelate your profit snowball.
===================
Parameter Explaination
====================
Price = datasource for indicator calculation
Fixed position size option = if uncheck, the "Start position size" parameter will be % of your initial capital. If checked, it will fixed position size ( like 1 BTC )
Start Position Logic = condition to enter first trade
- MACD singal > 0 : Self explanatory, default macd value
- Stochastic RSI cross up : enter when sto line cross up from bottom ( 20 )
- ATR channel : enter trade if price cross above 2.3 ATR
Take Profit Percent = take profit target % from average entry
Start martingale ..= if price compare to average position entry less than this %, it will start to double down ( martingale )
Martingale Multiplier = you can specific how big you'll double down, default is 2
Trade Direction = long only for now
Use date rang = self explanatory
** make sure to setup your initial capital in properties tab **
On chart
=======
White Line = Average position price
Orange Line = your current equity
If equity less than 0, it will close any remaining positions ( It's mean your position got liquidated )
If price > equity line for "take profit percent" it will close any remaining positions.
=======
As you can see, this strategy survive 2018 drop and pump profit to 1000+% ( Check in the strategy tester tab > list of trades )
But in May 2020 -50% drop in just 3 days, your whole portfolio got liquidated.
Actually, after some digging in profit and backtest result.
This strategy, when it can survive a shape drop, can generate a lot of profit.
So, if you want to use martingale. Make sure to use only small chunk of your profit from "low-risk" strategy to accelerate your profit generation ( aka degen port )
DO NOT greedy and use all of your initial capital or borrowed money to use with this strategy!
LUBEThis is a chart meant for 30m BTCUSD but could be used for many other assets, and there are inputs to play with.
I decided on the strange title "LUBE" because I was measuring how many of the previous 500 bars had the current price level already been in. I wanted to discover when the price was in a new zone or an area that it hadn't spent much time in recently... the LUBE zone.
Think of the blue line as showing you the current level friction. If the blue line is high, price is quagmired and not moving quickly. Price could trend sideways for a while before breaking out. A high blue line is a high traffic zone for trading. When the blue line dips low, it's encountering a price zone the asset has not been observed in recently, and this could mean price could break out and move more freely and quickly when it does. We get a trade entry signal if the blue line dips below the bottom white line. The bottom white line is currently set to -10. Think about the lowest the blue line has been recently as 0, and the highest as 100. It is set by default (for BTCUSD 30m chart) to -10 meaning the blue line has to dip a little (-10%) below the lowest it has experienced recently to initiate a trade. This is the LUBE zone. The bottom white line shows that level. Again this is a level lower than the lowest amount of friction experienced in price action for the last 100 bars, but offset by 5 bars showing where that level was at 5 bars ago. We want to dip below that to initiate a trade.
The direction to trade in is determined by a very quick moving weighted moving average (variable name is "fir") to see if the recent trend is up or down. To end a trade, an arbitrary number between 0 and 100 is picked telling us when we are experiencing enough friction again to end the trade. I have it preset to 50 (think of it as 50/100 or half way between the white bars. At a 50% friction level it's time to get out of the trade.
Some shortcomings are missing the bulk of big moves, and experiencing whipsaws where price action zips up and then comes straight back down. Overall the backtest looks sweet enough to use on 2x leverage, experiencing a 17.78% max drawdown at the time of publishing. I wouldn't push the leverage any higher.
To get alerts change the word "strategy" to "study" and delete lines 60-67.
Bot traders using alerts: beware the alert conditions. If a trade goes directly from long to short (which happens rarely), without closing a trade first, it might not act properly. If you use bots to trade, for "LONG" please close any old trades first before putting in instructions to open a leveraged long. To go "SHORT" please remember to close any old trade first as well, and things *should* work out just fine.
Good luck, have fun, and feel free to mess up and butcher this code to your own liking. I'm not responsible if anything bad that happens to you if you use this trading system, or for any bugs you may encounter.
How To Set Backtest Time Ranges
Example how to set the time range window to be backtested for both entries and exits. Additional examples are also included showing how to set the date range and toggle plot visibility.
By incorporating this code with your own strategy's logic, it will allow you to backtest various time windows.
Much gratitude to @LucF and @a.tesla2018 for help with including ':1234567' for time ranges on weekends. Thank you both!
NOTICE: This is an example script and not meant to be used as an actual strategy. By using this script or any portion thereof, you acknowledge that you have read and understood that this is for research purposes only and I am not responsible for any financial losses you may incur by using this script!
Grover Llorens Activator Strategy AnalysisThe Grover Llorens Activator is a trailing stop indicator deeply inspired by the parabolic SAR indicator, and aim to provide early exit points and reversal detection. The indicator was posted not so long ago, you can find it here :
Today a strategy using the indicator is proposed, and its profitability is analyzed on 3 different markets with the main time frame being 1 hour, remember that lower time frames involve lower absolute price changes, therefore we are way more affected by the spread, and we can require a larger position sizing depending on our investment target, trading higher time-frames is always a good practice and this is why 1 hour is selected. Based on the result we might make various conclusions regarding the indicator accuracy and might have ideas on future improvements of the indicator.
I'am not great when it comes to strategy design, i still hope to share correct and useful information in this post, let me know your thoughts on the post format and if i should make more of these.
Setup And Rules
The analysis is solely based on the indicator signals, money management isn't taken into account, this allow us to have an idea on the indicator robustness and resilience, particularly on extremely volatile markets and ones exhibiting a chaotic structure, altho it is normally good practice to close any position before a market closure in order to avoid any potential major gaps.
The settings used are 480 for length and 14 for mult, this create relatively mid term signals that are suited for a trend indicator such as the Grover Llorens Activator, unfortunately we can't infer the indicator optimal settings, thats how it is with any technical indicator anyway.
Here are the rules of our strategy :
long : closing price cross over the indicator
short : closing price cross under the indicator
We use constant position sizing, once a signal is triggered all the previous positions are closed.
Description Of The Statistics Used
Various statistics are presented in this post, here is a brief description of the main ones :
Percent Profitability (higher = better): Percentage of winning trades, that is : winning trades/total number of trades × 100
Maximum Drawdown (lower = better) : The highest difference between a peak and a valley in the balance, that is : peak - valley , in percentage : (peak - valley)/peak × 100
Profit Factor (higher = better) : Gross profit divided by gross loss, values under 1 represent gross losses superior to the gross profits
Remember that more volatility = more risk, since higher absolute price changes can logically cause larger losses.
EURUSD
The first market analyzed is the Forex market with the EURUSD major pair with a position sizing of 1000 units (1 micro lot). Since October EURUSD is not showing any particular strong trend but posses a discrete rising motion, fortunately cycles can be observed.
The equity was rising until two trades appeared causing a decline in the equity. Before October a bearish market could be observed.
We can see that the equity is rising, the trend still posses various retracements that affect our indicator, however we can see that the indicator totally nail the end of the trend, thats the power of converging toward the price.
In short :
$ 86.63 net profit
340 closed trades
37.65 % profitable (thats a lot of loosing trades)
1.19 profit factor
$ 76.67 max drawdown
Applying a spread would create negative results (in general the average spread is used), not a great start...
BTCUSD
The cryptocurrency market is relatively more volatile than others, which also mean potentially higher returns, we test the indicator using certainly the most traded cryptocurrency, BTCUSD. We will use a position sizing of 1 unit.
In the case of BTCUSD the strategy balance is relatively stationary around the initial capital, with of course high dispersion.
from september to december the market is bearish with various ranging periods, no apparent cycles can be observed, except maybe in the ranging period of october, this ranging period is followed by a non linear trend (relatively parabolic) that the indicator failed to capture in its integrity (this is a recurrent problem and it is starting to piss me off xD).
In short :
$ 2010.64 net profit (aka how i bet the crypto market)
395 closed trades
38.23 % profitable
1.036 profit factor
$ 5738.01 max drawdown (aka how i lost to the crypto market)
AMD
AMD stand for Advanced Micro Devices and is a company focused on the development of computer technology, i love the microprocessor market and i really like AMD who start this year in a pretty great way with a net bullish trend.
The performance of the indicator on AMD is decent (at last !) with the equity producing many new higher highs. The indicator performance still drop in the middle end of 2019 with a large equity drawdown of 17$ caused by the gap of august 8. Unfortunately AMD, like lot of well behaving stocks can only tells us that the indicator has good performances on heavily trending markets with no excess of noise or chaotic structures.
In short :
$ 17.86 net profit (Enough for a consistent lunch)
295 closed trades
36.27 % profitable
1.414 profit factor
$ 10.37 max drawdown.
Conclusion
A strategy using the recently proposed Grover Llorens activator has been presented. We can easily conclude that the indicator can't possibly generate long term returns under chaotic and volatile markets, and could even produce unnecessary trades in trending markets without much parasitic fluctuations such as noise and retracements (think about a simple linear trend) since the indicator converge toward the price and would therefore automatically cross over/under the trend, thus guaranteeing a false signal.
However we have seen its ability to provide accurate early reversal detection shine from time to time, thus over performing lagging indicators in this aspect, however the duration of price fluctuations isn't fixed at a certain period, the rate of convergence should be way faster during volatile fluctuations, of moderate speed during more cyclic fluctuations, and really slow with apparent long term trends, this could be achieved by making the indicator adaptive, but it won't really make it necessarily perform better.
That said i still believe that converging trend indicators are really interesting and aim to capture the non lasting behavior of price fluctuations, they shouldn't receive so much hate (think about the poor p-sar).
Thanks for reading !