Template Trailing Strategy

jason5480 Uppdaterad   
This script is meant to be used as a generic template for new strategies. Take Profit, Stop Loss logic is provided out of the box with (or without) their trailing variations while the trailing for entry and exit orders can also be enabled and be configured!
Custom quantity risk management is provided along with the ability to set custom signal messages that can be send through webhook to your bot platform.
To create a new Strategy copy this script and replace the openLongPosition, closeLongPosition, openShortPosition, closeShortPosition variables under the STRATEGY section with your own logic.
Take some time to check the different options on all sections to have better understanding of the capabilities that script provide you for free!
  • Add the option to select different moving average types for fast and slow MA instead of a fixed SMA.
  • Make use of math_utils library
  • Add an option to ignore close signals from crossover/crossunder so users can play exclusively with stop loss and take profit configuration
  • Fix some typos
Feature Release:
  • Now Strategy support two types of deal conditions (Internal and External). Internal is the "build-in" two MA cross over/under logic that is standalone. However, as proposed by @EltAlt now simple External deal conditions can also be constructed by this strategy! User can add his favorite indicator in the same chart as this strategy and use the output of this indicator as an External Input for the start and end Deal Conditions to open and close position and enter and exit orders.
  • Add option for different/secondary Stop Loss % and ATR Multipliers after the Take Profit Target is reached. As suggested by @PlusUltraTrading this will give more flexibility to the end user when he wants to apply more loose/strict stop loss rules after the initial take profit target was hit.

    At this point I want to thank all those who contributed with their ideas, comments and their personal time. This motivated me to build this template at its generic enough, but also useful for everyone current state. Use it wisely!
  • Now you can set multiple Take Profit Targets for each entry! The initial target may use different method that the additional step targets (e.g. set initial TP at 3ATR and the next target at +5% on top of the initial TP price)
  • Beatification of the Input tab with emojis and "tabs" when sub-menus are implied.
  • Minor Bug and typo fixes for previously released features.
  • Several refactorings in the code, added descriptions for each module.
\nFix Release:
  • The minimum number of take profits can be 0
  • Some code cleanup
  • Add session time filter
  • Now user can chose between three different ATR trailing methods Static, Dynamic and Ladder
  • Fix a bug that caused entry and exit trailing to not monotonically follow the trend when an external input indicator was triggered a signal second time before the strategy enters or exit the position.
  • Add the option to close at market price at the end of a session
  • Some code refactoring
  • New trailing Stop Loss, Entry and Exit method called Local Extrema. This technique allow the user to set his target price in the local maximum/minimum price plus/minus some ticks.
  • New Quantity method that is strictly based on equity percentage (rather than the capital at risk percentage).
  • New option for Initial Take Profit target price to set it to the Local Extrema (minimum/maximum) plus/minus some ticks.
  • New implementation of the session filter now it is more versatile and accurate.
Make Session filter cyclical to capture overnight sessions.
  • The convention for overnight session day now is the end day in order to match the build-in session logic
  • Fix a bug that causing Risk-Reward Take profit Method (RR) to not work correctly when Stop Loss Method was set to Local max/min (LOC)
  • Add ADX trend filter option
  • Add the ability to close early if the first take profit target is not hit within some bars from the entry
  • Add up to 5 TP alert messages that can be used
  • Now the user can use up tp 20 different variables in the alert messages that are passed as input to the strategy. Strategy will replace their current value before trigger the alert. Some of the variables are the TP, the SL prices and the quantities of entries and exits of the positions.
  • Use time_filtes library and string_variables
  • Add {%{RISK}} {@{TICKER}} {@{BASE}} {@{QUOTE}} alert message variables
  • Make trailing entry to use stop order instead of market
  • Make trailing exit to use stop order instead of market
  • Fix a bug that caused the very first quantity calculation to be wrong when the trailing entry was enabled
  • Fix some typos in the alert messages
  • Some code refactoring and optimizations
  • New feature: Cooldown! Now you can wait after the completion for a couple of bars before enter the next trade!
  • Replace deprecated "when=" with if statements in strategy calls
  • Fix some rounding numerical inconsistencies for take profit quantities
  • Minor code clean up
  • Add support for new signal indicator convention (see for more)
  • Add ticker prefix and post fix variables for the alert messages
  • Rephrase the default alert messages to demonstrate more string variables
  • Use qty_percent after TV team fixed the API taking into account the initial position size
  • Change fastMA default color to yellow
  • Change trailing entry price default color to blue
  • Huge refactoring in the Stop Loss section! Now Stop Loss consists of two modes that can be set independently. The Move and the Trailing modes.
  • Added the ability to move the Stop Loss multiple times when a new Take Profit target is reached
  • Added the ability to change the trailing distance parameters in a step like manner every time a new Take Profit target is reached (a more generic version of old "Use Sec %/Mul" feature)
  • Now you can select on which Take Profit target you will start the Stop Loss trailing for the "TP" Trailing Activation Mode.
  • Increased the maximum number of lines and labels that can be drawn to 300 and 200 respectively
  • Added new string variables {${ENTRY}}, {${CLOSE+}}, {${CLOSE+}}, {${OPEN}}, {${HIGH}}, {${LOW}}
  • Other minor fixes and optimizations
  • New "update" alerts were introduced. Now user is able to get a message when Stop Loss value is change, the same is try for trailing entry and exit.
  • Changed the way take profit target prices are calculated when they are used with trailing entry. Now the basis of calculations is the entry price (white line) instead of the price when the open position signal was triggered.
  • Add the option to refer to other than the exchange timezone in the "Filter - Time" settings.
  • Fixed a precision bug that caused the sum of all TPs amounts that were reached to not add up to the total percentage.
  • Added {${ENTRY+}} {${ENTRY-}} {${EXIT+}} and {${EXIT-}} string variables that can be used with and without trailing for long and shorts.
  • Update time_filters library
  • Some minor performance optimizations
Happy 1.5K lines script!
  • Added new STATS section where statistics about the trades as a whole can be inspected. While TV backtest engine provides accurate statistics based on each order separately, usually you need to see the trade as a whole to be able to fine-tune your strategy!
  • Update time_filters library
  • Update string_variables library
  • Fix some annoying bugs
  • Changed some defaults to have better performance by default (Sorry for any inconvenience)
Have a nice holiday!
  • Update string_variables library. Percentage variables (%) were dopped. Use raw variables (#) instead and the "Percentage Range" checkbox to define the range of percentages to or
  • Minor tweaks to boost alert performance
  • Fix a bug that was causing stop loss messages to be empty when the take profit quantity was set to 100%
  • Some more optimizations
  • As a friendly remainder to use your own "custom signal indicator" for start and end deal conditions that match your own strategy logic, I added even more statistics and new metrics (feedback is always welcome!)
  • Change the settings so the order type (market, stop-limit) for entry and exit is independent from the trailing logic
  • For those who use stop-limit orders for entry and exit now they can send cancellation signals from their indicator (check "Two MA Signal Indicator" for more)
  • Moved the old Filters - Trend logic under the Strategy - Internal. Now those filters are not applied into the external logic coming from your indicator. If you used them in combination with your custom indicator before you have to MOVE THAT LOGIC to your own indicator too (sorry).
  • Now you can customize the colors of each label and line category on each section
  • Some bug fixes optimizations and other improvements made (as always)
  • Change some settings to better reflect the underlying functionality
  • Some aesthetic changes were also made
  • Added more strict validation criteria for the cancelation signals. Now a open/close should be in-progress to consider a cancel signal valid. This will also remove some visual clutter.
  • Added the option to choose what price to follow when trailing front/rear (high/low)
  • Added the option to choose on which TP to activate the move stop loss ONCE (first TP by default)
  • The ema of the internal strategy now use security in a "secure" way so it does not repaint in higher timeframes in real-time bars.
  • For the Local Extrema Method (LOC) added an option in the shared variables section to use ATR instead of TICKS to calculate the margin offset on top of the min/max price target.
  • Update exernal_input_utils library
  • Now entries and exits support limit order type. Also, trailing adapted accordingly to this case (compared to the stop-limit orders).
  • Add option to set a minimum initial take profit percentage. So you can make sure that you will compensate for the commissions in every trade.
  • Some aesthetic changes and options to hide labels and change the entry price color from the settings.
  • Some terminology changes (deviation -> distance) to better match the meaning of some variables.
  • Bug fixes and improvements (as always).
  • Added new fixed order size quantity method (SIZE)
  • Early close feature extended so now you can chose any TP target to disable the close signal
  • Now if a new open signal is received while you try to enter with limit or stop-limit order the TTS will pick the "best" price between the new proposed and the previous.
  • Some more info was added to the Open tooltip and some aesthetic changes in the Trade stats
  • If a limit or stop-limit order is unfilled when an open signal in the other direction is received, then the TTS will cancel the previous limit order
  • Fix for LOC method to function with limit orders
  • If you close a position with reverse open (e.g. in a long position a start short signal is emitted) the position will close with market order not matter the exit order type (this only applies to close position signals).
  • Fix some bugs regarding alerts.
  • Fix a bug that caused a TP target to be considered as "reached" when there were trades back to back.
  • Fixed a bug that was causing stop-limit orders to not always get executed.
  • Added stop orders for those wo want to make sure their order is executed in markets with "price gaps" (in contrast to stop-limit).
  • Better visualization for stop-limit orders to also shoe the limit price.
  • The logic that track the "completed trades" had been reworked. Now cooldown feature also takes into account trades that entered and exited in a single bar.
  • Some "defaults" were changed to the simpler option so the first impression if the script is less cluttered.
  • Add the option to limit the stop loss distance (percentagewise) by setting max and min values. This will result in better risk management when using the ATR and LOC methods.
  • Add the option to not use reverse orders when a start deal condition is met that points to the other direction than the existing position. If reverse orders are un-checked the TTS will ignore the signal.
  • Add Min/Max option also to the Entry and Exit price calculations
  • Fix a misleading typo in the settings that showed the min as max and the max as min.
  • Added two new distance methods for take profit targets. A fixed profit based method where you enter the desired profit per TP target in quote currency (commissions are taken into account). A tick based method that can be used in lower timeframes.
  • Set default commission in the strategy.
  • Add limits (min/max) in stepped take profit targets.
  • Refactoring, bug fixes and optimizations as always.
  • Some new bugs for you to find :D.
    Happy new year!
  • Declutter the status line, price scale, and data window so it is easier to spot the price of interest when you mouse over a bar.
  • Upgrade time_filters external_input_utils anmd distance_percentile libararies.
  • Some internal optimizations.
  • New Stop Loss(ish) option to wait for close confirmation
  • Now you can choose barrier for each trailing type (stop loss, entry, exit)
  • Update internal libraries and make optimizations
  • Added slippage and fill limit for more realistic backtest results
  • Revamp the way take profit targets are rendered and limit them up to five
  • Some aesthetic changes.
  • Detect "inconclusive" trades where both take profit and stop loss targets were hit at the same bar. Analytics should be enabled.
  • Small fixes and optimizations as usual.
Happy anniversary! It was a good year full of useful incremental changes. This script/framework has evolved significantly since its inception and I consider it to be in a "feature complete" state.
I want to thank all those who gave me feedback and helped to shape it into its current form.
This script/framework will continue to help traders to "fast prototype" their own ideas by "plugging in" their signal indicators.
Using this script/framework you can apply techniques and existing ideas on top of the "main" logic your signal indicator provides.
Enjoy with caution and criticism!
  • New Quantity Method 'CONTR' to support a fixed number of contracts in futures markets.
  • Some bug fixes.
  • Added standard deviation as an option for volatility measurement and (STDEV) as a method for distance placement for take profit, stop loss, entry, and exit.
  • Decoupled the shared "Margin LOC Method" and assigned it to each relevant section separately. This means you can use a different type of margin for LOC entry and LOC stop loss.
  • Commissions in the Inputs tab used by TTS are now expressed in percentages like in the Properties tab. So those numbers should match for accurate results.
  • Optimization of alert messages generation using the "string_utils" library.
  • Fixes, improvements, internal library updates, and aesthetic changes.
  • New string variables for alert messages. The variables can be used both for long and short messages and they 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}}
    WARNING! If you used the "old" string variables you should replace them with the new equivalent.
  • Split the enabling "all event alerts" functionality into the entry, close/exit, take profit, and stop loss to save some computational resources when they are not needed.
  • Two new price-based stop loss move activation modes ONCEPRICE and MULTIPRICE. The old ONCE and MULTI taka profit based modes were renamed to ONCETP and MULTITP accordingly
  • Simplification of all Distance Method related inputs. Now there is one multiplier MUL for each method that represents the number of the units of the method.
  • Rename the LOC method local extrema to HHLL highest high/lowest low for more clarity and add an option for a margin.
  • Support for signals with breakout entry in both directions.
  • Some aesthetic changes, refactorings, and optimizations.
  • TTS now adjusts the take profit and stop loss targets after market and stop orders. The adjustment is the difference between the expected entry and the actual entry price. This difference might be caused by slippage and/or gaps between bars.
  • Output the position sign -1, 0, 1 so it can be used by signal indicators to produce more informed decisions.
Skript med en öppen källkod

I sann TradingView-anda har författaren publicerat detta skript med öppen källkod så att andra handlare kan förstå och verifiera det. Hatten av för författaren! Du kan använda det gratis men återanvändning av den här koden i en publikation regleras av våra ordningsregler. Du kan ange den som favorit för att använda den i ett diagram.

Frånsägelse av ansvar

Informationen och publikationerna är inte avsedda att vara, och utgör inte heller finansiella, investerings-, handels- eller andra typer av råd eller rekommendationer som tillhandahålls eller stöds av TradingView. Läs mer i Användarvillkoren.

Vill du använda det här skriptet i ett diagram?