Fourier For Loop [BackQuant]Fourier For Loop
PLEASE Read the following, as understanding an indicator's functionality is essential before integrating it into a trading strategy. Knowing the core logic behind each tool allows for a sound and strategic approach to trading.
Introducing BackQuant's Fourier For Loop (FFL) — a cutting-edge trading indicator that combines Fourier transforms with a for-loop scoring mechanism. This innovative approach leverages mathematical precision to extract trends and reversals in the market, helping traders make informed decisions. Let's break down the components, rationale, and potential use-cases of this indicator.
Understanding Fourier Transform in Trading
The Fourier Transform decomposes price movements into their frequency components, allowing for a detailed analysis of cyclical behavior in the market. By transforming the price data from the time domain into the frequency domain, this indicator identifies underlying patterns that traditional methods may overlook.
In this script, Fourier transforms are applied to the specified calculation source (defaulted to HLC3). The transformation yields magnitude values that can be used to score market movements over a defined range. This scoring process helps uncover long and short signals based on relative strength and trend direction.
Why Use Fourier Transforms?
Fourier Transforms excel in identifying recurring cycles and smoothing noisy data, making them ideal for fast-paced markets where price movements may be erratic. They also provide a unique perspective on market volatility, offering traders additional insights beyond standard indicators.
Calculation Logic: For-Loop Scoring Mechanism
The For Loop Scoring mechanism compares the magnitude of each transformed point in the series, summing the results to generate a score. This score forms the backbone of the signal generation system.
Long Signals: Generated when the score surpasses the defined long threshold (default set at 40). This indicates a strong bullish trend, signaling potential upward momentum.
Short Signals: Triggered when the score crosses under the short threshold (default set at -10). This suggests a bearish trend or potential downside risk.'
Thresholds & Customization
The indicator offers customizable settings to fit various trading styles:
Calculation Periods: Control how many periods the Fourier transform covers.
Long/Short Thresholds: Adjust the sensitivity of the signals to match different timeframes or risk preferences.
Visualization Options: Traders can visualize the thresholds, change the color of bars based on trend direction, and even color the background for enhanced clarity.
Trading Applications
This Fourier For Loop indicator is designed to be versatile across various market conditions and timeframes. Some of its key use-cases include:
Cycle Detection: Fourier transforms help identify recurring patterns or cycles, giving traders a head-start on market direction.
Trend Following: The for-loop scoring system helps confirm the strength of trends, allowing traders to enter positions with greater confidence.
Risk Management: With clearly defined long and short signals, traders can manage their positions effectively, minimizing exposure to false signals.
Final Note
Incorporating this indicator into your trading strategy adds a layer of mathematical precision to traditional technical analysis. Be sure to adjust the calculation start/end points and thresholds to match your specific trading style, and remember that no indicator guarantees success. Always backtest thoroughly and integrate the Fourier For Loop into a balanced trading system.
Thus following all of the key points here are some sample backtests on the 1D Chart
Disclaimer: Backtests are based off past results, and are not indicative of the future .
INDEX:BTCUSD
INDEX:ETHUSD
BINANCE:SOLUSD
Backtest
Interest Rate Trading (Manually Added Rate Decisions) [TANHEF]Interest Rate Trading: How Interest Rates Can Guide Your Next Move.
How were interest rate decisions added?
All interest rate decision dates were manually retrieved from the 'Record of Policy Actions' and 'Minutes of Actions' on the Federal Reserve's website due to inconsistent dates from other sources. These were manually added as Pine Script currently only identifies rate changes, not pauses.
█ Simple Explanation:
This script is designed for analyzing and backtesting trading strategies based on U.S. interest rate decisions which occur during Federal Open Market Committee (FOMC) meetings, to make trading decisions. No trading strategy is perfect, and it's important to understand that expectations won't always play out. The script leverages historical interest rate changes, including increases, decreases, and pauses, across multiple economic time periods from 1971 to the present. The tool integrates two key data sources for interest rates—USINTR and FEDFUNDS—to support decision-making around rate-based trades. The focus is on identifying opportunities and tracking trades driven by interest rate movements.
█ Interest Rate Decision Sources:
As noted above, each decision date has been manually added from the 'Record of Policy Actions' and 'Minutes of Actions' documents on the Federal Reserve's website. This includes +50 years of more than 600 rate decisions.
█ Interest Rate Data Sources:
USINTR: Reflects broader U.S. interest rate trends, including Treasury yields and various benchmarks. This is the preferred option as it corresponds well to the rate decision dates.
FEDFUNDS: Tracks the Federal Funds Rate, which is a more specific rate targeted by the Federal Reserve. This does not change on the exact same days as the rate decisions that occur at FOMC meetings.
█ Trade Criteria:
A variety of trading conditions are predefined to suit different trading strategies. These conditions include:
Increase/Decrease: Standard rate increases or decreases.
Double/Triple Increase/Decrease: A series of consecutive changes.
Aggressive Increase/Decrease: Rate changes that exceed recent movements.
Pause: Identification of no changes (pauses) between rate decisions, including double or triple pauses.
Complex Patterns: Combinations of pauses, increases, or decreases, such as "Pause after Increase" or "Pause or Increase."
█ Trade Execution and Exit:
The script allows automated trade execution based on selected criteria:
Auto-Entry: Option to enter trades automatically at the first valid period.
Max Trade Duration: Optional exit of trades after a specified number of bars (candles).
Pause Days: Minimum duration (in days) to validate rate pauses as entry conditions. This is especially useful for earlier periods (prior to the 2000s), where rate decisions often seemed random compared to the consistency we see today.
█ Visualization:
Several visual elements enhance the backtesting experience:
Time Period Highlighting: Economic time periods are visually segmented on the chart, each with a unique color. These periods include historical phases such as "Stagflation (1971-1982)" and "Post-Pandemic Recovery (2021-Present)".
Trade and Holding Results: Displays the profit and loss of trades and holding results directly on the chart.
Interest Rate Plot: Plots the interest rate movements on the chart, allowing for real-time tracking of rate changes.
Trade Status: Highlights active long or short positions on the chart.
█ Statistics and Criteria Display:
Stats Table: Summarizes trade results, including wins, losses, and draw percentages for both long and short trades.
Criteria Table: Lists the selected entry and exit criteria for both long and short positions.
█ Economic Time Periods:
The script organizes interest rate decisions into well-defined economic periods, allowing traders to backtest strategies specific to historical contexts like:
(1971-1982) Stagflation
(1983-1990) Reaganomics and Deregulation
(1991-1994) Early 1990s (Recession and Recovery)
(1995-2001) Dot-Com Bubble
(2001-2006) Housing Boom
(2007-2009) Global Financial Crisis
(2009-2015) Great Recession Recovery
(2015-2019) Normalization Period
(2019-2021) COVID-19 Pandemic
(2021-Present) Post-Pandemic Recovery
█ User-Configurable Inputs:
Rate Source Selection: Choose between USINTR or FEDFUNDS as the primary interest rate source.
Trade Criteria Customization: Users can select the criteria for long and short trades, specifying when to enter or exit based on changes in the interest rate.
Time Period: Select the time period that you want to isolate testing a strategy with.
Auto-Entry and Pause Settings: Options to automatically enter trades and specify the number of days to confirm a rate pause.
Max Trade Duration: Limits how long trades can remain open, defined by the number of bars.
█ Trade Logic:
The script manages entries and exits for both long and short trades. It calculates the profit or loss percentage based on the entry and exit prices. The script tracks ongoing trades, dynamically updating the profit or loss as price changes.
█ Examples:
One of the most popular opinions is that when rate starts begin you should sell, then buy back in when rate cuts stop dropping. However, this can be easily proven to be a difficult task. Predicting the end of a rate cut is very difficult to do with the the exception that assumes rates will not fall below 0.25%.
2001-2009
Trade Result: +29.85%
Holding Result: -27.74%
1971-2024
Trade Result: +533%
Holding Result: +5901%
█ Backtest and Real-Time Use:
This backtester is useful for historical analysis and real-time trading. By setting up various entry and exit rules tied to interest rate movements, traders can test and refine strategies based on real historical data and rate decision trends.
This powerful tool allows traders to customize strategies, backtest them through different economic periods, and get visual feedback on their trading performance, helping to make more informed decisions based on interest rate dynamics. The main goal of this indicator is to challenge the belief that future events must mirror the 2001 and 2007 rate cuts. If everyone expects something to happen, it usually doesn’t.
Descriptive Backtesting Framework (DBF)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:
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:
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**
Filtered MACD with Backtest [UAlgo]The "Filtered MACD with Backtest " indicator is an advanced trading tool designed for the TradingView platform. It combines the Moving Average Convergence Divergence (MACD) with additional filters such as Moving Average (MA) and Average Directional Index (ADX) to enhance trading signals. This indicator aims to provide more reliable entry and exit points by filtering out noise and confirming trends. Additionally, it includes a comprehensive backtesting module to simulate trading strategies and assess their performance based on historical data. The visual backtest module allows traders to see potential trades directly on the chart, making it easier to evaluate the effectiveness of the strategy.
🔶 Customizable Parameters :
Price Source Selection: Users can choose their preferred price source for calculations, providing flexibility in analysis.
Filter Parameters:
MA Filter: Option to use a Moving Average filter with types such as EMA, SMA, WMA, RMA, and VWMA, and a customizable length.
ADX Filter: Option to use an ADX filter with adjustable length and threshold to determine trend strength.
MACD Parameters: Customizable fast length, slow length, and signal smoothing for the MACD indicator.
Backtest Module:
Entry Type: Supports "Buy and Sell", "Buy", and "Sell" strategies.
Stop Loss Types: Choose from ATR-based, fixed point, or X bar high/low stop loss methods.
Reward to Risk Ratio: Set the desired take profit level relative to the stop loss.
Backtest Visuals: Display entry, stop loss, and take profit levels directly on the chart with
colored backgrounds.
Alerts: Configurable alerts for buy and sell signals.
🔶 Filtered MACD : Understanding How Filters Work with ADX and MA
ADX Filter:
The Average Directional Index (ADX) measures the strength of a trend. The script calculates ADX using the user-defined length and applies a threshold value.
Trading Signals with ADX Filter:
Buy Signal: A regular MACD buy signal (crossover of MACD line above the signal line) is only considered valid if the ADX is above the set threshold. This suggests a stronger uptrend to potentially capitalize on.
Sell Signal: Conversely, a regular MACD sell signal (crossunder of MACD line below the signal line) is only considered valid if the ADX is above the threshold, indicating a stronger downtrend for potential shorting opportunities.
Benefits: The ADX filter helps avoid whipsaws or false signals that might occur during choppy market conditions with weak trends.
MA Filter:
You can choose from various Moving Average (MA) types (EMA, SMA, WMA, RMA, VWMA) for the filter. The script calculates the chosen MA based on the user-defined length.
Trading Signals with MA Filter:
Buy Signal: A regular MACD buy signal is only considered valid if the closing price is above the MA value. This suggests a potential uptrend confirmed by the price action staying above the moving average.
Sell Signal: Conversely, a regular MACD sell signal is only considered valid if the closing price is below the MA value. This suggests a potential downtrend confirmed by the price action staying below the moving average.
Benefits: The MA filter helps identify potential trend continuation opportunities by ensuring the price aligns with the chosen moving average direction.
Combining Filters:
You can choose to use either the ADX filter, the MA filter, or both depending on your strategy preference. Using both filters adds an extra layer of confirmation for your signals.
🔶 Backtesting Module
The backtesting module in this script allows you to visually assess how the filtered MACD strategy would have performed on historical data. Here's a deeper dive into its features:
Backtesting Type: You can choose to backtest for buy signals only, sell signals only, or both. This allows you to analyze the strategy's effectiveness in different market conditions.
Stop-Loss Types: You can define how stop-loss orders are placed:
ATR (Average True Range): This uses a volatility measure (ATR) multiplied by a user-defined factor to set the stop-loss level.
Fixed Point: This allows you to specify a fixed dollar amount or percentage value as the stop-loss.
X bar High/Low: This sets the stop-loss at a certain number of bars (defined by the user) above/below the bar's high (for long positions) or low (for short positions).
Reward-to-Risk Ratio: Define the desired ratio between your potential profit and potential loss on each trade. The backtesting module will calculate take-profit levels based on this ratio and the stop-loss placement.
🔶 Disclaimer:
Use with Caution: This indicator is provided for educational and informational purposes only and should not be considered as financial advice. Users should exercise caution and perform their own analysis before making trading decisions based on the indicator's signals.
Not Financial Advice: The information provided by this indicator does not constitute financial advice, and the creator (UAlgo) shall not be held responsible for any trading losses incurred as a result of using this indicator.
Backtesting Recommended: Traders are encouraged to backtest the indicator thoroughly on historical data before using it in live trading to assess its performance and suitability for their trading strategies.
Risk Management: Trading involves inherent risks, and users should implement proper risk management strategies, including but not limited to stop-loss orders and position sizing, to mitigate potential losses.
No Guarantees: The accuracy and reliability of the indicator's signals cannot be guaranteed, as they are based on historical price data and past performance may not be indicative of future results.
FreedX Grid Backtest█ FreedX Grid Backtest is an open-source tool that offers accurate GRID calculations for GRID trading strategies. This advanced tool allows users to backtest GRID trading parameters with precision, accurately reflecting exchange functionalities. We are committed to enhancing trading strategies through precise backtesting solutions and address the issue of unreliable backtesting practices observed on GRID trading strategies. FreedX Grid Backtest is designed for optimal calculation speed and plotting efficiency, ensuring users to achieve fastest calculations during their analysis.
█ GRID TRADING STRATEGY SETTINGS
The core of the FreedX Grid Backtest tool lies in its ability to simulate grid trading strategies. Grid trading involves placing orders at regular intervals within a predefined price range, creating a grid of orders that capitalize on market volatility.
Features:
⚙️ Backtest Range:
→ Purpose: Allows users to specify the backtesting range of GRID strategy. Closes all positions at the end of this range.
→ How to Use: Drag the dates to fit the desired backtesting range.
⚙️ Investment & Compounding:
→ Purpose: Allows users to specify the total investment amount and select between fixed and compound investment strategies. Compounding adjusts trade quantities based on performance, enhancing the grid strategy's adaptability to market changes.
→ How to Use: Set the desired investment amount and choose between "Fixed" or "Compound" for the investment method.
⚙️ Leverage & Grid Levels:
→ Purpose: Leverage amplifies the investment amount, increasing potential returns (and risks). Users can define the number of grid levels, which determines how the investment is distributed across the grid.
→ How to Use: Input the desired leverage and number of grids. The tool automatically calculates the distribution of funds across each grid level.
⚙️ Distribution Type & Mode:
→ Purpose: Users can select the distribution type (Arithmetic or Geometric) to set how grid levels are determined. The mode (Neutral, Long, Short) dictates the direction of trades within the grid.
→ How to Use: Choose the distribution type and mode based on the desired trading strategy and market outlook.
⚙️ Enable LONG/SHORT Grids exclusively:
█ MANUAL LEVELS AND STOP TRIGGERS
Beyond automated settings, the tool offers manual adjustments for traders seeking finer control over their grid strategies.
Features:
⚙️ Manual Level Adjustment:
→ Purpose: Enables traders to manually set the top, reference, and bottom levels of the grid, offering precision control over the trading range.
→ How to Use: Activate manual levels and adjust the top, reference, and bottom levels as needed to define the grid's scope.
⚙️ Stop Triggers:
→ Purpose: Provides an option to set upper and lower price limits, acting as stop triggers to close or terminate trades. This feature safeguards investments against significant market movements outside the anticipated range.
→ How to Use: Enable stop triggers and specify the upper and lower limits. The tool will automatically manage positions based on these parameters.
---
This guide gives you a quick and clear overview of the FreedX Grid Backtest tool, explaining how you can use this cutting-edge tool to improve your trading strategies.
Grid Bot BacktestingBinance, Bybit, Bitget, and other cross-exchange (grid) trading bot backtesting.
Auto bound: Automatically setting upper and lower price bounds.
Manual: Setting upper and lower price bounds manually.
The graph below represents the overall asset changes (initial investment amount + current position profit + grid profit).
Try using backtesting when setting up a grid bot on the exchange!
바이낸스, 바이비트, 비트겟 등 교차거래(그리드) 봇 백테스팅
Auto bound : 자동으로 상,하단 가격 설정
Manual : 직접 상,하단 가격 설정
아래 그래프는 총 자산 변화입니다.(초기투자금액 + 현재 포지션 수익 + 그리드 수익)
거래소에서 그리드 봇 설정할 때 백테스팅 유용하게 써보세요!
Ehlers Combo Strategy🚀 Presenting the Enhanced Ehlers Combo Strategy 🚀
Hello Traders! 👋 I'm thrilled to share the latest version of the Ehlers Combo Strategy v2.0. This powerful algorithm combines Ehlers Elegant Oscillator, Decycler, Instantaneous Trendline, Spearman Rank, and introduces the Signal to Noise Ratio for even more precise trading signals.
📊 Strategy Highlights:
Ehlers Elegant Oscillator: Captures market momentum and turning points.
Ehlers Decycler: Filters out market noise for clearer trend signals.
Instantaneous Trendline: Offers a dynamic view of the market trend.
Spearman Rank: Analyzes market rank correlations for enhanced insights.
Signal to Noise Ratio (SNR): Filters out noise for more accurate signals.
💡 Key Features & Customizations:
Adaptive Length: Enable adaptive length based on the market's current conditions.
SNR Threshold: Set your desired SNR threshold for filtering signals.
Exit Length: Define the length for exit signals.
📈 Trading Signals:
Long Entry: Elegant Oscillator and Decycler cross above 0, source crosses above Decycler, source is greater than an increasing Instantaneous Trendline, Spearman Rank is positive, and SNR exceeds the threshold.
Long Exit: Source crosses below the Instantaneous Trendline after entering a long position.
Short Entry: Elegant Oscillator and Decycler cross below 0, source crosses below Decycler, source is less than a decreasing Instantaneous Trendline, Spearman Rank is negative, and SNR exceeds the threshold.
Short Exit: Source crosses above the Instantaneous Trendline after entering a short position.
📊 Insights & Enhancements:
Dynamic Length: The strategy adapts its length dynamically based on market conditions.
Improved SNR: Signal to Noise Ratio ensures better filtering of signals.
Enhanced Visualization: The Elegant Oscillator now features improved color coding for a clearer interpretation.
🚨 Disclaimer:
Trading involves risk, and this script should be used judiciously. It's not a guaranteed profit machine, but with careful use, it can be a valuable addition to your toolkit.
Feel free to backtest, tweak, and make it your own! Let's conquer the markets together! 💪📈
🚀✨ Happy Trading! ✨🚀
---
🙌 Credits:
A big shoutout to the original contributors:
@blackcat1402
@cheatcountry
@DasanC
Back Week For BacktestIt is Backtest Calculator For Essential and Plus plan holders, the length of available intraday data is calculated as follows: from now to 6 weeks back multiplied by timeframe(in minutes), i.e. you can go 6 weeks back on the 1-minute chart, 12 weeks back on the 2-minute chart, 30 weeks back on the 5-minute chart, 90 weeks back on the 15-minute chart and so on. The higher timeframe is selected, the more intraday data is available.
This show creates a weekday label based on the data in the plans allowed by TradingView. This show creates a weekday label based on the data in the plans allowed by TradingView. How much data is available for Bar Replay? According to the article, we can replay 6 weeks backwards for a 1-minute chart. This indicator is a label that shows how far we can go back, consisting of multiplying each minute by 6 between 1 minute and 60 minutes.
1 minute => 6 week backtest
2 minutes => 12 week backtest
.....
15 minutes => 90 week backtest
...
59 minutes => 354 week backtest
Backtesting ModuleDo you often find yourself creating new 'strategy()' scripts for each trading system? Are you unable to focus on generating new systems due to fatigue and time loss incurred in the process? Here's a potential solution: the 'Backtesting Module' :)
INTRODUCTION
Every trading system is based on four basic conditions: long entry, long exit, short entry and short exit (which are typically defined as boolean series in Pine Script).
If you can define the conditions generated by your trading system as a series of integers, it becomes possible to use these variables in different scripts in efficient ways. (Pine Script is a convenient language that allows you to use the integer output of one indicator as a source in another.)
The 'Backtesting Module' is a dynamic strategy script designed to adapt to your signals. It boasts two notable features:
⮞ It produces a backtest report using the entry and exit variables you define.
⮞ It not only serves for system testing but also to combine independent signals into a single system. (This functionality enables to create complex strategies and report on their success!)
The module tests Golden and Death cross signals by default, when you enter your own conditions the default signals will be neutralized. The methodology is described below.
PREPARATION
There are three simple steps to connect your own indicator to the Module.
STEP 1
Firstly, you must define entry and exit variables in your own script. Let's elucidate it with a straightforward example. Consider a system generating long and short signals based on the intersections of two moving averages. Consequently, our conditions would be as follows:
// Signals
long = ta.crossover(ta.sma(close, 14), ta.sma(close, 28))
short = ta.crossunder(ta.sma(close, 14), ta.sma(close, 28))
Now, the question is: How can we convert boolean variables into integer variables? The answer is conditional ternary block, defined as follows:
// Entry & Exit
long_entry = long ? 1 : 0
long_exit = short ? 1 : 0
short_entry = short ? 1 : 0
short_exit = long ? 1 : 0
The mechanics of the Entry & Exit variables are simple. The variable takes on a value of 1 when your trading system generates the signal and if your system does not produce any signal, variable returns 0. In this example, you see how exit signals can be generated in a trading system that only contains entry signals. If you have a system with original exit signals, you can also use them directly. (Please mind the NOTES section below).
STEP 2
To utilize the Entry & Exit variables as source in another script, they must be plotted on the chart. Therefore, the final detail to include in the script containing your trading system would be as follows:
// Plot The Output
plot(long_entry, "Long Entry", display=display.data_window, editable=false)
plot(long_exit, "Long Exit", display=display.data_window, editable=false)
plot(short_entry, "Short Entry", display=display.data_window, editable=false)
plot(short_exit, "Short Exit", display=display.data_window, editable=false)
STEP 3
Now, we are ready to test the system! Load the Backtesting Module indicator onto the chart along with your trading system/indicator. Then set the outputs of your system (Long Entry, Long Exit, Short Entry, Short Exit) as source in the module. That's it.
FEATURES & ORIGINALITY
⮞ Primarily, this script has been created to provide you with an easy and practical method when testing your trading system.
⮞ I thought it might be nice to visualize a few useful results. The Backtesting Module provides insights into the outcomes of both long and short trades by computing the number of trades and the success percentage.
⮞ Through the 'Trade' parameter, users can specify the market direction in which the indicator is permitted to initiate positions.
⮞ Users have the flexibility to define the date range for the test.
⮞ There are optional features allowing users to plot entry prices on the chart and customize bar colors.
⮞ The report and the test date range are presented in a table on the chart screen. The entry price can be monitored in the data window.
⮞ Note that results are based on realized returns, and the open trade is not included in the displayed results. (The only exception is the 'Unrealized PNL' result in the table.)
STRATEGY SETTINGS
The default parameters are as follows:
⮞ Initial Balance : 10000 (in units of currency)
⮞ Quantity : 10% of equity
⮞ Commission : 0.04%
⮞ Slippage : 0
⮞ Dataset : All bars in the chart
For a realistic backtest result, you should size trades to only risk sustainable amounts of equity. Do not risk more than 5-10% on a trade. And ALWAYS configure your commission and slippage parameters according to pessimistic scenarios!
NOTES
⮞ This script is intended solely for development purposes. And it'll will be available for all the indicators I publish.
⮞ In this version of the module, all order types are designed as market orders. The exit size is the sum of the entry size.
⮞ As your trading conditions grow more intricate, you might need to define the outputs of your system in alternative ways. The method outlined in this description is tailored for straightforward signal structures.
⮞ Additionally, depending on the structure of your trading system, the backtest module may require further development. This encompasses stop-loss, take-profit, specific exit orders, quantity, margin and risk management calculations. I am considering releasing improvements that consider these options in future versions.
⮞ An example of how complex trading signals can be generated is the OTT Collection. If you're interested in seeing how the signals are constructed, you can use the link below.
THANKS
Special thanks to PineCoders for their valuable moderation efforts.
I hope this will be a useful example for the TradingView community...
DISCLAIMER
This is just an indicator, nothing more. It is provided for informational and educational purposes exclusively. The utilization of this script does not constitute professional or financial advice. The user solely bears the responsibility for risks associated with script usage. Do not forget to manage your risk. And trade as safely as possible. Best of luck!
Captain Backtest Model [TFO]Created by @imjesstwoone and @mickey1984, this trade model attempts to capture the expansion from the 10:00-14:00 EST 4h candle using just 3 simple steps. All of the information presented in this description has been outlined by its creators, all I did was translate it to Pine Script. All core settings of the trade model may be edited so that users can test several variations, however this description will cover its default, intended behavior using NQ 5m as an example.
Step 1 is to identify our Price Range. In this case, we are concerned with the highest high and the lowest low created from 6:00-10:00 EST.
Step 2 is to wait for either the high or low of said range to be taken out. Whichever side gets taken first determines the long/short bias for the remainder of the Trade Window (i.e. if price takes the range high, bias is long, and vice versa). Bias must be determined by 11:15 EST, otherwise no trades will be taken. This filter is intended to weed out "choppy" trading days.
Step 3 is to wait for a retracement and enter with a close through the previous candle's high (if long biased) or low (if short biased). There are a couple toggleable criteria that we use to define a retracement; one is checking for opposite close candles that indicate a pullback; another is checking if price took the previous candle's low (if long biased) or high (if short biased).
This trade model was initially tested for index futures, particularly ES and NQ, using a 5m chart, however this indicator allows us to backtest any symbol on any timeframe. Creators @imjesstwoone and @mickey1984 specified a 5 point stop loss on ES and a 25 point stop loss on NQ with their testing.
I've personally found some success in backtesting NQ 5m using a 25 point stop loss and 75 point profit target (3:1 R). Enabling the Use Fixed R:R parameter will ensure that these stops and targets are utilized, otherwise it will enter and hold the position until the close of the Trade Window.
*Backtesting System ⚉ OVERVIEW ⚉
One of the best Systems for Backtesting your Strategies.
Incredibly flexible, simple, fast and feature-rich system — will solve most of your queries without much effort.
Many systems for setting StopLoss, TakeProfit, Risk Management and advanced Filters.
All you need to do is plug in your indicator and start Backtesting .
I intentionally left the option to use my System on Full Power before you load your indicator into it.
The system uses the built-in simple and popular moving average crossover signal for this purpose. (EMA 50 & 200).
Also Highly Recommend that you Fully use ALL of the features of this system so that you understand how they work before you ask questions.
Also tried to leave TIPS for each feature everywhere, read Tips, activate them and see how they work.
But before you use this system, I Recommend you to read the following description in Full.
—————— How to connect your indicator in 2 steps:
Adapt your indicator by adding only 2 lines of code and then connect it to this Backtesting System.
Step 1 — Create your connector, For doing so:
• 1 — Find or create in your indicator where are the conditions printing the Long-Buy and Short-Sell signals.
• 2 — Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator wether it's a MACD, RSI , Pivots, or whatever indicator with Clear Buy and Sell conditions.
//@version=5
indicator('Moving Average Cross', overlay = true)
MA200 = ta.𝚎𝚖𝚊(close, 200)
MA50 = ta.𝚎𝚖𝚊(close, 50)
// Generate Buy and Sell conditions
buy = ta.crossover (MA200, MA50)
sell = ta.crossunder (MA200, MA50)
plot(MA200, color=color.green)
plot(MA50 , color=color.red )
bgcolor(color = buy ? color.green : sell ? color.red : na, title='SIGNALS')
// ———————————————— SIGNAL FOR SYSTEM ————————————————
Signal = buy ? +1 : sell ? -1 : 0
plot(Signal, title='🔌Connector🔌', display = display.none)
// —————— 🔥 The Backtesting System expects the value to be exactly +1 for the 𝚋𝚞𝚕𝚕𝚒𝚜𝚑 signal, and -1 for the 𝚋𝚎𝚊𝚛𝚒𝚜𝚑 signal
Basically, I identified my Buy & Sell conditions in the code and added this at the bottom of my indicator code
Now you can connect your indicator to the Backtesting System using the Step 2
Step 2 — Connect the connector
• 1 — Add your updated indicator to a TradingView chart and Add the Backtesting System as well to the SAME chart
• 2 — Open the Backtesting System settings and in the External Source field select your 🔌Connector🔌 (which comes from your indicator)
_______________________________
⚉ MAIN SETTINGS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
𝐄𝐱𝐭𝐞𝐫𝐧𝐚𝐥 𝐒𝐨𝐮𝐫𝐜𝐞 — Select your indicator. Add your indicator by following the 2 steps described above and select it in the menu. To familiarize yourself with the system until you select your indicator, you will have an in-built strategy of crossing the two moving EMA's of 50 and 200.
Long Deals — Enable/Disable Long Deals.
Short Deals — Enable/Disable Short Deals.
Wait End Deal — Enable/Disable waiting for a trade to close at Stop Loss/Take Profit. Until the trade closes on the Stop Loss or Take Profit, no new trade will open.
Reverse Deals — To force the opening of a trade in the opposite direction.
ReEntry Deal — Automatically open the same new deal after the deal is closed.
ReOpen Deal — Reopen the trade if the same signal is received. For example, if you are already in the long and a new signal is received in the long, the trade will reopen. * Does not work if Wait End Deal is enabled.
𝐓𝐚𝐤𝐞 𝐏𝐫𝐨𝐟𝐢𝐭:
None — Disables take profit. Useful if you only want to use dynamic stoplosses such as MA, Fast-Trailing, ATR Trail.
FIXED % — Fixed take profit in percent.
FIXED $ — Fixed Take in Money.
ATR — Fixed Take based on ATR.
R:R — Fixed Take based on the size of your stop loss. For example, if your stop is 10% and R:R=1, then the Take would be 10%. R:R=3 Take would be 30%, etc.
HH / LL — Fixed Take based on the previous maximum/minimum (extremum).
𝐒𝐭𝐨𝐩 𝐋𝐨𝐬𝐬:
None — Disables Stop Loss. Useful if you want to work without a stop loss. *Be careful if Wait End Deal is enabled, the trade may not close for a long time until it reaches the Take.
FIXED % — Fixed Stop in percent.
FIXED $ — Fixed Stop in Money.
TRAILING — Dynamic Trailing Stop like on the stock exchanges.
FAST TRAIL — Dynamic Fast Trailing Stop moves immediately in profit and stays in place if the price stands still or the price moves in loss.
ATR — Fixed Stop based on the ATR.
ATR TRAIL — Dynamic Trailing Stop based on the ATR.
LO / HI — A Fixed Stop based on the last Maximum/Minimum extemum. Allows you to place a stop just behind or above the low/high candle.
MA — Dynamic Stop based on selected Moving Average. * You will have 8 types of MA (EMA, SMA, HMA, etc.) to choose from, but you can easily add dozens of other MAs, which makes this type of stop incredibly flexible.
Add % — If true, then with the "𝗦𝘁𝗼𝗽 %" parameter you can add percentages to any of the current SL. Can be especially useful when using Stop - 𝗔𝗧𝗥 or 𝗠𝗔 or 𝗟𝗢/𝗛𝗜. For example with 𝗟𝗢/𝗛𝗜 to put a stop for the last High/Low and add 0.5% additional Stoploss.
Fixed R:R — If the stop loss is Dynamic (Trailing or MA) then if R:R true can also be made Dynamic * Use it carefully, the function is experimental.
_________________________________________
⚉ TAKE PROFIT LEVELS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
A unique method of constructing intermediate Take Profit Levels will allow you to select up to 5 intermediate Take Profit Levels and one intermediate Stop Loss.
Intermediate Take Profit Levels are perfectly calculated into 5 equal parts in the form of levels from the entry point to the final Take Profit target.
All you need to do is to choose the necessary levels for fixing and how much you want to fix at each level as a percentage. For example, TP 3 will always be exactly between the entry point and the Take Profit target. And the value of TP 3 = 50 will close 50% of the amount of the remaining size of the position.
Note: all intermediate SL/TP are closed from the remaining position amount and not from the initial position size, as TV does by default.
SL 0 Position — works in the same way as TP 1-5 but it's Stop. With this parameter you can set the position where the intermediate stop will be set.
Breakeven on TP — When activated, it allows you to put the stop loss at Breakeven after the selected TP is reached. For this function to work as it should - you need to activate an intermediate Take. For example, if TP 3 is activated and Breakeven on TP = 3, then after the price reaches this level, the Stop loss will go to Breakeven.
* This function will not work with Dynamic Stoplosses, because it simply does not make sense.
CoolDown # Bars — When activated, allows you to add a delay before a new trade is opened. A new trade after CoolDown will not be opened until # bars pass and a new signal appears.
_____________________________
⚉ TIME FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Powerful time filter code that allows you to filter data based on specific time zones, dates, and session days. This code is ideal for those who need to analyze data from different time zones and weed out irrelevant data.
With Time Filter, you can easily set the starting and ending time zones by which you want to filter the data.
You can also set a start and end date for your data and choose which days of the week to include in the analysis. In addition, you can specify start and end times for a specific session, allowing you to focus your analysis on specific time periods.
_________________________________
⚉ SIGNAL FILTERS ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Signal Filters — allows you to easily customize and optimize your trading strategies based on 10 filters.
Each filter is designed to help you weed out inaccurate signals to minimize your risks.
Let's take a look at their features:
__________________________________
⚉ RISK MANAGEMENT ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
Risk management tools that allow you to set the maximum number of losing trades in a row, a limit on the number of trades per day or week and other filters.
Loss Streak — Set Max number of consecutive loss trades.
Win Streak — Max Winning Streak Length.
Row Loss InDay — Max of consecutive days with a loss in a row.
DrawDown % — Max DrawDown (in % of strategy equity).
InDay Loss % — Set Max Intraday Loss.
Daily Trades — Limit the number of MAX trades per day.
Weekly Trades — Limit the number of MAX trades per week.
* 🡅 I would Not Recommend using these functions without understanding how they work.
Order Size — Position Size
• NONE — Use the default position size settings in Tab "Properties".
• EQUITY — The amount of the allowed position as a percentage of the initial capital.
• Use Net Profit — On/Off the use of profit in the following trades. *Only works if the type is EQUITY.
• SIZE — The size of the allowed position in monetary terms.
• Contracts — The size of the allowed position in the contracts. 1 Сontract = Сurrent price.
________________
⚉ NOTES ⚉
‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
It is important to note that I have never worked with Backtesting and the functions associated with them before.
It took me about a month of slow work to build this system.
I want to say Big Thanks:
• The PineScripters🌲 group in Telegram , the guys suggested how to implement some features. Especially @allanster
• Thanks to all those people who share their developments for free on TV and not only.
• I also thank myself for not giving up and finishing the project, and not trying to monetize the system by selling it. * Although I really want the money :)
I tried hard to make it as fast and convenient as possible for everyone who will use my code.
That's why I didn't use any libraries and dozens of heavy functions, and I managed to fit in 8+-functions for the whole code.
Absolutely every block of code I tried to make full-fledged modular, that it was easy to import/edit for myself (you).
I have abused the Ternary Pine operator a little (a lot) so that the code was as compact as possible.
Nevertheless, I tried very hard to keep my code very understandable even for beginners.
At last I managed to write 500 lines of code, making it one of the fastest and most feature-rich systems out there.
I hope everyone enjoys my work.
Put comments and write likes.
Backtest AdapterThis is a proof-of-concept Backtest Adapter that can be used with my recent publication "Machine Learning: Lorentzian Classification" located here:
This adapter is helpful because it enables interactive backtesting with TradingView's built-in "Strategy Tester" framework without the need to translate the logic from an "indicator" script to a "strategy" script.
To use this, one must have the "Machine Learning: Lorentzian Classification" script and this Backtest Adapter open simultaneously on the same chart. From there, simply change the "Source" setting of the Backtest Adapter to "Lorentzian Classification: Backtest Stream" to transfer the entry/exit signals stream to the Backtest Adapter.
For an example of how to implement your own backtest stream in your indicators, please refer to the "Backtesting" section in the source code of the "Machine Learning: Lorentzian Classification" script, which is shown below for convenience:
[-_-] Level Breakout, Auto Backtesting StrategyDescription:
A Long only strategy based on breakout from a certain level formed by High price. It has auto-backtesting capabilities (you set ranges for the three main parameters: Lookback, TP and SL; the strategy then goes through different combinations of those parameters and displays a table with results that you can sort by Percentage of profitable trades AND/OR Net profit AND/OR Number of trades). So you can, for example, sort only by Net profit to find combination of parameters that gives highest net profit, or sort by Net profit and Percentage profitable to find a combination of parameters that gives the best balance between profitability and profit. The auto-backtesting also takes into account the commission which is set in % in the inputs (make sure to set the same value in properties of the strategy so that auto-backtesting and real backtesting results match).
NOTE: auto-backtesting only find the best combinations and displays them in a table, you will then need to manually set the Lookback, TP and SL inputs for real backtesting to match.
Parameters:
- Lookback -> # of bars for filtering signals; recommended range from 2 to 5
- TP (%) -> take profit; recommended range from 5 to 10
- SL (%) -> stop loss; recommended range from 1 to 5
- Commission (%) -> commission per trade
- Min/Max Lookback -> lookback range for auto-backtesting
- Min/Max TP -> take profit range for auto-backtesting
- Min/Max SL -> stop loss range for auto-backtesting
- Percentage profitable -> sort by percentage of profitable trades
- Net profit -> sort by net profit
- Number of trades -> sort by number of trades
Session candles & reversals / quantifytools— Overview
Like traditional candles, session based candles are a visualization of open, high, low and close values, but based on session time periods instead of typical timeframes such as daily or weekly. Session candles are formed by fetching price at session start (open), highest price during session (high), lowest price during session (low) and price at session end (close). On top of candles, session based moving average is formed and session reversals detected. Session reversals are also backtested, using win rate and magnitude metrics to better understand what to expect from session reversals and which ones have historically performed the best.
By default, following session time periods are used:
Session #1: London (08:00 - 17:00, UTC)
Session #2: New York (13:00 - 22:00, UTC)
Session #3: Sydney (21:00 - 06:00, UTC)
Session #4: Tokyo (00:00 - 09:00, UTC)
Session time periods can be changed via input menu.
— Reversals
Session reversals are patterns that show a rapid change in direction during session. These formations are more familiarly known as wicks or engulfing candles. Following criteria must be met to qualify as a session reversal:
Wick up:
Lower high, lower low, close >= 65% of session range (0% being the very low, 100% being the very high) and open >= 40% of session range.
Wick down:
Higher high, higher low, close <= 35% of session range and open <= 60% of session range.
Engulfing up:
Higher high, lower low, close >= 65% of session range.
Engulfing down:
Higher high, lower low, close <= 35% of session range.
Session reversals are always based on prior corresponding session , e.g. to qualify as a NY session engulfing up, NY session must have a higher high and lower low relative to prior NY session , not just any session that has taken place in between. Session reversals should be viewed the same way wicks/engulfing formations are viewed on traditional timeframe based candles. Essentially, wick reversals (light green/red labels) tell you most of the motion during session was reversed. Engulfing reversals (dark green/red labels) on the other hand tell you all of the motion was reversed and new direction set.
— Backtesting
Session reversals are backtested using win rate and magnitude metrics. A session reversal is considered successful when next corresponding session closes higher/lower than session reversal close . Win rate is formed by dividing successful session reversal count with total reversal count, e.g. 5 successful reversals up / 10 reversals up total = 50% win rate. Win rate tells us what are the odds (historically) of session reversal producing a clean supporting move that was persistent enough to close that way too.
When a session reversal is successful, its magnitude is measured using percentage increase/decrease from session reversal close to next corresponding session high/low . If NY session closes higher than prior NY session that was a reversal up, the percentage increase from prior session close (reversal close) to current session high is measured. If NY session closes lower than prior NY session that was a reversal down, the percentage decrease from prior session close to current session low is measured.
Average magnitude is formed by dividing all percentage increases/decreases with total reversal count, e.g. 10 total reversals up with 1% increase each -> 10% net increase from all reversals -> 10% total increase / 10 total reversals up = 1% average magnitude. Magnitude metric supports win rate by indicating the depth of successful session reversal moves.
To better understand the backtesting calculations and more importantly to verify their validity, backtesting visuals for each session can be plotted on the chart:
All backtesting results are shown in the backtesting panel on top right corner, with highest win rates and magnitude metrics for both reversals up and down marked separately. Note that past performance is not a guarantee of future performance and session reversals as they are should not be viewed as a complete strategy for long/short plays. Always make sure reversal count is sufficient to draw reliable conclusions of performance.
— Session moving average
Users can form a session based moving average with their preferred smoothing method (SMA , EMA , HMA , WMA , RMA) and length, as well as choose which sessions to include in the moving average. For example, a moving average based on New York and Tokyo sessions can be formed, leaving London and Sydney completely out of the calculation.
— Visuals
By default, script hides your candles/bars, although in the case of candles borders will still be visible. Switching to bars/line will make your regular chart visuals 100% hidden. This setting can be turned off via input menu. As some sessions overlap, each session candle can be separately offsetted forward, clearing the overlaps. Users can also choose which session candles to show/hide.
Session periods can be highlighted on the chart as a background color, applicable to only session candles that are activated. By default, session reversals are referred to as L (London), N (New York), S (Sydney) and T (Tokyo) in both reversal labels and backtesting table. By toggling on "Numerize sessions", these will be replaced with 1, 2, 3 and 4. This will be helpful when using a custom session that isn't any of the above.
Visual settings example:
Session candles are plotted in two formats, using boxes and lines as well as plotcandle() function. Session candles constructed using boxes and lines will be clear and much easier on the eyes, but will apply only to first 500 bars due to Tradingview related limitations. Rest of the session candles go back indefinitely, but won't be as clean:
All colors can be customized via input menu.
— Timeframe & session time period considerations
As a rule of thumb, session candles should be used on timeframes at or below 1H, as higher timeframes might not match with session period start/end, leading to incorrect plots. Using 1 hour timeframe will bring optimal results as greatest amount historical data is available without sacrificing accuracy of OHLC values. If you are using a custom session that is not based on hourly period (e.g. 08:00 - 15:00 vs. 08.00 - 15.15) make sure you are using a timeframe that allows correct plots.
Session time periods applied by default are rough estimates and might be out of bounds on some charts, like NYSE listed equities. This is rarely a problem on assets that have extensive trading hours, like futures or cryptocurrency. If a session is out of bounds (asset isn't traded during the set session time period) the script won't plot given session candle and its backtesting metrics will be NA. This can be fixed by changing the session time periods to match with given asset trading hours, although you will have to consider whether or not this defeats the purpose of having candles based on sessions.
— Practical guide
Whether based on traditional timeframes or sessions, reversals should always be considered as only one piece of evidence of price turning. Never react to them without considering other factors that might support the thesis, such as levels and multi-timeframe analysis. In short, same basic charting principles apply with session candles that apply with normal candles. Use discretion.
Example #1 : Focusing efforts on session reversals at distinct support/resistance levels
A reversal against a level holds more value than a reversal by itself, as you know it's a placement where liquidity can be expected. A reversal serves as a confirming reaction for this expectation.
Example #2 : Focusing efforts on highest performing reversals and avoiding poorly performing ones
As you have data backed evidence of session reversal performance, it makes sense to focus your efforts on the ones that perform best. If some session reversal is clearly performing poorly, you would want to avoid it, since there's nothing backing up its validity.
Example #3 : Reversal clusters
Two is better than one, three is better than two and so on. If there are rapid changes in direction within multiple sessions consecutively, there's heavier evidence of a dynamic shift in price. In such case, it makes sense to hold more confidence in price halting/turning.
Quantitative Backtesting Panel + ROI Table - ShortsThis script is an aggregate of a backtesting panel with quantitative metrics, ROI table and open ROI reader. It also contains a mechanism for having a fixed percentage stop loss, similar to native TV backtester. For shorts only.
Backtesting Panel:
- Certain metrics are color coded, with green being good performance, orange being neutral, red being undesirable.
• ROI : return with the system, in %
• ROI(COMP=1): return if money is compounded at a rate of 100%
• Hit rate: accuracy of the system, as a %
• Profit factor: gross profit/gross loss
• Maximum drawdown: the maximum value from a peak to a successive trough of the system's equity curve
• MAE: Maximum Adverse Excursion. The biggest loss of a trade suffered while the position is still open
• Total trades: total number of closed trades
• Max gain/max loss: shows the biggest win over the biggest loss suffered
• Sharpe ratio: measures the performance of the system with adjusted risk (no comparison to risk-free asset)
• CAGR: Compound Annual Growth Rate. The mean annual rate of growth of the system of n years (provided n>1)
• Kurtosis: measures how heavily the tails of the distribution differ from that of a normal distribution (symmetric on both sides of mean where mean=0, standard deviation=1). A normal distribution has a kurtosis of 3, and skewness of 0. The kurtosis indicates whether or not the tails of the returns contain extreme values
• Skewness: measures the symmetry of the distribution of returns
- Leptokurtic: K > 0. Having more kurtosis than a normal distribution. It's stretched up and to the side too (2nd pic down). High kurtosis (leptokurtic) is bad as the wider tails (called heavy tails) suggest there is relatively high probability of extreme events
- Mesokurtic: K =0. Having the same kurtosis as a normal distribution
- Platykurtic: K < 0. Having less kurtosis than a normal distribution. This suggests there are light tails and fewer extreme events in the distribution
- Skewness is good: +/- 0.5 (fairly symmetrical)
- Skewness is average: -1 to -0.5 or 0.5 to 1 (moderately skewed)
- Skewness is bad: > +/- 1 (highly skewed)
Evolving ROI table:
- The table of ROI values evolve with the year and month. The sum of each year is given. Please avoid using it on non-cryptocurrencies or any market whose trading session is not 24/7
Open ROI reader:
- At the top center is the open ROI of a trade
Quantitative Backtesting Panel + ROI Table - LongsThis script is an aggregate of a backtesting panel with quantitative metrics, ROI table and open ROI reader. It also contains a mechanism for having a fixed percentage stop loss, similar to native TV backtester. For longs only.
Backtesting Panel:
- Certain metrics are color coded, with green being good performance, orange being neutral, red being undesirable.
• ROI : return with the system, in %
• ROI(COMP=1): return if money is compounded at a rate of 100%
• Hit rate: accuracy of the system, as a %
• Profit factor: gross profit/gross loss
• Maximum drawdown: the maximum value from a peak to a successive trough of the system's equity curve
• MAE: Maximum Adverse Excursion. The biggest loss of a trade suffered while the position is still open
• Total trades: total number of closed trades
• Max gain/max loss: shows the biggest win over the biggest loss suffered
• Sharpe ratio: measures the performance of the system with adjusted risk (no comparison to risk-free asset)
• CAGR: Compound Annual Growth Rate. The mean annual rate of growth of the system of n years (provided n>1)
• Kurtosis: measures how heavily the tails of the distribution differ from that of a normal distribution (symmetric on both sides of mean where mean=0, standard deviation=1). A normal distribution has a kurtosis of 3, and skewness of 0. The kurtosis indicates whether or not the tails of the returns contain extreme values
• Skewness: measures the symmetry of the distribution of returns
- Leptokurtic: K > 0. Having more kurtosis than a normal distribution. It's stretched up and to the side too (2nd pic down). High kurtosis (leptokurtic) is bad as the wider tails (called heavy tails) suggest there is relatively high probability of extreme events
- Mesokurtic: K =0. Having the same kurtosis as a normal distribution
- Platykurtic: K < 0. Having less kurtosis than a normal distribution. This suggests there are light tails and fewer extreme events in the distribution
- Skewness is good: +/- 0.5 (fairly symmetrical)
- Skewness is average: -1 to -0.5 or 0.5 to 1 (moderately skewed)
- Skewness is bad: > +/- 1 (highly skewed)
Evolving ROI table:
- The table of ROI values evolve with the year and month. The sum of each year is given. Please avoid using it on non-cryptocurrencies or any market whose trading session is not 24/7
Open ROI reader:
- At the top center is the open ROI of a trade
[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.
Catching the Bottom (by Coinrule)This script utilises the RSI and EMA indicators to enter and close the trade.
The relative strength index (RSI) is a momentum indicator used in technical analysis. RSI measures the speed and magnitude of a security's recent price changes to evaluate overvalued or undervalued conditions in the price of that security. The RSI is displayed as an oscillator (a line graph) on a scale of zero to 100. The RSI can do more than point to overbought and oversold securities. It can also indicate securities that may be primed for a trend reversal or corrective pullback in price. It can signal when to buy and sell. Traditionally, an RSI reading of 70 or above indicates an overbought situation. A reading of 30 or below indicates an oversold condition.
An exponential moving average (EMA) is a type of moving average (MA) that places a greater weight and significance on the most recent data points. The exponential moving average is also referred to as the exponentially weighted moving average. An exponentially weighted moving average reacts more significantly to recent price changes than a simple moving average simple moving average (SMA), which applies an equal weight to all observations in the period.
The strategy enters and exits the trade based on the following conditions.
ENTRY
RSI has a decrease of 3.
RSI <40.
EMA100 has crossed above the EMA50.
EXIT
RSI is greater than 65.
EMA9 has crossed above EMA50.
This strategy is back tested from 1 April 2022 to simulate how the strategy would work in a bear market and provides good returns.
Pairs that produce very strong results include ETH on the 5m timeframe, BNB on 5m timeframe, XRP on the 45m timeframe, MATIC on the 30m timeframe and MATIC on the 2H timeframe.
The strategy assumes each order is using 30% of the available coins to make the results more realistic and to simulate you only ran this strategy on 30% of your holdings. A trading fee of 0.1% is also taken into account and is aligned to the base fee applied on Binance.
[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)
Coral Trend Pullback Strategy (TradeIQ)Description:
Strategy is taken from the TradeIQ YouTube video called "I Finally Found 80% Win Rate Trading Strategy For Crypto".
Check out the full video for further details/clarification on strategy entry/exit conditions.
The default settings are exactly as TradeIQ described in his video.
However I found some better results by some tweaking settings, increasing R:R ratio and by turning off confirmation indicators.
This would suggest that perhaps the current confirmation indicators are not the best options. I'm happy to try add some other optional confirmation indicators if they look to be more effective.
Recommended timeframe: 1H
Strategy incorporates the following features:
Risk management:
Configurable X% loss per stop loss
Configurable R:R ratio
Trade entry:
Based on strategy conditions below
Trade exit:
Based on strategy conditions below
Backtesting:
Configurable backtesting range by date
Trade drawings:
Each entry condition indicator can be turned on and off
TP/SL boxes drawn for all trades. Can be turned on and off
Trade exit information labels. Can be turned on and off
NOTE: Trade drawings will only be applicable when using overlay strategies
Alerting:
Alerts on LONG and SHORT trade entries
Debugging:
Includes section with useful debugging techniques
Strategy conditions
Trade entry:
LONG
C1: Coral Trend is bullish
C2: At least 1 candle where low is above Coral Trend since last cross above Coral Trend
C3: Pullback happens and price closes below Coral Trend
C4: Coral Trend colour remains bullish for duration of pullback
C5: After valid pullback, price then closes above Coral Trend
C6: Optional confirmation indicators (choose either C6.1 or C6.2 or NONE):
C6.1: ADX and DI (Single indicator)
C6.1.1: Green line is above red line
C6.1.2: Blue line > 20
C6.1.3: Blue trending up over last 1 candle
C6.2: Absolute Strengeh Histogram + HawkEye Volume Indicator (Two indicators combined)
C6.2.1: Absolute Strengeh Histogram colour is blue
C6.2.2: HawkEye Volume Indicator colour is green
SHORT
C1: Coral Trend is bearish
C2: At least 1 candle where high is below Coral Trend since last cross below Coral Trend
C3: Pullback happens and price closes above Coral Trend
C4: Coral Trend colour remains bearish for duration of pullback
C5: After valid pullback, price then closes below Coral Trend
C6: Optional confirmation indicators (choose either C6.1 or C6.2 or NONE):
C6.1: ADX and DI (Single indicator)
C6.1.1: Red line is above green line
C6.1.2: Blue line > 20
C6.1.3: Blue trending up over last 1 candle
C6.2: Absolute Strengeh Histogram + HawkEye Volume Indicator (Two indicators combined)
C6.2.1: Absolute Strengeh Histogram colour is red
C6.2.2: HawkEye Volume Indicator colour is red
NOTE: All the optional confirmation indicators cannot be overlayed with Coral Trend so feel free to add each separately to the chart for visual purposes
Trade exit:
Stop Loss: Calculated by recent swing low over previous X candles (configurable with "Local High/Low Lookback")
Take Profit: Calculated from R:R multiplier * Stop Loss size
Credits
Strategy origin: TradeIQ's YouTube video called "I Finally Found 80% Win Rate Trading Strategy For Crypto"
It combines the following indicators for trade entry conditions:
Coral Trend Indicator by @LazyBear (Main indicator)
Absolute Strength Histogram | jh by @jiehonglim (Optional confirmation indicator)
Indicator: HawkEye Volume Indicator by @LazyBear (Optional confirmation indicator)
ADX and DI by @BeikabuOyaji (Optional confirmation indicator)
Simple and Profitable Scalping Strategy (ForexSignals TV)Strategy is based on the "SIMPLE and PROFITABLE Forex Scalping Strategy" taken from YouTube channel ForexSignals TV.
See video for a detailed explaination of the whole strategy.
I'm not entirely happy with the performance of this strategy yet however I do believe it has potential as the concept makes a lot of sense.
I'm open to any ideas people have on how it could be improved.
Strategy incorporates the following features:
Risk management:
Configurable X% loss per stop (default to 1%)
Configurable R:R ratio
Trade entry:
Based on stratgey conditions outlined below
Trade exit:
Based on stratgey conditions outlined below
Backtesting:
Configurable backtesting range by date
Trade drawings:
Each entry condition indicator can be turned on and off
TP/SL boxes drawn for all trades. Can be turned on and off
Trade exit information labels. Can be turned on and off
NOTE: Trade drawings will only be applicable when using overlay strategies
Debugging:
Includes section with useful debugging techniques
Strategy conditions
Trade entry:
LONG
C1: On higher timeframe trend EMAs, Fast EMA must be above Slow EMA
C2: On higher timeframe trend EMAs, price must be above Fast EMA
C3: On current timeframe entry EMAs, Fast EMA must be above Medium EMA and Medium EMA must be above Slow EMA
C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in upward direction for previous X candles (configurable)
C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines
C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s)
C7: Price must break through the high of the last X candles (plus price buffer) to trigger entry (stop order entry)
SHORT
C1: On higher timeframe trend EMAs, Fast EMA must be below Slow EMA
C2: On higher timeframe trend EMAs, price must be below Fast EMA
C3: On current timeframe entry EMAs, Fast EMA must be below Medium EMA and Medium EMA must be below Slow EMA
C4: On current timeframe entry EMAs, all 3 EMA lines must have fanned out in downward direction for previous X candles (configurable)
C5: On current timeframe entry EMAs, previous candle must have closed above and not touched any EMA lines
C6: On current timeframe entry EMAs, current candle must have pulled back to touch the EMA line(s)
C7: Price must break through the low of the last X candles (plus price buffer) to trigger entry (stop order entry)
Trade entry:
Calculated position size based on risk tolerance
Entry price is a stop order set just above (buffer configurable) the recent swing high/low (long/short)
Trade exit:
Stop Loss is set just below (buffer configurable) trigger candle's low/high (long/short)
Take Profit calculated from Stop Loss using R:R ratio
Credits
"SIMPLE and PROFITABLE Forex Scalping Strategy" taken from YouTube channel ForexSignals TV
SUPPORT RESISTANCE STRATEGY [5MIN TF]A SUPPORT RESISTANCE BREAKOUT STRATEGY for 5 minute Time-Frame , that has the time condition for Indian Markets
The Timing can be changed to fit other markets, scroll down to "TIME CONDITION" to know more.
The commission is also included in the strategy .
The basic idea is when ,
1) Price crosses above Resistance Level ,indicated by Red Line, is a Long condition.
2) Price crosses below Support Level ,indicated by Green Line , is a Short condition.
3) Candle high crosses above ema1, is a part of the Long condition .
4) Candle low crosses below ema1, is a part of the Short condition .
5) Volume Threshold is an added confirmation for long/short positions.
6) Maximum Risk per trade for the intraday trade can be changed .
7) Default qty size is set to 50 contracts , which can be changed under settings → properties → order size.
8) ATR is used for trailing after entry, as mentioned in the inputs below.
// ═════════════════════════//
// ————————> INPUTS <————————— //
// ═════════════════════════//
→ L_Bars ———————————> Length of Resistance / Support Levels.
→ R_Bars ———————————> Length of Resistance / Support Levels.
→ Volume Break ———————> Volume Breakout from range to confirm Long/Short position.
→ Price Cross Ema —————> Added condition as explained above (3) and (4).
→ ATR LONG —————————> ATR stoploss trail for Long positions.
→ ATR SHORT ————————> ATR stoploss trail for Short positions.
→ RISK ————————————> Maximum Risk per trade intraday.
The strategy was back-tested on TCS ,the input values and the results are mentioned under "BACKTEST RESULTS" below.
// ═════════════════════════ //
// ————————> PROPERTIES<——————— //
// ═════════════════════════ //
Default_qty_size ————> 50 contracts , which can be changed under
Settings
↓
Properties
↓
Order size
// ═══════════════════════════════//
// ————————> TIME CONDITION <————————— //
// ═══════════════════════════════//
The time can be changed in the script , Add it → click on ' { } ' → Pine editor→ making it a copy [right top corner} → Edit the line 27.
The Indian Markets open at 9:15am and closes at 3:30pm.
The 'time_cond' specifies the time at which Entries should happen .
"Close All" function closes all the trades at 3pm , at the open of the next candle.
To change the time to close all trades , Go to Pine Editor → Edit the line 92 .
All open trades get closed at 3pm , because some brokers don't allow you to place fresh intraday orders after 3pm .
// ═══════════════════════════════════════════════ //
// ————————> BACKTEST RESULTS ( 100 CLOSED TRADES )<————————— //
// ═══════════════════════════════════════════════ //
INPUTS can be changed for better Back-Test results.
The strategy applied to NSE:TCS ( 5 min Time-Frame and contract size 50) gives us 60% profitability , as shown below
It was tested for a period a 6 months with a Profit Factor of 1.8 ,net Profit of 30,000 Rs profit .
Sharpe Ratio : 0.49
Sortino Ratio : 1.4
The graph has a Linear Curve with Consistent Profits.
The INPUTS are as follows,
1) L_Bars —————————> 4
2) R_Bars —————————> 4
3) Volume Break ————> 5
4) Price Cross Ema ——> 100
5) ATR LONG ——————> 2.4
6) ATR SHORT —————> 2.6
7) RISK —————————> 2000
8) Default qty size ——> 50
NSE:TCS
Save it to favorites.
Apply it to your charts Now !!
Thank You ☺ NSE:TCS
Regression Channel, Candles and Candlestick Patterns by MontyRegression Candles by ugurvu
Regression Channel by Tradingview
All Candlestick Patterns By Tradingview
This script was combined for a friend of mine who needed this.
This Script has regression candles by ugurvu, Regression channel and Candlestick patterns by tradingview.
The intention was to fuse these together so more information can be processed on the cost of a single indicator.