OPEN-SOURCE SCRIPT

*Auto Backtest & Optimize Engine

471
Full-featured Engine for Automatic Backtesting and parameter optimization. Allows you to test millions of different combinations of stop-loss and take profit parameters, including on any connected indicators.

⭕️ Key Futures
  • Quickly identify the optimal parameters for your strategy.
  • Automatically generate and test thousands of parameter combinations.
  • A simple Genetic Algorithm for result selection.
  • Saves time on manual testing of multiple parameters.
  • Detailed analysis, sorting, filtering and statistics of results.
  • Detailed control panel with many tooltips.
  • Display of key metrics: Profit, Win Rate, etc..
  • Comprehensive Strategy Score calculation.
  • In-depth analysis of the performance of different types of stop-losses.
  • Possibility to use to calculate the best Stop-Take parameters for your position.
  • Ability to test your own functions and signals.
  • Customizable visualization of results.
  • Flexible Stop-Loss Settings:
    • Auto ━ Allows you to test all types of Stop Losses at once(listed below).
    • S.VOLATY ━ Static stop based on volatility (Fixed, ATR, STDEV).
    • Trailing ━ Classic trailing stop following the price.
    • Fast Trail ━ Accelerated trailing stop that reacts faster to price movements.
    • Volatility ━ Dynamic stop based on volatility indicators.
    • Chandelier ━ Stop based on price extremes.
    • Activator ━ Dynamic stop based on SAR.
    • MA ━ Stop based on moving averages (9 different types).
    • SAR ━ Parabolic SAR (Stop and Reverse).
  • Advanced Take-Profit Options:
    • R:R: Risk/Reward ━ sets TP based on SL size.
    • T.VOLATY ━ Calculation based on volatility indicators (Fixed, ATR, STDEV).
  • Testing Modes:
    • Stops ━ Cyclical stop-loss testing
    • Pivot Point Example ━ Example of using pivot points
    • External Example ━ Built-in example how test functions with different parameters
    • External Signal ━ Using external signals


⭕️ Usage

━ First Steps:
  1. When opening, select any point on the chart. It will not affect anything until you turn on Manual Start mode (more on this below).
  2. The chart will immediately show the best results of the default Auto mode. You can switch Part's to try to find even better results in the table.
  3. Now you can display any result from the table on the chart by entering its ID in the settings.
  4. Repeat steps 3-4 until you determine which type of Stop Loss you like best. Then set it in the settings instead of Auto mode.
    cuplikan
    * Example: I flipped through 14 parts before I liked the first result and entered its ID so I could visually evaluate it on the chart.
  5. Then select the stop loss type, choose it in place of Auto mode and repeat steps 3-4 or immediately follow the recommendations of the algorithm.
  6. Now the Genetic Algorithm at the bottom right will prompt you to enter the Parameters you need to search for and select even better results.
  7. Parameters must be entered All at once before they are updated. Enter recommendations strictly in fields with the same names.
  8. Repeat steps 5-6 until there are approximately 10 Part's left or as you like. And after that, easily pour through the remaining Parts and select the best parameters.

cuplikan
━ Example of the finished result.
cuplikan
━ Example of use with Takes
You can also test at the same time along with Take Profit. In this example, I simply enabled Risk/Reward mode and immediately specified in the TP field Maximum RR, Minimum RR and Step. So in this example I can test (3-1) / 0.1 = 20 Takes of different sizes. There are additional tips in the settings.

* Soon you will start to understand how the system works and things will become much easier.
* If something doesn't work, just reset the engine settings and start over again.
* Use the tips I have left in the settings and on the Panel.

━ Details:
  • Sort ━ Sorting results by Score, Profit, Trades, etc..
  • Filter ━ Filtring results by Score, Profit, Trades, etc..
  • Trade Type ━ Ability to disable Long\Short but only from statistics.
  • BackWin ━ Backtest Window Number of Candle the script can test.
  • Manual Start ━ Enabling it will allow you to call a Stop from a selected point. which you selected when you started the engine.
    * If you have a real open position then this mode can help to save good Stop\Take for it.
  • 1 - 9 Сheckboxs ━ Allow you to disable any stop from Auto mode.
  • Ex Source - Allow you to test Stops/Takes from connected indicators.
    Connection guide:
    * Format the signal for your indicator in a similar style and then select it in Ex Source.


⭕️ How it Works
Hypothesis of Uniform Distribution of Rare Elements After Mixing.

* I'd like to attach more details to My hypothesis but it won't be very relevant here. Since this is a whole separate topic, I will leave the minimum part for understanding the engine.


Practical Application
To apply this hypothesis, I needed a way to generate and thoroughly mix numerous possible combinations. Within Pine, generating over 100,000 combinations presents significant challenges, and storing millions of combinations requires excessive resources.

I developed an efficient mechanism that generates combinations in random order to address these limitations. While conventional methods often produce duplicates or require generating a complete list first, my approach guarantees that the first 10% of possible combinations are both unique and well-distributed. Based on my hypothesis, this sampling is sufficient to determine optimal testing parameters.

Most generators and randomizers fail to accommodate both my hypothesis and Pine's constraints. My solution utilizes a simple Linear Congruential Generator (LCG) for pseudo-randomization, enhanced with prime numbers to increase entropy during generation. I pre-generate the entire parameter range and then apply systematic mixing. This approach, combined with a hybrid combinatorial array-filling technique with linear distribution, delivers excellent generation quality.

My engine can efficiently generate and verify 300 unique combinations per batch. Based on the above, to determine optimal values, only 10-20 Parts need to be manually scrolled through to find the appropriate value or range, eliminating the need for exhaustive testing of millions of parameter combinations.

For the Score statistic I applied all the same, generated a range of Weights, distributed them randomly for each type of statistic to avoid manual distribution.
Score ━ based on Trade, Profit, WinRate, Profit Factor, Drawdown, Sharpe & Sortino & Omega & Calmar Ratio.

⭕️ Notes
For attentive users, a little tricks :)
  1. To save time, switch parts every 3 seconds without waiting for it to load. After 10-20 parts, stop and wait for loading. If the pause is correct, you can switch between the rest of the parts without loading, as they will be cached. This used to work without having to wait for a pause, but now it does slower. This will save a lot of time if you are going to do a deeper backtest.
  2. Sometimes you'll get the error “The scripts take too long to execute.”
    For a quick fix you just need to switch the TF or Ticker back and forth and most likely everything will load.
    The error appears because of problems on the side of the site because the engine is very heavy. It can also appear if you set too long a period for testing in BackWin or use a heavy indicator for testing.
  3. Manual Start - Allow you to Start you Result from any point. Which in turn can help you choose a good stop-stick for your real position.
    cuplikan


* It took me half a year from idea to current realization. This seems to be one of the few ways to build something automatic in backtest format and in this particular Pine environment. There are already better projects in other languages, and they are created much easier and faster because there are no limitations except for personal PC. If you see solutions to improve this system I would be glad if you share the code. At the moment I am tired and will continue him not soon.

Also You can use my previosly big Backtest project with more manual settings(updated soon)
*Backtesting System

Pernyataan Penyangkalan

Informasi dan publikasi tidak dimaksudkan untuk menjadi, dan bukan merupakan saran keuangan, investasi, perdagangan, atau rekomendasi lainnya yang diberikan atau didukung oleh TradingView. Baca selengkapnya di Persyaratan Penggunaan.