[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.
Strategytemplate
[fpemehd] Strategy TemplateHello Guys! Nice to meet you all!
This is my fourth script!
This is the Strategy Template for traders who wants to make their own strategy.
I made this based on the open source strategies by jason5480, kevinmck100, myncrypto. Thank you All!
### StopLoss
1. Can Choose Stop Loss Type: Percent, ATR, Previous Low / High.
2. Can Chosse inputs of each Stop Loss Type.
### Take Profit
1. Can set Risk Reward Ratio for Take Profit.
- To simplify backtest, I erased all other options except RR Ratio.
- You can add Take Profit Logic by adding options in the code.
2. Can set Take Profit Quantity.
### Risk Manangement
1. Can choose whether to use Risk Manangement Logic.
- This controls the Quantity of the Entry.
- e.g. If you want to take 3% risk per trade and stop loss price is 6% below the long entry price,
then 50% of your equity will be used for trade.
2. Can choose How much risk you would take per trade.
### Plot
1. Added Labels to check the data of entry / exit positions.
2. Changed and Added color different from the original one. (green: #02732A, red: #D92332, yellow: #F2E313)
Strategy Template - V2This is an educational script created to demonstrate few basic building blocks of a trend based strategy and how to achieve different entry and exit types. My initial intention was to create a comprehensive strategy template which covers all the aspects of strategy. But, ended up creating fully fledged strategy based on trend following.
This is an enhancement on Strategy-Template But this script is comparitively more complex. Hence I decided to create new version instead of updating the existing one.
Lets dive deep.
SIMPLE COMPONENTS OF TREND FOLLOWING STRATEGY
TREND BIAS - This defines the direction of trend. Idea is not to trade against the trend direction. If the bias is bullish, look for long opportunities and if bias is bearish, look for short opportunities. Stay out of the market when the bias is neutral.
Often, trend bias is determined based on longer timeframe conditions. Example - 200 Moving Average, Higher timeframe moving averages, Higher timeframe high-lows etc. can be used for determining the trend bias.
In this script, I am using Weekly donchian channels combined with daily donchian channels to define trend bias.
Long Bias - 40 Day donchian channel sits completely in upper portion of 40 Week dochnial channel.
Short Bias - 40 Day donchian channel sits completely in lower portion of 40 Week donchian channel.
ENTRY CONDITION - Entry signals are generated only in the direction of bias. Hence, when in LongBias, we only get Long signals and when in short bias, we only get short signals.
In our case, when in Long Bias - if price hits 40 day high for the first time, this creates our long entry signal. Similarly when in Short Bias , price hitting 40 day low will create signal for going short. Since we do not take trades opposite to trend, no entry conditions are formed when price hits 40 day high in Short Bias or 40 day low in Long Bias.
EXIT CONDITION - Exit conditions are formed when we get signals of trend failure.
In our case, when in long trade, price hitting 40 day low creates exit signal. Similarly when in short trade price hitting 40 day high creates exit signal for short trade.
DIFFERENT TYPES OF ENTRY AND EXIT
In this script, I have tried to demonstrate different entry and exit types.
Entry types
Market - Enter immediately when entry signal is received. That is, in this case when price crossover over high in long bias and crosses under low in short bias
Stop - This method includes estimating at what level new highs are made and creating a stop buy order at that level. This way, we do not miss if the break out is stronger. But, susciptible to fail during fakeouts.
Limit - This method includes executing a limit order to buy at lower price or sell at higher price. In trend following methods, downside of limit order is when there is genuine breakout, these limit orders may not hit and during trend failures the limit orders are likely to hit and go straight to stop.
Stop-Limit - this is same as stop order but will also place a limit condition to avoid buying on overextended breakout or with lots of slippage.
Exit types
Market - whether to keep the existing trade running or whether to close it is determined after close of each bar and exit orders are executed manually upon receiving exit signal.
Stop - We place stop loss orders beforehand when there is a trade in place. This can help in avoiding big movements against trade within bar. But, this may also stop on false signals or fakeouts.
Take profit
Stop - No take profits are configured.
Target - 30% of the positions are closed when take profit levels are hit. Take profit levels are defined by risk reward.
USING THE CODE AS TEMPLATE
As mentioned earlier, I intended to create a fully fledged strategy template. But, ended up creating a fully fledged stratgy. However, you can take some part of this code and use it to start your own strategy. Will explain what all things can be adopted without worrying about the strategy implementation within
Strategy definition : This can be copied as is and just change the title of strategy. This defines some of the commonly used parameters of strategy which can help with close to realistic backtesting results for your coded strategy and comparison with buy and hold.
Generic Strategy Parameters : The parameter which defines controlling alllowed trade direction and trading window are present here. This again can be copied as is and variable inDateRange can be directly used in entry conditions.
Generic Methods : f_getMovingAverage and f_secureSecurity are handy and can be used as is. atr method provideded by pine gives you ATR based on RMA. If you want SMA or any other moving average based ATR, you can use the method f_getCustomAtr
Trade Statements : This section has all types of trading instructions which includes market/stop/limit/stop-limit type of entries and exits and take profit statements. You can adopt the type of entry you are interested in and change when condition to suit your strategy.
Trade conditions and levels : This section is required. But, cannot be copied. All the trade logic goes here which also sets parameters which are used in when of Trade Statements.
Hope this helps.