Khaled Tamim's Avellaneda-Stoikov StrategyDescription:
This strategy applies the Avellaneda-Stoikov (A-S) model to generate buy and sell signals for underlying assets based on option pricing theory. The A-S model estimates bid and ask quotes for options contracts considering factors like volatility (sigma), time to expiration (T), and risk aversion (gamma).
Key Concepts:
Avellaneda-Stoikov Model: A mathematical framework for option pricing that incorporates volatility, time decay, and risk tolerance.
Bid-Ask Quotes: The theoretical buy and sell prices for an option contract.
Inventory Management: The strategy tracks its long or short position based on signals.
How it Works:
A-S Model Calculation: The avellanedaStoikov function calculates bid and ask quotes using the underlying asset's closing price, user-defined parameters (gamma, sigma, T, k, and M), and a small fee (adjustable).
Signal Generation: The strategy generates long signals when the closing price falls below the adjusted bid quote and short signals when it exceeds the adjusted ask quote.
Trade Execution: Buy and sell orders are triggered based on the generated signals (long for buy, short for sell).
Inventory Tracking: The strategy's net profit reflects the current inventory level (long or short position).
Customization:
Gamma (γ): Controls risk aversion in the A-S model (higher values imply lower risk tolerance).
Sigma (σ): Represents the underlying asset's expected volatility.
T: Time to expiration for the hypothetical option (defaults to a short-term option).
k: A constant factor in the A-S model calculations.
M: Minimum price buffer for buy/sell signals (prevents excessive churn).
Important Note:
This strategy simulates option pricing behavior for a theoretical option and does not directly trade options contracts. Backtesting results may not reflect actual market conditions.
Further Considerations:
The 0.1% fee is a placeholder and may need adjustment based on real-world trading costs.
Consider using realistic timeframes for T (e.g., expiry for a real option)
Disclaimer: This strategy is for educational purposes only and does not constitute financial advice.
Educational
Volume-Supported Linear Regression Trend Modified StrategyHi everyone, this will be my first published script on Tradingview, maybe more to come.
For quite some time I have been looking for a script that performs no matter if price goes up or down or sideways. I believe this strategy comes pretty close to that. Although nowhere near the so called "buy&hold equity" of BTC, it has produced consistent profits even when price goes down.
It is a strategy which seems to work best on the 1H timeframe for cryptocurrencies.
Just by testing different settings for SL and TP you can customize it for each pair.
THE STRATEGY:
Basically, I used the Volume Supported Linear Regression Trend Model that LonesomeTheBlue has created and modified a few things such as entry and exit conditions. So all credits go to him!
LONG ENTRY: When there is a bullish cross of the short term trend (the histogram/columns), while the long term trend is above 0 and rising.
SHORT ENTRY: When there is a bearish cross (green to red) of the short-term trend (the histogram/columns), while the long term trend is beneath 0 and decreasing.
LONG EXIT: Bearish crossover of short-term trend while long term trend is below 0
SHORT EXIT: Bullish crossover of short-term trend while long term trend is above 0
Combining this with e.g. a SL of 2% and a TP of 20% (as used in my backtesting), combined with pyramiding and correct risk management, it gives pretty consistent results.
Be aware, this is only for educational purpose and in no means financial advise. Past results do not guarantee future results. This strategy can lose money!
Enjoy :)
PS: It works not only on BTC of course, works even better on some other major crypto pairs. I'll leave it to you to find out which ones ;)
Fibonacci Trend Reversal StrategyIntroduction
This publication introduces the " Fibonacci Retracement Trend Reversal Strategy, " tailored for traders aiming to leverage shifts in market momentum through advanced trend analysis and risk management techniques. This strategy is designed to pinpoint potential reversal points, optimizing trading opportunities.
Overview
The strategy leverages Fibonacci retracement levels derived from @IMBA_TRADER's lance Algo to identify potential trend reversals. It's further enhanced by a method called " Trend Strength Over Time " (TSOT) (by @federalTacos5392b), which utilizes percentile rankings of price action to measure trend strength. This also has implemented Dynamic SL finder by utilizing @veryfid's ATR Stoploss Finder which works pretty well
Indicators:
Fibonacci Retracement Levels : Identifies critical reversal zones at 23.6%, 50%, and 78.6% levels.
TSOT (Trend Strength Over Time) : Employs percentile rankings across various timeframes to gauge the strength and direction of trends, aiding in the confirmation of Fibonacci-based signals.
ATR (Average True Range) : Implements dynamic stop-loss settings for both long and short positions, enhancing trade security.
Strategy Settings :
- Sensitivity: Set default at 18, adjustable for more frequent or sparse signals based on market volatility.
- ATR Stop Loss Finder: Multiplier set at 3.5, applying the ATR value to determine stop losses dynamically.
- ATR Length: Default set to 14 with RMA smoothing.
- TSOT Settings: Hard-coded to identify percentile ranks, with no user-adjustable inputs due to its intrinsic calculation method.
Trade Direction Options : Configurable to support long, short, or both directions, adaptable to the trader's market assessment.
Entry Conditions :
- Long Entry: Triggered when the price surpasses the mid Fibonacci level (50%) with a bullish TSOT signal.
- Short Entry: Activated when the price falls below the mid Fibonacci level with a bearish TSOT indication.
Exit Conditions :
- Employs ATR-based dynamic stop losses, calibrated according to current market volatility, ensuring effective risk management.
Strategy Execution :
- Risk Management: Features adjustable risk-reward settings and enables partial take profits by default to systematically secure gains.
- Position Reversal: Includes an option to reverse positions based on new TSOT signals, improving the strategy's responsiveness to evolving market conditions.
The strategy is optimized for the BYBIT:WIFUSDT.P market on a scalping (5-minute) timeframe, using the default settings outlined above.
I spent a lot of time creating the dynamic exit strategies for partially taking profits and reversing positions so please make use of those and feel free to adjust the settings, tool tips are also provided.
For Developers: this is published as open-sourced code so that developers can learn something especially on dynamic exits and partial take profits!
Good Luck!
Disclaimer
This strategy is shared for educational purposes and must be thoroughly tested under diverse market conditions. Past performance does not guarantee future results. Traders are advised to integrate this strategy with other analytical tools and tailor it to specific market scenarios. I was only sharing what I've crafted while strategizing over a Solana Meme Coin.
FreedX Grid Backtest█ FreedX Grid Backtest is an open-source tool that offers accurate GRID calculations for GRID trading strategies. This advanced tool allows users to backtest GRID trading parameters with precision, accurately reflecting exchange functionalities. We are committed to enhancing trading strategies through precise backtesting solutions and address the issue of unreliable backtesting practices observed on GRID trading strategies. FreedX Grid Backtest is designed for optimal calculation speed and plotting efficiency, ensuring users to achieve fastest calculations during their analysis.
█ GRID TRADING STRATEGY SETTINGS
The core of the FreedX Grid Backtest tool lies in its ability to simulate grid trading strategies. Grid trading involves placing orders at regular intervals within a predefined price range, creating a grid of orders that capitalize on market volatility.
Features:
⚙️ Backtest Range:
→ Purpose: Allows users to specify the backtesting range of GRID strategy. Closes all positions at the end of this range.
→ How to Use: Drag the dates to fit the desired backtesting range.
⚙️ Investment & Compounding:
→ Purpose: Allows users to specify the total investment amount and select between fixed and compound investment strategies. Compounding adjusts trade quantities based on performance, enhancing the grid strategy's adaptability to market changes.
→ How to Use: Set the desired investment amount and choose between "Fixed" or "Compound" for the investment method.
⚙️ Leverage & Grid Levels:
→ Purpose: Leverage amplifies the investment amount, increasing potential returns (and risks). Users can define the number of grid levels, which determines how the investment is distributed across the grid.
→ How to Use: Input the desired leverage and number of grids. The tool automatically calculates the distribution of funds across each grid level.
⚙️ Distribution Type & Mode:
→ Purpose: Users can select the distribution type (Arithmetic or Geometric) to set how grid levels are determined. The mode (Neutral, Long, Short) dictates the direction of trades within the grid.
→ How to Use: Choose the distribution type and mode based on the desired trading strategy and market outlook.
⚙️ Enable LONG/SHORT Grids exclusively:
█ MANUAL LEVELS AND STOP TRIGGERS
Beyond automated settings, the tool offers manual adjustments for traders seeking finer control over their grid strategies.
Features:
⚙️ Manual Level Adjustment:
→ Purpose: Enables traders to manually set the top, reference, and bottom levels of the grid, offering precision control over the trading range.
→ How to Use: Activate manual levels and adjust the top, reference, and bottom levels as needed to define the grid's scope.
⚙️ Stop Triggers:
→ Purpose: Provides an option to set upper and lower price limits, acting as stop triggers to close or terminate trades. This feature safeguards investments against significant market movements outside the anticipated range.
→ How to Use: Enable stop triggers and specify the upper and lower limits. The tool will automatically manage positions based on these parameters.
---
This guide gives you a quick and clear overview of the FreedX Grid Backtest tool, explaining how you can use this cutting-edge tool to improve your trading strategies.
Trend Deviation strategy - BTC [IkkeOmar]Intro:
This is an example if anyone needs a push to get started with making strategies in pine script. This is an example on BTC, obviously it isn't a good strategy, and I wouldn't share my own good strategies because of alpha decay.
This strategy integrates several technical indicators to determine market trends and potential trade setups. These indicators include:
Directional Movement Index (DMI)
Bollinger Bands (BB)
Schaff Trend Cycle (STC)
Moving Average Convergence Divergence (MACD)
Momentum Indicator
Aroon Indicator
Supertrend Indicator
Relative Strength Index (RSI)
Exponential Moving Average (EMA)
Volume Weighted Average Price (VWAP)
It's crucial for you guys to understand the strengths and weaknesses of each indicator and identify synergies between them to improve the strategy's effectiveness.
Indicator Settings:
DMI (Directional Movement Index):
Length: This parameter determines the number of bars used in calculating the DMI. A higher length may provide smoother results but might lag behind the actual price action.
Bollinger Bands:
Length: This parameter specifies the number of bars used to calculate the moving average for the Bollinger Bands. A longer length results in a smoother average but might lag behind the price action.
Multiplier: The multiplier determines the width of the Bollinger Bands. It scales the standard deviation of the price data. A higher multiplier leads to wider bands, indicating increased volatility, while a lower multiplier results in narrower bands, suggesting decreased volatility.
Schaff Trend Cycle (STC):
Length: This parameter defines the length of the STC calculation. A longer length may result in smoother but slower-moving signals.
Fast Length: Specifies the length of the fast moving average component in the STC calculation.
Slow Length: Specifies the length of the slow moving average component in the STC calculation.
MACD (Moving Average Convergence Divergence):
Fast Length: Determines the number of bars used to calculate the fast EMA (Exponential Moving Average) in the MACD.
Slow Length: Specifies the number of bars used to calculate the slow EMA in the MACD.
Signal Length: Defines the number of bars used to calculate the signal line, which is typically an EMA of the MACD line.
Momentum Indicator:
Length: This parameter sets the number of bars over which momentum is calculated. A longer length may provide smoother momentum readings but might lag behind significant price changes.
Aroon Indicator:
Length: Specifies the number of bars over which the Aroon indicator calculates its values. A longer length may result in smoother Aroon readings but might lag behind significant market movements.
Supertrend Indicator:
Trendline Length: Determines the length of the period used in the Supertrend calculation. A longer length results in a smoother trendline but might lag behind recent price changes.
Trendline Factor: Specifies the multiplier used in calculating the trendline. It affects the sensitivity of the indicator to price changes.
RSI (Relative Strength Index):
Length: This parameter sets the number of bars over which RSI calculates its values. A longer length may result in smoother RSI readings but might lag behind significant price changes.
EMA (Exponential Moving Average):
Fast EMA: Specifies the number of bars used to calculate the fast EMA. A shorter period results in a more responsive EMA to recent price changes.
Slow EMA: Determines the number of bars used to calculate the slow EMA. A longer period results in a smoother EMA but might lag behind recent price changes.
VWAP (Volume Weighted Average Price):
Default settings are typically used for VWAP calculations, which consider the volume traded at each price level over a specific period. This indicator provides insights into the average price weighted by trading volume.
backtest range and rules:
You can specify the start date for backtesting purposes.
You can can select the desired trade direction: Long, Short, or Both.
Entry and Exit Conditions:
LONG:
DMI Cross Up: The Directional Movement Index (DMI) indicates a bullish trend when the positive directional movement (+DI) crosses above the negative directional movement (-DI).
Bollinger Bands (BB): The price is below the upper Bollinger Band, indicating a potential reversal from the upper band.
Momentum Indicator: Momentum is positive, suggesting increasing buying pressure.
MACD (Moving Average Convergence Divergence): The MACD line is above the signal line, indicating bullish momentum.
Supertrend Indicator: The Supertrend indicator signals an uptrend.
Schaff Trend Cycle (STC): The STC indicates a bullish trend.
Aroon Indicator: The Aroon indicator signals a bullish trend or crossover.
When all these conditions are met simultaneously, the strategy considers it a favorable opportunity to enter a long trade.
SHORT:
DMI Cross Down: The Directional Movement Index (DMI) indicates a bearish trend when the negative directional movement (-DI) crosses above the positive directional movement (+DI).
Bollinger Bands (BB): The price is above the lower Bollinger Band, suggesting a potential reversal from the lower band.
Momentum Indicator: Momentum is negative, indicating increasing selling pressure.
MACD (Moving Average Convergence Divergence): The MACD line is below the signal line, signaling bearish momentum.
Supertrend Indicator: The Supertrend indicator signals a downtrend.
Schaff Trend Cycle (STC): The STC indicates a bearish trend.
Aroon Indicator: The Aroon indicator signals a bearish trend or crossover.
When all these conditions align, the strategy considers it an opportune moment to enter a short trade.
Disclaimer:
THIS ISN'T AN OPTIMAL STRATEGY AT ALL! It was just an old project from when I started learning pine script!
The backtest doesn't promise the same results in the future, always do both in-sample and out-of-sample testing when backtesting a strategy. And make sure you forward test it as well before implementing it!
Furthermore this strategy uses both trend and mean-reversion systems, that is usually a no-go if you want to build robust trend systems .
Don't hesitate to comment if you have any questions or if you have some good notes for a beginner.
Aroon and ASH strategy - ETHERIUM [IkkeOmar]Intro:
This post introduces a Pine Script strategy, as an example if anyone needs a push to get started. This example is a strategy on ETH, obviously it isn't a good strategy, and I wouldn't share my own good strategies because of alpha decay. This strategy combines two technical indicators: Aroon and Absolute Strength Histogram (ASH).
Overview:
The strategy employs the Aroon indicator alongside the Absolute Strength Histogram (ASH) to determine market trends and potential trade setups. Aroon helps identify the strength and direction of a trend, while ASH provides insights into the strength of momentum. By combining these indicators, the strategy aims to capture profitable trading opportunities in Ethereum markets. Normally when developing strats using indicators, you want to find some good indicators, but you NEED to understand their strengths and weaknesses, other indicators can be incorporated to minimize the downs of another indicator. Try to look for synergy in your indicators!
Indicator settings:
Aroon Indicator:
- Two sets of parameters are used for the Aroon indicator:
- For Long Positions: Aroon periods are set to 56 (upper) and 20 (lower).
- For Short Positions: Aroon periods are set to 17 (upper) and 55 (lower).
Absolute Strength Histogram (ASH):
ASH is calculated with a length of 9 bars using the closing price as the data source.
Trading Conditions:
The strategy incorporates specific conditions to initiate and exit trades:
Start Date:
Traders can specify the start date for backtesting purposes.
Trade Direction:
Traders can select the desired trade direction: Long, Short, or Both.
Entry and Exit Conditions:
1. Long Position Entry: A long position is initiated when the Aroon indicator crosses over (crossover) the lower Aroon threshold, indicating a potential uptrend.
2. Long Position Exit: A long position is closed when the Aroon indicator crosses under (crossunder) the lower Aroon threshold.
3. Short Position Entry: A short position is initiated when the Aroon indicator crosses under (crossunder) the upper Aroon threshold, signaling a potential downtrend.
4. Short Position Exit: A short position is closed when the Aroon indicator crosses over (crossover) the upper Aroon threshold.
Disclaimer:
THIS ISN'T AN OPTIMAL STRATEGY AT ALL! It was just an old project from when I started learning pine script!
The backtest doesn't promise the same results in the future, always do both in-sample and out-of-sample testing when backtesting a strategy. And make sure you forward test it as well before implementing it!
Strategy / Connectable [Azullian]The connectable strategy serves as a foundational component in our indicator system on TradingView, designed for intuitive testing, visualization, and construction of trading strategies. In concert with the connectable signal filter , it forms a cohesive unit that allows for efficient signal processing and strategy implementation. This integration enables the strategy to receive and act on weighted signals from various connectable indicators, making it a versatile tool for both novice and experienced traders.
Let's review the separate parts of this indicator.
█ STRATEGY INPUTS
We've provided an input to connect a signal filter or indicators or chains (→) which is set to 'Close' by default.
An input has several controls:
• Input: Connect indicators or signal filter here, choose indicators with a compatible : Signal connector.
• SM - Signal Mode: Choose a trading direction compatible with the settings in your signal filter
█ POSITION INVESTMENT
Determine the percentage of your trading budget you would like to use in each position based on the strategy's profit or loss.
• LINVB - Loss Investment Base: Choose which base to use to determine the investment percentage when the strategy is in a loss.
○ Equity: Use the equity as the base for percentage calculation.
○ Initial capital: Use the initial capital as the base for percentage calculation.
• LINV% - Loss Investment Percentage: Set a percentage of the chosen investment base as the investment for a new position.
○ For example, when 10% in loss, and a initial capital of $100, and the investment base is set to equity with a percentage of 50%, your investment will be 50% of $90, $45.
• PINVB - Profit Investment Base: Choose which base to use to determine the investment percentage when the strategy is in profit.
○ Equity: Use the equity as the base for percentage calculation.
○ Initial capital: Use the initial capital as the base for percentage calculation.
• PINV% - Profit Investment Percentage: Set a percentage of the chosen investment base as the investment for a new position.
○ For example, when 10% in profit, and an initial capital of $100, and the investment base is set to equity with a percentage of 100%, your investment will be 100% of $110, $110.
• RISK% - Risk Percentage:
○ Determine how much of the calculated position investment is at risk when the stop-loss is hit.
- For example, 1% of $45 represents a maximum loss of $0.45.
○ Risk percentage works together with the stop loss and the max leverage.
• MXLVG - Maximum Leverage:
○ Investigate the trading rules for your trading pair and use the maximum allowed amount of leverage.
○ To determine the number of contracts to be bought or sold, considering the stop loss and the specified risk percentage, the maximum leverage available will constrain the amount of leverage utilized to ensure that the maximum risk threshold is not exceeded. For instance, suppose the stop loss is set at 1%, and the risk percentage is defined as 10%. Initially, the calculated leverage to be used would be 10. However, if there is a maximum leverage cap set at 5, it would constrain the calculated leverage of 10 to adhere to the maximum limit of 5.
█ EXIT STOP LOSS
Determine the Stop Loss price based on your selected configuration.
As the stop loss is an integral part of the ordered contracts calculation used in conjunction with the Risk and Max leverage, you'll always need to provide a stop loss price.
• SLB - Stop Loss Base: Choose a stop loss mode for calculating stop loss prices.
○ Risk: Determines the price using the Risk parameter (RISK%) and maximum leverage (MXLVG). In this case, SLB% will not have any impact.
○ Price Entry + Offset: Calculates the stop loss price based on a offset percentage (SLB%) from the entry price of the position.
• SLB% - Stop Loss Base Percentage: Define an offset percentage that will be applied in the price entry + offset stop loss mode.
• SLT - Stop Loss Trailing:
○ Fixed: The initial stop loss will be kept and no trailing stop loss will be applied.
○ Trail Price: Computes the trailing stop loss price based on an offset percentage (SLT%) from the closing price of the current candle.
- If a better stop loss price is calculated, it will be set as the new stop loss price.
○ Trail Incr: Adapts the trailing stop loss price based on the offset percentage (SLT%).
- Each price change in favor of your position will incrementally adapt the trailing stop loss with SLT%.
• SLT% - Stop Loss Trailing Percentage: This percentage serves as an offset or increment depending on your chosen trailing mode.
█ EXIT TAKE PROFIT
Determine the Take Profit price based on your selected configuration.
• TPB - Take Profit Base: Choose a take profit mode for calculating take profit prices.
○ Reward: Determines the take profit price using the Risk parameter (RISK%) and the calculated Stop Loss price and the set reward percentage (TPB%).
- For example: Risk 1%, Calculated Stop loss price: $90, Entry price: $100, Reward (TPB%): 2%, will result in a take profit price on $120.
○ Price Entry + Offset: Calculates the take profit price based on a offset percentage (TPB%) from the entry price of the position.
- For example: Entry price: $100, Offset (TPB%): 2%, will result in a take profit price on $102.
• TPB% - Take Profit Base Percentage: Define an offset percentage that will be applied in the price entry + offset take profit mode.
• TPT - Take Profit Trailing:
○ Fixed: The initial take profit will be kept and no trailing take profit will be applied.
○ Trail Price: Computes the trailing take profit price based on an offset percentage (TPT%) from the closing price of the current candle.
- If an applicable take profit price is calculated, it will be set as the new take profit price.
○ Trail Incr: Adapts the trailing take profit price based on the offset percentage (TPT%). Each price change against your position will incrementally adapt the trailing take profit with TPT%.
• TPT% - Take Profit Trailing Percentage: This percentage serves as an offset or increment depending on your chosen trailing mode.
█ STRATEGY CONDITIONS
Specify when the strategy is permitted to execute trades.
• DATE: Enable the Date Range filter to restrict entries to a specific date range.
○ START: Set a start date and hour to commence trading.
○ END: Set an end date and hour to conclude trading within the defined range.
■ VISUALS
• LINE: Activate a colored dashed diagonal line to visually connect the entry and exit points of positions.
• SLTP: Enable visualization of stop loss, take profit, and break-even levels.
• PNL: Enable Break-Even and Close Lines along with a colored area in between to visualize profit and loss.
• ☼: Brightness % : Adjust the opacity of the plotted trading visuals.
• P - Profit Color : Choose the color for profit-related elements.
• L - Loss Color: Choose the color for loss-related elements.
• B - Breakeven Color : Select the color for break-even points.
• EL - Long Color: Specify the color for long positions.
• ES - Short Color: Specify the color for short positions.
• TRADE LABELING: For better analysis we've labeled all entries and exits conform with the type of order your strategy has executed, some examples:
○ XL-TP-150: Exit Long - Take Profit - Position 150
○ XS-TP-154: Exit Short - Take Profit - Position 154
○ XL-SL-160: Exit Long - Stop Loss - Position 160
○ XS-SL-164: Exit Short - Stop Loss - Position 164
█ USAGE OF CONNECTABLE INDICATORS
■ Connectable chaining mechanism
Connectable indicators can be connected directly to the signal monitor, signal filter or strategy , or they can be daisy chained to each other while the last indicator in the chain connects to the signal monitor, signal filter or strategy. When using a signal filter you can chain the filter to the strategy input to make your chain complete.
• Direct chaining: Connect an indicator directly to the signal monitor, signal filter or strategy through the provided inputs (→).
• Daisy chaining: Connect indicators using the indicator input (→). The first in a daisy chain should have a flow (⌥) set to 'Indicator only'. Subsequent indicators use 'Both' to pass the previous weight. The final indicator connects to the signal monitor, signal filter, or strategy.
■ Set up the strategy with a signal filter and an RSI indicator
Let's connect the Strategy to a connectable signal filter and a connectable RSI indicator :
1. Load all relevant indicators
• Load RSI / Connectable
• Load Signal filter / Connectable
• Load Strategy / Connectable
2. Signal Filter: Connect the RSI to the Signal Filter
• Open the signal filter settings
• Choose one of the three input dropdowns (1→, 2→, 3→) and choose : RSI / Connectable: Signal Connector
• Toggle the enable box before the connected input to enable the incoming signal
3. Signal Filter: Update the filter signals settings if needed
• The default settings of the filter enable EL (Enter Long), XL (Exit Long), ES (Enter Short) and XS (Exit Short).
4. Signal Filter: Update the weight threshold settings if needed
• All connectable indicators load by default with a score of 6 for each direction (EL, XL, ES, XS)
• By default, weight threshold (TH) is set at 5. This allows each occurrence to score, as the default score in each connectable indicator is 1 point above the threshold. Adjust to your liking.
5. Strategy: Connect the strategy to the signal filter in the strategy settings
• Select the strategy input → and select the Signal filter: Signal connector
6. Strategy: Enable filter compatible directions
• Set the signal mode of the strategy to a compatible direction with the signal filter.
Now that everything is connected, you'll notice green spikes in the signal filter representing long signals, and red spikes indicating short signals. Trades will also appear on the chart, complemented by a performance overview. Your journey is just beginning: delve into different scoring mechanisms, merge diverse connectable indicators, and craft unique chains. Instantly test your results and discover the potential of your configurations. Dive deep and enjoy the process!
█ BENEFITS
• Adaptable Modular Design: Arrange indicators in diverse structures via direct or daisy chaining, allowing tailored configurations to align with your analysis approach.
• Streamlined Backtesting: Simplify the iterative process of testing and adjusting combinations, facilitating a smoother exploration of potential setups.
• Intuitive Interface: Navigate TradingView with added ease. Integrate desired indicators, adjust settings, and establish alerts without delving into complex code.
• Signal Weight Precision: Leverage granular weight allocation among signals, offering a deeper layer of customization in strategy formulation.
• Advanced Signal Filtering: Define entry and exit conditions with more clarity, granting an added layer of strategy precision.
• Clear Visual Feedback: Distinct visual signals and cues enhance the readability of charts, promoting informed decision-making.
• Standardized Defaults: Indicators are equipped with universally recognized preset settings, ensuring consistency in initial setups across different types like momentum or volatility.
• Reliability: Our indicators are meticulously developed to prevent repainting. We strictly adhere to TradingView's coding conventions, ensuring our code is both performant and clean.
█ COMPATIBLE INDICATORS
Each indicator that incorporates our open-source 'azLibConnector' library and adheres to our conventions can be effortlessly integrated and used as detailed above.
For clarity and recognition within the TradingView platform, we append the suffix ' / Connectable' to every compatible indicator.
█ COMMON MISTAKES AND CLARIFICATIONS
• Removing an indicator from a chain: Deleting a linked indicator and confirming the "remove study tree" alert will also remove all underlying indicators in the object tree. Before removing one, disconnect the adjacent indicators and move it to the object stack's bottom.
• Point systems: The azLibConnector provides 500 points for each direction (EL: Enter long, XL: Exit long, ES: Enter short, XS: Exit short) Remember this cap when devising a point structure.
• Flow misconfiguration: In daisy chains the first indicator should always have a flow (⌥) setting of 'indicator only' while other indicator should have a flow (⌥) setting of 'both'.
• Recalculate: While this strategy has undergone extensive testing, enabling recalculation options like 'After order is filled' or 'On every tick' may lead to unexpected behavior.
• Fill orders: The strategy is thoroughly tested, yet enabling fill order options such as 'Using bar magnifier', 'On bar close', or 'Using standard OHLC' might result in unexpected outcomes.
• Layout and abbreviations: To maintain a consistent structure, we use abbreviations for each input. While this may initially seem complex, you'll quickly become familiar with them. Each abbreviation is also explained in the inline tooltips.
• Optimized for crypto trading: While many principles are common across markets, this strategy is specifically optimized and tested for crypto trading.
• Inputs: Connecting a connectable indicator directly to the strategy delivers the raw signal without a weight threshold, meaning every signal will trigger a trade.
█ A NOTE OF GRATITUDE
Through years of exploring TradingView and Pine Script, we've drawn immense inspiration from the community's knowledge and innovation. Thank you for being a constant source of motivation and insight.
█ RISK DISCLAIMER
Azullian's content, tools, scripts, articles, and educational offerings are presented purely for educational and informational uses. Please be aware that past performance should not be considered a predictor of future results.
Triple MA HTF strategy - Dynamic SmoothingThe triple MA strategy is a simple but effective method to trade the trend. The advantage of this script over the existing triple MA strategies is that the user can open a lower time frame chart and select higher time frame inputs for different MA types mainting the visibility on the chart. The dynamic smoothing code makes sure the HTF trendlines are not jagged, but a fluid line visiable on the lower time frame chart. The script comes with a MA crossover and crossunder strategy explained below.
Moving Averages (MA) Crossover for Entry:
Long Entry: A long entry signal is triggered when the moving average line 1 crosses above the moving average line 2. This crossover indicates a potential shift in market sentiment towards the upside. However, to validate this signal, the strategy checks if the moving average 3 on a higher time frame (eg. 4 hour) is in an upward trend. This additional filter ensures that the trade aligns with the prevailing trend on a broader time scale, increasing the probability of success.
Short Entry: Conversely, a short entry signal occurs when the moving average line 1 crosses below the moving average line 2. This crossover suggests a possible downturn in market momentum. However, for a short trade to be confirmed, the strategy verifies that the moving average 3 on the higher time frame is in a downward trend. This confirmation ensures that the trade is in harmony with the overarching market direction.
Exit from Long Position: The strategy triggers an exit signal from a long position when the moving average line 1 crosses below the moving average line 2. This crossover indicates a potential reversal in the market trend, prompting the trader to close their long position and take profits or minimize losses.
Exit from Short Position: Similarly, an exit signal from a short position occurs when the moving average line 1 crosses above the moving average line 2. This crossover suggests a potential shift in market sentiment towards the upside, prompting the trader to exit their short position and manage their risk accordingly.
Features of the script
This Triple MA Strategy is basically the HTF Trend Filter displayed 3 times on the chart. For more infomation on how the MA with dynamic smoothing is calculated I recommend reading the following script:
For risk management I included a simple script to opt for % of eauity or # of contracts of in the instrument. For explanation on how the risk management settings work I refer to my ealier published script:
The strategy is a simplified example for setting up an entry and exit logic based on multiple moving avarages. Hence the script is meant for educational purposes only.
Table to filter trades per dayThis script contains a block of code that allows users to filter the total number of trades, loss trades, win trades and win rate per day in a table. This makes it easier to compare which days were profitable and which were not.
Be aware that this script can only be used in strategy scripts. To use the script, open it and copy every line from "START" to "STOP". Then, paste these lines at the very bottom of the strategy script that you want to attach it to.
The user has the ability to adjust the position of the table and customize the size of the text displayed.
If the user sets "Check when the trade:" to "Opened", the script will monitor when the trade opens and add it to the table once it has been closed. If "Check when the trade:" is set to "Closed", the script will track when the trade is closed and add it to the table once it has been closed.
It is recommended to run the script on the "Exchange" setting for more accurate results, even though a "Set the timezone" option is available. This will prevent discrepancies caused by daylight saving time changes.
Please note that the code will only work properly if you choose a daily timeframe or lower.
Mean Reversion with Incremental Entry by HedgerLabsThe "Mean Reversion with Incremental Entry" strategy, designed by HedgerLabs, is an advanced TradingView strategy script focusing on the mean reversion technique in financial markets. This strategy is engineered for traders who prefer a systematic approach with an emphasis on incremental entries based on price movements relative to a moving average.
Key Features:
Moving Average Based Strategy: Central to this strategy is the simple moving average (SMA), around which all trade entries and exits revolve. Traders can customize the MA length, making it flexible for various trading styles and timeframes.
Incremental Entry Mechanism: Unique to this strategy is the incremental entry system. The strategy initiates an initial trade when the price deviates from the MA by a specified percentage. Subsequent entries are made at incremental steps, defined by the trader, as the price moves further away from the MA. This method can potentially capitalize on increasing market volatility.
Dynamic Position Management: The strategy intelligently manages positions by entering long when the price is below the MA and short when above, allowing for adaptive positioning in different market conditions.
Automated Exit Logic: Exit points are determined when the price touches the MA, aiming to close positions at potential reversal points for optimized trade outcomes.
Continuous Market Analysis: With 'calc_on_every_tick' enabled, the strategy constantly evaluates market conditions, ensuring prompt reaction to price movements.
Usage Scenario:
This strategy is particularly beneficial in markets exhibiting mean-reverting behavior. It is suitable for traders focusing on swing trading or those who prefer to scale into positions during periods of high volatility.
Disclaimer:
Please remember that this strategy is for informational and educational purposes only and is not intended as financial or investment advice. Trading in financial markets carries risks, including the potential loss of capital. We advise doing your own research and consulting with a financial expert before making any investment decisions.
TrailingTakeProfit exampleQuite recently I came upon a concept of Trailing Take Profit and I couldn't find a PineScript which implements it for the fastest possible execution, so here it is :)
Everybody knows Trailing StopLoss - an invisible mechanism follows the price and exits the trade once the price retreats too much from its recent most extended favourable value. Trailing TakeProfit does the similar thing, but at the opposite end - the trade gets closed if a price moves too well, in too favourable extent.
Why close the trade if it is going so good? Well, whatever goes up, must go down and vice versa. It is expected, that after fast rally a market will soon fall and after a dump it will go up. So Trailing TakeProfit's role is to secure profits.
But how does Trailing TakeProfit differ from the standard one? "Trailing" means, the exit level is moving. Its role is to be executed only after a rapid favourable move within 1-2 candles, not more. We never know when a rapid move happens, but when it does, we wanna catch those pips and quickly exit without looking back.
Visually Trailing TakeProfit levels are... bands. In this script example these are ATR multiplied bands (aka Keltner Channel), but they could also be Bollinger Bands or something else.
The code is simple just to focus on this single functionality, so you can quickly copy-paste it into your script. Entries are triggered by default SMA crosses.
P.S. I wouldn't be myself, if I didn't add alert messages compatible with the syntax of recently revamped TradingConnector - both in the code already and in the table showing them.
TASC 2024.01 Gap Momentum System█ OVERVIEW
TASC's January 2024 edition of Traders' Tips features an article titled “Gap Momentum” by Perry J. Kaufman. The article discusses how a trader might create a momentum strategy based on opening gap data. This script implements the Gap Momentum system presented therein.
█ CONCEPTS
In the article, Perry J. Kaufman introduces Gap Momentum as a cumulative series constructed in the same way as On-Balance Volume (OBV) , but using gap openings (today’s open minus yesterday’s close).
To smoothen the resulting time series (i.e., obtain the " signal line "), the author applies a simple moving average . Subsequently, he proposes the following two trading rules for a long-only trading system:
• Enter a long position when the signal line is moving higher.
• Exit when the signal line is moving lower.
█ CALCULATIONS
The calculation of Gap Momentum involves the following steps:
1. Calculate the ratio of the sum of positive gaps over the past N days to the sum of negative gaps (absolute values) over the same time period.
2. Add the resulting gap ratio to the cumulative time series. This time series is the Gap Momentum.
3. Keep moving forward, as in an N-day moving average.
Supertrend Advance Pullback StrategyHandbook for the Supertrend Advance Strategy
1. Introduction
Purpose of the Handbook:
The main purpose of this handbook is to serve as a comprehensive guide for traders and investors who are looking to explore and harness the potential of the Supertrend Advance Strategy. In the rapidly changing financial market, having the right tools and strategies at one's disposal is crucial. Whether you're a beginner hoping to dive into the world of trading or a seasoned investor aiming to optimize and diversify your portfolio, this handbook offers the insights and methodologies you need. By the end of this guide, readers should have a clear understanding of how the Supertrend Advance Strategy works, its benefits, potential pitfalls, and practical application in various trading scenarios.
Overview of the Supertrend Advance Pullback Strategy:
At its core, the Supertrend Advance Strategy is an evolution of the popular Supertrend Indicator. Designed to generate buy and sell signals in trending markets, the Supertrend Indicator has been a favorite tool for many traders around the world. The Advance Strategy, however, builds upon this foundation by introducing enhanced mechanisms, filters, and methodologies to increase precision and reduce false signals.
1. Basic Concept:
The Supertrend Advance Strategy relies on a combination of price action and volatility to determine the potential trend direction. By assessing the average true range (ATR) in conjunction with specific price points, this strategy aims to highlight the potential starting and ending points of market trends.
2. Methodology:
Unlike the traditional Supertrend Indicator, which primarily focuses on closing prices and ATR, the Advance Strategy integrates other critical market variables, such as volume, momentum oscillators, and perhaps even fundamental data, to validate its signals. This multidimensional approach ensures that the generated signals are more reliable and are less prone to market noise.
3. Benefits:
One of the main benefits of the Supertrend Advance Strategy is its ability to filter out false breakouts and minor price fluctuations, which can often lead to premature exits or entries in the market. By waiting for a confluence of factors to align, traders using this advanced strategy can increase their chances of entering or exiting trades at optimal points.
4. Practical Applications:
The Supertrend Advance Strategy can be applied across various timeframes, from intraday trading to swing trading and even long-term investment scenarios. Furthermore, its flexible nature allows it to be tailored to different asset classes, be it stocks, commodities, forex, or cryptocurrencies.
In the subsequent sections of this handbook, we will delve deeper into the intricacies of this strategy, offering step-by-step guidelines on its application, case studies, and tips for maximizing its efficacy in the volatile world of trading.
As you journey through this handbook, we encourage you to approach the Supertrend Advance Strategy with an open mind, testing and tweaking it as per your personal trading style and risk appetite. The ultimate goal is not just to provide you with a new tool but to empower you with a holistic strategy that can enhance your trading endeavors.
2. Getting Started
Navigating the financial markets can be a daunting task without the right tools. This section is dedicated to helping you set up the Supertrend Advance Strategy on one of the most popular charting platforms, TradingView. By following the steps below, you'll be able to integrate this strategy into your charts and start leveraging its insights in no time.
Setting up on TradingView:
TradingView is a web-based platform that offers a wide range of charting tools, social networking, and market data. Before you can apply the Supertrend Advance Strategy, you'll first need a TradingView account. If you haven't set one up yet, here's how:
1. Account Creation:
• Visit TradingView's official website.
• Click on the "Join for free" or "Sign up" button.
• Follow the registration process, providing the necessary details and setting up your login credentials.
2. Navigating the Dashboard:
• Once logged in, you'll be taken to your dashboard. Here, you'll see a variety of tools, including watchlists, alerts, and the main charting window.
• To begin charting, type in the name or ticker of the asset you're interested in the search bar at the top.
3. Configuring Chart Settings:
• Before integrating the Supertrend Advance Strategy, familiarize yourself with the chart settings. This can be accessed by clicking the 'gear' icon on the top right of the chart window.
• Adjust the chart type, time intervals, and other display settings to your preference.
Integrating the Strategy into a Chart:
Now that you're set up on TradingView, it's time to integrate the Supertrend Advance Strategy.
1. Accessing the Pine Script Editor:
• Located at the top-center of your screen, you'll find the "Pine Editor" tab. Click on it.
• This is where custom strategies and indicators are scripted or imported.
2. Loading the Supertrend Advance Strategy Script:
• Depending on whether you have the script or need to find it, there are two paths:
• If you have the script: Copy the Supertrend Advance Strategy script, and then paste it into the Pine Editor.
• If searching for the script: Click on the “Indicators” icon (looks like a flame) at the top of your screen, and then type “Supertrend Advance Strategy” in the search bar. If available, it will show up in the list. Simply click to add it to your chart.
3. Applying the Strategy:
• After pasting or selecting the Supertrend Advance Strategy in the Pine Editor, click on the “Add to Chart” button located at the top of the editor. This will overlay the strategy onto your main chart window.
4. Configuring Strategy Settings:
• Once the strategy is on your chart, you'll notice a small settings ('gear') icon next to its name in the top-left of the chart window. Click on this to access settings.
• Here, you can adjust various parameters of the Supertrend Advance Strategy to better fit your trading style or the specific asset you're analyzing.
5. Interpreting Signals:
• With the strategy applied, you'll now see buy/sell signals represented on your chart. Take time to familiarize yourself with how these look and behave over various timeframes and market conditions.
3. Strategy Overview
What is the Supertrend Advance Strategy?
The Supertrend Advance Strategy is a refined version of the classic Supertrend Indicator, which was developed to aid traders in spotting market trends. The strategy utilizes a combination of data points, including average true range (ATR) and price momentum, to generate buy and sell signals.
In essence, the Supertrend Advance Strategy can be visualized as a line that moves with the price. When the price is above the Supertrend line, it indicates an uptrend and suggests a potential buy position. Conversely, when the price is below the Supertrend line, it hints at a downtrend, suggesting a potential selling point.
Strategy Goals and Objectives:
1. Trend Identification: At the core of the Supertrend Advance Strategy is the goal to efficiently and consistently identify prevailing market trends. By recognizing these trends, traders can position themselves to capitalize on price movements in their favor.
2. Reducing Noise: Financial markets are often inundated with 'noise' - short-term price fluctuations that can mislead traders. The Supertrend Advance Strategy aims to filter out this noise, allowing for clearer decision-making.
3. Enhancing Risk Management: With clear buy and sell signals, traders can set more precise stop-loss and take-profit points. This leads to better risk management and potentially improved profitability.
4. Versatility: While primarily used for trend identification, the strategy can be integrated with other technical tools and indicators to create a comprehensive trading system.
Type of Assets/Markets to Apply the Strategy:
1. Equities: The Supertrend Advance Strategy is highly popular among stock traders. Its ability to capture long-term trends makes it particularly useful for those trading individual stocks or equity indices.
2. Forex: Given the 24-hour nature of the Forex market and its propensity for trends, the Supertrend Advance Strategy is a valuable tool for currency traders.
3. Commodities: Whether it's gold, oil, or agricultural products, commodities often move in extended trends. The strategy can help in identifying and capitalizing on these movements.
4. Cryptocurrencies: The volatile nature of cryptocurrencies means they can have pronounced trends. The Supertrend Advance Strategy can aid crypto traders in navigating these often tumultuous waters.
5. Futures & Options: Traders and investors in derivative markets can utilize the strategy to make more informed decisions about contract entries and exits.
It's important to note that while the Supertrend Advance Strategy can be applied across various assets and markets, its effectiveness might vary based on market conditions, timeframe, and the specific characteristics of the asset in question. As always, it's recommended to use the strategy in conjunction with other analytical tools and to backtest its effectiveness in specific scenarios before committing to trades.
4. Input Settings
Understanding and correctly configuring input settings is crucial for optimizing the Supertrend Advance Strategy for any specific market or asset. These settings, when tweaked correctly, can drastically impact the strategy's performance.
Grouping Inputs:
Before diving into individual input settings, it's important to group similar inputs. Grouping can simplify the user interface, making it easier to adjust settings related to a specific function or indicator.
Strategy Choice:
This input allows traders to select from various strategies that incorporate the Supertrend indicator. Options might include "Supertrend with RSI," "Supertrend with MACD," etc. By choosing a strategy, the associated input settings for that strategy become available.
Supertrend Settings:
1. Multiplier: Typically, a default value of 3 is used. This multiplier is used in the ATR calculation. Increasing it makes the Supertrend line further from prices, while decreasing it brings the line closer.
2. Period: The number of bars used in the ATR calculation. A common default is 7.
EMA Settings (Exponential Moving Average):
1. Period: Defines the number of previous bars used to calculate the EMA. Common periods are 9, 21, 50, and 200.
2. Source: Allows traders to choose which price (Open, Close, High, Low) to use in the EMA calculation.
RSI Settings (Relative Strength Index):
1. Length: Determines how many periods are used for RSI calculation. The standard setting is 14.
2. Overbought Level: The threshold at which the asset is considered overbought, typically set at 70.
3. Oversold Level: The threshold at which the asset is considered oversold, often at 30.
MACD Settings (Moving Average Convergence Divergence):
1. Short Period: The shorter EMA, usually set to 12.
2. Long Period: The longer EMA, commonly set to 26.
3. Signal Period: Defines the EMA of the MACD line, typically set at 9.
CCI Settings (Commodity Channel Index):
1. Period: The number of bars used in the CCI calculation, often set to 20.
2. Overbought Level: Typically set at +100, denoting overbought conditions.
3. Oversold Level: Usually set at -100, indicating oversold conditions.
SL/TP Settings (Stop Loss/Take Profit):
1. SL Multiplier: Defines the multiplier for the average true range (ATR) to set the stop loss.
2. TP Multiplier: Defines the multiplier for the average true range (ATR) to set the take profit.
Filtering Conditions:
This section allows traders to set conditions to filter out certain signals. For example, one might only want to take buy signals when the RSI is below 30, ensuring they buy during oversold conditions.
Trade Direction and Backtest Period:
1. Trade Direction: Allows traders to specify whether they want to take long trades, short trades, or both.
2. Backtest Period: Specifies the time range for backtesting the strategy. Traders can choose from options like 'Last 6 months,' 'Last 1 year,' etc.
It's essential to remember that while default settings are provided for many of these tools, optimal settings can vary based on the market, timeframe, and trading style. Always backtest new settings on historical data to gauge their potential efficacy.
5. Understanding Strategy Conditions
Developing an understanding of the conditions set within a trading strategy is essential for traders to maximize its potential. Here, we delve deep into the logic behind these conditions, using the Supertrend Advance Strategy as our focal point.
Basic Logic Behind Conditions:
Every strategy is built around a set of conditions that provide buy or sell signals. The conditions are based on mathematical or statistical methods and are rooted in the study of historical price data. The fundamental idea is to recognize patterns or behaviors that have been profitable in the past and might be profitable in the future.
Buy and Sell Conditions:
1. Buy Conditions: Usually formulated around bullish signals or indicators suggesting upward price momentum.
2. Sell Conditions: Centered on bearish signals or indicators indicating downward price momentum.
Simple Strategy:
The simple strategy could involve using just the Supertrend indicator. Here:
• Buy: When price closes above the Supertrend line.
• Sell: When price closes below the Supertrend line.
Pullback Strategy:
This strategy capitalizes on price retracements:
• Buy: When the price retraces to the Supertrend line after a bullish signal and is supported by another bullish indicator.
• Sell: When the price retraces to the Supertrend line after a bearish signal and is confirmed by another bearish indicator.
Indicators Used:
EMA (Exponential Moving Average):
• Logic: EMA gives more weight to recent prices, making it more responsive to current price movements. A shorter-period EMA crossing above a longer-period EMA can be a bullish sign, while the opposite is bearish.
RSI (Relative Strength Index):
• Logic: RSI measures the magnitude of recent price changes to analyze overbought or oversold conditions. Values above 70 are typically considered overbought, and values below 30 are considered oversold.
MACD (Moving Average Convergence Divergence):
• Logic: MACD assesses the relationship between two EMAs of a security’s price. The MACD line crossing above the signal line can be a bullish signal, while crossing below can be bearish.
CCI (Commodity Channel Index):
• Logic: CCI compares a security's average price change with its average price variation. A CCI value above +100 may mean the price is overbought, while below -100 might signify an oversold condition.
And others...
As the strategy expands or contracts, more indicators might be added or removed. The crucial point is to understand the core logic behind each, ensuring they align with the strategy's objectives.
Logic Behind Each Indicator:
1. EMA: Emphasizes recent price movements; provides dynamic support and resistance levels.
2. RSI: Indicates overbought and oversold conditions based on recent price changes.
3. MACD: Showcases momentum and direction of a trend by comparing two EMAs.
4. CCI: Measures the difference between a security's price change and its average price change.
Understanding strategy conditions is not just about knowing when to buy or sell but also about comprehending the underlying market dynamics that those conditions represent. As you familiarize yourself with each condition and indicator, you'll be better prepared to adapt and evolve with the ever-changing financial markets.
6. Trade Execution and Management
Trade execution and management are crucial aspects of any trading strategy. Efficient execution can significantly impact profitability, while effective management can preserve capital during adverse market conditions. In this section, we'll explore the nuances of position entry, exit strategies, and various Stop Loss (SL) and Take Profit (TP) methodologies within the Supertrend Advance Strategy.
Position Entry:
Effective trade entry revolves around:
1. Timing: Enter at a point where the risk-reward ratio is favorable. This often corresponds to confirmatory signals from multiple indicators.
2. Volume Analysis: Ensure there's adequate volume to support the movement. Volume can validate the strength of a signal.
3. Confirmation: Use multiple indicators or chart patterns to confirm the entry point. For instance, a buy signal from the Supertrend indicator can be confirmed with a bullish MACD crossover.
Position Exit Strategies:
A successful exit strategy will lock in profits and minimize losses. Here are some strategies:
1. Fixed Time Exit: Exiting after a predetermined period.
2. Percentage-based Profit Target: Exiting after a certain percentage gain.
3. Indicator-based Exit: Exiting when an indicator gives an opposing signal.
Percentage-based SL/TP:
• Stop Loss (SL): Set a fixed percentage below the entry price to limit potential losses.
• Example: A 2% SL on an entry at $100 would trigger a sell at $98.
• Take Profit (TP): Set a fixed percentage above the entry price to lock in gains.
• Example: A 5% TP on an entry at $100 would trigger a sell at $105.
Supertrend-based SL/TP:
• Stop Loss (SL): Position the SL at the Supertrend line. If the price breaches this line, it could indicate a trend reversal.
• Take Profit (TP): One could set the TP at a point where the Supertrend line flattens or turns, indicating a possible slowdown in momentum.
Swing high/low-based SL/TP:
• Stop Loss (SL): For a long position, set the SL just below the recent swing low. For a short position, set it just above the recent swing high.
• Take Profit (TP): For a long position, set the TP near a recent swing high or resistance. For a short position, near a swing low or support.
And other methods...
1. Trailing Stop Loss: This dynamic SL adjusts with the price movement, locking in profits as the trade moves in your favor.
2. Multiple Take Profits: Divide the position into segments and set multiple TP levels, securing profits in stages.
3. Opposite Signal Exit: Exit when another reliable indicator gives an opposite signal.
Trade execution and management are as much an art as they are a science. They require a blend of analytical skill, discipline, and intuition. Regularly reviewing and refining your strategies, especially in light of changing market conditions, is crucial to maintaining consistent trading performance.
7. Visual Representations
Visual tools are essential for traders, as they simplify complex data into an easily interpretable format. Properly analyzing and understanding the plots on a chart can provide actionable insights and a more intuitive grasp of market conditions. In this section, we’ll delve into various visual representations used in the Supertrend Advance Strategy and their significance.
Understanding Plots on the Chart:
Charts are the primary visual aids for traders. The arrangement of data points, lines, and colors on them tell a story about the market's past, present, and potential future moves.
1. Data Points: These represent individual price actions over a specific timeframe. For instance, a daily chart will have data points showing the opening, closing, high, and low prices for each day.
2. Colors: Used to indicate the nature of price movement. Commonly, green is used for bullish (upward) moves and red for bearish (downward) moves.
Trend Lines:
Trend lines are straight lines drawn on a chart that connect a series of price points. Their significance:
1. Uptrend Line: Drawn along the lows, representing support. A break below might indicate a trend reversal.
2. Downtrend Line: Drawn along the highs, indicating resistance. A break above might suggest the start of a bullish trend.
Filled Areas:
These represent a range between two values on a chart, usually shaded or colored. For instance:
1. Bollinger Bands: The area between the upper and lower band is filled, giving a visual representation of volatility.
2. Volume Profile: Can show a filled area representing the amount of trading activity at different price levels.
Stop Loss and Take Profit Lines:
These are horizontal lines representing pre-determined exit points for trades.
1. Stop Loss Line: Indicates the level at which a trade will be automatically closed to limit losses. Positioned according to the trader's risk tolerance.
2. Take Profit Line: Denotes the target level to lock in profits. Set according to potential resistance (for long trades) or support (for short trades) or other technical factors.
Trailing Stop Lines:
A trailing stop is a dynamic form of stop loss that moves with the price. On a chart:
1. For Long Trades: Starts below the entry price and moves up with the price but remains static if the price falls, ensuring profits are locked in.
2. For Short Trades: Starts above the entry price and moves down with the price but remains static if the price rises.
Visual representations offer traders a clear, organized view of market dynamics. Familiarity with these tools ensures that traders can quickly and accurately interpret chart data, leading to more informed decision-making. Always ensure that the visual aids used resonate with your trading style and strategy for the best results.
8. Backtesting
Backtesting is a fundamental process in strategy development, enabling traders to evaluate the efficacy of their strategy using historical data. It provides a snapshot of how the strategy would have performed in past market conditions, offering insights into its potential strengths and vulnerabilities. In this section, we'll explore the intricacies of setting up and analyzing backtest results and the caveats one must be aware of.
Setting Up Backtest Period:
1. Duration: Determine the timeframe for the backtest. It should be long enough to capture various market conditions (bullish, bearish, sideways). For instance, if you're testing a daily strategy, consider a period of several years.
2. Data Quality: Ensure the data source is reliable, offering high-resolution and clean data. This is vital to get accurate backtest results.
3. Segmentation: Instead of a continuous period, sometimes it's helpful to backtest over distinct market phases, like a particular bear or bull market, to see how the strategy holds up in different environments.
Analyzing Backtest Results:
1. Performance Metrics: Examine metrics like the total return, annualized return, maximum drawdown, Sharpe ratio, and others to gauge the strategy's efficiency.
2. Win Rate: It's the ratio of winning trades to total trades. A high win rate doesn't always signify a good strategy; it should be evaluated in conjunction with other metrics.
3. Risk/Reward: Understand the average profit versus the average loss per trade. A strategy might have a low win rate but still be profitable if the average gain far exceeds the average loss.
4. Drawdown Analysis: Review the periods of losses the strategy could incur and how long it takes, on average, to recover.
9. Tips and Best Practices
Successful trading requires more than just knowing how a strategy works. It necessitates an understanding of when to apply it, how to adjust it to varying market conditions, and the wisdom to recognize and avoid common pitfalls. This section offers insightful tips and best practices to enhance the application of the Supertrend Advance Strategy.
When to Use the Strategy:
1. Market Conditions: Ideally, employ the Supertrend Advance Strategy during trending market conditions. This strategy thrives when there are clear upward or downward trends. It might be less effective during consolidative or sideways markets.
2. News Events: Be cautious around significant news events, as they can cause extreme volatility. It might be wise to avoid trading immediately before and after high-impact news.
3. Liquidity: Ensure you are trading in assets/markets with sufficient liquidity. High liquidity ensures that the price movements are more reflective of genuine market sentiment and not due to thin volume.
Adjusting Settings for Different Markets/Timeframes:
1. Markets: Each market (stocks, forex, commodities) has its own characteristics. It's essential to adjust the strategy's parameters to align with the market's volatility and liquidity.
2. Timeframes: Shorter timeframes (like 1-minute or 5-minute charts) tend to have more noise. You might need to adjust the settings to filter out false signals. Conversely, for longer timeframes (like daily or weekly charts), you might need to be more responsive to genuine trend changes.
3. Customization: Regularly review and tweak the strategy's settings. Periodic adjustments can ensure the strategy remains optimized for the current market conditions.
10. Frequently Asked Questions (FAQs)
Given the complexities and nuances of the Supertrend Advance Strategy, it's only natural for traders, both new and seasoned, to have questions. This section addresses some of the most commonly asked questions regarding the strategy.
1. What exactly is the Supertrend Advance Strategy?
The Supertrend Advance Strategy is an evolved version of the traditional Supertrend indicator. It's designed to provide clearer buy and sell signals by incorporating additional indicators like EMA, RSI, MACD, CCI, etc. The strategy aims to capitalize on market trends while minimizing false signals.
2. Can I use the Supertrend Advance Strategy for all asset types?
Yes, the strategy can be applied to various asset types like stocks, forex, commodities, and cryptocurrencies. However, it's crucial to adjust the settings accordingly to suit the specific characteristics and volatility of each asset type.
3. Is this strategy suitable for day trading?
Absolutely! The Supertrend Advance Strategy can be adjusted to suit various timeframes, making it versatile for both day trading and long-term trading. Remember to fine-tune the settings to align with the timeframe you're trading on.
4. How do I deal with false signals?
No strategy is immune to false signals. However, by combining the Supertrend with other indicators and adhering to strict risk management protocols, you can minimize the impact of false signals. Always use stop-loss orders and consider filtering trades with additional confirmation signals.
5. Do I need any prior trading experience to use this strategy?
While the Supertrend Advance Strategy is designed to be user-friendly, having a foundational understanding of trading and market analysis can greatly enhance your ability to employ the strategy effectively. If you're a beginner, consider pairing the strategy with further education and practice on demo accounts.
6. How often should I review and adjust the strategy settings?
There's no one-size-fits-all answer. Some traders adjust settings weekly, while others might do it monthly. The key is to remain responsive to changing market conditions. Regular backtesting can give insights into potential required adjustments.
7. Can the Supertrend Advance Strategy be automated?
Yes, many traders use algorithmic trading platforms to automate their strategies, including the Supertrend Advance Strategy. However, always monitor automated systems regularly to ensure they're operating as intended.
8. Are there any markets or conditions where the strategy shouldn't be used?
The strategy might generate more false signals in markets that are consolidative or range-bound. During significant news events or times of unexpected high volatility, it's advisable to tread with caution or stay out of the market.
9. How important is backtesting with this strategy?
Backtesting is crucial as it allows traders to understand how the strategy would have performed in the past, offering insights into potential profitability and areas of improvement. Always backtest any new setting or tweak before applying it to live trades.
10. What if the strategy isn't working for me?
No strategy guarantees consistent profits. If it's not working for you, consider reviewing your settings, seeking expert advice, or complementing the Supertrend Advance Strategy with other analysis methods. Remember, continuous learning and adaptation are the keys to trading success.
Other comments
Value of combining several indicators in this script and how they work together
Diversification of Signals: Just as diversifying an investment portfolio can reduce risk, using multiple indicators can offer varied perspectives on potential price movements. Each indicator can capture a different facet of the market, ensuring that traders are not overly reliant on a single data point.
Confirmation & Reduced False Signals: A common challenge with many indicators is the potential for false signals. By requiring confirmation from multiple indicators before acting, the chances of acting on a false signal can be significantly reduced.
Flexibility Across Market Conditions: Different indicators might perform better under different market conditions. For example, while moving averages might excel in trending markets, oscillators like RSI might be more useful during sideways or range-bound conditions. A mashup strategy can potentially adapt better to varying market scenarios.
Comprehensive Analysis: With multiple indicators, traders can gauge trend strength, momentum, volatility, and potential market reversals all at once, providing a holistic view of the market.
How do the different indicators in the Supertrend Advance Strategy work together?
Supertrend: This is primarily a trend-following indicator. It provides traders with buy and sell signals based on the volatility of the price. When combined with other indicators, it can filter out noise and give more weight to strong, confirmed trends.
EMA (Exponential Moving Average): EMA gives more weight to recent price data. It can be used to identify the direction and strength of a trend. When the price is above the EMA, it's generally considered bullish, and vice versa.
RSI (Relative Strength Index): An oscillator that measures the magnitude of recent price changes to evaluate overbought or oversold conditions. By cross-referencing with other indicators like EMA or MACD, traders can spot potential reversals or confirmations of a trend.
MACD (Moving Average Convergence Divergence): This indicator identifies changes in the strength, direction, momentum, and duration of a trend in a stock's price. When the MACD line crosses above the signal line, it can be a bullish sign, and when it crosses below, it can be bearish. Pairing MACD with Supertrend can provide dual confirmation of a trend.
CCI (Commodity Channel Index): Initially developed for commodities, CCI can indicate overbought or oversold conditions. It can be used in conjunction with other indicators to determine entry and exit points.
In essence, the synergy of these indicators provides a balanced, comprehensive approach to trading. Each indicator offers its unique lens into market conditions, and when they align, it can be a powerful indication of a trading opportunity. This combination not only reduces the potential drawbacks of each individual indicator but leverages their strengths, aiming for more consistent and informed trading decisions.
Backtesting and Default Settings
• This indicator has been optimized to be applied for 1 hour-charts. However, the underlying principles of this strategy are supply and demand in the financial markets and the strategy can be applied to all timeframes. Daytraders can use the 1min- or 5min charts, swing-traders can use the daily charts.
• This strategy has been designed to identify the most promising, highest probability entries and trades for each stock or other financial security.
• The combination of the qualifiers results in a highly selective strategy which only considers the most promising swing-trading entries. As a result, you will normally only find a low number of trades for each stock or other financial security per year in case you apply this strategy for the daily charts. Shorter timeframes will result in a higher number of trades / year.
• Consequently, traders need to apply this strategy for a full watchlist rather than just one financial security.
• Default properties: RSI on (length 14, RSI buy level 50, sell level 50), EMA, RSI, MACD on, type of strategy pullback, SL/TP type: ATR (length 10, factor 3), trade direction both, quantity 5, take profit swing hl 5.1, highest / lowest lookback 2, enable ATR trail (ATR length 10, SL ATR multiplier 1.4, TP multiplier 2.1, lookback = 4, trade direction = both).
Stx Monthly Trades ProfitMonthly profit displays profits in a grid and allows you to know the gain related to the investment during each month.
The profit could be computed in terms of gain/trade_cost or as percentage of equity update.
Settings:
- Profit: Monthly profit percentage or percentage of equity
- Table position
This strategy is intended only as a container for the code and for testing the script of the profit table.
Setting of strategy allows to select the test case for this snippet (percentage grid).
Money management: not relevant as strategy is a test case.
This script stand out as take in account the gain of each trade in relation to the capital invested in each trade. For example consider the following scenario:
Capital of 1000$ and we invest a fixed amount of 1000$ (I know is too risky but is a good example), we gain 10% every month.
After 10 months our capital is of 2000$ and our strategy is perfect as we have the same performance every month.
Instead, evaluating the percentage of equity we have 10% the first month, 9.9% the second (1200$/1100$ - 1) and 5.26% the tenth month. So seems that strategy degrade with times but this is not true.
For this reason, to evaluate my strategy I prefer to see the montly return of investment.
WARNING: The strategy provided with this script is only a test case and allows to see the behavior with different "trades" management, for these reason commision are set to zero.
At the moment only the provided test cases are handled:
test 1 - single entry and single exit;
test 2 - single entry and multiple exits;
test 3 - single entry and switch position;
TradingView.To Strategy Template (with Dyanmic Alerts)Hello traders,
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of TradingView.TO alerts, sparing users the time and effort of mastering the TradingView.TO syntax and manually create alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via TradingView.TO bot.
IMPORTANT NOTES
TradingView.TO is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, Metatrader 4/5, ...) for automating trading.
Many traders don't know how to create TradingView.TO dynamically-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create TradingView.TO alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for BTC/USDT on the 5 minutes chart, 1 alert for BTC/USDT on the 15-minute chart (assuming you want your bot to trade the BTC/USDT on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) TradingView.TO uses webhook technology - setting a webhook URL from the alerts notifications tab is required.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
III) Order Types and Position Sizing
- Choose between market or limit orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either USD or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in USD for “risk-free” trades.
V) Miscellaneous:
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Logger
The TradingView.TO commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a TradingView.TO trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for TradingView.TO.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your TradingView.TO account
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with TradingView.TO.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
ProfitView Strategy TemplateHello traders,
This script took me a full week of coding/testing, sweat, and tears - and I’m too nice as I’m giving it for free to the community.
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
This Pine Script v5 template facilitates the dynamic construction of ProfitView alerts, sparing users the time and effort of mastering the ProfitView syntax and manually creating alert commands.
This powerful tool gives much power to those who don't know how to code in Pinescript and want to automate their indicators' signals via the ProfitView Chrome extension.
IMPORTANT NOTES
ProfitView is a trading bot software that forwards TradingView alerts to your brokers (examples: Binance, Oanda, Coinbase, Bybit, etc.) for automating trading.
Many traders don't know how to dynamically create ProfitView-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create ProfitView alerts dynamically.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) ProfitView doesn't use webhook technology, so setting a webhook URL from the alerts notifications tab is unnecessary.
KEY FEATURES
I) Modular Indicator Connection
* plug your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether a MACD , ZigZag, Pivots , higher-highs, lower-lows or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) BOT Risk Management:
- Max Drawdown:
Mode: Select whether the max drawdown is calculated in percentage (%) or USD.
Value: If the max drawdown reaches this specified value, set a value to halt the bot.
- Max Consecutive Days:
Use Max Consecutive Days BOT Halt: Enable/Disable halting the bot if the max consecutive losing days value is reached.
- Max Consecutive Days: Set the maximum number of consecutive losing days allowed before halting the bot.
- Max Losing Streak:
Use Max Losing Streak: Enable/Disable a feature to prevent the bot from taking too many losses in a row.
- Max Losing Streak Length: Set the maximum length of a losing streak allowed.
Margin Call:
- Use Margin Call: Enable/Disable a feature to exit when a specified percentage away from a margin call to prevent it.
Margin Call (%): Set the percentage value to trigger this feature.
- Close BOT Total Loss:
Use Close BOT Total Loss: Enable/Disable a feature to close all trades and halt the bot if the total loss is reached.
- Total Loss ($): Set the total loss value in USD to trigger this feature.
Intraday BOT Risk Management:
- Intraday Losses:
Use Intraday Losses BOT Halt: Enable/Disable halting the bot on reaching specified intraday losses.
Mode: Select whether the intraday loss is calculated in percentage (%) or USD.
- Max Intraday Losses (%): Set the value for maximum intraday losses.
Limit Intraday Trades:
- Use Limit Intraday Trades: Enable/Disable a feature to limit the number of intraday trades.
- Max Intraday Trades: Set the maximum number of intraday trades allowed.
Restart Intraday EA:
- Use Restart Intraday EA: Enable/Disable a feature to restart the bot at the first bar of the next day if it has been stopped with an intraday risk management safeguard.
III) Order Types and Position Sizing
- Choose between market, limit, or stop orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
I know it's redundant. - the template needs this value from the "Inputs" tab to build the alerts, and the Backtester needs it from the "Properties" tab.
IV) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either pips or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in pips for “risk-free” trades.
V) Miscellaneous
Retry order openings if they fail.
Order Types:
Select and specify order type and price settings.
Position Size:
Define the type and size of positions.
Leverage:
Leverage settings, including margin type and hedge mode.
Session:
Limit trades to specific sessions.
Dates:
Limit trades to a specific date range.
Trades Direction:
Direction: Specify the market direction for opening positions.
VI) Notifications (Telegram/Discord/Email/IFTTT/Twilio/SMS)
Customize notifications sent to Telegram, Discord, Email, IFTTT, Twilio, and ProfitView Logger.
VII) Logger
The ProfitView commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a ProfitView trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for ProfitView.
I tested them all and checked with the support team what could/couldn’t be done.
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your ProfitView account and do the settings correctly in your Chrome extension. If you don't know how to do it, read the documentation + ask for help in the ProfitView Discord support channel.
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with ProfitView.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1%
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
Best regards,
Dave
Pineconnector Strategy Template (Connect Any Indicator)Hello traders,
If you're tired of manual trading and looking for a solid strategy template to pair with your indicators, look no further.
This Pine Script v5 strategy template is engineered for maximum customization and risk management.
Best part?
It’s optimized for Pineconnector, allowing seamless integration with MetaTrader 4 and 5.
This powerful tool gives a lot of power to those who don't know how to code in Pinescript and are looking to automate their indicators' signals on Metatrader 4/5.
IMPORTANT NOTES
Pineconnector is a trading bot software that forwards TradingView alerts to your Metatrader 4/5 for automating trading.
Many traders don't know how to dynamically create Pineconnector-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to break options from your script and then create the orders accordingly.
This script showcases how to create Pineconnector alerts dynamically.
Pineconnector doesn't support alerts with multiple Take Profits.
As a workaround, for 2 TPs, I had to open two trades.
It's not optimal, as we end up paying more spreads for that extra trade - however, depending on your trading strategy, it may not be a big deal.
TRADINGVIEW ALERTS
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example: 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) Select the Order fills and alert() function calls condition
3) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
4) Don't forget to set the Pineconnector webhook URL in the Notifications tab of the TradingView alerts UI.
You’ll find the URL on the Pineconnector documentation website.
EA CONFIGURATION
1) The Pyramiding in the EA on Metatrader must be set to 2 if you want to trade with 2 TPs => as it's opening 2 trades.
If you only want 1 TP, set the EA Pyramiding to 1.
Regarding the other EA settings, please refer to the Pineconnector documentation on their website.
2) In the EA, you can set a risk (= position size type) in %/lots/USD, as in the TradingView backtest settings.
KEY FEATURES
I) Modular Indicator Connection
* plug in your existing indicator into the template.
* Only two lines of code are needed for full compatibility.
Step 1: Create your connector
Adapt your indicator with only 2 lines of code and then connect it to this strategy template.
To do so:
1) Find in your indicator where the conditions print the long/buy and short/sell signals.
2) Create an additional plot as below
I'm giving an example with a Two moving averages cross.
Please replicate the same methodology for your indicator, whether it's a MACD , ZigZag , Pivots , higher-highs, lower-lows, or whatever indicator with clear buy and sell conditions.
//@version=5
indicator("Supertrend", overlay = true, timeframe = "", timeframe_gaps = true)
atrPeriod = input.int(10, "ATR Length", minval = 1)
factor = input.float(3.0, "Factor", minval = 0.01, step = 0.01)
= ta.supertrend(factor, atrPeriod)
supertrend := barstate.isfirst ? na : supertrend
bodyMiddle = plot(barstate.isfirst ? na : (open + close) / 2, display = display.none)
upTrend = plot(direction < 0 ? supertrend : na, "Up Trend", color = color.green, style = plot.style_linebr)
downTrend = plot(direction < 0 ? na : supertrend, "Down Trend", color = color.red, style = plot.style_linebr)
fill(bodyMiddle, upTrend, color.new(color.green, 90), fillgaps = false)
fill(bodyMiddle, downTrend, color.new(color.red, 90), fillgaps = false)
buy = ta.crossunder(direction, 0)
sell = ta.crossunder(direction, 0)
//////// CONNECTOR SECTION ////////
Signal = buy ? 1 : sell ? -1 : 0
plot(Signal, title = "Signal", display = display.data_window)
//////// CONNECTOR SECTION ////////
Important Notes
🔥 The Strategy Template expects the value to be exactly 1 for the bullish signal and -1 for the bearish signal
Now, you can connect your indicator to the Strategy Template using the method below or that one.
Step 2: Connect the connector
1) Add your updated indicator to a TradingView chart
2) Add the Strategy Template as well to the SAME chart
3) Open the Strategy Template settings, and in the Data Source field, select your 🔌Connector🔌 (which comes from your indicator)
Note it doesn’t have to be named 🔌Connector🔌 - you can name it as you want - however, I recommend an explicit name you can easily remember.
From then, you should start seeing the signals and plenty of other stuff on your chart.
🔥 Note that whenever you update your indicator values, the strategy statistics and visuals on your chart will update in real-time
II) Customizable Risk Management
- Choose between percentage or USD modes for maximum drawdown.
- Set max consecutive losing days and max losing streak length.
- I used the code from my friend @JosKodify for the maximum losing streak. :)
Will halt the EA and backtest orders fill whenever either of the safeguards above are “broken”
III) Intraday Risk Management
- Limit the maximum intraday losses both in percentage or USD.
- Option to set a maximum number of intraday trades.
- If your EA gets halted on an intraday chart, auto-restart it the next day.
IV) Spread and Account Filters
- Trade only if the spread is below a certain pip value.
- Set requirements based on account balance or equity.
V) Order Types and Position Sizing
- Choose between market, limit, or stop orders.
- Set your position size directly in the template.
Please use the position size from the “Inputs” and not the “Properties” tab.
Reason : The template sends the order on the same candle as the entry signals - at those entry signals candles, the position size isn’t computed yet, and the template can’t then send it to Pineconnector.
However, you can use the position size type (USD, contracts, %) from the “Properties” tab for backtesting.
In the EA, you can define the position size type for your orders in USD or lots or %.
VI) Advanced Take-Profit and Stop-Loss Options
- Choose to set your SL/TP in either pips or percentages.
- Option for multiple take-profit levels and trailing stop losses.
- Move your stop loss to break even +/- offset in pips for “risk-free” trades.
VII) Logger
The Pineconnector commands are logged in the TradingView logger.
You'll find more information about it in this TradingView blog post .
WHY YOU MIGHT NEED THIS TEMPLATE
1) Transform your indicator into a Pineconnector trading bot more easily than before
Connect your indicator to the template
Create your alerts
Set your EA settings
2) Save Time
Auto-generated alert messages for Pineconnector.
I tested them all, and I checked with the support team what could/can’t be done
3) Be in Control
Manage your trading risks with advanced features.
4) Customizable
Fits various trading styles and asset classes.
REQUIREMENTS
* Make sure you have your Pineconnector license ID.
* Create your alerts with the Pineconnector webhook URL
* If there is any issue with the template, ask me in the comments section - I’ll answer quickly.
BACKTEST RESULTS FROM THIS POST
1) I connected this strategy template to a dummy Supertrend script.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with Pineconnector.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
This strategy is a template to be connected to any indicator - the sky is the limit. :)
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
* Initial Capital: 100000 USD
* Position Size: 1 contract
* Commission Percent: 0.075%
* Slippage: 1 tick
* No margin/leverage used
WHAT’S COMING NEXT FOR YOU GUYS?
I’ll make the same template for ProfitView, then for AutoView, and then for Alertatron.
All of those are free and open-source.
I have no affiliations with any of those companies - I'm publishing those templates as they will be useful to many of you.
Dave
Heatmap MACD Strategy - Pineconnector (Dynamic Alerts)Hello traders
This script is an upgrade of this template script.
Heatmap MACD Strategy
Pineconnector
Pineconnector is a trading bot software that forwards TradingView alerts to your Metatrader 4/5 for automating trading.
Many traders don't know how to dynamically create Pineconnector-compatible alerts using the data from their TradingView scripts.
Traders using trading bots want their alerts to reflect the stop-loss/take-profit/trailing-stop/stop-loss to breakeven options from your script and then create the orders accordingly.
This script showcases how to create Pineconnector alerts dynamically.
Pineconnector doesn't support alerts with multiple Take Profits.
As a workaround, for 2 TPs, I had to open two trades.
It's not optimal, as we end up paying more spreads for that extra trade - however, depending on your trading strategy, it may not be a big deal.
TradingView Alerts
1) You'll have to create one alert per asset X timeframe = 1 chart.
Example : 1 alert for EUR/USD on the 5 minutes chart, 1 alert for EUR/USD on the 15-minute chart (assuming you want your bot to trade the EUR/USD on the 5 and 15-minute timeframes)
2) For each alert, the alert message is pre-configured with the text below
{{strategy.order.alert_message}}
Please leave it as it is.
It's a TradingView native variable that will fetch the alert text messages built by the script.
3) Don't forget to set the webhook URL in the Notifications tab of the TradingView alerts UI.
EA configuration
The Pyramiding in the EA on Metatrader must be set to 2 if you want to trade with 2 TPs => as it's opening 2 trades.
If you only want 1 TP, set the EA Pyramiding to 1.
Regarding the other EA settings, please refer to the Pineconnector documentation on their website.
Logger
The Pineconnector commands are logged in the TradingView logger.
You'll find more information about it from this TradingView blog post
Important Notes
1) This multiple MACDs strategy doesn't matter much.
I could have selected any other indicator or concept for this script post.
I wanted to share an example of how you can quickly upgrade your strategy, making it compatible with Pineconnector.
2) The backtest results aren't relevant for this educational script publication.
I used realistic backtesting data but didn't look too much into optimizing the results, as this isn't the point of why I'm publishing this script.
3) This template is made to take 1 trade per direction at any given time.
Pyramiding is set to 1 on TradingView.
The strategy default settings are:
Initial Capital: 100000 USD
Position Size: 1 contract
Commission Percent: 0.075%
Slippage: 1 tick
No margin/leverage used
For example, those are realistic settings for trading CFD indices with low timeframes but not the best possible settings for all assets/timeframes.
Concept
The Heatmap MACD Strategy allows selecting one MACD in five different timeframes.
You'll get an exit signal whenever one of the 5 MACDs changes direction.
Then, the strategy re-enters whenever all the MACDs are in the same direction again.
It takes:
long trades when all the 5 MACD histograms are bullish
short trades when all the 5 MACD histograms are bearish
You can select the same timeframe multiple times if you don't need five timeframes.
For example, if you only need the 30min, the 1H, and 2H, you can set your timeframes as follow:
30m
30m
30m
1H
2H
Risk Management Features
All the features below are pips-based.
Stop-Loss
Trailing Stop-Loss
Stop-Loss to Breakeven after a certain amount of pips has been reached
Take Profit 1st level and closing X% of the trade
Take Profit 2nd level and close the remaining of the trade
Custom Exit
I added the option ON/OFF to close the opened trade whenever one of the MACD diverges with the others.
Help me help the community
If you see any issue when adding your strategy logic to that template regarding the orders fills on your Metatrader, please let me know in the comments.
I'll use your feedback to make this template more robust. :)
What's next?
I'll publish a more generic template built as a connector so you can connect any indicator to that Pineconnector template.
Then, I'll publish a template for Capitalise AI, ProfitView, AutoView, and Alertatron.
Thank you
Dave
IU Break of any session StrategyHow this script works:
1. This script is an intraday trading strategy script which buy and sell on the bases of user-defined intraday session range breakout and gives alert(if the alert is set) message too when the new position is open.
2. It calculate the session as per the user inputs or user defined custom session.
3. The script stores the highest and lowest value of the whole session.
4. It take a long position on the first break and close above the highest value.
5. It take a short position on the break and close below the lowest value.
6. The script takes one position in one day.
7. The stop loss for this script is the previous low(if long) or high(if short).
8. Take profit is 1:2 and it's adjustable.
9. This script work on every kind of market.
How The Useful For The User :
1. User can backtest any session range breakout he wants to trade.
2. User can get alert when the new position is open.
3. User can change the Risk to Reward in order to find the best Risk to Reward.
4. User can see the highest and lowest value of the session with respect to analyzing his trading objective.
5. This strategy script highlights which session range breakout performs best and which performs worst.
Time Session Filter - MACD exampleTime Session Filter in TradingView Strategy: A Comprehensive Guide
Welcome to this educational TradingView blog where we dive deep into the functionality and utility of the time session filter in trading strategies. It's interesting to note that the time session filter is a commonly overlooked feature in Pine Script, often not integrated into overall trading strategies. Yet, when used wisely, this tool can significantly enhance your trading approach. In essence, the session filter ensures that trades are only made within a specific, user-defined time frame. By incorporating this often-neglected building block, you can make your strategy more adaptable to various market conditions and trading preferences.
What is a Time Session Filter?
A time session filter is designed to:
Select Times of the Day to Trade: The filter allows you to choose specific hours during the day in which trades are allowed to be excecuted.
Toggle Days to Trade: You can decide which days of the week you want to trade, giving you the flexibility to avoid days that are historically not profitable for your strategy.
Close Trade When Session Ends: The filter can automatically close any open trade once the specified time session concludes, reducing the risk associated with holding positions outside your chosen time frame.
The user interface is streamlined, taking minimal space for the input sections, making it convenient to integrate with other indicators in your overall strategy script. In addition the script colors the background of the chart green when the timesession filter is on and makes the background red when the filter doesn't allow any trades. This helps you to visualise the selected timeframes in relation to chart patterns.
Best Practices for Time Selection
From my personal trading experience I share some input settings you can try to play around with:
Stocks: Trading stocks sometimes yield better results if you only trade in the mornings until lunchtime. This is the period when markets are generally more active, and traders are keenly participating.
Cryptocurrencies: For cryptocurrencies, it sometimes makes sense to avoid trading on Fridays, a day when futures contracts often expire. Various other market-moving events also typically occur on Fridays.
Random Selection: Interestingly, sometimes choosing a random selection of times and days can improve the script's performance, adding an element of unpredictability that might outperform more systematic approaches.
Strategy Overview
This strategy script incorporates various elements, including risk position size and MACD indicator, to provide a comprehensive trading strategy. For a detailed explanation of risk position sizing, please refer to this article:
For a complete understanding of the MACD indicator utilized, visit the following explanation:
Additionally, for high time frame trend filters, consult this resource for more info:
Educational Purposes and Risks
Please note that this script is for educational purposes and serves merely as an example of how to incorporate a time session filter into a trading strategy for pinescript. It is a simplified strategy without a fixed stop-loss, which can result in higher exposure to significant losses. The time session filter can be a powerful addition to your trading strategy, providing you with the tools to tailor your approach according to time-specific market conditions. By understanding its functionalities and best practices, you can make more informed trading decisions, but always remember that trading carries inherent risks.
Happy trading!
Risk Management and Positionsize - MACD exampleMastering Risk Management
Risk management is the cornerstone of successful trading, and it's often the difference between turning a profit and suffering a loss. In light of its importance, I share a risk management tool which you can use for your trading strategies. The script not only assists in position sizing but also comes with built-in technical features that help in market timing. Let's delve into the nitty-gritty details.
Input Parameter: MarginFactor
One of the key features of the script is the MarginFactor input parameter. This element lets you control the portion of your equity used for placing each trade. A MarginFactor of -0.5 means 50% of your total equity will be deployed in placing the position size. Although Tradingview has a built-in option to adjust position sizing in a same way, I personally prefer to have the logic in my pinecode script. The main reason is userexperience in managing and testing different settings for different charts, timeframes and instruments (with the same strategy).
Stoploss and MarginFactor
If your strategy has a 4% stop-loss, you can choose to use only 50% of your equity by setting the MarginFactor to -0.5. In this case, you are effectively risking only 2% of your total capital per trade, which aligns well with the widely-accepted rule of thumb suggesting a 1-2% risk per trade. Similar if your stoploss is only 1% you can choose to change the MarginFactor to 1, resulting in a positionsize of 200% of your equity. The total risk would be again 2% per trade if your stoploss is set to 1%.
Max Drawdown and MarginFactor
Your MarginFactor setting can also be aligned with the maximum drawdown of your strategy, seen during a backtested period of 2-3 years. For example, if the max drawdown is 15%, you could calibrate your MarginFactor accordingly to limit your risk exposure.
Option to Toggle Number of Contracts
The script offers the option to toggle between using a percentage of equity for position sizing or specifying a fixed number of contracts. Utilizing a percentage of equity might yield unrealistic backtest results, especially over longer periods. This occurs because as the capital grows, the absolute position size also increases, potentially inflating the accumulated returns generated by the backtester. On the other hand, setting a fixed number of contracts as your position size offers a more stable and realistic ROI over the backtested period, as it removes the compounding effect on position sizes.
Key Features Strategy
MACD High Time Frame Entry and Exit Logic
The strategy employs a high time frame MACD (Moving Average Convergence Divergence) to make entry and exit decisions. You can easily adjust the timeframe settings and MACD settings in the inputsection to trade on lower timeframes. For more information on the HTF MACD with dynamic smoothing see:
Moving Average High Time Frame Filter
To reduce market 'noise', the strategy incorporates a high time frame moving average filter. This ensures that the trades are aligned with the dominant market trend (trading the trend). In the inputsection traders can easily switch between different type of moving averages. For more information about this HTF filter see:
Dynamic Smoothing
The script includes a feature for dynamic smoothing. The script contains The timeframeToMinutes(tf) function to convert any given time frame into its equivalent in minutes. For example, a daily (D) time frame is converted into 1440 minutes, a weekly (W) into 10,080 minutes, and so forth. Next the smoothing factor is calculated by dividing the minutes of the higher time frame by those of the current time frame. Finally, the script applies a Simple Moving Average (SMA) over the MACD, SIGNAL, and HIST values, MA filter using the dynamically calculated smoothing factor.
User Convenience: One of the major benefits is that traders don't need to manually adjust the smoothing factor when switching between different time frames. The script does this dynamically.
Visual Consistency: Dynamic smoothing helps traders to more accurately visualize and interpret HTF indicators when trading on lower time frames.
Time Frame Restriction: It's crucial to note that the operational time frame should always be lower than the time frame selected in the input sections for dynamic smoothing to function as intended.
By incorporating this dynamic smoothing logic, the script offers traders a nuanced yet straightforward way to adapt High Time Frame indicators for lower time frame trading, enhancing both adaptability and user experience.
Limitations: Exit Strategy
It's crucial to note that the script comes with a simplified exit strategy, devoid of features like a stop-loss, trailing stop-loss or multiple take profits. This means that while the script focuses on entries and risk management, it might result in higher losses if market conditions unexpectedly turn unfavorable.
Conclusion
Effective risk management is pivotal for trading success, and this TradingView script is designed to give you a better idea how to implement positions sizing with your preferred strategy. However, it's essential to note that this tool should not be considered financial advice. Always perform your due diligence and consult with financial advisors before making any trading decisions.
Feel free to use this risk management tool as building block in your trading scripts, Happy Trading!
Linear On MACDUnlocking the Magic of Linear Regression in TradingView
In the ever-evolving world of financial markets, traders and investors seek effective tools to gauge price movements, make informed decisions, and achieve their financial goals. One such tool that has proven its worth over time is linear regression, a mathematical concept that has found its way into technical analysis and trading strategies. In this blog post, we will explore the magic behind linear regression, delve into its history, and understand how it's widely used as a technical indicator.
The Birth of Linear Regression: From Mathematics to Trading
Linear regression is a statistical method that aims to model the relationship between two variables by fitting a linear equation to observed data. The formula for a linear regression line is typically expressed as y = a + bx, where y is the dependent variable, x is the independent variable, a is the intercept, and b is the slope.
While the roots of linear regression trace back to the field of statistics, it didn't take long for traders and investors to recognize its potential in the financial world. By applying linear regression to historical price data, traders can identify trends, assess the relationship between variables, and even predict potential future price levels.
The Linear On MACD Strategy
Let's take a closer look at a powerful example of how linear regression is employed in a trading strategy right within TradingView. The "Linear On MACD" strategy harnesses the potential of linear regression in conjunction with the Moving Average Convergence Divergence (MACD) indicator. The goal of this strategy is to generate buy and sell signals based on the interactions between the predicted stock price and the MACD indicator.
Here's a breakdown of the strategy's components:
Calculation of Linear Regression: The strategy begins by calculating linear regression coefficients for the historical stock price based on volume. This helps predict potential future price levels.
Predicted Stock Price: The linear regression results are then used to plot the predicted stock price on the chart. This provides a visual representation of where the price could trend based on historical data.
Buy and Sell Signals: The strategy generates buy signals when certain conditions are met. These conditions include the predicted stock price being between the open and close prices, a rising MACD, and other factors that suggest a potential bullish trend. On the other hand, sell signals are generated based on MACD trends and predicted price levels.
Risk Management: The strategy also incorporates risk tolerance levels to determine entry and exit points. This ensures that traders take into account their risk appetite when making trading decisions.
Embracing the Magic of Linear Regression
As we explore the "Linear On MACD" strategy, we uncover the power of linear regression in aiding traders and investors. Linear regression, a mathematical marvel, seamlessly merges with technical analysis to provide insights into potential price movements. Its historical significance in statistics blends perfectly with the demands of modern financial markets.
Whether you're a seasoned trader or a curious investor, the Linear On MACD strategy exemplifies how a robust mathematical concept can be harnessed to make informed trading decisions. By embracing the magic of linear regression, you're tapping into a tool that continues to evolve alongside the financial world it empowers.
Disclaimer: The information provided in this blog post is for educational purposes only and does not constitute financial advice. Trading and investing carry risks, and it's important to conduct thorough research and consider seeking professional advice before making any trading decisions.
Elliott Wave with Supertrend Exit - Strategy [presentTrading]## Introduction and How it is Different
The Elliott Wave with Supertrend Exit provides automated detection and validation of Elliott Wave patterns for algorithmic trading. It is designed to objectively identify high-probability wave formations and signal entries based on confirmed impulsive and corrective patterns.
* The Elliott part is mostly referenced from Elliott Wave by @LuxAlgo
Key advantages compared to discretionary Elliott Wave analysis:
- Wave Labeling and Counting: The strategy programmatically identifies swing pivot highs/lows with the Zigzag indicator and analyzes the waves between them. It labels the potential impulsive and corrective patterns as they form. This removes the subjectivity of manual wave counting.
- Pattern Validation: A rules-based engine confirms valid impulsive and corrective patterns by checking relative size relationships and fib ratios. Only confirmed wave counts are plotted and traded.
- Objective Entry Signals: Trades are entered systematically on the start of new impulsive waves in the direction of the trend. Pattern failures invalidate setups and stop out positions.
- Automated Trade Management: The strategy defines specific rules for profit targets at fib extensions, trailing stops at swing points, and exits on Supertrend reversals. This automates the entire trade lifecycle.
- Adaptability: The waveform recognition engine can be tuned by adjusting parameters like Zigzag depth and Supertrend settings. It adapts to evolving market conditions.
ETH 1hr chart
In summary, the strategy brings automation, objectivity and adaptability to Elliott Wave trading - removing subjective interpretation errors and emotional trading biases. It implements a rules-based, algorithmic approach for systematically trading Elliott Wave patterns across markets and timeframes.
## Trading Logic and Rules
The strategy follows specific trading rules based on the detected and validated Elliott Wave patterns.
Entry Rules
- Long entry when a new impulsive bullish (5-wave) pattern forms
- Short entry when a new impulsive bearish (5-wave) pattern forms
The key is entering on the start of a new potential trend wave rather than chasing.
Exit Rules
- Invalidation of wave pattern stops out the trade
- Close long trades on Supertrend downturn
- Close short trades on Supertrend upturn
- Use a stop loss of 10% of entry price (configurable)
Trade Management
- Scale out partial profits at Fibonacci levels
- Move stop to breakeven when price reaches 1.618 extension
- Trail stops below key swing points
- Target exits at next Fibonacci projection level
Risk Management
- Use stop losses on all trades
- Trade only highest probability setups
- Size positions according to chart timeframe
- Avoid overtrading when no clear patterns emerge
## Strategy - How it Works
The core logic follows these steps:
1. Find swing highs/lows with Zigzag indicator
2. Analyze pivot points to detect impulsive 5-wave patterns:
- Waves 1, 3, and 5 should not overlap
- Waves 3 and 5 must be longer than wave 1
- Confirm relative size relationships between waves
3. Validate corrective 3-wave patterns:
- Look for overlapping, choppy waves that retrace the prior impulsive wave
4. Plot validated waves and Fibonacci retracement levels
5. Signal entries when a new impulsive wave pattern forms
6. Manage exits based on pattern failures and Supertrend reversals
Impulsive Wave Validation
The strategy checks relative size relationships to confirm valid impulsive waves.
For uptrends, it ensures:
```
Copy code- Wave 3 is longer than wave 1
- Wave 5 is longer than wave 2
- Waves do not overlap
```
Corrective Wave Validation
The strategy identifies overlapping corrective patterns that retrace the prior impulsive wave within Fibonacci levels.
Pattern Failure Invalidation
If waves fail validation tests, the strategy invalidates the pattern and stops signaling trades.
## Trade Direction
The strategy detects impulsive and corrective patterns in both uptrends and downtrends. Entries are signaled in the direction of the validated wave pattern.
## Usage
- Use on charts showing clear Elliott Wave patterns
- Start with daily or weekly timeframes to gauge overall trend
- Optimize Zigzag and Supertrend settings as needed
- Consider combining with other indicators for confirmation
## Default Settings
- Zigzag Length: 4 bars
- Supertrend Length: 10 bars
- Supertrend Multiplier: 3
- Stop Loss: 10% of entry price
- Trading Direction: Both