OPEN-SOURCE SCRIPT

Descriptive Backtesting Framework (DBF)

Actualizado
As the name suggests, this is a backtesting framework made to offer full backtesting functionality to any custom indicator in a visually descriptive way.
Any trade taken will be very clear to visualize on the chart and the equity line will be updated live allowing us to use the REPLAY feature to view the strategy performing in real time.
Stops and Targets will also get draw on the chart with labels and tooltips and there will be a table on the top right corner displaying lots of descriptive metrics to measure your strategy's performance.
IF YOU DECIDE TO USE THIS FRAMEWORK, PLEASE READ **EVERYTHING** BELOW

HOW TO USE IT

Step 1 - Insert Your Strategy Indicators:
Inside this framework's code, right at the beginning, you will find a dedicated section where you can manually insert any set of indicators you desire.
Just replace the example code in there with your own strategy indicators.

Step 2 - Specify The Conditions To Take Trades:
After that, there will be another section where you need to specify your strategy's conditions to enter and exit trades.
When met, those conditions will fire the trading signals to the trading engine inside the framework.
If you don't wish to use some of the available signals, please just assign false to the signal.
DO NOT DELETE THE SIGNAL VARIABLES

Step 3 - Specify Entry/Exit Prices, Stops & Targets:
Finally you'll reach the last section where you'll be able to specify entry/exit prices as well as add stops and targets.
On most cases, it's easier and more reliable to just use the close price to enter and exit trades.
If you decide to use the open price instead, please remember to change step 2 so that trades are taken on the open price of the next candle and not the present one to avoid the look ahead bias.
Stops and targets can be set in any way you want.
Also, please don't forget to update the spread. If your broker uses commissions instead of spreads or a combination of both, you'll need to manually incorporate those costs in this step.

And that's it! That's all you have to do.
Below this section you'll now see a sign warning you about not making any changes to the code below.
From here on, the framework will take care of executing the trades and calculating the performance metrics for you and making sure all calculations are consistent.

VISUAL FEATURES:

imagen

Price candles get painted according to the current trade.
They will be blue during long trades, purple on shorts and white when no trade is on.
When the framework receives the signals to start or close a trade, it will display those signals as shapes on the upper and lower limits of the chart:
  • DIAMOND: represents a signal to open a trade, the trade direction is represented by the shape's color;
  • CROSS: means a stop loss was triggered;
  • FLAG: means a take profit was triggered;
  • CIRCLE: means an exit trade signal was fired;


Hovering the mouse over the trade labels will reveal:
  • Asset Quantity;
  • Entry/Exit Prices;
  • Stops & Targets;
  • Trade Profit;
  • Profit As Percentage Of Trade Volume;

**Please note that there's a limit as to how many labels can be drawn on the chart at once.**
If you which to see labels from the beginning of the chart, you'll probably need to use the replay feature.

PERFORMANCE TABLE:

imagen

The performance table displays several performance metrics to evaluate the strategy.
All the performance metrics here are calculated by the framework. It does not uses the oficial pine script strategy tester.
All metrics are calculated in real time. If using the replay feature, they will be updated up to the last played bar.
Here are the available metrics and their definition:
  • INITIAL EQUITY: the initial amount of money we had when the strategy started, obviously...;
  • CURRENT EQUITY: the amount of money we have now. If using the replay feature, it will show the current equity up to the last bar played. The number on it's right side shows how many times our equity has been multiplied from it's initial value;
  • TRADE COUNT: how many trades were taken;
  • WIN COUNT: how many of those trades were wins. The percentage at the right side is the strategy WIN RATE;
  • AVG GAIN PER TRADE: the average percentage gain per trade. Very small values can indicate a fragile strategy that can behave in unexpected ways under high volatility conditions;
  • AVG GAIN PER WIN: the average percentage gain of trades that were profitable;
  • AVG GAIN PER LOSS: the average percentage loss on trades that were not profitable;
  • EQUITY MAX DD: the maximum drawdown experienced by our equity during the entire strategy backtest;
  • TRADE MAX DD: the maximum drawdown experienced by our equity after one single trade;
  • AVG MONTHLY RETURN: the compound monthly return that our strategy was able to create during the backtested period;
  • AVG ANNUAL RETURN: this is the strategy's CAGR (compound annual growth rate);
  • ELAPSED MONTHS: number of months since the backtest started;
  • RISK/REWARD RATIO: shows how profitable the strategy is for the amount of risk it takes. Values above 1 are very good (and rare). This is calculated as follows: (Avg Annual Return) / mod(Equity Max DD). Where mod() is the same as math.abs();


AVAILABLE SETTINGS:

  • SPREAD: specify your broker's asset spread
  • ENABLE LONGS / SHORTS: you can keep both enable or chose to take trades in only one direction
  • MINIMUM BARS CLOSED: to avoid trading before indicators such as a slow moving average have had time to populate, you can manually set the number of bars to wait before allowing trades.
  • INITIAL EQUITY: you can specify your starting equity
  • EXPOSURE: is the percentage of equity you wish to risk per trade. When using stops, the strategy will automatically calculate your position size to match the exposure with the stop distance. If you are not using stops then your trade volume will be the percentage of equity specified here. 100 means you'll enter trades with all your equity and 200 means you'll use a 2x leverage.
  • MAX LEVERAGE ALLOWED: In some situations a short stop distance can create huge levels of leverage. If you want to limit leverage to a maximum value you can set it here.
  • SEVERAL PLOTTING OPTIONS: You'll be able to specify which of the framework visuals you wish to see drawn on the chart.


FRAMEWORK **LIMITATIONS**:

  • When stop and target are both triggered in the same candle, this framework isn't able to enter faster timeframes to check which one was triggered first, so it will take the pessimistic assumption and annul the take profit signal;
  • This framework doesn't support pyramiding;
  • This framework doesn't support both long and short positions to be active at the same time. So for example, if a short signal is received while a long trade is open, the framework will close the long trade and then open a short trade;


FINAL CONSIDERATIONS:

I've been using this framework for a good time and I find it's better to use and easier to analyze a strategy's performance then relying on the oficial pine script strategy tester. However, I CANNOT GUARANTEE IT TO BE BUG FREE.

**PLEASE PERFORM A MANUAL BACKTEST BEFORE USING ANY STRATEGY WITH REAL MONEY**
Notas de prensa
Just a minor updated to avoid confusion.
Changed the standard spread to zero to avoid distortions when the user forgot to update it.
backtestbacktestingChart patterns

Script de código abierto

Siguiendo fielmente el espíritu de TradingView, el autor de este script lo ha publicado en código abierto, permitiendo que otros traders puedan entenderlo y verificarlo. ¡Olé por el autor! Puede utilizarlo de forma gratuita, pero tenga en cuenta que la reutilización de este código en la publicación se rige por las Normas internas. Puede añadir este script a sus favoritos y usarlo en un gráfico.

¿Quiere utilizar este script en un gráfico?


Mateus Rapini
También en:

Exención de responsabilidad