MMI Auto Backtesting StrategyDescription:
A strategy based on ATR with auto-backtesting capabilities, Take Profit and Stop Loss (either Normal or Trailing). It allows you to select ranges of values and step for each parameter, and backtest the strategy on a multitude of input combinations at once. You can alternatively use a constant value for each parameter. The backtesting results strive to be as close as possible to those given by Tradingview Strategy Tester.
The strategy displays a table with results for different input combinations. This has columns showing current input combination as well as the following stats: Net Profit, Number of trades, % of Profitable trades, Profit Factor, Max Drawdown, Max Runup, Average Trade and Average number of bars in a trade.
You can sort the table by any column (including sorting by multiple columns at the same time) to find, for example, input combination that gives highest Net Profit (or, if sorting by multiple columns, to find input combination with the best balance of Net Profit and % of Profitable trades). You can filter by any column as well (or multiple columns at the same time), using logical expressions like "< value", "> value", "<= value", ">= value". And you can use logical expressions like "< value%" for Net Profit, Max Drawdown, Max Runup and Average trade to filter by percentage value. You will see a "↓" symbol in column's header if that column is sorted from Highest to Lowest, a "↑" symbol if it's sorted from Lowest to Highest and a "𐕢" symbol if that column is being filtered.
The table has customisable styles (like text color, background color of cells, etc.), and can show the total number of backtested combinations with the time taken to test them. You can also change Initial Capital and Position Size (either Contracts, Currency or % of Equity).
Parameters:
The following parameters are located in the "INPUTS (USUAL STRATEGY)" group, and control the behaviour of strategy itself (not the auto-backtesting functionality):
- Period: ATR Length
- Multiplier: ATR Multiplier
- DPO: length of the filtering moving average
- SL: stop loss
- TP: take profit
- Use Stop Loss: enable stop loss
- Stop Loss Mode: stop loss mode (either Normal or Trailing)
- Use Take Profit: enable take profit
- Wicks: use high & low price, or close price
The strategy also has various parameters separated by different groups:
- INPUTS (AUTO-BACKTESTING): has the same parameters as the "INPUTS (USUAL STRATEGY)" group, but controls the input combinations for auto-backtesting; all the numeric parameters have 3 values: F/V (from), T (to) and S (step); if the checkbox to the left of F/V parameter is off, the value of F/V will indicate the constant value used for that parameter (if the checkbox is on, the values will be from F/V to T using step S)
- STRATEGY: contains strategy related parameters like Initial Capital and Position Size
- BACKTESTING: allows you to display either Percentage, Absolute or Both values in the table and has checkboxes that allow you to exclude certain columns from the table
- SORTING: allows you to select sorting mode (Highest to Lowest or vice versa) and has checkboxes in case you want to sort by multiple columns at the same time
- FILTERING: has a text field for each column of the strategy where you can type logical expressions to filter the values
- TABLE: contains styling parameters
Many parameters have the "(i)" description marker, so hover over it to see more details.
Problems:
- The script works best on lower timeframes and continuous markets (trades 24/7), in other cases the backtesting results may vary from those that Tradingview shows
- The script shows closest results when Take Profit and Stop Loss are not used
- Max Runup percentage value is often wrong
Limitations:
- As we are limited by the maximum time a script can be running (which is 20s for Free plan and 40s for Paid plans), we can only backtest several hundreds of combinations within that timeframe (though it depends on the parameters, market and timeframe of the chart you use)
Optimizer
Kioseff Trading - AI-Optimized RSIAI-Optimized RSI
Introducing AI-Optimized RSI: a streamlined solution for traders of any skill level seeking to rapidly test and optimize RSI. Capable of analyzing thousands of strategies, this tool cuts through the complexity to identify the most profitable, reliable, or efficient approaches.
Paired with TradingView's native backtesting capabilities, the AI-Optimized RSI learns from historical performance data. Set up is easy for all skill levels, and it makes fine-tuning trading alerts and RSI straightforward.
Features
Purpose : Uncover optimal RSI settings and entry levels with precision. Say goodbye to random guesses and arbitrary indicator use—this tool provides clear direction based on data.
Target Performance : You set the goal, and AI-RSI seeks it out, whether it's maximizing profits, efficient trading, or achieving the highest win rate.
AI-Powered : With intelligent AI recommendations, the tool dynamically fine-tunes your RSI approach, steering you towards ideal strategy performance.
Rapid Testing : Evaluate thousands of RSI strategies.
Dual Direction : Perfect both long and short RSI strategies with equal finesse.
Deep Insights : Access detailed metrics including profit factor, PnL, win rate, trade counts, and more, all within a comprehensive strategy script.
Instant Alerts : Set alerts and trade.
Full Customization : Test and optimize all RSI settings, including cross levels, profit targets and stop losses.
Simulated Execution : Explore the impact of limit orders and other trade types through simulation.
Integrative Capability : Combine your own custom indicators or others from the TradingView community for a personalized optimization experience.
Flexible Timeframes : Set your optimization and backtesting to any date range.
Key Settings
The image above shows explanations for a list of key settings for the optimizer.
Direction : This setting controls trade direction: Long or Short.
Entry Condition : Define RSI entry: Select whether to trigger trades on RSI crossunders or crossovers.
RSI Lengths Range : Choose the range of RSI periods to test and find the best one.The AI will find the best RSI period for you.
RSI Cross Range : Set the range for RSI levels where crosses trigger trade signals. The AI will find the best level for you.
Combinations : Select how many RSI strategies to compare.
Optimization Type : Choose the goal for optimization and the AI: profit, win rate, or efficiency.
Profit Target : Set your profit target with this setting.
Stop Loss : Decide your maximum allowable loss (stop loss) per trade.
Limit Order : Specify whether to include limit orders in the strategy.
Stop Type : Choose your stop strategy: a fixed stop loss or a trailing stop.
How to: Find the best RSI for trading
It's important to remember that merely having the AI-Optimized RSI on your chart doesn't automatically provide you with the best strategy. You need to follow the AI's guidance through an iterative process to discover the optimal RSI settings and strategy.
1.Starting Your Strategy Setup
Begin by deciding your goals for each trade: your profit target and stop loss. You'll also choose how to manage your stops – whether they stay put (fixed) or move with the price (trailing), and whether you want to exit trades at a specific price (limit orders). Keep the initial settings for RSI lengths and cross ranges at their default to give the tool a broad testing field. The AI's guidance will refine these settings to pinpoint the most effective ones through a process of comprehensive testing.
The image above shows our chart prior to any optimization efforts.
Note: the settings shown above in the key settings section will be used to start our demonstration.
2. Follow AI’s suggestions
Optimization Prompt: After loading your strategy, the indicator will prompt you to change the RSI length range and RSI level range to a better performing range.
Continue changing the RSI length range and RSI level range to match the indicator's suggestions until "Best Found" is displayed!
The image above shows results after we applied the tool’s suggestions. New suggestions have appeared, and we will continue to apply them.
Continue to adjust settings as recommended by the optimizer. If no better options are found, the optimizer will suggest increasing the number of combinations. Repeat this process until the optimizer indicates that the optimal setting has been identified.
Success! With the "Best Found" notification, an optimized RSI is now active. The AI will keep refining the strategy based on ongoing performance, ensuring continuous optimization.
AI Mode
AI Mode incorporates Heuristic-Based Adaptive Learning to fine-tune trading strategies in a continuous manner. This feature consists of two main components:
Heuristic-Based Decision Making: The algorithm evaluates multiple RSI-based trading strategies using specific metrics such as Profit and Loss (PNL), Win Rate, and Most Efficient Profit. These metrics act as heuristics to assist the algorithm in identifying suitable strategies for trade execution.
Online Learning: The algorithm updates the performance evaluations of each strategy based on incoming market data. This enables the system to adapt to current market conditions.
Incorporating both heuristic-based decision-making and online learning, this feature aims to provide a framework for trading strategy optimization.
Settings
AI Mode Aggressiveness:
Description: The "AI Mode Aggressiveness" setting allows you to fine-tune the AI's trading behavior. This setting ranges from “Low” to “High”, with “High” indicating a more assertive trading approach.
Functionality: This feature filters trading strategies based on a proprietary evaluation method. A higher setting narrows down the strategies that the AI will consider, leaning towards more aggressive trading. Conversely, a lower setting allows for a more conservative approach by broadening the pool of potential strategies.
Adaptive Learning Aggressiveness:
Description: When Adaptive Learning is enabled, the "Adaptive Learning Aggressiveness" setting controls how dynamically the AI adapts to market conditions using selected performance metrics.
Functionality: This setting impacts the AI's responsiveness to shifts in strategy performance. By adjusting this setting, you can control how quickly the AI moves away from strategies that may have been historically successful but are currently underperforming, towards strategies that are showing current promise.
Optimization
Trading system optimization is immensely advantageous when executed with prudence.
Technical-oriented, mechanical trading systems work when a valid correlation is methodical to the extent that an objective, precisely-defined ruleset can consistently exploit it. If no such correlation exists, or a technical-oriented system is erroneously designed to exploit an illusory correlation (absent predictive utility), the trading system will fail.
Evaluate results practically and test parameters rigorously after discovery. Simply mining the best-performing parameters and immediately trading them is unlikely a winning strategy. Put as much effort into testing strong-performing parameters and building an accompanying system as you would any other trading strategy. Automated optimization involves curve fitting - it's the responsibility of the trader to validate a replicable sequence or correlation and the trading system that exploits it.
Kioseff Trading - AI-Optimized Supertrend
AI-Optimized Supertrend
Introducing AI-Optimized Supertrend: a streamlined solution for traders of any skill level seeking to rapidly test and optimize Supertrend. Capable of analyzing thousands of strategies, this tool cuts through the complexity to identify the most profitable, reliable, or efficient approaches.
Paired with TradingView's native backtesting capabilities, the AI-Optimized Supertrend learns from historical performance data. Set up is easy for all skill levels, and it makes fine-tuning trading alerts and Supertrend straightforward.
Features
Rapid Supertrend Strategy Testing : Quickly evaluate thousands of Supertrend strategies to find the most effective ones.
AI-Assisted Optimization : Leverage AI recommendations to fine-tune strategies for superior results.
Multi-Objective Optimization : Prioritize Supertrend based on your preference for the highest win rate, maximum profit, or efficiency.
Comprehensive Analytics : The strategy script provides an array of statistics such as profit factor, PnL, win rate, trade counts, max drawdown, and an equity curve to gauge performance accurately.
Alerts Setup : Conveniently set up alerts to be notified about critical trade signals or changes in performance metrics.
Versatile Stop Strategies : Experiment with profit targets, trailing stops, and fixed stop losses.
Binary Supertrend Exploration : Test binary Supertrend strategies.
Limit Orders : Analyze the impact of limit orders on your trading strategy.
Integration with External Indicators : Enhance strategy refinement by incorporating custom or publicly available indicators from TradingView into the optimization process.
Key Settings
The image above shows explanations for a list of key settings for the optimizer.
Set the Factor Range Limits : The AI suggests optimal upper and lower limits for the Factor range, defining the sensitivity of the Supertrend to price fluctuations. A wider range tests a greater variety, while a narrower range focuses on fine-tuning.
Adjust the ATR Range : Use the AI's recommendations to establish the upper and lower bounds for the Average True Range (ATR), which influences the Supertrend's volatility threshold.
ATR Flip : This option lets you interchange the order of ATR and Factor values to quicky test different sequences, giving you the flexibility to explore various combinations and their impact on the Supertrend indicator's performance.
Strategies Evaluated : Adjust this setting to determine how many Supertrend strategies you want to assess and compare.
Enable AI Mode : Turn this feature on to allow the AI to determine and employ the optimal Supertrend strategy with the desired performance metric, such as the highest win rate or maximum profitability.
Target Metric : Adjust this to direct the AI towards optimizing for maximum profit, top win rates, or the most efficient profits.
AI Mode Aggressiveness : Set how assertively the AI pursues the chosen performance goal, such as highest profit or win rate.
Strategy Direction : Choose to focus the AI's testing and optimization on either long or short Supertrend strategies.
Stop Loss Type : Specify the stop loss approach for optimization—fixed value, a trailing stop, or Supertrend direction changes.
Limit Order : Decide if you want to execute trades using limit orders for setting your profit targets, stop losses, or apply them to both.
Profit Target : Define your desired profit level when using either a fixed stop loss or a trailing stop.
Stop Loss : Define your desired stop loss when using either a fixed stop loss or a trailing stop.
How to: Find the best Supertrend for trading
It's important to remember that merely having the AI-Optimized Supertrend on your chart doesn't automatically provide you with the best strategy. You need to follow the AI's guidance through an iterative process to discover the optimal Supertrend settings and strategy.
Optimizing Supertrend involves adjusting two key parameters: the Factor and the Average True Range (ATR). These parameters significantly influence the Supertrend indicator's sensitivity and responsiveness to price movements.
Factor : This parameter multiplies the ATR to determine the distance of the Supertrend line from the price. Higher values will create a wider band, potentially leading to fewer trade signals, while lower values create a narrower band, which may result in more signals but also more noise.
ATR (Average True Range) : ATR measures market volatility. By using the ATR, the Supertrend adapts to changing market volatility; a higher ATR value means a more volatile market, so the Supertrend adjusts accordingly.
During the optimization process, these parameters are systematically varied to determine the combination that yields the best performance based on predefined criteria such as profitability, win rate, or risk management efficiency. The optimization aims to find the optimal Factor and ATR settings.
1.Starting Your Strategy Setup
Begin by deciding your goals for each trade: your profit target and stop loss, or if all trades exit when Supertrend changes direction. You'll also choose how to manage your stops – whether they stay put (fixed) or move with the price (trailing), and whether you want to exit trades at a specific price (limit orders). Keep the initial settings for Supertrend Factor Range and Supertrend ATR Range at their default to give the tool a broad testing field. The AI's guidance will refine these settings to pinpoint the most effective ones through a process of comprehensive testing.
Demonstration Start: We'll begin with the settings outlined in the key settings section, using Supertrend's direction change to the downside as our exit signal for all trades.
2. Continue applying the AI’s suggestions
Keep updating your optimization settings based on the AI's recommendations. Proceed with this iterative optimization until the "Best Found" message is displayed, signaling that the most effective strategy has been identified.
While following the AI's suggestions, we've been prompted with a new suggestion: increase the
number of strategies evaluated. Keep following the AI's new suggestions to evaluate more strategies. Do this until the "Best Found" message shows up.
Success! We continued to follow the AI’s suggestions until “Best Found” was indicated!
AI Mode
AI Mode incorporates Heuristic-Based Adaptive Learning to fine-tune trading strategies in a continuous manner. This feature consists of two main components:
Heuristic-Based Decision Making: The algorithm evaluates multiple Supertrend-based trading strategies using metrics such as Profit and Loss (PNL), Win Rate, and Most Efficient Profit. These metrics act as heuristics to assist the algorithm in identifying suitable strategies for trade execution.
Online Learning: The algorithm updates the performance evaluations of each strategy based on incoming market data. This enables the system to adapt to current market conditions.
Incorporating both heuristic-based decision-making and online learning, this feature aims to provide a framework for trading strategy optimization.
AI Mode Settings
AI Mode Aggressiveness:
Description: The "AI Mode Aggressiveness" setting allows you to fine-tune the AI's trading behavior. This setting ranges from “Low” to “High”, with “High” indicating a more assertive trading approach.
Functionality: This feature filters trading strategies based on a proprietary evaluation method. A higher setting narrows down the strategies that the AI will consider, leaning towards more aggressive trading. Conversely, a lower setting allows for a more conservative approach by broadening the pool of potential strategies.
Optimization
Trading system optimization is immensely advantageous when executed with prudence.
Technical-oriented, mechanical trading systems work when a valid correlation is methodical to the extent that an objective, precisely-defined ruleset can consistently exploit it. If no such correlation exists, or a technical-oriented system is erroneously designed to exploit an illusory correlation (absent predictive utility), the trading system will fail.
Evaluate results practically and test parameters rigorously after discovery. Simply mining the best-performing parameters and immediately trading them is unlikely a winning strategy. Put as much effort into testing strong-performing parameters and building an accompanying system as you would any other trading strategy. Automated optimization involves curve fitting - it's the responsibility of the trader to validate a replicable sequence or correlation and the trading system that exploits it.
Optimizer ~ Beta 0.1 | Belfort TradersOptimizer
The Optimizer backtests the maximum amount of moving averages which can be possible created ((max amount of bars / 2)-1) and compares them all with one another to then plot the most profitable strategy.
Current Achievement:
-> Get it to work, make it work with 106 different moving averages. ==> Beta 0.1
Roadmap:
0.15 Basic Comparison of 5k moving averages <= 07.06.22
0.2 Risk Management Basics <= 07.06.22
0.3 Finding the most profitable timeframe <= 07.06.22
0.4 Testing the limits of Tradingview <= 14.06.22
0.5 Complex array sorting list, comparing 1k moving averages, taking the most profitable out, going to the next list ==> Bypassing calculation limit by doing that. <= 14.06.22
0.6 Volatility adjusted moving averages <= 14.06.22
==> Find more likely profitable moving averages, run those first -> Increase efficiency
0.7 Add second filter (Either most profitable strategy or most reliable strategy) ==> Order Frequency Ratio <= 14.06.22
0.8 Complex Risk Management <= 14.06.22
0.9 Reliability Ratio weekly volatility average filter used as a protective filter if current weekly volume is drastically different from the past's weekly volatility average with fractal patterns
<= 21.06.22
1.0 Finished Optimizer
Portfolio Management for this Performance:
Initial Capital: 20000 USD
Risk per Trade: 10% of capital
Commission: 0.01%
Slippage: 4 ticks
Position size optimizer RNR_0// 1. When market volatility is severe, the use of equal weight systems is eliminated.
// 2. It is a bad strategy to concentrate bets since they drive the short position, which ultimately influences the whole book of trade.
// 3. Expect your short positions to get squeezed by at least 10% during the next five trading days.
// 4. When there are bear markets, the correlation goes to 1. Allow for the fact that both Longs and Shorts will go against you at the same time.
// 5. Unprofitable trades increase in magnitude rapidly.
// 6. Unlike in an up-trending market, there are no 2-3 wins. Winners shrink and contribute less. So, there is an opposite tendency toward oversized positions.
// 7. In contrast to a bull market, in contrast to the long. The winners shrink in size and contribute less. As a result, there is an inverse trend toward oversized positions.
// 9. The winners shrink in size, while the losers grow exponentially The challenge is to size positions in such a manner that they contribute favorably when successful but do not completely obliterate performance when unsuccessful.
Randomly select enter and exit
```
longCondition = bar_index % 33 == 0
if (longCondition and afterStartDate )
strategy.entry("buy", strategy.long, qty = qty)
shortCondition = bar_index % 44 == 0
if (shortCondition)
strategy.close("buy")
```