EDMA Scalping Strategy (Exponentially Deviating Moving Average)This strategy uses crossover of Exponentially Deviating Moving Average (MZ  EDMA ) along with Exponential Moving Average for trades entry/exits. Exponentially Deviating Moving Average (MZ  EDMA ) is derived from Exponential Moving Average to predict better exit in top reversal case.
 EDMA   Philosophy 
 EDMA  is calculated in following steps:
 
 In first step, Exponentially expanding moving line is calculated with same code as of EMA but with different smoothness (1 instead of 2).
 In 2nd step, Exponentially contracting moving line is calculated using 1st calculated line as source input and also using same code as of EMA but with different smoothness (1 instead of 2).
 In 3rd step, Hull Moving Average with 2/3 of  EDMA  length is calculated using final line as source input. This final HMA will be equal to Exponentially Deviating Moving Average.
 
 EDMA  Defaults 
Currently default  EDMA  and EMA length is set to 20 period which I've found better for higher timeframes but this can be adjusted according to user's timeframe. I would soon add Multi Timeframe option in script too.  Chikou  filter's period is set to 25.
 Additional Features 
 
 EMA Band:  EMA band is shown on chart to better visualize EMA cross with  EDMA .
 Dynamic Coloring:  Chikou Filter library is used for derivation of dynamic coloring of  EDMA  and its band.
 Trade Confirmation with  Chikou  Filter:  Trend filteration from Chikou filter library is used as an option to enhance trades signals accuracy.
 Strategy Default Test Settings 
For backtesting purpose, following settings are used:
 
 Initial capital=10000 USD
 Default quantity value = 5 % of total capital
 Commission value = 0.1 %
 Pyramiding isn't included.
 Backtesting data never assures that the same results would occur in future and also above settings use very less of total portfolio for trades, which in a way results less maximum drawdown along with less total profit on initial capital too. For example, increasing default quantity value will definity increase maximum drawdown value. The other way is also to use fix contracts in backtesting but it all depends on users general practice. Best option is to explore backtesting results with manually modified settings on different charts, before trusting them for other uses in future.
 
 Usage and In-Detail Backtesting 
 
 This strategy has built-in option to enable trade confirmations with  Chikou  filter which will reduce the total number of trades increasing profit factor.
 Symmetrically Weighted Moving Average (SWMA) on input source, may risk repainting in real-time data. Better option is to run a trade on bar close or simply left this optin unchecked.
 I've set  Chikou  filter unchecked  to increase number of trades (greater than 100) on higher timeframe (12H) and this can be changed according to your precision requirement and timeframe.
 Timeframes lower than 4H usually have more noise. So its better to use higher  EDMA  and EMA length on lower timeframes which will decrease total number of offsetting trades increasing average total number of bars within a single trade. 
 
Original "Exponentially Deviating Moving Average (MZ  EDMA )" Indicator can be found here.
"backtesting"に関するスクリプトを検索
Advanced Multi-Timeframe Trading System (Risk Managed)Description:
This strategy is an original approach that combines two main analytical components to identify potential trade opportunities while simulating realistic trading conditions:
	1.	Market Trend Analysis via an Approximate Hurst Exponent
	•	What It Does:
The strategy computes a rough measure of market trending using an approximate Hurst exponent. A value above 0.5 suggests persistent, trending behavior, while a value below 0.5 indicates a tendency toward mean-reversion.
	•	How It’s Used:
The Hurst exponent is calculated on both the chart’s current timeframe and a higher timeframe (default: Daily) to capture both local and broader market dynamics.
	2.	Fibonacci Retracement Levels
	•	What It Does:
Using daily high and low data from a selected timeframe (default: Daily), the script computes key Fibonacci retracement levels.
	•	How It’s Used:
	•	The 61.8% level (Golden Ratio) serves as a key threshold:
	•	A long entry is signaled when the price crosses above this level if the daily Hurst exponent confirms a trending market.
	•	The 38.2% level is used to identify short-entry opportunities when the price crosses below it and the daily Hurst indicates non-trending conditions.
Signal Logic:
	•	Long Entry:
When the price crosses above the 61.8% Fibonacci level (Golden Ratio) and the daily Hurst exponent is greater than 0.5, suggesting a trending market.
	•	Short Entry:
When the price crosses below the 38.2% Fibonacci level and the daily Hurst exponent is less than 0.5, indicating a less trending or potentially reversing market.
Risk Management & Trade Execution:
	•	Stop-Loss:
Each trade is risk-managed with a stop-loss set at 2% below (for longs) or above (for shorts) the entry price. This ensures that no single trade risks more than a small, sustainable portion of the account.
	•	Take Profit:
A take profit order targets a risk-reward ratio of 1:2 (i.e., the target profit is twice the amount risked).
	•	Position Sizing:
Trades are executed with a fixed position size equal to 10% of account equity.
	•	Trade Frequency Limits:
	•	Daily Limit: A maximum of 5 trades per day
	•	Overall Limit: No more than 510 trades during the backtesting period (e.g., since 2019)
These limits are imposed to simulate realistic trading frequency and to avoid overtrading in backtest results.
Backtesting Parameters:
	•	Initial Capital: $10,000
	•	Commission: 0.1% per trade
	•	Slippage: 1 tick per bar
These settings aim to reflect the conditions faced by the average trader and help ensure that the backtesting results are realistic and not misleading.
Chart Overlays & Visual Aids:
	•	Fibonacci Levels:
The key Fibonacci retracement levels are plotted on the chart, and the zone between the 61.8% and 38.2% levels is highlighted to show a key retracement area.
	•	Market Trend Background:
The chart background is tinted green when the daily Hurst exponent indicates a trending market (value > 0.5) and red otherwise.
	•	Information Table:
An on-chart table displays key parameters such as the current Hurst exponent, daily Hurst value, the number of trades executed today, and the global trade count.
Disclaimer:
Past performance is not indicative of future results. This strategy is experimental and provided solely for educational purposes. It is essential that you backtest and paper trade using your own settings before considering any live deployment. The Hurst exponent calculation is an approximation and should be interpreted as a rough gauge of market behavior. Adjust the parameters and risk management settings according to your personal risk tolerance and market conditions.
Additional Notes:
	•	Originality & Usefulness:
This script is an original mashup that combines trend analysis with Fibonacci retracement methods. The description above explains how these components work together to provide trading signals.
	•	Realistic Results:
The strategy uses realistic account sizes, commission rates, slippage, and risk management rules to generate backtesting results that are representative of real-world trading.
	•	Educational Purpose:
This script is intended to support the TradingView community by offering insights into combining multiple analysis techniques in one strategy. It is not a “get-rich-quick” system but rather an educational tool to help traders understand risk management and trade signal logic.
By using this script, you acknowledge that trading involves risk and that you are responsible for testing and adjusting the strategy to fit your own trading environment. This publication is fully open source, and any modifications should include proper attribution if significant portions of the code are reused.
ICT Judas Swing | Flux Charts💎 GENERAL OVERVIEW 
Introducing our new ICT Judas Swing Indicator! This indicator is built around the ICT's "Judas Swing" strategy. The strategy looks for a liquidity grab around NY 9:30 session and a Fair Value Gap for entry confirmation. For more information about the process, check the "HOW DOES IT WORK" section.
  
Features of the new ICT Judas Swing :
 
  Implementation of ICT's Judas Swing Strategy
  2 Different TP / SL Methods
  Customizable Execution Settings
  Customizable Backtesting Dashboard
  Alerts for Buy, Sell, TP & SL Signals
 
📌 HOW DOES IT WORK ? 
The strategy begins by identifying the New York session from 9:30 to 9:45 and marking recent liquidity zones. These liquidity zones are determined by locating high and low pivot points: buyside liquidity zones are identified using high pivots that haven't been invalidated, while sellside liquidity zones are found using low pivots. A break of either buyside or sellside liquidity must occur during the 9:30-9:45 session, which is interpreted as a liquidity grab by smart money. The strategy assumes that after this liquidity grab, the price will reverse and move in the opposite direction. For entry confirmation, a fair value gap (FVG) in the opposite direction of the liquidity grab is required. A buyside liquidity grab calls for a bearish FVG, while a sellside grab requires a bullish FVG. Based on the type of FVG—bullish for buys and bearish for sells—the indicator will then generate a Buy or Sell signal.
  
After the Buy or Sell signal, the indicator immediately draws the take-profit (TP) and stop-loss (SL) targets. The indicator has three different TP & SL modes, explained in the "Settings" section of this write-up.
You can set up alerts for entry and TP & SL signals, and also check the current performance of the indicator and adjust the settings accordingly to the current ticker using the backtesting dashboard.
🚩 UNIQUENESS 
This indicator is an all-in-one suit for the ICT's Judas Swing concept. It's capable of plotting the strategy, giving signals, a backtesting dashboard and alerts feature. Different and customizable algorithm modes will help the trader fine-tune the indicator for the asset they are currently trading. Three different TP / SL modes are available to suit your needs. The backtesting dashboard allows you to see how your settings perform in the current ticker. You can also set up alerts to get informed when the strategy is executable for different tickers.
  
⚙️ SETTINGS 
1. General Configuration
Swing Length -> The swing length for pivot detection. Higher settings will result in  
FVG Detection Sensitivity -> You may select between Low, Normal, High or Extreme FVG detection sensitivity. This will essentially determine the size of the spotted FVGs, with lower sensitivies resulting in spotting bigger FVGs, and higher sensitivies resulting in spotting all sizes of FVGs.
2. TP / SL
TP / SL Method -> 
a) Dynamic: The TP / SL zones will be auto-determined by the algorithm based on the Average True Range (ATR) of the current ticker.
b) Fixed : You can adjust the exact TP / SL ratios from the settings below. 
Dynamic Risk -> The risk you're willing to take if "Dynamic" TP / SL Method is selected. Higher risk usually means a better winrate at the cost of losing more if the strategy fails. This setting is has a crucial effect on the performance of the indicator, as different tickers may have different volatility so the indicator may have increased performance when this setting is correctly adjusted.
ICT Unicorn | Flux Charts💎 GENERAL OVERVIEW 
Introducing our new ICT Unicorn Indicator! This indicator is built around the ICT's "Unicorn" strategy. The strategy uses Breaker Blocks and Fair Value Gaps for entry confirmation. For more information about the process, check the "HOW DOES IT WORK" section.
  
Features of the new ICT Unicorn Indicator :
 
  Implementation of ICT's Unicorn Strategy
  Toggleable Retracement Entry Method
  3 Different TP / SL Methods
  Customizable Execution Settings
  Customizable Backtesting Dashboard
  Alerts for Buy, Sell, TP & SL Signals
 
  
📌 HOW DOES IT WORK ? 
The ICT Unicorn entry model merges the concepts of Breaker Blocks and Fair Value Gaps (FVGs), offering a distinct method for identifying trade opportunities. By integrating these two elements, we can have a position entry with stop-loss and take-profit targets on the potential support & resistance zones. This model is particularly reliable for trade entry, as it combines two powerful entry techniques.
An ICT Unicorn Model consists of a FVG which is overlapping with a Breaker Block of the same type. Here is an example :
  
When a FVG overlaps with a Breaker Block of the same type, the indicator gives a Buy or Sell signal depending on the FVG type (Bullish & Bearish). If the "Require Retracement" option is enabled in the settings, the signals are not given immediately. Instead, the current price of the ticker will need to touch the FVG once more before the signals are given.
After the Buy or Sell signal, the indicator immediately draws the take-profit (TP) and stop-loss (SL) targets. The indicator has three different TP & SL modes, explained in the "Settings" section of this write-up.
You can set up alerts for entry and TP & SL signals, and also check the current performance of the indicator and adjust the settings accordingly to the current ticker using the backtesting dashboard.
🚩 UNIQUENESS 
This indicator is an all-in-one suit for the ICT's Unicorn concept. It's capable of plotting the strategy, giving signals, a backtesting dashboard and alerts feature. Different and customizable algorithm modes will help the trader fine-tune the indicator for the asset they are currently trading. Three different TP / SL modes are available to suit your needs. The backtesting dashboard allows you to see how your settings perform in the current ticker. You can also set up alerts to get informed when the strategy is executable for different tickers.
  
⚙️ SETTINGS 
1. General Configuration
FVG Detection Sensitivity -> You may select between Low, Normal, High or Extreme FVG detection sensitivity. This will essentially determine the size of the spotted FVGs, with lower sensitivies resulting in spotting bigger FVGs, and higher sensitivies resulting in spotting all sizes of FVGs.
Swing Length -> Swing length is used when finding order block formations. Smaller values will result in finding smaller order & breaker blocks.
Require Retracement -> 
a) Disabled : The entry signal is given immediately once a FVG overlaps with a Breaker Block of the same type.
b) Enabled : The current price of the ticker will need to touch the FVG once more before the entry signal is given.
2. TP / SL
TP / SL Method -> 
a) Unicorn : This is the default option. The SL will be set to the lowest low of the last 100 bars with an extra offset in a Buy signal. For Sell signals, the SL will be set to the highest high of the last 100 bars with an extra offset. The TP is then set to a value using the SL value and maintaining a risk-reward ratio.
b) Dynamic: The TP / SL zones will be auto-determined by the algorithm based on the Average True Range (ATR) of the current ticker.
c) Fixed : You can adjust the exact TP / SL ratios from the settings below. 
Dynamic Risk -> The risk you're willing to take if "Dynamic" TP / SL Method is selected. Higher risk usually means a better winrate at the cost of losing more if the strategy fails. This setting is has a crucial effect on the performance of the indicator, as different tickers may have different volatility so the indicator may have increased performance when this setting is correctly adjusted.
Negroni Opening Range StrategyStrategy Summary:
This tool can be used to help identify breakouts from a range during a time-zone of your choosing. It plots a pre-market range, an opening range, it also includes moving average levels that can be used as confluence, as well as plotting previous day SESSION highs and lows.
There are several options on how you wish to close out the trades, all described in more detail below.
Back-testing Inputs:
You define your timezone.
You define how many trades to open on any given day.
You decide to go: long only, short only, or long & short (CAREFUL: "Long & Short" can open trades that effectively closes-out existing ones, for better AND worse!)
You define between which times the strategy will open trades.
You define when it closes any open trades (preventing overnight trades, or leaving trades open into US data times!!). 
This hopefully helps make back-testing reflect YOUR trading hours.
NOTE: Renko or Heikin-Ashi charts
For ALL strategies, don’t use Renko or Heikin-Ashi charts unless you know EXACTLY the implications. 
Specific to my strategy, using a renko chart can make this 85-90% profitable (I wish it was!!) Although they can be useful, renko charts don’t always capture real wicks, so the renko chart may show your trade up-only but your broker (who is not using renko!!) will have likely stopped you out on a wick somewhere along the line. 
NOTE: TradingView ‘Deep backtesting’
For ALL strategies, be cynical of all backtesting (e.g. repainting issues etc) as well as ‘Deep backtesting’ results. 
Specific to this strategy, the default settings here SHOULD BE OK, but unfortunately at the time of writing, we can’t see on the chart what exactly ‘deep backtesting’ is calculating. In the past I have noted a number of trades that were not closed at the end of the day, despite my ‘end of day’ trade closing being enabled, so there were big winners and losers that would not have materialized otherwise. As I say, this seems ok at these settings but just always be cynical!!
Opening Range Inputs
You define a pre-market range (example: 08:00 - 09:00).
You define an opening range (example: 09:00 - 09:30).
The strategy will give an update at the close of the opening range to let you know if the opening range has broken out the pre-market range (OR Breakout), or if it has remained inside (OR Inside). The label appears at the end of the opening range NOT at the bar that ‘broke-out’. 
This is just a visual cue for you, it has no bearing on what the strategy will do.
The strategy default will trade off the pre-market range, but you can untick this if you prefer to trade off the opening range.
Opening Trades:
Strategy goes long when the bar (CLOSE) crosses-over the ‘pre-market’ high (not the ‘opening range’ high); and the time is within your trading session, and you have not maxed out your number of trades for the day!
Strategy goes short when the bar (CLOSE) crosses-under the ‘pre-market’ low (not the ‘opening range low); and the time is within your trading session, and you have not maxed out your number of trades for the day!
Remember, you can untick this if you prefer to trade off the opening range instead.
NOTES: 
Using momentum indicators can help (RSI and MACD): especially to trade range plays in failed breakouts, when momentum shifts… but the strategy won’t do this for you!
Using an anchored vwap at the session open can also provide nice confluence, as well as take-profit levels at the upper/lower of 3x standard deviation.
CLOSING TRADES: 
You have 6 take-profit (TP) options:
1) Full TP: uses ATR Multiplier - Full TP at the ATR parameters as defined in inputs.
2) Take Partial profits: ATR Multiplier - Takes partial profits based on parameters as defined in inputs (i.e close 40% of original trade at TP1, close another 40% of original trade at TP2, then the remainder at Full TP as set in option 1.).
3) Full TP: Trailing Stop - Applies a Trailing Stop at the number of points, as defined in inputs.
4) Full TP: MA cross - Takes profit when price crosses ‘Trend MA’ as defined in inputs. 
5) Scalp: Points - closes at a set number of points, as defined in inputs.
6) Full TP: PMKT Multiplier - places a SL at opposite pre-market Hi/Low (we go long at a break-out of the pre-market high, 50% would place a SL at the pre-market range mid-point; 100% would place a SL at the pre-market low)'. This takes profit at the input set in option 1).
Dual Chain StrategyDual Chain Strategy - Technical Overview 
 How It Works: 
The Dual Chain Strategy is a unique approach to trading that utilizes Exponential Moving Averages (EMAs) across different timeframes, creating two distinct "chains" of trading signals. These chains can work  independently  or together, capturing both long-term trends and short-term price movements.
 Chain 1 (Longer-Term Focus): 
 Entry Signal:  The entry signal for Chain 1 is generated when the closing price crosses above the EMA calculated on a weekly timeframe. This suggests the start of a bullish trend and prompts a long position.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
 Exit Signal:  The exit signal is triggered when the closing price crosses below the EMA on a daily timeframe, indicating a potential bearish reversal.
exitLongChain1 = enableChain1 and ta.crossunder(src1, exitEMA1)
 Parameters:  Chain 1's EMA length is set to 10 periods by default, with the flexibility for user adjustment to match various trading scenarios.
 Chain 2 (Shorter-Term Focus): 
 Entry Signal:  Chain 2 generates an entry signal when the closing price crosses above the EMA on a 12-hour timeframe. This setup is designed to capture quicker, shorter-term movements.
bullishChain2 = enableChain2 and ta.crossover(src2, entryEMA2)
 Exit Signal:  The exit signal occurs when the closing price falls below the EMA on a 9-hour timeframe, indicating the end of the shorter-term trend.
exitLongChain2 = enableChain2 and ta.crossunder(src2, exitEMA2)
 Parameters:  Chain 2's EMA length is set to 9 periods by default, and can be customized to better align with specific market conditions or trading strategies.
 Key Features: 
 Dual EMA Chains:  The strategy's originality shines through its dual-chain configuration, allowing traders to monitor and react to both long-term and short-term market trends. This approach is particularly powerful as it combines the strengths of trend-following with the agility of momentum trading.
 Timeframe Flexibility:  Users can modify the timeframes for both chains, ensuring the strategy can be tailored to different market conditions and individual trading styles. This flexibility makes it versatile for various assets and trading environments.
 Independent Trade Logic:  Each chain operates independently, with its own set of entry and exit rules. This allows for simultaneous or separate execution of trades based on the signals from either or both chains, providing a robust trading system that can handle different market phases.
 Backtesting Period:  The strategy includes a configurable backtesting period, enabling thorough performance assessment over a historical range. This feature is crucial for understanding how the strategy would have performed under different market conditions.
time_cond = time >= startDate and time <= finishDate
 What It Does: 
The Dual Chain Strategy offers traders a distinctive trading tool that merges two separate EMA-based systems into one cohesive framework. By integrating both long-term and short-term perspectives, the strategy enhances the ability to adapt to changing market conditions. The originality of this script lies in its innovative dual-chain design, providing traders with a unique edge by allowing them to capitalize on both significant trends and smaller, faster price movements.
Whether you aim to capture extended market trends or take advantage of more immediate price action, the Dual Chain Strategy provides a comprehensive solution with a high degree of customization and strategic depth. Its flexibility and originality make it a valuable tool for traders seeking to refine their approach to market analysis and execution.
 How to Use the Dual Chain Strategy 
 Step 1: Access the Strategy 
Add the Script: Start by adding the Dual Chain Strategy to your TradingView chart. You can do this by searching for the script by name or using the link provided.
Select the Asset: Apply the strategy to your preferred trading pair or asset, such as #BTCUSD, to see how it performs.
 Step 2: Configure the Settings 
Enable/Disable Chains:
The strategy is designed with two independent chains. You can choose to enable or disable each chain depending on your trading style and the market conditions.
enableChain1 = input.bool(true, title='Enable Chain 1')
enableChain2 = input.bool(true, title='Enable Chain 2')
By default, both chains are enabled. If you prefer to focus only on longer-term trends, you might disable Chain 2, or vice versa if you prefer shorter-term trades.
Set EMA Lengths:
Adjust the EMA lengths for each chain to match your trading preferences.
Chain 1: The default EMA length is 10 periods. This chain uses a weekly timeframe for entry signals and a daily timeframe for exits.
len1 = input.int(10, minval=1, title='Length Chain 1 EMA', group="Chain 1")
Chain 2: The default EMA length is 9 periods. This chain uses a 12-hour timeframe for entries and a 9-hour timeframe for exits.
len2 = input.int(9, minval=1, title='Length Chain 2 EMA', group="Chain 2")
Customize Timeframes:
You can customize the timeframes used for entry and exit signals for both chains.
Chain 1:
Entry Timeframe: Weekly
Exit Timeframe: Daily
tf1_entry = input.timeframe("W", title='Chain 1 Entry Timeframe', group="Chain 1")
tf1_exit = input.timeframe("D", title='Chain 1 Exit Timeframe', group="Chain 1")
Chain 2:
Entry Timeframe: 12 Hours
Exit Timeframe: 9 Hours
tf2_entry = input.timeframe("720", title='Chain 2 Entry Timeframe (12H)', group="Chain 2")
tf2_exit = input.timeframe("540", title='Chain 2 Exit Timeframe (9H)', group="Chain 2")
Set the Backtesting Period:
Define the period over which you want to backtest the strategy. This allows you to see how the strategy would have performed historically.
startDate = input.time(timestamp('2015-07-27'), title="StartDate")
finishDate = input.time(timestamp('2026-01-01'), title="FinishDate")
 Step 3: Analyze the Signals 
Understand the Entry and Exit Signals:
Buy Signals: When the price crosses above the entry EMA, the strategy generates a buy signal.
bullishChain1 = enableChain1 and ta.crossover(src1, entryEMA1)
Sell Signals: When the price crosses below the exit EMA, the strategy generates a sell signal.
bearishChain2 = enableChain2 and ta.crossunder(src2, entryEMA2)
Review the Visual Indicators:
The strategy plots buy and sell signals on the chart with labels for easy identification:
BUY C1/C2 for buy signals from Chain 1 and Chain 2.
SELL C1/C2 for sell signals from Chain 1 and Chain 2.
This visual aid helps you quickly understand when and why trades are being executed.
 Step 4: Optimize the Strategy 
Backtest Results:
Review the strategy’s performance over the backtesting period. Look at key metrics like net profit, drawdown, and trade statistics to evaluate its effectiveness.
Adjust the EMA lengths, timeframes, and other settings to see how changes affect the strategy’s performance.
Customize for Live Trading:
Once satisfied with the backtest results, you can apply the strategy settings to live trading. Remember to continuously monitor and adjust as needed based on market conditions.
 Step 5: Implement Risk Management 
Use Realistic Position Sizing:
Keep your risk exposure per trade within a comfortable range, typically between 1-2% of your trading capital.
Set Alerts:
Set up alerts for buy and sell signals, so you don’t miss trading opportunities.
Paper Trade First:
Consider running the strategy in a paper trading account to understand its behavior in real market conditions before committing real capital.
 This dual-layered approach offers a distinct advantage: it enables the strategy to adapt to varying market conditions by capturing both broad trends and immediate price action without one chain's activity impacting the other's decision-making process. The independence of these chains in executing transactions adds a level of sophistication and flexibility that is rarely seen in more conventional trading systems, making the Dual Chain Strategy not just unique, but a powerful tool for traders seeking to navigate complex market environments. 
CCI and MACD Auto Trading Strategy with Risk/RewardOverview:
This strategy combines the Commodity Channel Index (CCI) and the Moving Average Convergence Divergence (MACD) indicators to automate trading decisions. It dynamically sets stop-loss and take-profit levels based on recent lows and highs, ensuring a risk/reward ratio of 1:1.5. This script aims to leverage trend and momentum signals while maintaining effective risk management.
Originality and Usefulness:
This script is not just a simple mashup of CCI and MACD indicators; it incorporates dynamic risk management by setting stop-loss and take-profit levels based on recent price action. This approach helps traders to:
・Identify potential trend reversals using the combination of CCI and MACD signals.
・Manage trades effectively by setting realistic stop-loss and take-profit levels based on recent market data.
・Maintain a balanced risk/reward ratio, which is essential for sustainable trading.
Indicators Used:
・CCI (Commodity Channel Index):
 ・Measures the deviation of the price from its average over a specified period, typically ranging from -100 to +100.
 ・Helps identify overbought and oversold conditions.
・MACD (Moving Average Convergence Divergence):
 ・Utilizes the difference between short-term and long-term moving averages to indicate trend strength and direction.
 ・Provides momentum signals that can be used for timing entries and exits.
How It Works:
Entry Conditions:
Long Entry:
 ・The MACD histogram is above zero.
 ・The CCI crosses above the -100 line.
Short Entry:
 ・The MACD histogram is below zero.
 ・The CCI crosses below the +100 line.
Exit Conditions:
Long Positions:
 ・The stop-loss is set at the recent low.
 ・The take-profit is set at 1.5 times the distance between the entry price and the stop-loss.
Short Positions:
 ・The stop-loss is set at the recent high.
 ・The take-profit is set at 1.5 times the distance between the entry price and the stop-loss.
Risk Management:
・The script dynamically adjusts stop-loss and take-profit levels based on recent market data, ensuring that the risk/reward ratio is maintained at 1:1.5.
 ・This approach helps in managing the risk effectively while aiming for consistent profits.
Strategy Properties:
 ・Account Size: Configured for a realistic account size suitable for the average trader.
 ・Commission and Slippage: Includes settings for realistic commission and slippage to reflect real market conditions.
 ・Risk per Trade: Designed to risk no more than 5-10% of equity per trade, aligning with sustainable trading practices.
 ・Backtesting Results: Configured to generate a sufficient sample size (ideally more than 100 trades) for reliable backtesting results.
Revised Backtesting Settings
Ensure that your backtesting settings are realistic:
・Account Size: Set a realistic initial capital suitable for the average trader.
・Commission and Slippage: Include realistic commission fees and slippage.
・Risk Management: Ensure that each trade risks no more than 5-10% of the account equity.
・Sufficient Sample Size: Choose a dataset that will generate more than 100 trades to provide a       robust sample size.
Versatile Moving Average StrategyVersatile Moving Average Strategy (VMAS)
Overview:
The Versatile Moving Average Strategy (VMAS) is designed to provide traders with a flexible approach to trend-following, utilizing multiple types of moving averages. This strategy allows for customization in choosing the moving average type and length, catering to various market conditions and trading styles.
Key Features:
- Multiple Moving Average Types: Choose from SMA, EMA, SMMA (RMA), WMA, VWMA, HULL, LSMA, and ALMA to best suit your trading needs.
- Customizable Inputs: Adjust the moving average length, source of price data, and stop-loss source to fine-tune the strategy.
- Target Percent: Set the percentage difference between successive profit targets to manage your risk and rewards effectively.
- Position Management: Enable or disable long and short positions, allowing for versatility in different market conditions.
- Commission and Slippage: The strategy includes realistic commission settings to ensure accurate backtesting results.
Strategy Logic:
1. Moving Average Calculation: The selected moving average is calculated based on user-defined parameters.
2. Entry Conditions:
- A long position is entered when the entry source crosses over the moving average, if long positions are enabled.
- A short position is entered when the entry source crosses under the moving average, if short positions are enabled.
3. Stop-Loss: Positions are closed if the stop-loss source crosses the moving average in the opposite direction.
4. Profit Targets: Multiple profit targets are defined, with each target set at an incremental percentage above (for long positions) or below (for short positions) the entry price.
Default Properties:
- Account Size: $10000
- Commission: 0.01% per trade
- Risk Management: Positions are sized to risk 80% of the equity per trade, because we get very tight stoploss when position is open.
- Sample Size: Backtesting has been conducted to ensure a sufficient sample size of trades, ideally more than 100 trades.
How to Use:
1. Configure Inputs: Set your preferred moving average type, length, and other input parameters.
2. Enable Positions: Choose whether to enable long, short, or both types of positions.
3. Backtest and Analyze: Run backtests with realistic settings and analyze the results to ensure the strategy aligns with your trading goals.
4. Deploy and Monitor: Once satisfied with the backtesting results, deploy the strategy in a live environment and monitor its performance.
This strategy is suitable for traders looking to leverage moving averages in a versatile and customizable manner. Adjust the parameters to match your trading style and market conditions for optimal results.
Note: Ensure the strategy settings used for publication are the same as those described here. Always conduct thorough backtesting before deploying any strategy in a live trading environment.
CNTLibraryLibrary   "CNTLibrary" 
Custom Functions To Help Code In Pinescript V5
Coded By Christian Nataliano
First Coded In 10/06/2023
Last Edited In 22/06/2023
Huge Shout Out To © ZenAndTheArtOfTrading and his ZenLibrary V5, Some Of The Custom Functions Were Heavily Inspired By Matt's Work & His Pine Script Mastery Course
Another Shout Out To The TradingView's Team Library ta V5 
//====================================================================================================================================================
//  Custom Indicator Functions 
//====================================================================================================================================================
 GetKAMA(KAMA_lenght, Fast_KAMA, Slow_KAMA) 
  Calculates An Adaptive Moving Average Based On Perry J Kaufman's Calculations
  Parameters:
     KAMA_lenght (int) : Is The KAMA Lenght
     Fast_KAMA (int) : Is The KAMA's Fastes Moving Average
     Slow_KAMA (int) : Is The KAMA's Slowest Moving Average
  Returns: Float Of The KAMA's Current Calculations
 GetMovingAverage(Source, Lenght, Type) 
  Get Custom Moving Averages Values
  Parameters:
     Source (float) : Of The Moving Average, Defval = close
     Lenght (simple int) : Of The Moving Average, Defval = 50
     Type (string) : Of The Moving Average, Defval = Exponential Moving Average
  Returns: The Moving Average Calculation Based On Its Given Source, Lenght & Calculation Type (Please Call Function On Global Scope)
 GetDecimals() 
  Calculates how many decimals are on the quote price of the current market © ZenAndTheArtOfTrading
  Returns: The current decimal places on the market quote price
 Truncate(number, decimalPlaces) 
  Truncates (cuts) excess decimal places © ZenAndTheArtOfTrading
  Parameters:
     number (float) 
     decimalPlaces (simple float) 
  Returns: The given number truncated to the given decimalPlaces
 ToWhole(number) 
  Converts pips into whole numbers © ZenAndTheArtOfTrading
  Parameters:
     number (float) 
  Returns: The converted number
 ToPips(number) 
  Converts whole numbers back into pips © ZenAndTheArtOfTrading
  Parameters:
     number (float) 
  Returns: The converted number
 GetPctChange(value1, value2, lookback) 
  Gets the percentage change between 2 float values over a given lookback period © ZenAndTheArtOfTrading
  Parameters:
     value1 (float) 
     value2 (float) 
     lookback (int) 
 BarsAboveMA(lookback, ma) 
  Counts how many candles are above the MA © ZenAndTheArtOfTrading
  Parameters:
     lookback (int) 
     ma (float) 
  Returns: The bar count of how many recent bars are above the MA
 BarsBelowMA(lookback, ma) 
  Counts how many candles are below the MA © ZenAndTheArtOfTrading
  Parameters:
     lookback (int) 
     ma (float) 
  Returns: The bar count of how many recent bars are below the EMA
 BarsCrossedMA(lookback, ma) 
  Counts how many times the EMA was crossed recently © ZenAndTheArtOfTrading
  Parameters:
     lookback (int) 
     ma (float) 
  Returns: The bar count of how many times price recently crossed the EMA
 GetPullbackBarCount(lookback, direction) 
  Counts how many green & red bars have printed recently (ie. pullback count) © ZenAndTheArtOfTrading
  Parameters:
     lookback (int) 
     direction (int) 
  Returns: The bar count of how many candles have retraced over the given lookback & direction
 GetSwingHigh(Lookback, SwingType) 
  Check If Price Has Made A Recent Swing High
  Parameters:
     Lookback (int) : Is For The Swing High Lookback Period, Defval = 7
     SwingType (int) : Is For The Swing High Type Of Identification, Defval = 1
  Returns: A Bool - True If Price Has Made A Recent Swing High
 GetSwingLow(Lookback, SwingType) 
  Check If Price Has Made A Recent Swing Low
  Parameters:
     Lookback (int) : Is For The Swing Low Lookback Period, Defval = 7
     SwingType (int) : Is For The Swing Low Type Of Identification, Defval = 1
  Returns: A Bool - True If Price Has Made A Recent Swing Low
//====================================================================================================================================================
//  Custom Risk Management Functions 
//====================================================================================================================================================
 CalculateStopLossLevel(OrderType, Entry, StopLoss) 
  Calculate StopLoss Level
  Parameters:
     OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
     Entry (float) : Is The Entry Level Of The Order, Defval = na
     StopLoss (float) : Is The Custom StopLoss Distance, Defval = 2x ATR Below Close
  Returns: Float - The StopLoss Level In Actual Price As A
 CalculateStopLossDistance(OrderType, Entry, StopLoss) 
  Calculate StopLoss Distance In Pips
  Parameters:
     OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
     Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
     StopLoss (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
  Returns: Float - The StopLoss Value In Pips
 CalculateTakeProfitLevel(OrderType, Entry, StopLossDistance, RiskReward) 
  Calculate TakeProfit Level
  Parameters:
     OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
     Entry (float) : Is The Entry Level Of The Order, Defval = na
     StopLossDistance (float) 
     RiskReward (float) 
  Returns: Float  - The TakeProfit Level In Actual Price
 CalculateTakeProfitDistance(OrderType, Entry, TakeProfit) 
  Get TakeProfit Distance In Pips
  Parameters:
     OrderType (int) : Is To Determine A Long / Short Position, Defval = 1
     Entry (float) : Is The Entry Level Of The Order, NEED TO INPUT PARAM
     TakeProfit (float) : Level Based On Previous Calculation, NEED TO INPUT PARAM
  Returns: Float - The TakeProfit Value In Pips
 CalculateConversionCurrency(AccountCurrency, SymbolCurrency, BaseCurrency) 
  Get The Conversion Currecny Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
  Parameters:
     AccountCurrency (simple string) : Is For The Account Currency Used 
     SymbolCurrency (simple string) : Is For The Current Symbol Currency (Front Symbol)
     BaseCurrency (simple string) : Is For The Current Symbol Base Currency (Back Symbol)
  Returns: Tuple Of A Bollean (Convert The Currency ?) And A String (Converted Currency)
 CalculateConversionRate(ConvertCurrency, ConversionRate) 
  Get The Conversion Rate Between Current Account Currency & Current Pair's Quoted Currency (FOR FOREX ONLY)
  Parameters:
     ConvertCurrency (bool) : Is To Check If The Current Symbol Needs To Be Converted Or Not
     ConversionRate (float) : Is The Quoted Price Of The Conversion Currency (Input The request.security Function Here)
  Returns: Float Price Of Conversion Rate (If In The Same Currency Than Return Value Will Be 1.0)
 LotSize(LotSizeSimple, Balance, Risk, SLDistance, ConversionRate) 
  Get Current Lot Size
  Parameters:
     LotSizeSimple (bool) : Is To Toggle Lot Sizing Calculation (Simple Is Good Enough For Stocks & Crypto, Whilst Complex Is For Forex)
     Balance (float) : Is For The Current Account Balance To Calculate The Lot Sizing Based Off
     Risk (float) : Is For The Current Risk Per Trade To Calculate The Lot Sizing Based Off
     SLDistance (float) : Is The Current Position StopLoss Distance From Its Entry Price
     ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
  Returns: Float - Position Size In Units
 ToLots(Units) 
  Converts Units To Lots
  Parameters:
     Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
  Returns: Float - Position Size In Lots
 ToUnits(Lots) 
  Converts Lots To Units
  Parameters:
     Lots (float) : Is For How Many Lots Need To Be Converted Into Units (Minimun 0.01 Units)
  Returns: Int - Position Size In Units
 ToLotsInUnits(Units) 
  Converts Units To Lots Than Back To Units
  Parameters:
     Units (float) : Is For How Many Units Need To Be Converted Into Lots (Minimun 1000 Units)
  Returns: Float - Position Size In Lots That Were Rounded To Units
 ATRTrail(OrderType, SourceType, ATRPeriod, ATRMultiplyer, SwingLookback) 
  Calculate ATR Trailing Stop
  Parameters:
     OrderType (int) : Is To Determine A Long / Short Position, Defval = 1 
     SourceType (int) : Is To Determine Where To Calculate The ATR Trailing From, Defval = close
     ATRPeriod (simple int) : Is To Change Its ATR Period, Defval = 20
     ATRMultiplyer (float) : Is To Change Its ATR Trailing Distance, Defval = 1
     SwingLookback (int) : Is To Change Its Swing HiLo Lookback (Only From Source Type 5), Defval = 7
  Returns: Float - Number Of The Current ATR Trailing
 DangerZone(WinRate, AvgRRR, Filter) 
  Calculate Danger Zone Of A Given Strategy
  Parameters:
     WinRate (float) : Is The Strategy WinRate
     AvgRRR (float) : Is The Strategy Avg RRR
     Filter (float) : Is The Minimum Profit It Needs To Be Out Of BE Zone, Defval = 3
  Returns: Int - Value, 1 If Out Of Danger Zone, 0 If BE, -1 If In Danger Zone
 IsQuestionableTrades(TradeTP, TradeSL) 
  Checks For Questionable Trades (Which Are Trades That Its TP & SL Level Got Hit At The Same Candle)
  Parameters:
     TradeTP (float) : Is The Trade In Question Take Profit Level
     TradeSL (float) : Is The Trade In Question Stop Loss Level
  Returns: Bool - True If The Last Trade Was A "Questionable Trade"
//====================================================================================================================================================
//  Custom Strategy Functions 
//====================================================================================================================================================
 OpenLong(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue) 
  Open A Long Order Based On The Given Params
  Parameters:
     EntryID (string) : Is The Trade Entry ID, Defval = "Long"
     LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
     LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
     StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
     Comment (string) : Is The Order Comment, Defval = Long Entry Order
     CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
  Returns: Void
 OpenShort(EntryID, LotSize, LimitPrice, StopPrice, Comment, CommentValue) 
  Open A Short Order Based On The Given Params
  Parameters:
     EntryID (string) : Is The Trade Entry ID, Defval = "Short"
     LotSize (float) : Is The Lot Size Of The Trade, Defval = 1
     LimitPrice (float) : Is The Limit Order Price To Set The Order At, Defval = Na / Market Order Execution
     StopPrice (float) : Is The Stop Order Price To Set The Order At, Defval = Na / Market Order Execution
     Comment (string) : Is The Order Comment, Defval = Short Entry Order
     CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na
  Returns: Void
 TP_SLExit(FromID, TPLevel, SLLevel, PercentageClose, Comment, CommentValue) 
  Exits Based On Predetermined TP & SL Levels
  Parameters:
     FromID (string) : Is The Trade ID That The TP & SL Levels Be Palced 
     TPLevel (float) : Is The Take Profit Level
     SLLevel (float) : Is The StopLoss Level
     PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
     Comment (string) : Is The Order Comment, Defval = Exit Order
     CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na 
  Returns: Void
 CloseLong(ExitID, PercentageClose, Comment, CommentValue, Instant) 
  Exits A Long Order Based On A Specified Condition
  Parameters:
     ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Long"
     PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
     Comment (string) : Is The Order Comment, Defval = Exit Order
     CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na 
     Instant (bool) : Is For Exit Execution Type, Defval = false
  Returns: Void
 CloseShort(ExitID, PercentageClose, Comment, CommentValue, Instant) 
  Exits A Short Order Based On A Specified Condition
  Parameters:
     ExitID (string) : Is The Trade ID That Will Be Closed, Defval = "Short"
     PercentageClose (float) : Is The Amount To Close The Order At (In Percentage) Defval = 100
     Comment (string) : Is The Order Comment, Defval = Exit Order
     CommentValue (string) : Is For Custom Values In The Order Comment, Defval = Na 
     Instant (bool) : Is For Exit Execution Type, Defval = false
  Returns: Void
 BrokerCheck(Broker) 
  Checks Traded Broker With Current Loaded Chart Broker
  Parameters:
     Broker (string) : Is The Current Broker That Is Traded 
  Returns: Bool - True If Current Traded Broker Is Same As Loaded Chart Broker
 OpenPC(LicenseID, OrderType, UseLimit, LimitPrice, SymbolPrefix, Symbol, SymbolSuffix, Risk, SL, TP, OrderComment, Spread) 
  Compiles Given Parameters Into An Alert String Format To Open Trades Using Pine Connector
  Parameters:
     LicenseID (string) : Is The Users PineConnector LicenseID
     OrderType (int) : Is The Desired OrderType To Open
     UseLimit (bool) : Is If We Want To Enter The Position At Exactly The Previous Closing Price
     LimitPrice (float) : Is The Limit Price Of The Trade (Only For Pending Orders)
     SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
     Symbol (string) : Is The Traded Symbol
     SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
     Risk (float) : Is The Trade Risk Per Trade / Fixed Lot Sizing
     SL (float) : Is The Trade SL In Price / In Pips
     TP (float) : Is The Trade TP In Price / In Pips
     OrderComment (string) : Is The Executed Trade Comment
     Spread (float) : is The Maximum Spread For Execution
  Returns: String - Pine Connector Order Syntax Alert Message
 ClosePC(LicenseID, OrderType, SymbolPrefix, Symbol, SymbolSuffix) 
  Compiles Given Parameters Into An Alert String Format To Close Trades Using Pine Connector
  Parameters:
     LicenseID (string) : Is The Users PineConnector LicenseID
     OrderType (int) : Is The Desired OrderType To Close
     SymbolPrefix (string) : Is The Current Symbol Prefix (If Any)
     Symbol (string) : Is The Traded Symbol
     SymbolSuffix (string) : Is The Current Symbol Suffix (If Any)
  Returns: String - Pine Connector Order Syntax Alert Message
//====================================================================================================================================================
//  Custom Backtesting Calculation Functions 
//====================================================================================================================================================
 CalculatePNL(EntryPrice, ExitPrice, LotSize, ConversionRate) 
  Calculates Trade PNL Based On Entry, Eixt & Lot Size
  Parameters:
     EntryPrice (float) : Is The Trade Entry
     ExitPrice (float) : Is The Trade Exit
     LotSize (float) : Is The Trade Sizing
     ConversionRate (float) : Is The Currency Conversion Rate (Used For Complex Lot Sizing Only)
  Returns: Float - The Current Trade PNL
 UpdateBalance(PrevBalance, PNL) 
  Updates The Previous Ginve Balance To The Next PNL
  Parameters:
     PrevBalance (float) : Is The Previous Balance To Be Updated
     PNL (float) : Is The Current Trade PNL To Be Added
  Returns: Float - The Current Updated PNL
 CalculateSlpComm(PNL, MaxRate) 
  Calculates Random Slippage & Commisions Fees Based On The Parameters
  Parameters:
     PNL (float) : Is The Current Trade PNL 
     MaxRate (float) : Is The Upper Limit (In Percentage) Of The Randomized Fee
  Returns: Float - A Percentage Fee Of The Current Trade PNL
 UpdateDD(MaxBalance, Balance) 
  Calculates & Updates The DD Based On Its Given Parameters
  Parameters:
     MaxBalance (float) : Is The Maximum Balance Ever Recorded
     Balance (float) : Is The Current Account Balance
  Returns: Float - The Current Strategy DD
 CalculateWR(TotalTrades, LongID, ShortID) 
  Calculate The Total, Long & Short Trades Win Rate
  Parameters:
     TotalTrades (int) : Are The Current Total Trades That The Strategy Has Taken
     LongID (string) : Is The Order ID Of The Long Trades Of The Strategy
     ShortID (string) : Is The Order ID Of The Short Trades Of The Strategy
  Returns: Tuple Of Long WR%, Short WR%, Total WR%, Total Winning Trades, Total Losing Trades, Total Long Trades & Total Short Trades
 CalculateAvgRRR(WinTrades, LossTrades) 
  Calculates The Overall Strategy Avg Risk Reward Ratio
  Parameters:
     WinTrades (int) : Are The Strategy Winning Trades
     LossTrades (int) : Are The Strategy Losing Trades
  Returns: Float - The Average RRR Values
 CAGR(StartTime, StartPrice, EndTime, EndPrice) 
  Calculates The CAGR Over The Given Time Period © TradingView
  Parameters:
     StartTime (int) : Is The Starting Time Of The Calculation
     StartPrice (float) : Is The Starting Price Of The Calculation
     EndTime (int) : Is The Ending Time Of The Calculation
     EndPrice (float) : Is The Ending Price Of The Calculation
  Returns: Float - The CAGR Values
//====================================================================================================================================================
//  Custom Plot Functions 
//====================================================================================================================================================
 EditLabels(LabelID, X1, Y1, Text, Color, TextColor, EditCondition, DeleteCondition) 
  Edit / Delete Labels
  Parameters:
     LabelID (label) : Is The ID Of The Selected Label
     X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
     Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
     Text (string) : Is The Text Than Wants To Be Written In The Label
     Color (color) : Is The Color Value Change Of The Label Text
     TextColor (color) 
     EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
     DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
  Returns: Void
 EditLine(LineID, X1, Y1, X2, Y2, Color, EditCondition, DeleteCondition) 
  Edit / Delete Lines
  Parameters:
     LineID (line) : Is The ID Of The Selected Line
     X1 (int) : Is The X1 Coordinate IN BARINDEX Xloc
     Y1 (float) : Is The Y1 Coordinate IN PRICE Yloc
     X2 (int) : Is The X2 Coordinate IN BARINDEX Xloc
     Y2 (float) : Is The Y2 Coordinate IN PRICE Yloc
     Color (color) : Is The Color Value Change Of The Line
     EditCondition (int) : Is The Edit Condition of The Line (Setting Location / Color)
     DeleteCondition (bool) : Is The Delete Condition Of The Line If Ture Deletes The Prev Itteration Of The Line
  Returns: Void
//====================================================================================================================================================
//  Custom Display Functions (Using Tables) 
//====================================================================================================================================================
 FillTable(TableID, Column, Row, Title, Value, BgColor, TextColor, ToolTip) 
  Filling The Selected Table With The Inputed Information
  Parameters:
     TableID (table) : Is The Table ID That Wants To Be Edited
     Column (int) : Is The Current Column Of The Table That Wants To Be Edited
     Row (int) : Is The Current Row Of The Table That Wants To Be Edited 
     Title (string) : Is The String Title Of The Current Cell Table
     Value (string) : Is The String Value Of The Current Cell Table
     BgColor (color) : Is The Selected Color For The Current Table
     TextColor (color) : Is The Selected Color For The Current Table
     ToolTip (string) : Is The ToolTip Of The Current Cell In The Table
  Returns: Void
 DisplayBTResults(TableID, BgColor, TextColor, StartingBalance, Balance, DollarReturn, TotalPips, MaxDD) 
  Filling The Selected Table With The Inputed Information
  Parameters:
     TableID (table) : Is The Table ID That Wants To Be Edited
     BgColor (color) : Is The Selected Color For The Current Table
     TextColor (color) : Is The Selected Color For The Current Table
     StartingBalance (float) : Is The Account Starting Balance
     Balance (float) 
     DollarReturn (float) : Is The Account Dollar Reture
     TotalPips (float) : Is The Total Pips Gained / loss
     MaxDD (float) : Is The Maximum Drawdown Over The Backtesting Period
  Returns: Void
 DisplayBTResultsV2(TableID, BgColor, TextColor, TotalWR, QTCount, LongWR, ShortWR, InitialCapital, CumProfit, CumFee, AvgRRR, MaxDD, CAGR, MeanDD) 
  Filling The Selected Table With The Inputed Information
  Parameters:
     TableID (table) : Is The Table ID That Wants To Be Edited
     BgColor (color) : Is The Selected Color For The Current Table
     TextColor (color) : Is The Selected Color For The Current Table
     TotalWR (float) : Is The Strategy Total WR In %
     QTCount (int) : Is The Strategy Questionable Trades Count
     LongWR (float) : Is The Strategy Total WR In %
     ShortWR (float) : Is The Strategy Total WR In %
     InitialCapital (float) : Is The Strategy Initial Starting Capital
     CumProfit (float) : Is The Strategy Ending Cumulative Profit
     CumFee (float) : Is The Strategy Ending Cumulative Fee (Based On Randomized Fee Assumptions)
     AvgRRR (float) : Is The Strategy Average Risk Reward Ratio
     MaxDD (float) : Is The Strategy Maximum DrawDown In Its Backtesting Period
     CAGR (float) : Is The Strategy Compounded Average GRowth In %
     MeanDD (float) : Is The Strategy Mean / Average Drawdown In The Backtesting Period
  Returns: Void
//====================================================================================================================================================
//  Custom Pattern Detection Functions 
//====================================================================================================================================================
 BullFib(priceLow, priceHigh, fibRatio) 
  Calculates A Bullish Fibonacci Value (From Swing Low To High) © ZenAndTheArtOfTrading
  Parameters:
     priceLow (float) 
     priceHigh (float) 
     fibRatio (float) 
  Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
 BearFib(priceLow, priceHigh, fibRatio) 
  Calculates A Bearish Fibonacci Value (From Swing High To Low) © ZenAndTheArtOfTrading
  Parameters:
     priceLow (float) 
     priceHigh (float) 
     fibRatio (float) 
  Returns: The Fibonacci Value Of The Given Ratio Between The Two Price Points
 GetBodySize() 
  Gets The Current Candle Body Size IN POINTS © ZenAndTheArtOfTrading
  Returns: The Current Candle Body Size IN POINTS
 GetTopWickSize() 
  Gets The Current Candle Top Wick Size IN POINTS © ZenAndTheArtOfTrading
  Returns: The Current Candle Top Wick Size IN POINTS
 GetBottomWickSize() 
  Gets The Current Candle Bottom Wick Size IN POINTS © ZenAndTheArtOfTrading
  Returns: The Current Candle Bottom Wick Size IN POINTS
 GetBodyPercent() 
  Gets The Current Candle Body Size As A Percentage Of Its Entire Size Including Its Wicks © ZenAndTheArtOfTrading
  Returns: The Current Candle Body Size IN PERCENTAGE
 GetTopWickPercent() 
  Gets The Current Top Wick Size As A Percentage Of Its Entire Body Size
  Returns: Float - The Current Candle Top Wick Size IN PERCENTAGE
 GetBottomWickPercent() 
  Gets The Current Bottom Wick Size As A Percentage Of Its Entire Bodu Size
  Returns: Float - The Current Candle Bottom Size IN PERCENTAGE
 BullishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack) 
  Checks If The Current Bar Is A Bullish Engulfing Candle
  Parameters:
     Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
     RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Engulfing Pattern, Defval = na
     EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
     NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
  Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Engulfing Candle
 BearishEC(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack) 
  Checks If The Current Bar Is A Bearish Engulfing Candle
  Parameters:
     Allowance (int) : To Give Flexibility Of Engulfing Pattern Detection In Markets That Have Micro Gaps, Defval = 0
     RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Engulfing Pattern, Defval = na
     EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
     NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
  Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Engulfing Candle
 Hammer(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod) 
  Checks If The Current Bar Is A Hammer Candle
  Parameters:
     Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
     ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
     NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
     ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
     ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
  Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
 Star(Fib, ColorMatch, NearSwings, SwingLookBack, ATRFilterCheck, ATRPeriod) 
  Checks If The Current Bar Is A Hammer Candle
  Parameters:
     Fib (float) : To Specify Which Fibonacci Ratio To Use When Determining The Hammer Candle, Defval = 0.382 Ratio
     ColorMatch (bool) : To Filter Only Bullish Closed Hammer Candle Pattern, Defval = false
     NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing Low, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
     ATRFilterCheck (float) : To Filter Smaller Hammer Candles That Might Be Better Classified As A Doji Candle, Defval = 1
     ATRPeriod (simple int) : To Change ATR Period Of The ATR Filter, Defval = 20
  Returns: Bool - True If The Current Bar Matches The Requirements of a Hammer Candle
 Doji(MaxWickSize, MaxBodySize, DojiType, NearSwings, SwingLookBack) 
  Checks If The Current Bar Is A Doji Candle
  Parameters:
     MaxWickSize (float) : To Specify The Maximum Lenght Of Its Upper & Lower Wick, Defval = 2
     MaxBodySize (float) : To Specify The Maximum Lenght Of Its Candle Body IN PERCENT, Defval = 0.05
     DojiType (int) 
     NearSwings (bool) : To Specify If We Want The Doji To Be Near A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High / Low (Only In Dragonlyf / Gravestone Mode), Defval = 10
  Returns: Bool - True If The Current Bar Matches The Requirements of a Doji Candle
 BullishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack) 
  Checks If The Current Bar Is A Bullish Harami Candle
  Parameters:
     Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
     RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bullsih Harami Pattern, Defval = na
     EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
     NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing Low, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing Low, Defval = 10
  Returns: Bool - True If The Current Bar Matches The Requirements of a Bullish Harami Candle
 BearishIB(Allowance, RejectionWickSize, EngulfWick, NearSwings, SwingLookBack) 
  Checks If The Current Bar Is A Bullish Harami Candle
  Parameters:
     Allowance (int) : To Give Flexibility Of Harami Pattern Detection In Markets That Have Micro Gaps, Defval = 0
     RejectionWickSize (float) : To Filter Out long (Upper And Lower) Wick From The Bearish Harami Pattern, Defval = na
     EngulfWick (bool) : To Specify If We Want The Pattern To Also Engulf Its Upper & Lower Previous Wicks, Defval = false
     NearSwings (bool) : To Specify If We Want The Pattern To Be Near A Recent Swing High, Defval = true
     SwingLookBack (int) : To Specify How Many Bars Back To Detect A Recent Swing High, Defval = 10
  Returns: Bool - True If The Current Bar Matches The Requirements of a Bearish Harami Candle
//====================================================================================================================================================
//  Custom Time Functions 
//====================================================================================================================================================
 BarInSession(sess, useFilter) 
  Determines if the current price bar falls inside the specified session © ZenAndTheArtOfTrading
  Parameters:
     sess (simple string) 
     useFilter (bool) 
  Returns: A boolean - true if the current bar falls within the given time session
 BarOutSession(sess, useFilter) 
  Determines if the current price bar falls outside the specified session © ZenAndTheArtOfTrading
  Parameters:
     sess (simple string) 
     useFilter (bool) 
  Returns: A boolean - true if the current bar falls outside the given time session
 DateFilter(startTime, endTime) 
  Determines if this bar's time falls within date filter range © ZenAndTheArtOfTrading
  Parameters:
     startTime (int) 
     endTime (int) 
  Returns: A boolean - true if the current bar falls within the given dates
 DayFilter(monday, tuesday, wednesday, thursday, friday, saturday, sunday) 
  Checks if the current bar's day is in the list of given days to analyze © ZenAndTheArtOfTrading
  Parameters:
     monday (bool) 
     tuesday (bool) 
     wednesday (bool) 
     thursday (bool) 
     friday (bool) 
     saturday (bool) 
     sunday (bool) 
  Returns: A boolean - true if the current bar's day is one of the given days
 AUSSess() 
  Checks If The Current Australian Forex Session In Running
  Returns: Bool - True If Currently The Australian Session Is Running
 ASIASess() 
  Checks If The Current Asian Forex Session In Running
  Returns: Bool - True If Currently The Asian Session Is Running
 EURSess() 
  Checks If The Current European Forex Session In Running
  Returns: Bool - True If Currently The European Session Is Running
 USSess() 
  Checks If The Current US Forex Session In Running
  Returns: Bool - True If Currently The US Session Is Running
 UNIXToDate(Time, ConversionType, TimeZone) 
  Converts UNIX Time To Datetime
  Parameters:
     Time (int) : Is The UNIX Time Input
     ConversionType (int) : Is The Datetime Output Format, Defval = DD-MM-YYYY
     TimeZone (string) : Is To Convert The Outputed Datetime Into The Specified Time Zone, Defval = Exchange Time Zone
  Returns: String - String Of Datetime
Optimized Zhaocaijinbao strategyIntroduction: 
The Optimized Zhaocaijinbao strategy is a mid and long-term quantitative trading strategy that combines momentum and trend factors. It generates buy and sell signals by using a combination of exponential moving averages, moving averages, volume and slope indicators.  It generates buy signals when the stock is above the 35-day moving average, the trading volume is higher than the 20-day moving average, and the stock is in an upward trend on a weekly timeframe."招财进宝" is a Chinese phrase that can be translated to "Attract Wealth and Bring in Treasure" in English. It is a common expression used to wish for good luck and prosperity in various contexts, such as in business or personal finances.
Highlights: 
The strategy has several special optimizations that make it unique.
Firstly, the strategy is optimized for T+1 trading in the Chinese stock market and is only suitable for long positions. The optimizations are also applicable to international stock markets.
Secondly, the trend strategy is optimized to only show indicators on the right side and oscillations. This helps to prevent false signals in choppy markets.
Thirdly, the strategy uses a risk factor for dynamic position sizing to ensure position sizes are adjusted according to the current net asset value and risk preferences. This helps to lower drawdown risks.
 
 
 
The strategy has good resilience even without using stop loss modules in backtesting, making it suitable for trading hourly, 2-hourly, and daily K-line charts (depending on the stock being traded). We recommend experimenting with backtesting using SSE 1-hour or 2-hour or daily Kline charts.
 Backtesting outcomes: 
The strategy was backtested over the period from October 13th, 2005 to April 14th, 2023, using daily candlestick charts for the commodity code SSE:600763, with a currency of CNY and tick size of 0.01. The strategy used an initial capital of 1,000,000 CNY, with order sizes set to 10% equity and a pyramid of 1 order. The strategy also had a Max Position Size of 0.01 and a Risk Factor of 2.
Here is a summary of the performance of the trading strategy:
Total net profit: 288,577.32 CNY, representing a return of 128.86%
Total number of closed trades: 61
Winning trades: 37, representing a win rate of 60.66%
Profit factor: 2.415
Largest losing trade: 222,021.46 CNY, representing a loss of 14.08%
Average trade: 21,124.22 CNY, representing a return of 3.1%
Average holding period for all trades: 12 days 
 Conclusion: 
In conclusion, the Optimized Zhaocaijinbao strategy is a mid and long-term quantitative trading strategy that combines momentum and trend factors. It is suitable for both Chinese stocks and global stocks. While the Optimized Zhaocaijinbao strategy has performed well in backtesting, it is important to note that past performance is not a guarantee of future results. Traders should conduct their own research and analysis and exercise caution when using any trading strategy.
Heikin Ashi Candle Startegy for Long PositionThis strategy utilize Heikin-Ashi candlestick chart. 
Heikin-Ashi technique is a Japanese candlestick-based technical trading tool that uses candlestick charts to represent and visualize market price data.
Heikin-Ashi candle is essentially taking an average of the movement. 
There is a tendency with Heikin-Ashi for the candles to stay red during a downtrend and green during an uptrend.
This strategy only apply for long trading position.
The idea is trader will waiting 3 green candles for validation period (confirmation) before entering long position.
Different timeframe will result different result.
Number of validation period can be changed to see different result
This strategy has parameter for take profit percentage, trailing stop and stop loss.
User can set maximum active position to minimize risk and qty order.
This tool is useful for user who wants to backtest Heikin-Ashi trading strategy.
Script will emit alert when long position is opened and closed.
Warning of Backtesting
Backtesting is backward-looking. As the name implies, you are testing how something would have worked if you traded it perfectly in the past. 
Past performance does not indicate future performance and you should not assume it does.
Backtesting assumes you never miss-fire, that you get in and out at the exactly perfect moment each time.
Backtesting assumes you have perfect liquidity, and your limit orders fill at a specific, pre-defined price every time (either the open, close, low, high, or some average of these).
Disclaimer
Do your own research and consider fundamental price of asset.
The indicators provided on this script is for educational purposes only.
Author does not offer advisory or brokerage services, nor does it recommend or advise users to buy or sell particular stocks or securities.
Please examined script and give feedback for further improvement.
Script are open to public, everyone see and clone source code or just apply to chart. Please make comment for improvement.
Patient Trendfollower (7)(alpha)Patient Trendfollower consists of 21 and 55 EMA, Commodity Channel Index and Supertrend indicator. It confirms a trend and gives you a signal on a pullback. Original creation worked on 1h EURUSD chart.
  
►Long setup:
• 21 EMA is above 55 EMA, which is above the Supertrend indicator.
• Commodity Channel Index is an oscillator, which prints into the chart if extreme levels are reached. Green is for a level above 100 or below -100, red is above 140 or below -140 and black is above 180 or below -180. 
• If 21 EMA > 55EMA > Supertrend and an oversold signal appear, you can buy into the trend.
• When backtesting on 1h EURUSD, profit target 400 pips worked best with a stop-loss below Supertrend's bottom and the size of your spread.
• A picture shows two valid entries.
 : This part still malfunctions and shows red dots over some green ones. It is important to disable red ones in the settings to see green ones.
Some more long signals:
  
Some short signals:
  
►Backtesting data with default settings and trading only green CCI signals with mentioned risk management strategy:
• 212 closed trades
• 58.96% profitable with average win trade 348 USD and average loss trade 263 USD when only green signals are followed.
• Profit factor 1.903, Sharpee 0.792
• 20 bars is average for all trades, short trades were 18 bars long on average.
With given data, you can see the strategy is profitable by itself. However, original risk management settings do work only on 1h charts of EURUSD and would need to be adjusted for other instruments based on average volatility.
Even though the profitability is low, you can increase your odds by a great margin, if you properly use price action (impulsive and corrective moves, patterns, bar analysis), if you trade when major exchanges are open, you may also use wave analysis such as Elliot Waves or Market Profiles to predict whether the next day might be a trending day. My backtesting program didn't consider these ideas.
Unfortunately, I won't be making backtesting strategy public with it anytime soon, because it still has some parts that do not work. I am ok with that since I understand the code and know what does malfunction and how. Then, there are parts which I am not sure how to fix yet. This is why the indicator is still considered alpha.
In the future when a strategy is published, you will also be able to set your own overbought/oversold values without entering the code itself and probably some other features. But I am not in a hurry for that. You can give me feedback on UX and try to figure out the best setups for other symbols, it might help to improve the automatic testing script when I know what I should achieve. My main point is to make this public for friends who can already be using it on EURUSD at least.
Close doesn't always have to be 400 pips, you might want to close on a logical level such as strong resistance or a trendline too.
Thanks to:
• @everget for providing Supertrend solution.
• Satik FX who hand-tested the system by hand and reported results in this  article . He is my main inspiration for creating the complete indicator as one because I want to be able to show and hide it with a single click.  My future scripts will also work as a whole strategy each by itself. 
• The number in the script's name comes from Satik's numbering. A mentioned article was his seventh shared strategy.
HatiKO EnvelopesPublished source code is subject to the terms of the GNU Affero General Public License v3.0
This script describes and provides backtesting functionality to internal strategy of algorithmic crypto trading software "HatiKO bot". 
Suitable for backtesting any Cryptocurrency Pair on any Exchange/Platform, any Timeframe.
Core Mechanics of this strategy are based on theory of price always returning to Moving Average + Envelopes indicator (Moving_average_envelope from Wiki) 
Developement of this script and trading software is inspired by:
 
"Essential Technical Analysis: Tools and Techniques to Spot Market Trends" by Leigh Stevens (published on 12th of April 2002) 
"Moving Average Envelopes" by ChartSchool, StockCharts platform (published on 13th of April 2015 or earlier)
"Коля Колеснік" from Crypto Times channel ("Метод сетка", published on 19th of August 2018)
"3 ways to use Moving Average Envelopes" by Rich Fitton, published on Trader's Nest (published on 28st of November 2018 or earlier)
noro's "Robot WhiteBox ShiftMA" strategy v1 script, published on TradingView platform (published on 29th of August 2018)
"Moving Average Envelopes: A Popular Trading Tool" Investopedia article (published 25th of June 2019)
and KROOL1980's blogpost on Argolabs ("Гридерство или Сетка как источник прибыли на форекс", published on 27th of February 2015)
Core Features:
1) Up to 4 Envelopes in each direction (Long/Short)
2) Use any of 6 different basis MAs, optionally use different MAs for Opening and Closure
3) Use different Timeframes for MA calculation, without any repainting and lookahead bias.
4) Fixed order size, not Martingale strategy
5) Close open position earlier by using Deviation parameter 
6) PineScript v4 code
Options description:
Lot - % from your initial balance to use for order size calculation
Timeframe Short - Timeframe to use for Short Opening MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Short - Type of MA to use for Short Opening MA calculation, can be chosen from dropdown list, default is SMA
Data Short - Source of Price for Short Opening MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Short - Period used for Short Opening MA calculation, should be >=1, default is 3
MA offset Short - Offset for MA value used for Short Envelopes calculation, should be >= 0, default is 0
Timeframe Long - Timeframe to use for Long Opening MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Long - Type of MA to use for Long Opening MA calculation, can be chosen from dropdown list, default is SMA
Data Long - Source of Price for Long Opening MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Long - Period used for Long Opening MA calculation, should be >=1, default is 3
MA offset Long - Offset for MA value used for Long Envelopes calculation, should be >= 0, default is 0
Mode close MA Short - Enable different MA for Short position Closure, default is "false". If false, Closure MA = Opening MA
Timeframe Short Close - Timeframe to use for Short Position Closure MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Close Short - Type of MA to use for Short Position Closure MA calculation, can be chosen from dropdown list, default is SMA
Data Short Close - Source of Price for Short Closure MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Short Close - Period used for Short Opening MA calculation, should be >=1, default is 3
Short Deviation - % to move from MA value, used to close position above or beyond MA, can be negative, default is 0
MA offset Short Close - Offset for MA value used for Short Position Closure calculation, should be >= 0, default is 0
Mode close MA Long - Enable different MA for Long position Closure, default is "false". If false, Closure MA = Opening MA
Timeframe Long Close - Timeframe to use for Long Position Closure MA calculation, can be chosen from dropdown list, default is Current Graph Timeframe
MA Type Close Long - Type of MA to use for Long Position Closure MA calculation, can be chosen from dropdown list, default is SMA
Data Long Close - Source of Price for Long Closure MA calculation, can be chosen from dropdown list, default is OHLC4
MA Length Long Close - Period used for Long Opening MA calculation, should be >=1, default is 3
Long Deviation - % to move from MA value, used to close position above or beyond MA, can be negative, default is 0
MA offset Long Close - Offset for MA value used for Long Position Closure calculation, should be >= 0, default is 0
Short Shift 1..4 - % from MA value to put Envelopes at, for Shorts numbers should be positive, the higher is number, the higher should be Shift position, example: "Shift 1 = 1, shift 2 = 2, etc."
Long Shift 1..4 - % from MA value to put Envelopes at, for Longs numbers should be negative, the lower is number, the lower should be Shift position, example: "Shift 1 = -1, shift 2 = -2, etc."
From Year 20XX - Backtesting Starting Year number, only 20xx supported as script is cryptocurrency-oriented.
To Year 20XX - Backtesting Final Year number, only 20xx supported as script is cryptocurrency-oriented.
From Month - Years starting Month, optional tweaking, changing not recommended
To Month - Years ending Month, optional tweaking, changing not recommended
From day - Months starting day, optional tweaking, changing not recommended
To day - Months ending day, optional tweaking, changing not recommended
Graph notes:
Green lines - Long Envelopes.
Red lines - Short Envelopes.
Orange line - MA for closing of Short positions.
Lime line - MA for closing of Long positions.
**************************************************************************************************************************************************************************************************************
Опубликованный исходный код регулируется Условиями Стандартной Общественной Лицензии GNU Affero v3.0
Этот скрипт описывает и предоставляет функции бектеста для внутренней стратегии алгоритмического программного обеспечения "HatiKO bot".
Подходит для тестирования любой криптовалютной пары на любой бирже/платформе, на любом таймфрейме.
Кор-механика этой стратегии основана на теории всегда возвращающейся к значению МА цены с использованием индикатора Envelopes (Moving_average_envelope from Wiki) 
Разработка этого скрипта и программного обеспечения для торговли вдохновлена следующими источниками:
Книга "Essential Technical Analysis: Tools and Techniques to Spot Market Trends" Ли Стивенса (опубликовано 12 апреля 2002 года) 
«Moving Average Envelopes» от ChartSchool, платформа StockCharts (опубликовано 13 апреля 2015 года или раньше)
«Коля Колеснік» с канала Crypto Times («Метод сетка», опубликовано 19 августа 2018 года)
«3 ways to use Moving Average Envelopes» Рича Фиттона, опубликованные в «Trader's Nest» (опубликовано 28 ноября 2018 года или раньше)
Скрипт стратегии noro "Robot WhiteBox ShiftMA" v1, опубликованный на платформе TradingView(опубликовано 29 августа 2018 года)
«Moving Average Envelopes: A Popular Trading Tool», статья Investopedia (опубликовано 25 июня 2019 года)
Блог KROOL1980 из Argolabs («Гридерство или Сетка как источник прибыли на форекс», опубликовано 27 февраля 2015 года)
Основные особенности:
1) До 4-х Ордеров в каждом из направлении (Лонг / Шорт)
2) Выбор из 6-ти разных базовых МА, опционально используйте разные МА для открытия и закрытия.
3) Используйте разные таймфреймы для расчета MA, без перерисовки и "эффекта стеклянного шара".
4) Фиксированный размер ордера, а не стратегия Мартингейла
5) Возможность закрытия открытой позиции заблаговременно, используя параметр Deviation
6) Код реализован на PineScript v4
Описание параметров:
Lot - % от вашего первоначального баланса, используется при расчете размера Ордера
Timeframe Short - таймфрейм, используемый для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Short - тип MA, используемый для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию SMA
Data Short - источник цены для расчета МА Открытия Шорт позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Short - период, используемый для расчета МА Открытия Шорт позиций, должен быть >= 1, по умолчанию 3
MA Offset Short - смещение значения MA, используемого для расчета Шорт Ордеров, должно быть >= 0, по умолчанию 0
Timeframe Long - таймфрейм, используемый для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Long - тип MA, используемый для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию SMA
Data Long - источник цены для расчета МА Открытия Лонг позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Long - период, используемый для расчета МА Открытия Лонг позиций, должен быть >= 1, по умолчанию 3
MA Offset Long - смещение значения MA, используемого для расчета Лонг Ордеров, должно быть >= 0, по умолчанию 0
Mode close MA Short - Включает отдельное MA для закрытия Шорт позиции, по умолчанию «false». Если false, MA Закрытия = MA Открытия
Timeframe Short Close - таймфрейм, используемый для расчета МА Закрытия Шорт позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Close Short - тип MA, используемый при расчете МА Закрытия Шорт позиции. Mожно выбрать из списка, по умолчанию SMA
Data Short Close - источник цены для расчета МА Закрытия Шорт позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Short Close - период, используемый для расчета МА Закрытия Шорт позиции, должен быть >= 1, по умолчанию 3
Short Deviation - % отклонения от значения MA, используется для закрытия позиции выше или ниже рассчитанного значения MA, может быть отрицательным, по умолчанию 0
MA Offset Short Close - смещение значения MA, используемого для расчета закрытия Шорт позиции, должно быть >= 0, по умолчанию 0
Mode close MA Long - Включает разные MA для закрытия Лонг позиции, по умолчанию «false». Если false, MA Закрытия = MA Открытия
Timeframe Long Close - таймфрейм, используемый для расчета МА Закрытия Лонг позиций, может быть выбран из списка, по умолчанию - таймфрейм текущего графика
MA Type Close Long - тип MA, используемый при расчете МА Закрытия Лонг позиции. Mожно выбрать из списка, по умолчанию SMA
Data Long Close - источник цены для расчета МА Закрытия Лонг позиций, может быть выбран из списка, по умолчанию OHLC4
MA Length Long Close - период, используемый для расчета МА Закрытия Лонг позиции, должен быть >= 1, по умолчанию 3
Long Deviation -% для перехода от значения MA, используется для закрытия позиции выше или ниже рассчитанного значения MA, может быть отрицательным, по умолчанию 0
MA Offset Long Close - смещение значения MA, используемого для расчета закрытия Лонг позиции, должно быть >= 0, по умолчанию 0
Short Shift 1..4 - % от значения MA для размещения Ордеров, для Шорт Ордеров должен быть положительным, чем выше номер, тем выше должна располагаться позиция Shift, например: «Shift 1 = 1, Shift 2 = 2 и т.д. "
Long Shift 1..4 - % от значения MA для размещения Ордеров, для Лонг Ордеров должно быть отрицательным, чем ниже число, тем ниже должна располагаться позиция Shift, например: «Shift 1 = -1, Shift 2 = -2, и т.д."
From Year 20XX - Год начала тестирования, из-за ориентированности на криптовалюты поддерживаются только значения формата 20хх.
To Year 20XX - Год окончания тестирования, из-за ориентированности на криптовалюты поддерживаются только значения формата 20хх.
From Month - Начальный месяц, опционально, менять не рекомендуется
To Month - Конечный месяц, опционально, менять не рекомендуется
From day - Начальный день месяца, опционально, менять не рекомендуется
To day - Конечный день месяца, опционально, менять не рекомендуется
Пояснения к графику:
Зеленые линии - Лонг Ордера.
Красные линии - Шорт Ордера.
Оранжевая линия - MA Закрытия Шорт позиций.
Лаймовая линия - MA Закрытия Лонг позиций.
SMA Cross Entry & Exit StrategyThis is a TradingView Strategy Script meaning you can't execute real trades using your exchange API connected to your TradingView account, it is designed for backtesting only 
This is a basic backtesting script for charting the bullish and bearish cross of two user defined simple moving averages, select the cog next to the name of the script ON the price chart in the left hand corner. The script will print to the screen either "Long Entry" or "Short Entry" depending on the direction of the cross. The script using TradingView strategies will subsequently close the opposite of the position that is executed when the bullish or bearish cross occurs. Simply put, if you are short and a bullish cross occurs, your short trade will close and be logged in strategies and the long will fire. You can pyramid the long and short positions to continue entering as long as the trend doesn't flip. You will find this in the script settings. Since this script is for backtesting you can manually set the "backtesting range" for TradingView Strategies and firing the "Long Entry" and "Short Entry". This as well, is in the settings. 
Notice: When the SMA cross occurs, you have to wait till the next candle before TradingView Strategy will print the "Long Entry" or "Short Entry" to the screen 
TradingView - How To Use Strategies: www.tradingview.com
Noro's SILA v1.6L StrategyBacktesting 
Backtesting (for all the time of existence of couple) only with software configurations to default (without optimization of parameters):
US = Uptrend-Sensivity
DS = Downtrend-Sensivity
It is recommended and by default:
- the normal market requires US=DS (for example US=5, DS=5)
- very bear market requires US DS, (for example US=5, DS=0)
- very bull market requires US DS, (US=0, DS=5)
Cryptocurrencies it is very bull market (US=0, DS=5)
 Backtesting BTC/FIAT 
D1 timeframe 
identical parameters for all pairs
BTC/USD (Bitstamp) profit of +41805%
BTC/EUR (BTC-e) profit of +1147%
BTC/RUB (BTC-e) profit of +1162%
BTC/JPY (Bitflyer) profit of +215%
BTC/CNY (BTCChina) profit of 54948%
Backtesting ALTCOIN/BTC
D1 timeframe 
identical parameters for all pairs
the exchange Poloniex
top-10 of cryptocurrencies on capitalization at the time of this text
NA = TradingView can't make backtest because of too low price of this cryptocurrency, or on the website there are no quotations of this cryptocurrency
ETH/BTC (Etherium) profit of +11690%
XRP/BTC (Ripple) loss of-100%
LTC/BTC (Litecoin) NA
ETC/BTC (Etherium Classic) profit of +214%
NEM/BTC loss of-49%
DASH/BTC profit of +106%
IOTA/BTC NA
XMR/BTC (Monero) profit of +96%
STRAT/BTC (Stratis) loss of-31%
ALTCOIN/ALTCOIN - not recomended
I don't need your money, I need reputation and likes.
Trend Entry_0 [TS_Indie]Trend Entry_0 — Mechanism Overview 
The core structure of this strategy is based on a price action reversal pattern, as detailed below:
 In the case of a Bullish Trend Reversal: 
  
The price initially moves in a  bearish direction.  When  candle A  forms a low lower than the previous low, the high of candle A becomes a key reference point.
If the  next candle  closes  above the high of candle A , it confirms a  Bullish Trend Reversal. 
* Upon a Bullish signal, a  Long position  is opened at the  opening price of the next candle (candle B). 
* When a subsequent Bearish signal occurs, the  Long position  is closed at the  opening price of the next candle (candle C). 
 In the case of a Bearish Trend Reversal: 
  
The price initially moves in a  bullish direction.  When  candle A  forms a high higher than the previous high, the low of candle A becomes a key reference point.
If the  next candle  closes  below the low of candle A , it confirms a  Bearish Trend Reversal. 
* Upon a Bearish signal, a  Short position  is opened at the  opening price of the next candle (candle B). 
* When a subsequent Bullish signal occurs, the  Short position  is closed at the  opening price of the next candle (candle C). 
 Options 
* The start and end dates of the backtest can be customized.
* The swing lines of the trend can be displayed as an optional visual aid.
* The user can choose whether to open only  Long  or  Short  positions.
 Backtest Results and Observations 
Based on the backtesting results of this strategy across various assets and timeframes, it has been observed that this approach works best on trending assets such as Gold, BTC, and stocks.
It also performs well on higher timeframes, starting from the Daily timeframe and above,  especially when taking Long positions only. 
However, when applied to currency pairs such as EUR/USD, the results tend to be less impressive.
I encourage everyone to try backtesting and further developing this strategy — adding new conditions or filters may potentially lead to improved performance.
 Disclaimer 
This script is intended solely for backtesting purposes, based on a particular price action pattern.
It does not constitute financial or investment advice.
Backtest results do not guarantee future performance.
Venza Rocket ScalperVenza Rocket Scalper: Compliant Description (Plaintext)
This strategy is a complex, multi-indicator trend-following system designed for intraday scalping on low-timeframe charts. It uses a confluence of four distinct filters to ensure high-conviction entries during optimal momentum and volume.
1. Overview and Core Logic
The entry signal requires simultaneous confirmation from the following components:
Trend Confirmation (Heikin-Ashi EMAs): The primary trend is established using Heikin-Ashi price action combined with an EMA (Fast=8) crossing and remaining above an EMA (Slow=21). This provides a smoother, momentum-based trend signal.
Momentum Strength (ADX/RSI): The trend must be validated by the ADX (default 16) to confirm sufficient directional strength, and the RSI (default 42) to confirm continued positive internal momentum.
Volume Validation: A dynamic filter requires the current bar's volume to be greater than the 20-period Volume MA (multiplied by the default 1.0 factor), ensuring trades are executed during periods of active market participation.
Session & Volatility Filter: Trades are restricted to a defined trading window (default UTC 12:00 to 20:00). The script also includes an optional Volatility Cap filter based on a long-term ATR to suppress entries during extreme volatility.
2. Trade Management and Realistic Risk
This strategy employs a robust, partial-exit risk management plan driven by the Average True Range (ATR) for sustainable risk control.
Initial Stop Loss (SL): The initial SL is tight and calculated dynamically using the 14-period ATR multiplied by an adjustable factor (default 0.7). This size is designed for micro-losses appropriate for scalping and is adapted slightly during high volatility.
Partial Exits & Profit Taking: The position is split into two equal halves for exit management:
50% Position (TP1): Exited at a 1R profit target, where 1R is defined as the exact value of the initial ATR-based SL.
50% Position (Run): Managed by a Trailing Stop Loss (TSL), with trail points also calculated dynamically using the current ATR.
Breakeven (BE) Lock: An optional feature (default: ON) automatically moves the stop loss to Breakeven (entry price plus 1 tick) once the position is 2 ticks in profit, locking in capital protection rapidly.
Daily Risk Controls: The strategy includes mandatory daily money management features (default: ON):
Max Daily Loss Stop: Stops all trading for the day if the cumulative closed P&L reaches -$500 (default).
Profit Protection Floor: If the closed P&L reaches a minimum threshold (default $110), any open position will be closed if the total daily P&L drops back below this floor, locking in minimum daily gains.
3. Strategy Properties & Backtesting Disclosure
The default settings are configured for high-liquidity futures or FX markets. Users must ensure their backtesting environment is realistic:
Risk Per Trade: The ATR-based SL aims to keep the risk per trade below 5% of a reasonable account size, which is critical for sustainable trading.
Contracts/Size: Default quantity is 3 contracts.
Commissions/Slippage: Commissions and slippage MUST be configured by the user in the Strategy Properties window to reflect real-world brokerage fees and execution costs.
Sample Size: The strategy should be run on a dataset that generates over 100 trades for statistically valid results.
MANDATORY DISCLAIMER: Past performance is not necessarily indicative of future results. Trading involves substantial risk. All claims of historical performance are substantiated by the backtesting results on the chart, but these results do not guarantee actual trading outcomes. Keep your language realistic.
Adaptive Trend  1m ### Overview
The "Adaptive Trend Impulse Parallel SL/TP 1m Realistic" strategy is a sophisticated trading system designed specifically for high-volatility markets like cryptocurrencies on 1-minute timeframes. It combines trend-following with momentum filters and adaptive parameters to dynamically adjust to market conditions, ensuring more reliable entries and risk management. This strategy uses SuperTrend for primary trend detection, enhanced by MACD, RSI, Bollinger Bands, and optional volume spikes. It incorporates parallel stop-loss (SL) and multiple take-profit (TP) levels based on ATR, with options for breakeven and trailing stops after the first TP. Optimized for realistic backtesting on short timeframes, it avoids over-optimization by adapting indicators to market speed and efficiency.
### Principles of Operation
The strategy operates on the principle of adaptive impulse trading, where entry signals are generated only when multiple conditions align to confirm a strong trend reversal or continuation:
1. **Trend Detection (SuperTrend)**: The core signal comes from an adaptive SuperTrend indicator. It calculates upper and lower bands using ATR (Average True Range) with dynamic periods and multipliers. A buy signal occurs when the price crosses above the lower band (from a downtrend), and a sell signal when it crosses below the upper band (from an uptrend). Adaptation is based on Rate of Change (ROC) to measure market speed, shortening periods in fast markets for quicker responses.
2. **Momentum and Trend Filters**:
   - **MACD**: Uses adaptive fast and slow lengths. In "Trend Filter" mode (default when "Use MACD Cross" is false), it checks if the MACD line is above/below the signal for long/short. In cross mode, it requires a crossover/crossunder.
   - **RSI**: Adaptive period RSI must be above 50 for longs and below 50 for shorts, confirming overbought/oversold conditions dynamically.
   - **Bollinger Bands (BB)**: Depending on the mode ("Midline" by default), it requires the price to be above/below the BB midline for longs/shorts, or a breakout in "Breakout" mode. Deviation adapts to market efficiency.
   - **Volume Spike Filter** (optional): Entries require volume to exceed an adaptive multiple of its SMA, signaling strong impulse.
3. **Volatility Filter**: Entries are only allowed if current ATR percentage exceeds a historical minimum (adaptive), preventing trades in low-volatility ranges.
4. **Risk Management (Parallel SL/TP)**:
   - **Stop-Loss**: Set at an adaptive ATR multiple below/above entry for long/short.
   - **Take-Profits**: Three levels at adaptive ATR multiples, with partial position closures (e.g., 51% at TP1, 25% at TP2, remainder at TP3).
   - **Post-TP1 Features**: Optional breakeven moves SL to entry after TP1. Trailing SL uses BB midline as a dynamic trail.
   - All levels are calculated per trade using the ATR at entry, making them "realistic" for 1m charts by widening SL and tightening initial TPs.
The strategy enters long on buy signals with all filters met, and short on sell signals. It uses pyramid margin (100% long/short) for full position sizing.
Adaptation is driven by:
- **Market Speed (normSpeed)**: Based on ROC, tightens multipliers in volatile periods.
- **Efficiency Ratio (ER)**: Measures trend strength, adjusting periods for trending vs. ranging markets.
This ensures the strategy "adapts" without manual tweaks, reducing false signals in varying conditions.
### Main Advantages
- **Adaptability**: Unlike static strategies, parameters dynamically adjust to market volatility and trend strength, improving performance across ranging and trending phases without over-optimization.
- **Realistic Risk Management for 1m**: Wider SL and tiered TPs prevent premature stops in noisy short-term charts, while partial profits lock in gains early. Breakeven/trailing options protect profits in extended moves.
- **Multi-Filter Confirmation**: Combines trend, momentum, and volume for high-probability entries, reducing whipsaws. The volatility filter avoids flat markets.
- **Debug Visualization**: Built-in plots for signals, levels, and component checks (when "Show Debug" is enabled) help users verify logic on charts.
- **Efficiency**: Low computational load, suitable for real-time trading on TradingView with alerts.
Backtesting shows robust results on volatile assets, with a focus on sustainable risk (e.g., SL at 3x ATR avoids excessive drawdowns).
### Uniqueness
What sets this strategy apart is its **fully adaptive framework** integrating multiple indicators with real-time market metrics (ROC for speed, ER for efficiency). Most trend strategies use fixed parameters, leading to poor adaptation; here, every key input (periods, multipliers, deviations) scales dynamically within bounds, creating a "self-tuning" system. The "parallel SL/TP with 1m realism" adds custom handling for micro-timeframes: tightened initial TPs for quick wins and adaptive min-ATR filter to skip low-vol bars. Unlike generic mashups, it justifies the combination—SuperTrend for trend, MACD/RSI/BB for impulse confirmation, volume for conviction—working synergistically to capture "trend impulses" while filtering noise. The post-TP1 breakeven/trailing tied to BB adds a unique profit-locking mechanism not common in open-source scripts.
### Recommended Settings
These settings are optimized and recommended for trading ASTER/USDT on Bybit, with 1-minute chart, x10 leverage, and cross margin mode. They provide a balanced risk-reward for this volatile pair:
- **Base Inputs**:
  - Base ATR Period: 10
  - Base SuperTrend ATR Multiplier: 2.5
  - Base MACD Fast: 8
  - Base MACD Slow: 17
  - Base MACD Signal: 6
  - Base RSI Period: 9
  - Base Bollinger Period: 12
  - Bollinger Deviation: 1.8
  - Base Volume SMA Period: 19
  - Base Volume Spike Multiplier: 1.8
  - Adaptation Window: 54
  - ROC Length: 10
- **TP/SL Settings**:
  - Use Stop Loss: True
  - Base SL Multiplier (ATR): 3
  - Use Take Profits: True
  - Base TP1 Multiplier (ATR): 5.5
  - Base TP2 Multiplier (ATR): 10.5
  - Base TP3 Multiplier (ATR): 19
  - TP1 % Position: 51
  - TP2 % Position: 25
  - Breakeven after TP1: False
  - Trailing SL after TP1: False
  - Base Min ATR Filter: 0.001
  - Use Volume Spike Filter: True
  - BB Condition: Midline
  - Use MACD Cross (false=Trend Filter): True
  - Show Debug: True
For backtesting, use initial capital of 30 USD, base currency USDT, order size 100 USDT, pyramiding 1, commission 0.1%, slippage 0 ticks, long/short margin 0%.
Always backtest on your platform and use risk management—risk no more than 1-2% per trade. This is not financial advice; trade at your own risk.
[PDR] Daily Rebalance█ OVERVIEW
This indicator is a powerful portfolio backtesting tool designed to simulate the performance of a static-weight, daily rebalancing strategy. It allows you to define a portfolio of up to 10 assets, set their target weights, and track its cumulative return against a user-defined benchmark and a risk-free rate.
The core of the script is its daily rebalancing logic, which calculates and logs every trade needed to bring the portfolio back to its target allocations at the close of each day. This provides a transparent and detailed view of how a static portfolio would have performed historically, including the impact of trading costs.
█ KEY FEATURES
 
  Daily Rebalancing: Simulates a portfolio that is rebalanced at the close of every day to maintain target asset allocations.
  Customizable Portfolio: Configure up to 10 different assets with specific weights. If all weights are left at 0, the script automatically creates an equal-weight portfolio from the selected assets.
  Performance Comparison: Plots the portfolio's equity curve against a user-defined benchmark (e.g.,  SET:SET50 ) and a risk-free return, allowing for easy relative performance analysis.
  Realistic Simulation: Accounts for trading costs like broker commission and minimum lot sizes for more accurate and grounded backtesting results.
  Detailed Performance Metrics: An on-chart table displays real-time statistics, including Current Drawdown, Max Drawdown, and Total Return for both your portfolio and the benchmark.
  Trade-by-Trade Logs: For full transparency, every rebalancing trade (BUY/SELL), including shares, price, notional value, and fees, is logged in the Pine Logs panel.
 
█ HOW TO USE
 
  **Apply to a Daily Chart:** This script is designed to work exclusively on the daily ( 1D ) timeframe. Applying it to any other timeframe will result in a runtime error.
  **Configure Settings:** Open the indicator's settings. Set your `Initial Capital`, `Start Time`, and the `Benchmark` symbol you wish to compare against.
  **Define Your Assets:** In the 'Assets' group, check the box to enable each asset you want to include, select the symbol, and define its target `Weight (%)`.
  **Set Trading Costs:** Adjust the `Broker Commission (%)` and `Minimal Buyable Lot` to match your expected trading conditions.
  **Analyze the Results:** The performance curves are plotted in the indicator pane below your main chart. The key metrics table is displayed on the bottom-right of your chart.
  **View Rebalancing Trades:** This is a crucial step for understanding the simulation. To see the detailed daily trades, you **must** open the **Pine Logs**. You can find this panel at the bottom of your TradingView window, next to the "Pine Editor" and "Strategy Tester" tabs. The logs provide a complete breakdown of every rebalancing action.
 
█ DISCLAIMER
This is a backtesting and simulation tool, not a trading signal generator. Its purpose is for research and performance analysis. Past performance is not indicative of future results. Always conduct your own research before making any investment decisions.
MACD Enhanced [DCAUT]█ MACD Enhanced  
 📊 ORIGINALITY & INNOVATION 
The MACD Enhanced represents a significant improvement over traditional MACD implementations. While Gerald Appel's original MACD from the 1970s was limited to exponential moving averages (EMA), this enhanced version expands algorithmic options by supporting 21 different moving average calculations for both the main MACD line and signal line independently.
This improvement addresses an important limitation of traditional MACD: the inability to adapt the indicator's mathematical foundation to different market conditions. By allowing traders to select from algorithms ranging from simple moving averages (SMA) for stability to advanced adaptive filters like Kalman Filter for noise reduction, this implementation changes MACD from a fixed-algorithm tool into a flexible instrument that can be adjusted for specific market environments and trading strategies.
The enhanced histogram visualization system uses a four-color gradient that helps communicate momentum strength and direction more clearly than traditional single-color histograms.
 📐 MATHEMATICAL FOUNDATION 
The core calculation maintains the proven MACD formula: Fast MA(source, fastLength) - Slow MA(source, slowLength), but extends it with algorithmic flexibility. The signal line applies the selected smoothing algorithm to the MACD line over the specified signal period, while the histogram represents the difference between MACD and signal lines.
 Available Algorithms: 
The implementation supports a comprehensive spectrum of technical analysis algorithms:
 
 Basic Averages:  SMA (arithmetic mean), EMA (exponential weighting), RMA (Wilder's smoothing), WMA (linear weighting)
 Advanced Averages:  HMA (Hull's low-lag), VWMA (volume-weighted), ALMA (Arnaud Legoux adaptive)
 Mathematical Filters:  LSMA (least squares regression), DEMA (double exponential), TEMA (triple exponential), ZLEMA (zero-lag exponential)
 Adaptive Systems:  T3 (Tillson T3), FRAMA (fractal adaptive), KAMA (Kaufman adaptive), MCGINLEY_DYNAMIC (reactive to volatility)
 Signal Processing:  ULTIMATE_SMOOTHER (low-pass filter), LAGUERRE_FILTER (four-pole IIR), SUPER_SMOOTHER (two-pole Butterworth), KALMAN_FILTER (state-space estimation)
 Specialized:  TMA (triangular moving average), LAGUERRE_BINOMIAL_FILTER (binomial smoothing)
 
Each algorithm responds differently to price action, allowing traders to match the indicator's behavior to market characteristics: trending markets benefit from responsive algorithms like EMA or HMA, while ranging markets require stable algorithms like SMA or RMA.
 📊 COMPREHENSIVE SIGNAL ANALYSIS 
 Histogram Interpretation: 
 
 Positive Values:  Indicate bullish momentum when MACD line exceeds signal line, suggesting upward price pressure and potential buying opportunities
 Negative Values:  Reflect bearish momentum when MACD line falls below signal line, indicating downward pressure and potential selling opportunities
 Zero Line Crosses:  MACD crossing above zero suggests transition to bullish bias, while crossing below indicates bearish bias shift
 Momentum Changes:  Rising histogram (regardless of positive/negative) signals accelerating momentum in the current direction, while declining histogram warns of momentum deceleration
 
 Advanced Signal Recognition: 
 
 Divergences:  Price making new highs/lows while MACD fails to confirm often precedes trend reversals
 Convergence Patterns:  MACD line approaching signal line suggests impending crossover and potential trade setup
 Histogram Peaks:  Extreme histogram values often mark momentum exhaustion points and potential reversal zones
 
 🎯 STRATEGIC APPLICATIONS 
 Comprehensive Trend Confirmation Strategies: 
 Primary Trend Validation Protocol: 
 
 Identify primary trend direction using higher timeframe (4H or Daily) MACD position relative to zero line
 Confirm trend strength by analyzing histogram progression: consistent expansion indicates strong momentum, contraction suggests weakening
 Use secondary confirmation from MACD line angle: steep angles (>45°) indicate strong trends, shallow angles suggest consolidation
 Validate with price structure: trending markets show consistent higher highs/higher lows (uptrend) or lower highs/lower lows (downtrend)
 
 Entry Timing Techniques: 
 
 Pullback Entries in Uptrends:  Wait for MACD histogram to decline toward zero line without crossing, then enter on histogram expansion with MACD line still above zero
 Breakout Confirmations:  Use MACD line crossing above zero as confirmation of upward breakouts from consolidation patterns
 Continuation Signals:  Look for MACD line re-acceleration (steepening angle) after brief consolidation periods as trend continuation signals
 
 Advanced Divergence Trading Systems: 
 Regular Divergence Recognition: 
 
 Bullish Regular Divergence:  Price creates lower lows while MACD line forms higher lows. This pattern is traditionally considered a potential upward reversal signal, but should be combined with other confirmation signals
 Bearish Regular Divergence:  Price makes higher highs while MACD shows lower highs. This pattern is traditionally considered a potential downward reversal signal, but trading decisions should incorporate proper risk management
 
 Hidden Divergence Strategies: 
 
 Bullish Hidden Divergence:  Price shows higher lows while MACD displays lower lows, indicating trend continuation potential. Use for adding to existing long positions during pullbacks
 Bearish Hidden Divergence:  Price creates lower highs while MACD forms higher highs, suggesting downtrend continuation. Optimal for adding to short positions during bear market rallies
 
 Multi-Timeframe Coordination Framework: 
 Three-Timeframe Analysis Structure: 
 
 Primary Timeframe (Daily):  Determine overall market bias and major trend direction. Only trade in alignment with daily MACD direction
 Secondary Timeframe (4H):  Identify intermediate trend changes and major entry opportunities. Use for position sizing decisions
 Execution Timeframe (1H):  Precise entry and exit timing. Look for MACD line crossovers that align with higher timeframe bias
 
 Timeframe Synchronization Rules: 
 
 Daily MACD above zero + 4H MACD rising = Strong uptrend context for long positions
 Daily MACD below zero + 4H MACD declining = Strong downtrend context for short positions
 Conflicting signals between timeframes = Wait for alignment or use smaller position sizes
 1H MACD signals only valid when aligned with both higher timeframes
 
 Algorithm Considerations by Market Type: 
 
 Trending Markets:  Responsive algorithms like EMA, HMA may be considered, but effectiveness should be tested for specific market conditions
 Volatile Markets:  Noise-reducing algorithms like KALMAN_FILTER, SUPER_SMOOTHER may help reduce false signals, though results vary by market
 Range-Bound Markets:  Stability-focused algorithms like SMA, RMA may provide smoother signals, but individual testing is required
 Short Timeframes:  Low-lag algorithms like ZLEMA, T3 theoretically respond faster but may also increase noise
 
 Important Note:  All algorithm choices and parameter settings should be thoroughly backtested and validated based on specific trading strategies, market conditions, and individual risk tolerance. Different market environments and trading styles may require different configuration approaches.
 📋 DETAILED PARAMETER CONFIGURATION 
 Comprehensive Source Selection Strategy: 
 Price Source Analysis and Optimization: 
 
 Close Price (Default):  Most commonly used, reflects final market sentiment of each period. Best for end-of-day analysis, swing trading, daily/weekly timeframes. Advantages: widely accepted standard, good for backtesting comparisons. Disadvantages: ignores intraday price action, may miss important highs/lows
 HL2 (High+Low)/2:  Midpoint of the trading range, reduces impact of opening gaps and closing spikes. Best for volatile markets, gap-prone assets, forex markets. Calculation impact: smoother MACD signals, reduced noise from price spikes. Optimal when asset shows frequent gaps, high volatility during specific sessions
 HLC3 (High+Low+Close)/3:  Weighted average emphasizing the close while including range information. Best for balanced analysis, most asset classes, medium-term trading. Mathematical effect: 33% weight to high/low, 33% to close, provides compromise between close and HL2. Use when standard close is too noisy but HL2 is too smooth
 OHLC4 (Open+High+Low+Close)/4:  True average of all price points, most comprehensive view. Best for complete price representation, algorithmic trading, statistical analysis. Considerations: includes opening sentiment, smoothest of all options but potentially less responsive. Optimal for markets with significant opening moves, comprehensive trend analysis
 
 Parameter Configuration Principles: 
 Important Note:  Different moving average algorithms have distinct mathematical characteristics and response patterns. The same parameter settings may produce vastly different results when using different algorithms. When switching algorithms, parameter settings should be re-evaluated and tested for appropriateness.
 Length Parameter Considerations: 
 
 Fast Length (Default 12):  Shorter periods provide faster response but may increase noise and false signals, longer periods offer more stable signals but slower response, different algorithms respond differently to the same parameters and may require adjustment
 Slow Length (Default 26):  Should maintain a reasonable proportional relationship with fast length, different timeframes may require different parameter configurations, algorithm characteristics influence optimal length settings
 Signal Length (Default 9):  Shorter lengths produce more frequent crossovers but may increase false signals, longer lengths provide better signal confirmation but slower response, should be adjusted based on trading style and chosen algorithm characteristics
 
 Comprehensive Algorithm Selection Framework: 
 MACD Line Algorithm Decision Matrix: 
 
 EMA (Standard Choice):  Mathematical properties: exponential weighting, recent price emphasis. Best for general use, traditional MACD behavior, backtesting compatibility. Performance characteristics: good balance of speed and smoothness, widely understood behavior
 SMA (Stability Focus):  Equal weighting of all periods, maximum smoothness. Best for ranging markets, noise reduction, conservative trading. Trade-offs: slower signal generation, reduced sensitivity to recent price changes
 HMA (Speed Optimized):  Hull Moving Average, designed for reduced lag. Best for trending markets, quick reversals, active trading. Technical advantage: square root period weighting, faster trend detection. Caution: can be more sensitive to noise
 KAMA (Adaptive):  Kaufman Adaptive MA, adjusts smoothing based on market efficiency. Best for varying market conditions, algorithmic trading. Mechanism: fast smoothing in trends, slow smoothing in sideways markets. Complexity: requires understanding of efficiency ratio
 
 Signal Line Algorithm Optimization Strategies: 
 
 Matching Strategy:  Use same algorithm for both MACD and signal lines. Benefits: consistent mathematical properties, predictable behavior. Best when backtesting historical strategies, maintaining traditional MACD characteristics
 Contrast Strategy:  Use different algorithms for optimization. Common combinations: MACD=EMA, Signal=SMA for smoother crossovers, MACD=HMA, Signal=RMA for balanced speed/stability, Advanced: MACD=KAMA, Signal=T3 for adaptive behavior with smooth signals
 Market Regime Adaptation:  Trending markets: both fast algorithms (EMA/HMA), Volatile markets: MACD=KALMAN_FILTER, Signal=SUPER_SMOOTHER, Range-bound: both slow algorithms (SMA/RMA)
 
 Parameter Sensitivity Considerations: 
 Impact of Parameter Changes: 
 
 Length Parameter Sensitivity:  Small parameter adjustments can significantly affect signal timing, while larger adjustments may fundamentally change indicator behavior characteristics
 Algorithm Sensitivity:  Different algorithms produce different signal characteristics. Thoroughly test the impact on your trading strategy before switching algorithms
 Combined Effects:  Changing multiple parameters simultaneously can create unexpected effects. Recommendation: adjust parameters one at a time and thoroughly test each change
 
 📈 PERFORMANCE ANALYSIS & COMPETITIVE ADVANTAGES 
 Response Characteristics by Algorithm: 
 
 Fastest Response:  ZLEMA, HMA, T3 - minimal lag but higher noise
 Balanced Performance:  EMA, DEMA, TEMA - good trade-off between speed and stability
 Highest Stability:  SMA, RMA, TMA - reduced noise but increased lag
 Adaptive Behavior:  KAMA, FRAMA, MCGINLEY_DYNAMIC - automatically adjust to market conditions
 
 Noise Filtering Capabilities: 
Advanced algorithms like KALMAN_FILTER and SUPER_SMOOTHER help reduce false signals compared to traditional EMA-based MACD. Noise-reducing algorithms can provide more stable signals in volatile market conditions, though results will vary based on market conditions and parameter settings.
 Market Condition Adaptability: 
Unlike fixed-algorithm MACD, this enhanced version allows real-time optimization. Trending markets benefit from responsive algorithms (EMA, HMA), while ranging markets perform better with stable algorithms (SMA, RMA). The ability to switch algorithms without changing indicators provides greater flexibility.
 Comparative Performance vs Traditional MACD: 
 
 Algorithm Flexibility:  21 algorithms vs 1 fixed EMA
 Signal Quality:  Reduced false signals through noise filtering algorithms
 Market Adaptability:  Optimizable for any market condition vs fixed behavior
 Customization Options:  Independent algorithm selection for MACD and signal lines vs forced matching
 Professional Features:  Advanced color coding, multiple alert conditions, comprehensive parameter control
 
 USAGE NOTES 
This indicator is designed for technical analysis and educational purposes. Like all technical indicators, it has limitations and should not be used as the sole basis for trading decisions. Algorithm performance varies with market conditions, and past characteristics do not guarantee future results. Always combine with proper risk management and thorough strategy testing.
Advanced Market Structure [OmegaTools]📌 Market Structure  
Advanced Market Structure is a next–generation indicator designed to decode price structure in real time by combining classical swing–based analysis with modern quantitative confirmation techniques. Built for traders who demand both precision and adaptability, it provides a robust multi–layered framework to identify structural shifts, trend continuations, and potential reversals across any asset class or timeframe.
Unlike traditional structure indicators that rely solely on visual swing identification, Market Structure   introduces an integrated methodology: pivot detection, Donchian trend modeling, statistical confirmation via Z–Score, and volume–based validation. Each element contributes to a comprehensive, systematic representation of the underlying market dynamics.
🔑 Core Features
1. Five Distinct Market Structure Modes
Standard Mode:
Captures structural breaks through classical swing high/low pivots. Ideal for discretionary traders looking for clarity in directional bias.
Confirmed Breakout Mode:
Requires validation beyond the initial pivot break, filtering out noise and reducing false positives.
Donchian Trend HL (High/Low):
Establishes structure based on absolute highs and lows over rolling lookback windows. This approach highlights broader momentum shifts and trend–defining extremes.
Donchian Trend CC (Close/Close):
Similar to HL mode, but calculated using closing prices, enabling more precise bias identification where close–to–close structure carries stronger statistical weight.
Average Mode:
A composite methodology that synthesizes the four models into a weighted signal, producing a balanced structural bias designed to minimize model–specific weaknesses.
2. Dynamic Pivot Recognition with Auto–Updating Levels
Swing highs and lows are automatically detected and plotted with adaptive horizontal levels. These dynamic support/resistance markers continuously extend into the future, ensuring that historically significant levels remain visible and actionable.
3. Color–Adaptive Candlesticks
Price bars are dynamically recolored to reflect the prevailing structural regime: bullish (default blue), bearish (default red), or neutral (gray). This enables instant visual recognition of regime changes without requiring external confirmation.
4. Statistical Reversal Triggers
The script integrates a 21–period Z–Score calculation applied to closing prices, combined with multi–layered volume confirmation (SMA and EMA convergence).
Bullish trigger: Z–Score < –2 with structural confirmation and volume support.
Bearish trigger: Z–Score > +2 with structural confirmation and volume support.
Signals are plotted as diamond markers above or below the bars, identifying potential high–probability reversal setups in real time.
5. Integrated Alpha Backtesting Engine
Each market structure mode is evaluated through a built–in backtesting routine, tracking hit ratios and consistency across the most recent ~2000 structural events.
Performance metrics (“Alpha”) are displayed directly on–chart via a dedicated Performance Dashboard Table, allowing side–by–side comparison of Standard, Confirmed Breakout, Donchian HL, Donchian CC, and Average models.
Traders can instantly evaluate which structural methodology best adapts to the current market conditions.
🎯 Practical Advantages
Systematic Clarity: Eliminates subjectivity in defining structural bias, offering a rules–based framework.
Statistical Transparency: Built–in performance metrics validate each mode in real time, allowing informed decision–making.
Noise Reduction: Confirmed Breakouts and Donchian modes filter out common traps in structural trading.
Multi–Asset Adaptability: Optimized for scalping, intraday, swing, and multi–day strategies across FX, equities, futures, commodities, and crypto.
Complementary Usage: Works as a stand–alone structure identifier or as a quantitative filter in larger algorithmic/trading frameworks.
⚙️ Ideal Users
Discretionary traders seeking an objective reference for structural bias.
Quantitative/systematic traders requiring on–chart statistical validation of structural regimes.
Technical analysts leveraging pivots, Donchian channels, and price action as part of broader frameworks.
Portfolio traders integrating structure into multi–factor models.
💡 Why This Tool?
Market Structure   is not a static indicator — it is an adaptive framework. By merging classical pivot theory with Donchian–style momentum analysis, and reinforcing both with statistical backtesting and volume confirmation, it provides traders with a unique ability:
To see the structure,
To measure its reliability,
And to act with confidence on quantifiably validated signals.
Live Market - Performance MonitorLive Market — Performance Monitor
Study material (no code) — step-by-step training guide for learners 
________________________________________
1) What this tool is — short overview
This indicator is a live market performance monitor designed for learning. It scans price, volume and volatility, detects order blocks and trendline events, applies filters (volume & ATR), generates trade signals (BUY/SELL), creates simple TP/SL trade management, and renders a compact dashboard summarizing market state, risk and performance metrics.
Use it to learn how multi-factor signals are constructed, how Greeks-style sensitivity is replaced by volatility/ATR reasoning, and how a live dashboard helps monitor trade quality.
________________________________________
2) Quick start — how a learner uses it (step-by-step)
1.	Add the indicator to a chart (any ticker / timeframe).
2.	Open inputs and review the main groups: Order Block, Trendline, Signal Filters, Display.
3.	Start with defaults (OB periods ≈ 7, ATR multiplier 0.5, volume threshold 1.2) and observe the dashboard on the last bar.
4.	Walk the chart back in time (use the last-bar update behavior) and watch how signals, order blocks, trendlines, and the performance counters change.
5.	Run the hands-on labs below to build intuition.
________________________________________
3) Main configurable inputs (what you can tweak)
•	Order Block Relevant Periods (default ~7): number of consecutive candles used to define an order block.
•	Min. Percent Move for Valid OB (threshold): minimum percent move required for a valid order block.
•	Number of OB Channels: how many past order block lines to keep visible.
•	Trendline Period (tl_period): pivot lookback for detecting highs/lows used to draw trendlines.
•	Use Wicks for Trendlines: whether pivot uses wicks or body.
•	Extension Bars: how far trendlines are projected forward.
•	Use Volume Filter + Volume Threshold Multiplier (e.g., 1.2): requires volume to be greater than multiplier × average volume.
•	Use ATR Filter + ATR Multiplier: require bar range > ATR × multiplier to filter noise.
•	Show Targets / Table settings / Colors for visualization.
________________________________________
4) Core building blocks — what the script computes (plain language)
Price & trend:
•	Spot / LTP: current close price.
•	EMA 9 / 21 / 50: fast, medium, slow moving averages to define short/medium trend.
o	trend_bullish: EMA9 > EMA21 > EMA50
o	trend_bearish: EMA9 < EMA21 < EMA50
o	trend_neutral: otherwise
Volatility & noise:
•	ATR (14): average true range used for dynamic target and filter sizing.
•	dynamic_zone = ATR × atr_multiplier: minimum bar range required for meaningful move.
•	Annualized volatility: stdev of price changes × sqrt(252) × 100 — used to classify volatility (HIGH/MEDIUM/LOW).
Momentum & oscillators:
•	RSI 14: overbought/oversold indicator (thresholds 70/30).
•	MACD: EMA(12)-EMA(26) and a 9-period signal line; histogram used for momentum direction and strength.
•	Momentum (ta.mom 10): raw momentum over 10 bars.
Mean reversion / band context:
•	Bollinger Bands (20, 2σ): upper, mid, lower.
o	price_position measures where price sits inside the band range as 0–100.
Volume metrics:
•	avg_volume = SMA(volume, 20) and volume_spike = volume > avg_volume × volume_threshold
o	volume_ratio = volume / avg_volume
Support & Resistance:
•	support_level = lowest low over 20 bars
•	resistance_level = highest high over 20 bars
•	current_position = percent of price between support & resistance (0–100)
________________________________________
5) Order Block detection — concept & logic
What it tries to find: a bar (the base) followed by N candles in the opposite direction (a classical order block setup), with a minimum % move to qualify. The script records the high/low of the base candle, averages them, and plots those levels as OB channels.
How learners should think about it (conceptual):
1.	An order block is a signature area where institutions (theory) left liquidity — often seen as a large bar followed by a sequence of directional candles.
2.	This indicator uses a configurable number of subsequent candles to confirm that the pattern exists.
3.	When found, it stores and displays the base candle’s high/low area so students can see how price later reacts to those zones.
Implementation note for learners: the tool keeps a limited history of OB lines (ob_channels). When new OBs exceed the count, the oldest lines are removed — good practice to avoid clutter.
________________________________________
6) Trendline detection — idea & interpretation
•	The script finds pivot highs and lows using a symmetric lookback (tl_period and half that as right/left).
•	It then computes a trendline slope from successive pivots and projects the line forward (extension_bars).
•	Break detection: Resistance break = close crosses above the projected resistance line; Support break = close crosses below projected support.
Learning tip: trendlines here are computed from pivot points and time. Watch how changing tl_period (bigger = smoother, fewer pivots) alters the trendlines and break signals.
________________________________________
7) Signal generation & filters — step-by-step
1.	Primary triggers:
o	Bullish trigger: order block bullish OR resistance trendline break.
o	Bearish trigger: bearish order block OR support trendline break.
2.	Filters applied (both must pass unless disabled):
o	Volume filter: volume must be > avg_volume × volume_threshold.
o	ATR filter: bar range (high-low) must exceed ATR × atr_multiplier.
o	Not in an existing trade: new trades only start if trade_active is false.
3.	Trend confirmation:
o	The primary trigger is only confirmed if trend is bullish/neutral for buys or bearish/neutral for sells (EMA alignment).
4.	Result:
o	When confirmed, a long or short trade is activated with TP/SL calculated from ATR multiples.
________________________________________
8) Trade management — what the tool does after a signal
•	Entry management: the script marks a trade as trade_active and sets long_trade or short_trade flags.
•	TP & SL rules:
o	Long: TP = high + 2×ATR ; SL = low − 1×ATR
o	Short: TP = low − 2×ATR ; SL = high + 1×ATR
•	Monitoring & exit:
o	A trade closes when price reaches TP or SL.
o	When TP/SL hit, the indicator updates win_count and total_pnl using a very simple calculation (difference between TP/SL and previous close).
o	Visual lines/labels are drawn for TP and updated as the trade runs.
Important learner notes:
•	The script does not store a true entry price (it uses close  in its P&L math), so PnL is an approximation — treat this as a learning proxy, not a position accounting system.
•	There’s no sizing, slippage, or fee accounted — students must manually factor these when translating to real trades.
•	This indicator is not a backtesting strategy; strategy.* functions would be needed for rigorous backtest results.
________________________________________
9) Signal strength & helper utilities
•	Signal strength is a composite score (0–100) made up of four signals worth 25 points each:
1.	RSI extreme (overbought/oversold) → 25
2.	Volume spike → 25
3.	MACD histogram magnitude increasing → 25
4.	Trend existence (bull or bear) → 25
•	Progress bars (text glyphs) are used to visually show RSI and signal strength on the table.
Learning point: composite scoring is a way to combine orthogonal signals — study how changing weights changes outcomes.
________________________________________
10) Dashboard — how to read each section (walkthrough)
The dashboard is split into sections; here's how to interpret them:
1.	Market Overview
o	LTP / Change%: immediate price & daily % change.
2.	RSI & MACD
o	RSI value plus progress bar (overbought 70 / oversold 30).
o	MACD histogram sign indicates bullish/bearish momentum.
3.	Volume Analysis
o	Volume ratio (current / average) and whether there’s a spike.
4.	Order Block Status
o	Buy OB / Sell OB: the average base price of detected order blocks or “No Signal.”
5.	Signal Status
o	🔼 BUY or 🔽 SELL if confirmed, or ⚪ WAIT.
o	No-trade vs Active indicator summarizing market readiness.
6.	Trend Analysis
o	Trend direction (from EMAs), market sentiment score (composite), volatility level and band/position metrics.
7.	Performance
o	Win Rate = wins / signals (percentage)
o	Total PnL = cumulative PnL (approximate)
o	Bull / Bear Volume = accumulated volumes attributable to signals
8.	Support & Resistance
o	20-bar highest/lowest — use as nearby reference points.
9.	Risk & R:R
o	Risk Level from ATR/price as a percent.
o	R:R Ratio computed from TP/SL if a trade is active.
10.	Signal Strength & Active Trade Status
•	Numeric strength + progress bar and whether a trade is currently active with TP/SL display.
________________________________________
11) Alerts — what will notify you
The indicator includes pre-built alert triggers for:
•	Bullish confirmed signal
•	Bearish confirmed signal
•	TP hit (long/short)
•	SL hit (long/short)
•	No-trade zone
•	High signal strength (score > 75%)
Training use: enable alerts during a replay session to be notified when the indicator would have signalled.
________________________________________
12) Labs — hands-on exercises for learners (step-by-step)
Lab A — Order Block recognition
1.	Pick a 15–30 minute timeframe on a liquid ticker.
2.	Use default OB periods (7). Mark each time the dashboard shows a Buy/Sell OB.
3.	Manually inspect the chart at the base candle and the following sequence — draw the OB zone by hand and watch later price reactions to it.
4.	Repeat with OB periods 5 and 10; note stability vs noise.
Lab B — Trendline break confirmation
1.	Increase trendline period (e.g., 20), watch trendlines form from pivots.
2.	When a resistance break is flagged, compare with MACD & volume: was momentum aligned?
3.	Note false breaks vs confirmed moves — change extension_bars to see projection effects.
Lab C — Filter sensitivity
1.	Toggle Use Volume Filter off, and record the number and quality of signals in a 2-day window.
2.	Re-enable volume filter and change threshold from 1.2 → 1.6; note how many low-quality signals are filtered out.
Lab D — Trade management simulation
1.	For each signalled trade, record the time, close  entry approximation, TP, SL, and eventual hit/miss.
2.	Compute actual PnL if you had entered at the open of the next bar to compare with the script’s PnL math.
3.	Tabulate win rate and average R:R.
Lab E — Performance review & improvement
1.	Build a spreadsheet of signals over 30–90 periods with columns: Date, Signal type, Entry price (real), TP, SL, Exit, PnL, Notes.
2.	Analyze which filters or indicators contributed most to winners vs losers and adjust weights.
________________________________________
13) Common pitfalls, assumptions & implementation notes (things to watch)
•	P&L simplification: total_pnl uses close  as a proxy entry price. Real entry/exit prices and slippage are not recorded — so PnL is approximate.
•	No position sizing or money management: the script doesn’t compute position size from equity or risk percent.
•	Signal confirmation logic: composite "signal_strength" is a simple 4×25 point scheme — explore different weights or additional signals.
•	Order block detection nuance: the script defines the base candle and checks the subsequent sequence. Be sure to verify whether the intended candle direction (base being bullish vs bearish) aligns with academic/your trading definition — read the code carefully and test.
•	Trendline slope over time: slope is computed using timestamps; small differences may make lines sensitive on very short timeframes — using bar_index differences is usually more stable.
•	Not a true backtester: to evaluate performance statistically you must transform the logic into a strategy script that places hypothetical orders and records exact entry/exit prices.
________________________________________
14) Suggested improvements for advanced learners
•	Record true entry price & timestamp for accurate PnL.
•	Add position sizing: risk % per trade using SL distance and account size.
•	Convert to strategy. (Pine Strategy)* to run formal backtests with equity curves, drawdowns, and metrics (Sharpe, Sortino).
•	Log trades to an external spreadsheet (via alerts + webhook) for offline analysis.
•	Add statistics: average win/loss, expectancy, max drawdown.
•	Add additional filters: news time blackout, market session filters, multi-timeframe confirmation.
•	Improve OB detection: combine wick/body, volume spike at base bar, and liquidity sweep detection.
________________________________________
15) Glossary — quick definitions
•	ATR (Average True Range): measure of typical range; used to size targets and stops.
•	EMA (Exponential Moving Average): trend smoothing giving more weight to recent prices.
•	RSI (Relative Strength Index): momentum oscillator; >70 overbought, <30 oversold.
•	MACD: momentum oscillator using difference of two EMAs.
•	Bollinger Bands: volatility bands around SMA.
•	Order Block: a base candle area with subsequent confirmation candles; a zone of institutional interest (learning model).
•	Pivot High/Low: local turning point defined by candles on both sides.
•	Signal Strength: combined score from multiple indicators.
•	Win Rate: proportion of signals that hit TP vs total signals.
•	R:R (Risk:Reward): ratio of potential reward (TP distance) to risk (entry to SL).
________________________________________
16) Limitations & assumptions (be explicit)
•	This is an indicator for learning — not a trading robot or broker connection.
•	No slippage, fees, commissions or tie-in to real orders are considered.
•	The logic is heuristic (rule-of-thumb), not a guarantee of performance.
•	Results are sensitive to timeframe, market liquidity, and parameter choices.
________________________________________
17) Practical classroom / study plan (4 sessions)
•	Session 1 — Foundations: Understand EMAs, ATR, RSI, MACD, Bollinger Bands. Run the indicator and watch how these numbers change on a single day.
•	Session 2 — Zones & Filters: Study order blocks and trendlines. Test volume & ATR filters and note changes in false signals.
•	Session 3 — Simulated trading: Manually track 20 signals, compute real PnL and compare to the dashboard.
•	Session 4 — Improvement plan: Propose changes (e.g., better PnL accounting, alternative OB rule) and test their impact.
________________________________________
18) Quick reference checklist for each signal
1.	Was an order block or trendline break detected? (primary trigger)
2.	Did volume meet threshold? (filter)
3.	Did ATR filter (bar size) show a real move? (filter)
4.	Was trend aligned (EMA 9/21/50)? (confirmation)
5.	Signal confirmed → mark entry approximation, TP, SL.
6.	Monitor dashboard (Signal Strength, Volatility, No-trade zone, R:R).
7.	After exit, log real entry/exit, compute actual PnL, update spreadsheet.
________________________________________
19) Educational caveat & final note
This tool is built for training and analysis: it helps you see how common technical building blocks combine into trade ideas, but it is not a trading recommendation. Use it to develop judgment, to test hypotheses, and to design robust systems with proper backtesting and risk control before risking capital.
________________________________________
20) Disclaimer (must include)
Training & Educational Only — This material and the indicator are provided for educational purposes only. Nothing here is investment advice or a solicitation to buy or sell financial instruments. Past simulated or historical performance does not predict future results. Always perform full backtesting and risk management, and consider seeking advice from a qualified financial professional before trading with real capital.
________________________________________
Infinite EMA with Alpha Control♾️  Infinite EMA with Alpha Control 
 What Makes This EMA "Infinite"? 
Unlike traditional EMA indicators that are limited to typical periods (1-5000), this Infinite EMA breaks all boundaries. You can create EMAs with periods of 1,000, 10,000, or even 1,000,000 bars - that's why it's called "infinite"! Also Infinite EMA starts working immediately from the very first bar on your chart
 Why This EMA is "Infinite": 
1.	Mathematically: When N → ∞, alpha → 0, meaning infinitely long "memory"
2.	Practically: You can set any period - even 100,000 bars
3.	Flexibility: Alpha allows precise control over the "forgetting speed"
 How Does It Work? 
The magic lies in the Alpha parameter. While regular EMAs use fixed formulas, this indicator gives you direct control over the EMA's "memory" through Alpha values:
•	High Alpha (0.1-0.2): Fast reaction, short memory
•	Medium Alpha (0.01-0.05): Balanced response
•	Low Alpha (0.0001-0.001): Extremely slow reaction, very long memory
•	Ultra-low Alpha (0.000001): Almost frozen in time
 The Mathematical Formula: 
Alpha = 2 / (Period + 1)
This means you can achieve any EMA period by adjusting Alpha, giving you infinite flexibility!
 Expanded "Infinite EMA" Table: 
Period EMA (N)	- Alpha (Rounded)	- Alpha (Exact)	- Description
10	     -           0.1818	      -          0.181818...	- Fast EMA
20	              -  0.0952	        -        0.095238...	- Short-term
50	              -  0.0392	       -         0.039215...	- Medium-term
100	              -  0.0198	       -         0.019801...	- Long-term
200	              -  0.0100	       -         0.009950...	- Standard long-term
500	              -  0.0040	       -         0.003996...	- Very long-term
1,000	      -  0.0020	       -         0.001998...	- Super long-term
2,000	      -  0.0010	       -         0.000999...	- Ultra long-term
5,000	      -  0.0004	       -         0.000399...	- Mega long-term
10,000	      -  0.0002	       -         0.000199...	- Giga long-term
25,000	      -  0.00008	       -         0.000079...	- Century-scale EMA
50,000	      -  0.00004	        -        0.000039...	- Practically motionless
100,000	      -  0.00002	        -        0.000019...	- "Glacial" EMA
500,000	     -   0.000004	        -        0.000003...	- Geological timescale
1,000,000	      -  0.000002	         -       0.000001...	- Approaching constant
5,000,000	     -   0.0000004	 -       0.0000003...	- Virtually static
10,000,000    -  0.0000002	          -      0.0000001...	- Nearly flat line
100,000,000   -   0.00000002	  -      0.00000001...	- Mathematical infinity
 Formula: Alpha = 2/(N+1) where N is the EMA period 
 Key Features: 
Dual EMA System: Run fast and slow EMAs simultaneously
Crossover Signals: Automatic buy/sell signals with customizable alerts
Alpha Control: Direct mathematical control over EMA behavior
Infinite Periods: From 1 to 100,000,000+ bars
Visual Customization: Colors, fills, backgrounds, signal sizes
Instant Start: Works accurately from the very first bar
Update Intervals: Control calculation frequency for noise reduction
 Why Choose Infinite EMA? 
1.	Unlimited Flexibility: Any period you can imagine
2.	Mathematical Precision: Direct alpha control for exact behavior
3.	Professional Grade: Suitable for all trading styles
4.	Easy to Use: Simple settings with powerful results
5.	No Warm-up Period: Accurate values from bar #1
 Simple Explanation: 
Think of EMA as a "memory system":
•	High Alpha = Short memory (forgets quickly, reacts fast)
•	Low Alpha = Long memory (remembers everything, moves slowly)
With Infinite EMA, you can set the "memory length" to anything from seconds to centuries!
⚡  Instant Start Feature - EMA from First Bar 
 Immediate Calculation from Bar #1 
Unlike traditional EMA indicators that require a "warm-up period" of N bars before showing accurate values, Infinite EMA starts working immediately from the very first bar on your chart.
 How It Works: 
 Traditional EMA Problem: 
•	Standard 200-period EMA: Needs 200+ bars to become accurate
•	First 200 bars: Shows incorrect/unstable values
•	Result: Large portions of historical data are unusable
 Infinite EMA Solution: 
 Bar #1: EMA = Current Price (perfect starting point)
Bar #2: EMA = Alpha × Price + (1-Alpha) × Previous EMA  
Bar #3: EMA = Alpha × Price + (1-Alpha) × Previous EMA
...and so on 
 Key Benefits: 
No Warm-up Period: Start trading signals from day one
Full Chart Coverage: Every bar has a valid EMA value
Historical Accuracy: Backtesting works on entire dataset
New Markets: Works perfectly on newly listed assets
Short Datasets: Effective even with limited historical data
 Practical Impact: 
Scenario	                         Traditional EMA                    Infinite EMA
New cryptocurrency	         Unusable for first 200 days  ✅ Works from day 1
Limited data (< 200 bars)	 Inaccurate values	           ✅ Fully functional
Backtesting	                 Must skip first 200 bars	   ✅ Test entire history
Real-time trading	         Wait for stabilization	   ✅ Trade immediately
 Technical Implementation: 
if barstate.isfirst
    EMA := currentPrice  // Perfect initialization
else  
    EMA := alpha × currentPrice + (1-alpha) × previousEMA
This smart initialization ensures mathematical accuracy from the very first calculation, eliminating the traditional EMA "ramp-up" problem.
 Why This Matters: 
For Backesters: Use 100% of available data
For Live Trading: Get signals immediately on any timeframe
For Researchers: Analyze complete datasets without gaps
Bottom Line: Infinite EMA is ready to work the moment you add it to your chart - no waiting, no warm-up, no exceptions!
Unlike traditional EMAs that require a "warm-up period" of 200+ bars before showing accurate values, Infinite EMA starts working immediately from bar #1.
This breakthrough eliminates the common problem where the first portion of your chart shows unreliable EMA data. Whether you're analyzing a newly listed cryptocurrency, working with limited historical data, or backtesting strategies, every single bar provides mathematically accurate EMA values.
No more waiting periods, no more unusable data sections - just instant, reliable trend analysis from the moment you apply the indicator to any chart.
🔄  Update Interval Bars Feature 
The Update Interval feature allows you to control how frequently the EMA recalculates, providing flexible noise filtering without changing the core mathematics.
Set to 1 for standard behavior (updates every bar), or increase to 5-10 for smoother signals that update less frequently. Higher intervals reduce market noise and false signals but introduce slightly more lag. This is particularly useful on volatile timeframes where you want the EMA's directional bias without every minor price fluctuation affecting the calculation.
Perfect for swing traders who prefer cleaner, more stable trend lines over hyper-responsive indicators.
 Conclusion 
The Infinite EMA transforms the traditional EMA from a fixed-period tool into a precision instrument with unlimited flexibility. By understanding the Alpha-Period relationship, traders can create custom EMAs that perfectly match their trading style, timeframe, and market conditions.
The "infinite" nature comes from the ability to set any period imaginable - from ultra-fast 2-bar EMAs to glacially slow 10-million-bar EMAs, all controlled through a single Alpha parameter.
________________________________________
 Whether you're a beginner looking for simple trend following or a professional researcher analyzing century-long patterns, Infinite EMA adapts to your needs. The power of infinite periods is now in your hands!  🚀
Go forward to the horizon. When you reach it, a new one will open up.
- J. P. Morgan






















