FreedX Backtest█ Our strategy template empowers TradingView users to effortlessly backtest any indicator, enhancing their trading strategy's effectiveness. In addition, users can create automated webhook alerts from the template. This document details our template's features and how to utilize them effectively.
█ TRADE DATE SETTINGS
The Trading Date Settings feature in our TradingView script allows you to refine their backtesting parameters by specifying trading dates and hours. This feature enhances the accuracy of the backtest by aligning it with specific time frames and days, ensuring that the strategy is tested under relevant market conditions.
Features:
⚙️ Enable Trading Between Specific Dates:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific date range.
💡 How to Use:
→ Input the Start Date and End Date for the backtest period.
→ The script will execute the strategy only within this specified date range.
⚙️ Enable Trading Between Specific Hours:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific hour range.
💡 How to Use:
→ Input the start and end hour for in Trading Session section.
→ The script will execute the strategy only within this specified hour range.
⚙️ Enable Trading on Specified Days of the Week:
🎯 Purpose:
→ Gives you the option to conduct backtesting on selected days of the week, tailoring the strategy to particular market behaviours that may occur on these days.
💡 How to Use:
→ Select the days of the week for the backtest.
→ The script will activate the trading strategy only on these chosen days.
█ BUY/SELL TRIGGER SETTINGS
The Buy/Sell Trigger Settings feature is designed to provide users with flexibility in defining the conditions for 'LONG' and 'SHORT' signals based on various indicator types. This customization is crucial for tailoring strategies to different trading styles and market conditions.
Features:
⚙️ Single-Line Plotted Indicators :
🎯 Purpose:
→ Enables you to select a single-line plotted indicator as a source for backtesting. You can define specific levels to trigger 'LONG' or 'SHORT' signals.
💡 How to Use:
→ Choose a Single-Line Plotted indicator as the source.
→ Set the top and bottom levels for the indicator.
→ The script triggers 'LONG' signals at the bottom level and 'SHORT' signals at the top level.
⚙️ Two-Line Plotted Indicators :
🎯 Purpose:
→ Allows backtesting with two-line cross plot sources. Signals are generated based on the crossover of these lines.
💡 How to Use:
→ Select two lines as 'Source 1' and 'Source 2' for the indicator.
→ The script triggers a 'LONG' signal when 'Source 1' crosses above 'Source 2'.
→ Conversely, a 'SHORT' signal is triggered when 'Source 2' crosses above 'Source 1'.
⚙️ Custom Signals :
🎯 Purpose:
→ This setting enables users to define their own criteria for LONG, SHORT, and CLOSE signals based on custom indicator outputs.
💡 How to Use:
→ Select the custom source for your signals.
→ Define the output values that correspond to each signal type (e.g., “1” for 'LONG', “-1” for SHORT, and “0” for CLOSE).
→ The script will trigger signals according to these custom-defined values.
█ TP/SL SETTINGS
The TP/SL (Take Profit/Stop Loss) Settings feature is designed to give users control over their profit securing and risk mitigation strategies. This feature allows for setting custom TP and SL levels, which can be critical in managing trades effectively.
Features:
Custom TP/SL Levels for Long/Short Signals:
🎯 Purpose:
→ Enables users to set specific percentage levels for Take Profit and Stop Loss on long and short signals.
💡 How to Use:
→ In the TP/SL Settings, input the desired percentage for Take Profit (TP) and Stop Loss (SL).
→ For example, to secure a profit at a 10% price increase on LONG signals, set the “Long TP Percentage” to “10”.
█ STRATEGY SETTINGS
Strategy Settings provide a range of options to customize the trading strategy. These settings include leverage, drawdown limits, position direction changes, and more, allowing users to tailor their strategy to their risk tolerance and market view.
Features:
⚙️ Enable Leverage :
🎯 Purpose:
→ Allows users to apply leverage to their trades.
☢️ Caution:
→ High leverage can significantly increase the risk of liquidation.
→ High leverage and a high stop-loss price may override your fixed stoploss percentage, adjusting the stop-loss to the liquidation price.
💡 How to Use:
→ Set the desired leverage ratio in the Strategy Settings.
⚙️ Enable Drawdown Limit:
🎯 Purpose:
→ Sets a maximum drawdown limit, automatically halting the strategy if this limit is reached, thereby controlling risk.
💡 How to Use:
→ Input the maximum drawdown limit (default: 100, min: 0, max: 100).
⚙️ Enable Reverse Position:
🎯 Purpose:
→ Automatically closes a current position and opens a new one in the opposite direction upon detecting a signal for a market trend change.
🎯 Example:
→ If a LONG signal is received while in a SHORT position, the script will close the SHORT position and open a LONG position.
💡 How to Use:
→ Activate this feature in the Strategy Settings.
⚙️ Enable Spot Mode:
🎯 Purpose:
→ Disables short orders, using short signals only for closing long positions.
💡 How to Use:
→ Select the 'Spot Mode' option in the Strategy Settings.
⚙️ Enable Invert Signals:
🎯 Purpose:
→ Inverts all indicator signals, changing LONG signals to SHORT and vice versa.
💡 How to Use:
→ Opt for the 'Invert Signals' feature in the Strategy Settings.
⚙️ Enable Trailing Stop:
🎯 Purpose:
→ Triggers a trailing stop order on the exchange instead of a standard stop market order.
☢️ Caution:
→ The backtesting of this feature on TradingView may not accurately reflect actual strategy performance due to discrepancies between TradingView and exchange mechanisms.
💡 How to Use:
→ Select 'Trailing Stop' in the Strategy Settings.
█ ADVANCED STRATEGY SETTINGS
Advanced Strategy Settings offer sophisticated methods for managing Stop Loss (SL) and Take Profit (TP) using the Average True Range (ATR). These settings are ideal for traders who want to incorporate volatility into their exit strategies.
Features:
⚙️ Enable ATR Stop Loss:
🎯 Purpose:
→ Automatically sets the Stop Loss price using the Average True Range at the time of entry.
💡 How to Use:
→ Activate 'ATR Stop Loss' to have the SL price calculated based on the current ATR.
⚙️ Enable ATR Take Profit:
🎯 Purpose:
→ Sets the Take Profit price based on the Average True Range at the time of entry.
💡 How to Use:
→ Choose 'ATR Take Profit' for TP price determination using ATR.
⚙️ Enable ATR Trailing Stop:
🎯 Purpose:
→ Dynamically updates the Stop Loss price with each new bar, according to the Average True Range.
💡 How to Use:
→ Activate 'ATR Trailing Stop'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
█ TREND FILTERING SETTINGS
Trend Filtering Settings are designed to align trading strategies with the prevailing market trend, enhancing the precision of trade entries and exits. These settings utilize moving averages for trend analysis and decision-making.
Features:
⚙️ Enable Trend Filtering:
🎯 Purpose:
→ Limits trades based on moving average trends, blocking short trades in an uptrend and vice versa.
💡 How to Use:
→ Enable 'Trend Filtering'.
→ Set Fast and Slow MA Lengths for trend analysis.
→ Select the Timeframe for moving averages.
→ Choose the Moving Average Type for trend filtering.
🎯 Note:
→ Be cautious with timeframe selections; lower timeframes than the base may cause inconsistencies.
⚙️ Enable Exit on Trend Reversal:
🎯 Purpose:
→ Automatically closes a position when a market trend reversal is detected.
💡 How to Use:
→ Turn on 'Exit on Trend Reversal' in the settings.
⚙️ Enable Trend Drawing On Chart:
🎯 Purpose:
→ Visually represents the trend filter directly on the chart for easy reference.
💡 How to Use:
→ Activate 'Trend Drawing On Chart' to see the trend filter overlaid on the trading chart.
█ AUTOMATED ALERT SETTINGS
Automated Alert Settings are designed to integrate your TradingView script with webhook alerts. These settings allow for enhanced strategy execution and management.
Features:
Enable Webhook Alerts:
🎯 Purpose:
→ Trigger BUY, SELL, CHANGE_DIRECTION or MOVE_STOP_LOSS .
💡 How to Use:
→ Enable 'Webhook Alerts' in the settings.
→ Enter your Strategy ID.
→ Optionally, activate 'Override Allocation Percentage' to bypass the preset allocation percentage.
☢️ Caution:
→ Overriding the allocation percentage may result in trade entry errors due to misalignment between entry cost and available balance.
█ DEBUGGING SETTINGS
Debugging Settings are crucial for users who want to analyze and optimize their strategies. These settings provide tools for visualizing alerts on charts and accessing detailed data outputs.
Features:
⚙️ Enable Alert Plotting:
🎯 Purpose:
→ Allows users to visualize trading alerts directly on the chart, aiding in strategy analysis and refinement.
💡 How to Use:
→ Activate 'Alert Plotting' to draw alerts on the chart.
☢️ Caution:
→ It is recommended to disable this feature when creating actual trading alerts, as it can cause latency in signal processing.
⚙️ Enable Debugger Mode:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Data Window.
💡 How to Use:
→ Turn on 'Debugger Mode' to access real-time data and metrics relevant to your strategy.
█ ADDITIONAL SETTINGS
⚙️ Enable Bar Magnifier
⚙️ Enable Using standard OHLC
Strategymaker
[MT] Strategy Backtest Template| Initial Release | | EN |
An update of my old script, this script is designed so that it can be used as a template for all those traders who want to save time when programming their strategy and backtesting it, having functions already programmed that in normal development would take you more time to program, with this template you can simply add your favorite indicator and thus be able to take advantage of all the functions that this template has.
🔴Stop Loss and 🟢Take Profit:
No need to mention that it is a Stop Loss and a Take Profit, within these functions we find the options of: fixed percentage (%), fixed price ($), ATR, especially for Stop Loss we find the Pivot Points, in addition to this, the price range between the entry and the Stop Loss can be converted into a trailing stop loss, instead, especially for the Take Profit we have an option to choose a 1:X ratio that complements very well with the Pivot Points.
📈Heikin Ashi Based Entries:
Heikin Ashi entries are trades that are calculated based on Heikin Ashi candles but their price is executed to Japanese candles, thus avoiding false results that occur in Heikin candlestick charts, this making in certain cases better results in strategies that are executed with this option compared to Japanese candlesticks.
📊Dashboard:
A more visual and organized way to see the results and necessary data produced by our strategy, among them we can see the dates between which our operations are made regardless if you have activated some time filter, usual data such as Profit, Win Rate, Profit factor are also displayed in this panel, additionally data such as the total number of operations, how many were gains and how many losses, the average profit and loss for each operation and finally the maximum profits and losses followed, which are data that will be very useful to us when we elaborate our strategies.
Feel free to use this template to program your own strategies, if you find errors or want to request a new feature let me know in the comments or through my social networks found in my tradingview profile.
| Update 1.1 | | EN |
➕Additions: '
Time sessions filter and days of the week filter added to the time filter section.
Option to add leverage to the strategy.
5 Moving Averages, RSI, Stochastic RSI, ADX, and Parabolic Sar have been added as indicators for the strategy.
You can choose from the 6 available indicators the way to trade, entry alert or entry filter.
Added the option of ATR for Take Profit.
Ticker information and timeframe are now displayed on the dashboard.
Added display customization and color customization of indicator plots.
Added customization of display and color plots of trades displayed on chart.
📝Changes:
Now when activating the time filter it is optional to add a start or end date and time, being able to only add a start date or only an end date.
Operation plots have been changed from plot() to line creation with line.new().
Indicator plots can now be controlled from the "plots" section.
Acceptable and deniable range of profit, winrate and profit factor can now be chosen from the "plots" section to be displayed on the dashboard.
Aesthetic changes in the section separations within the settings section and within the code itself.
The function that made the indicators give inputs based on heikin ashi candles has been changed, see the code for more information.
⚙️Fixes:
Dashboard label now projects correctly on all timeframes including custom timeframes.
Removed unnecessary lines and variables to take up less code space.
All code in general has been optimized to avoid the use of variables, unnecessary lines and avoid unnecessary calculations, freeing up space to declare more variables and be able to use fewer lines of code.
| Lanzamiento Inicial | | ES |
Una actualización de mi antiguo script, este script está diseñado para que pueda ser usado como una plantilla para todos aquellos traders que quieran ahorrar tiempo al programar su estrategia y hacer un backtesting de ella, teniendo funciones ya programadas que en el desarrollo normal te tomaría más tiempo programar, con esta plantilla puedes simplemente agregar tu indicador favorito y así poder aprovechar todas las funciones que tiene esta plantilla.
🔴Stop Loss y 🟢Take Profit:
No hace falta mencionar que es un Stop Loss y un Take Profit, dentro de estas funciones encontramos las opciones de: porcentaje fijo (%), precio fijo ($), ATR, en especial para Stop Loss encontramos los Pivot Points, adicionalmente a esto, el rango de precio entre la entrada y el Stop Loss se puede convertir en un trailing stop loss, en cambio, especialmente para el Take Profit tenemos una opción para elegir un ratio 1:X que se complementa muy bien con los Pivot Points.
📈Entradas Basadas en Heikin Ashi:
Las entradas Heikin Ashi son operaciones que son calculados en base a las velas Heikin Ashi pero su precio esta ejecutado a velas japonesas, evitando así́ los falsos resultados que se producen en graficas de velas Heikin, esto haciendo que en ciertos casos se obtengan mejores resultados en las estrategias que son ejecutadas con esta opción en comparación con las velas japonesas.
📊Panel de Control:
Una manera más visual y organizada de ver los resultados y datos necesarios producidos por nuestra estrategia, entre ellos podemos ver las fechas entre las que se hacen nuestras operaciones independientemente si se tiene activado algún filtro de tiempo, datos usuales como el Profit, Win Rate, Profit factor también son mostrados en este panel, adicionalmente se agregaron datos como el número total de operaciones, cuantos fueron ganancias y cuantos perdidas, el promedio de ganancias y pérdidas por cada operación y por ultimo las máximas ganancias y pérdidas seguidas, que son datos que nos serán muy útiles al elaborar nuestras estrategias.
Siéntete libre de usar esta plantilla para programar tus propias estrategias, si encuentras errores o quieres solicitar una nueva función házmelo saber en los comentarios o a través de mis redes sociales que se encuentran en mi perfil de tradingview.
| Actualización 1.1 | | ES |
➕Añadidos:
Filtro de sesiones de tiempo y filtro de días de la semana agregados al apartado de filtro de tiempo.
Opción para agregar apalancamiento a la estrategia.
5 Moving Averages, RSI, Stochastic RSI, ADX, y Parabolic Sar se han agregado como indicadores para la estrategia.
Puedes escoger entre los 6 indicadores disponibles la forma de operar, alerta de entrada o filtro de entrada.
Añadido la opción de ATR para Take Profit.
La información del ticker y la temporalidad ahora se muestran en el dashboard.
Añadido personalización de visualización y color de los plots de indicadores.
Añadido personalización de visualización y color de los plots de operaciones mostradas en grafica.
📝Cambios:
Ahora al activar el filtro de tiempo es opcional añadir una fecha y hora de inicio o fin, pudiendo únicamente agregar una fecha de inicio o solamente una fecha de fin.
Los plots de operaciones han cambiados de plot() a creación de líneas con line.new().
Los plots de indicadores ahora se pueden controlar desde el apartado "plots".
Ahora se puede elegir el rango aceptable y negable de profit, winrate y profit factor desde el apartado "plots" para mostrarse en el dashboard.
Cambios estéticos en las separaciones de secciones dentro del apartado de configuraciones y dentro del propio código.
Se ha cambiado la función que hacía que los indicadores dieran entradas en base a velas heikin ashi, mire el código para más información.
⚙️Arreglos:
El dashboard label ahora se proyecta correctamente en todas las temporalidades incluyendo las temporalidades personalizadas.
Se han eliminado líneas y variables innecesarias para ocupar menos espacio en el código.
Se ha optimizado todo el código en general para evitar el uso de variables, líneas innecesarias y evitar los cálculos innecesarios, liberando espacio para declarar más variables y poder utilizar menos líneas de código.
Indicators & Conditions Test Framework [DTU]Hello All,
This script is a framework to build strategies by combining indicators and conditions (long, short, exits). You are able to analyze your strategies in realtime by changing the input parameters related to indicators, conditions and their combinations.
OVERVIEW
With this Study/Strategy framework, you will be able to create strategy conditions, display them on the chart, and test them using existing indicators as well as external and custom indicators that you can add.
The main purpose of the Framework is to choose your indicators to be used in the conditions and test your strategy by producing your "Long, short, Exit long, Exit short" combinations.
Although may be, it can be a bit difficult and complicated at first start, but you can understand the logic on its use in a very short time.
Notes:
I removed external links off descriptive images and video to be comply with Trading view violation House Rules
Since I am new in the community and still trying to understand the pine script language I can make errors and violations on my script. Please Inform me on any issue that I made..
HOW TO
STEP 1: SETTINGS ______________________________________________________________________________________________________
SOURCE, TIMEFRAME, SECURITY
Select the Source, timeframe and Secure type that your indicators will use.
Here, the Secure entry consists of 3 parts and the f_security function is used to determine it.
a)Secure
This option is defined as reducing repaint in tradingview calculations as much as possible. The following function is used.
request.security(_symbol, _res, _src , lookahead=barmerge.lookahead_on)
b)Semi Secure
While this option can reduce repaint in tradingview calculations as much as possible, it is less secure. The following function is used.
request.security(_symbol, _res, _src )
c)Repaint
This option turns on the repaint feature. The following function is used.
request.security(_symbol, _res, _src ) : na
Ind Source:
You can the source that indicators will use their own calculations
Ext Source:
You can import external Indicator sources from here . It appears on condition/combination area as "EXT".
To export the External indicator plot it with a title. It will be visible in source dropdown input
PERIOD , ALERTS...
Period:
Determine your strategy testing period by selecting start and end date/time
(!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars.
The extra bar option may cause problems such as not appearing in the calculations or errors).
Plot Alerts:
Plot condition result as alerts arrows on the chart's bottom for "LONG" and the top for "SHORT" entries, exits
Close on opposite:
When selected, a long entry gets closed when a short entry opens and vice versa
Show Profit:
It appears if script is in strategy mode (not in study) this can display current or open profit for better reanalyzing your strategy entry exit points. (Currently under development)
PLOT TYPE OPERATIONS
This option has 4 entries
a) Mult
Sets the multiplier for the selected Plot Type (stochastic, Percentrank, Org Range (-1,1) ) except for "Original" in the range (-1,1).
EXAMPLE: When 1000 is selected, the indicator in the range of (-1,1) will appear in the range of (-1000, 1000) on the screen.
b) Shift
It determines the shift that will appear on the screen for the selected Plot Type (stochastic, Percentrank,Org Range (-1,1) ) in the range (-1,1) other than "Original".
EXAMPLE: When Shift:35000 and mult:1000 are selected, the indicator will appear in the range (34000, 36000) on the screen.
c) Smooth
This option (only for Stochastic & PercentRank) allows to smooth the indicator to be displayed.
Here, tradinview ta.swma function is used.
b) hline
Adjusts the horizontal lines to appear on the screen according to the mult factor for the range (-1,1)
The lines represent the values (-1, -05, 0, 05, 1)
STEP 2: INDICATORS ______________________________________________________________________________________________________
You need to choose indicators that you can use in strategy conditions.
Here, the indicators come from the dturkuler/lib_Indicators_DT open script library defined in the code
In addition, you can add the indicators that you will create in the area defined in the code to this list..
You can also import external indicators and test them with other variables on the system..
You can choose a maximum of 5 indicators that you can use in total. (can be increased in new versions)
Indicators are categorized in 3 main sections
Indicator Selection:
You can select your indicators from this area
a)Moving Averages
These are indicators such as EMA, SMA that you can show on the stock. They come from the library.
These indicators are fed from Settings/source. Only the length value can be used as a parameter.
In addition, line colors can be changed..
As of now, there are 28 indicators in the library in total and 5 indicators are left as future use for this field for now.
b)Other Indicators
These are different indicators from the stock value such as RSI, COG. They come from the library. These indicators are fed from Settings/source.
Only the length value can be used as a parameter. In addition, line colors can be changed.
As of now, there are 24 indicators in the library in total and 5 indicators are left as a future use for this field for now.
c)Custom Indicators
These indicators are the ones you can create by programming yourself in the source code..
The area at the bottom of the settings screen is reserved for the parameters of this type of indicators.
Indicator Length:
You can update your selected indicator length value from here. (Not: it doesn't work for custom indicators since they have their parameter on cust. Ind. input screen )
Indicator Plot Type:
Next to the indicators, there is an input selection field about how they will be displayed on the screen.
a)Original
The indicator is displayed on the screen with its current values. It is an ideal solution for displaying moving average indicators such as (EMA, SMA) over current stock.
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
For this reason, other options may be more suitable for these.
b)Stochastic
The indicator is displayed on the screen with stochastic calculation in the range of -1.1.
It uses the stochastic(50) calculation method to spread indicators such as (RSI, COB) over the range (-1,1).
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
c)PercentRank
The indicator is displayed on the screen with stochastic calculation in the range of -1.1. .
Since the values of indicators such as (RSI, COB) are low (-100,100 : -1.1), they appear at the bottom of the screen and make analysis difficult.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen
((!!! Do not use the values on the chart in your condition calculations. Instead, get the values from Data Window)
d)Org Range (-1,1)
If your indicator is in the range of -1.1, your indicator will be displayed on the screen with its original calculation in the range of -1.1.
Indicators in this selection can be fixed and monitored under stock on the screen with the parameters under the Plot Type section.
You can see the original values of the relevant indicator on the Data Window screen.
(!!! Do not use the values on the chart in your fitness calculations. Instead, get the values from Data Window)
STEP 2 NOTES:
STEP 3: CONDITIONS ______________________________________________________________________________________________________
After choosing the indicators you will use in the conditions, you move on to the "CONDITIONS" section.
There are 4 conditions type here.
• LONG ENTRY CONDITION
• SHORT ENTRY CONDITION
• LONG CLOSE CONDITION
• SHORT CLOSE CONDITION
The use of each condition is the same.
There are 3 combinations you can use in each condition. (can be increased in new versions)
a)COMBINATIONS
There are 3 combinations you can use in each condition. (can be increased in new versions)
Each combination are build from 4 parts
1)1st Indicator
If set to "NONE" this combination will not be used on calculations. You can select
IND1-5: from indicators (See above),
EXT: value from externally imported indicator
Stock built-in values: close, open...
2)Operator
Selected Operator compares 1st Indicator with the 2nd one. You can select different operators such as
crossover, crossunder, cross,>,<,=....
3)2nd Indicator
This indicator will be compared with the 1st one via selected Operator. You can select
IND1-5: from indicators (See above),
VALUE: a float value defined in the combinations value parameter
EXT: value from externally imported indicator
Stock builtin values: close,open...
4)Value
When the 2nd indicator field is "VALUE", value area compares the entered value.
ex: 1st indicator="open", op=">", 2nd indicator="VALUE", value=3000.12 means is(close>3000.12)
In other conditions, it compares the previous values of the indicator.
ex: 1st indicator="open", op=">" 2nd indicator is "close" and value is 2 means is(open>close )
EXAMPLES:
indicator 1= "IND1", Operator=">", indicator 2= "IND2" => is(IND1>IND2)
indicator 1= "IND1", Operator=">", indicator 2= "VALUE", "0.1" => is(IND1>0.9)
indicator 1= "IND2", Operator="crossover", indicator 2= "IND1" => is(IND2 crossover IND1) : like a=ta.crossover(IND2, IND1)
indicator 1= "IND1", Operator="<", indicator 2= "close" => is(IND1>close)
indicator 1= "IND1", Operator="<", indicator 2= "EXT" => is(IND1>EXT) , EXT mean external imported indicator that define on settings section
indicator 1= "IND1", Operator="<", indicator 2= "IND1", Value="1" => is (IND1>IND1 )
b)JOIN COMBINATIONS
Each combination in Condition is compared with the next one via JOIN operator
The join operator can be selected as AND or OR.
Examples:
1st combination= is(IND1>0.9) true
2nd combination= is(IND2 crossover IND1) false
1st combination "AND" 2ndcombination" => false (is(IND1>0.9) AND is(IND2 crossover IND1))
1st combination "OR" 2nd combination" => true (is(IND1>0.9) OR is(IND2 crossover IND1))
STEP 3 NOTES:
When the 2nd indicator field is "VALUE", value area compares the entered value. In other conditions, it compares the previous values of the indicator.
In cases where "VALUE" is not selected, integer values must be entered in this field. (float should not be entered. ie 1, 2 should be entered)
!!!If the 1st indicator is "NONE" in the combination, that combination is cancelled.
Each combination returns true/false, allowing the selected value to be compared with another value
Example: EMA(21)>EMA(50) returns true under all conditions or (EMA(21) crossover EMA(50)) returns true when passed.
You can use , Value of 5 indicators (IND1-IND5) or (VALUE) that you have defined in combinations or import indicator (EXT) or stock values (close, open, high...) in your calculations.
combination Compares the 1st indicator with 2nd indicator via the operator.
STEP 4: CUSTOM INDICATORS ______________________________________________________________________________________________________
There is an area in the code for designing Custom Indicators.
Here you can design your own indicators and use them in the framework.
You can also create unlimited parameters for your indicators in the SETTINGS custom indicator field.
For now, only 3 Custom indicators have been defined.
Examples are entered in the code for custom indicators.
STEP 4 NOTES:
Including / updating custom to the code is explained in the source code
• LIMITATIONS:
!!! According to your tradingview subscription, it takes the last 5000, 10000.. bars. More bar options may cause problems such as not appearing in the calculations or errors.
• RAMBLINGS:
• NOTES [ /i]
This Script can be used as an indicator if the last strategy parts in the code are commented out and converted to the initial strategy study.
It was originally prepared for my use with my own strategy framework and has export functions accordingly.
When integrated to my own strategy framework it brings many more features over strategy definition of trades.
• TODO [ /i]
TODO: Add tooltips to the settings screen
TODO: Add double triple, Quatr factor for all indicators (convert any indicator to factor2-4 facotr. ex: EMA to DEMA, TEMA, QEMA...)
TODO: Add factorized Fibo avg range indicator (good for trend definition and entry exit points)
TODO: Add bands to the indicator and conditions
TODO: Add debug window for exporting indicator's parameters
TODO: Add isRising(value) isFalling(value), is...(value) .... to combinations (they can be used as custom indicator also
TODO: Reassess condition entry screen for user friendly GUI
TODO: Increase # conditions from 3 to 4
TODO: Reassess strategy entries, exit and close (should be improved)
TODO: Add Alerts, Condiional alerts for indicator (study) part
TODO: Create export function v3 for Pinecoders Indicator framework
• THANKS:
For Pine script format docs RicardoSantos .
For Pine script coding standards Pinecoders .
For moving average script used on library s RodrigoKazuma .
STRATEGY TESTER ENGINE - ON CHART DISPLAY - PLUG & PLAYSo i had this idea while ago when @alexgrover published a script and dropped a nugget in between which replicates the result of strategy tester on chart as an indicator.
So it seemed fair to use one of his strategy to display the results.
This strategy tester can now be used in replay mode like an indicator and you can see what happen at a particular section of the chart which was is not possible in default strategy tester results of TV.
Please read how each result is calculated so you will know what you are using.
This engine shows most common results of strategy tester in a single screen, which are as follows:
1. Starting Capital
2. Current Profit Percentage
3. Max Profit Percentage
4. Gross Profit
5. Gross Loss
6. Total Closed Trades
7. Total Trades Won
8. Total Trades Lost
9. Percentage Profitable
10. Profit Factor
11. Current Drawdown
12. Max Drawdown
13. Liquidation
So elaborating on what is what:
1. Starting Capital - This stays 0, which signifies your starting balance as 0%. It is set to 0 so we can compare all other results without any change in variables. If set to 100, then all the results will be increased by 100. Some users might find it useful to set it to 100, then they can change code on line 41 from to and it should show starting balance as 100%.
2. Current Profit Percentage - This shows your current profit adjusted to current price of the candle, not like TV which shows after candle is close. There is a comment on the line 38 which can be removed and your can see unrealized profit as well in this section. Please note that this will affect Draw-down calculations later in this section.
3. Max Profit Percentage - This will show you your max profit achieved during your strategy run, which was not possible yet to see via strategy tester. So, now you can see how much profit was achieved by your strategy during the run and you can compare it with chart to see what happens during bull-run or bear-run, so you can further optimize your strategy to best suit your desired results.
4. Gross Profit - This is total percentage of profit your strategy achieved during entire run as if you never had any losses.
5. Gross Loss - This is total percentage of loss your strategy achieved during entire run as if you never had any profits.
6. Total Closed Trades - This is total number of trades that your strategy has executed so far.
7. Total Trades Won - This is the total number of trades that your strategy has executed that resulted in positive increase in equity.
8. Totals Trades Lost - This is the total number of trades that your strategy has executed that resulted in decrease in equity.
9. Percentage Profitable - This is the ratio between your current total winning trades divided by total closed trades, and finally multiplied by 100 to get percentage results.
10. Profit Factor - This is the ratio between Gross Profit and Gross Loss, so if profit factor is 2, then it indicates that you are set to gain 2 times per your risk per trade on average when total trades are executed.
11. Current Drawdown - This is important section and i want you to read this carefully. Here draw-down is calculated very differently than what TV shows. TV has access to candle data and calculates draw-down accordingly as per number of trades closed, but here DD is calculated as difference between max profit achieved and current profit. This way you can see how much percentage you are down from max peak of equity at current point in time. You can do back-test of the data and see when peak was achieved and how much your strategy did a draw-down candle by candle.
12. Max Drawdown - This is also calculated differently same as above, current draw-down. Here you can see how much max DD your strategy did from a peak profit of equity. This is not set as max profit percentage is set because you will see single number on display, while idea is to keep it custom. I will explain.
So lets say, your max DD on TV is 30%. Here this is of no use to see Max DD , as some people might want to see what was there max DD 1000 candles back or 10 candle back. So this will show you your max DD from the data you select. TV shows 25000 candle data in a chart if you go back, you can set the counter to 24999 and it will show you max DD as shown on TV, but if you want custom section to show max DD , it is now possible which was not possible before.
Also, now let's say you put DD as 24999 and open a chart of an asset that was listed 1 week ago, now on 1H chart max DD will never show up until you reach 24999 candle in data history, but with this you can now enter a manual number and see the data.
13. Liquidation - This is an interesting feature, so now when your equity balance is less than 0 and your draw-down goes to -100, it will show you where and at what point in time you got liquidated by adding a red background color in the entire section. This is the most fun part of this script, while you can only see max DD on TV.
------------------------------------------------------------------------------
How to Use -
1 word, plug and play. Yes. Actual codes start from line 33.
select overlay=false or remove it from the title in your strategy on first line,
Just copy the codes from line 33 to 103,
then go to end section of your strategy and paste the entire code from line 33 to line 103,
see if you have any duplicate variable, edit it,
Add to chart.
What you see above is very contracted view. Here is how it looks when zoomed in.
imgur.com
----------------------------------------------------------------------------------
Feel free to edit and share and use. If you use it in your scripts, drop me tag. Cheers.
Blackbox (Backtesting version)Blackbox Backtest version is a script with 12 built-in indicators, a list of different conditions you can check/uncheck to enter and exit the market on specific points and 3 different strategies styles.
Use this script to backtest different strategies.
It can't be used to create alerts.
If you found a good strategy and you want to do set alerts too you have to switch to Blackbox Alert version. It's the same script but without the strategy part.
Indicators:
Chaikin Money Flow
Chaikin Money Flow
Chaikin Oscillator
Volume Oscillator
Ichimoku Baseline
SSL
William R%
RSI
Bollinger Bands
ROC
RSI probability (custom)
EMAs
Aroon
ATR
... new indicators very soon
Conditions
Check/uncheck different conditions from setting panel for both entries and exits.
Combine them to create complex strategies and alerts.
This list is constantly updated.
Data Range
Set a data range to backtest.
From Year, Month, Day, Hour, Minute to Year, Month, Day, Hour, Minute.
Order size/settings
ATR Period
TP Multiplier (Used for Take Profit = ATR*TP Multiplier strategies)
SL Multiplier (Used for Stop Loss = ATR*SL Multiplier strategies)
Pips_tp Set a fixed amount of pips for your Take Profit level
Pips_sl Set a fixed amount of pips for your Stop Loss level
Select a strategy style
ATR as TP/SL
Fixed TP/SL
With Exit conditions
Stop Loss for exit conditions
Last update: 13/02/2020