TrippleMACDCryptocurrency Scalping Strategy for 1m Timeframe
Introduction:
Welcome to our cutting-edge cryptocurrency scalping strategy tailored specifically for the 1-minute timeframe. By combining three MACD indicators with different parameters and averaging them, along with applying RSI, we've developed a highly effective strategy for maximizing profits in the cryptocurrency market. This strategy is designed for automated trading through our bot, which executes trades using hooks. All trades are calculated for long positions only, ensuring optimal performance in a fast-paced market.
Key Components:
MACD (Moving Average Convergence Divergence):
We've utilized three MACD indicators with varying parameters to capture different aspects of market momentum.
Averaging these MACD indicators helps smooth out noise and provides a more reliable signal for trading decisions.
RSI (Relative Strength Index):
RSI serves as a complementary indicator, providing insights into the strength of bullish trends.
By incorporating RSI, we enhance the accuracy of our entry and exit points, ensuring timely execution of trades.
Strategy Overview:
Long Position Entries:
Initiate long positions when all three MACD indicators signal bullish momentum and the RSI confirms bullish strength.
This combination of indicators increases the probability of successful trades, allowing us to capitalize on uptrends effectively.
Utilizing Linear Regression:
Linear regression is employed to identify consolidation phases in the market.
Recognizing consolidation periods helps us avoid trading during choppy price action, ensuring optimal performance.
Suitability for Grid Trading Bots:
Our strategy is well-suited for grid trading bots due to frequent price fluctuations and opportunities for grid activation.
The strategy's design accounts for price breakthroughs, which are advantageous for grid trading strategies.
Benefits of the Strategy:
Consistent Performance Across Cryptocurrencies:
Through rigorous testing on various cryptocurrency futures contracts, our strategy has demonstrated favorable results across different coins.
Its adaptability makes it a versatile tool for traders seeking consistent profits in the cryptocurrency market.
Integration of Advanced Techniques:
By integrating multiple indicators and employing linear regression, our strategy leverages advanced techniques to enhance trading performance.
This strategic approach ensures a comprehensive analysis of market conditions, leading to well-informed trading decisions.
Conclusion:
Our cryptocurrency scalping strategy offers a sophisticated yet user-friendly approach to trading in the fast-paced environment of the 1-minute timeframe. With its emphasis on automation, accuracy, and adaptability, our strategy empowers traders to navigate the complexities of the cryptocurrency market with confidence. Whether you're a seasoned trader or a novice investor, our strategy provides a reliable framework for achieving consistent profits and maximizing returns on your investment.
지표 및 전략
Adaptaive MA PSAR Strategy [PivotProphet]This strategy, leverages a dynamic approach to moving averages, an adaptive Parabolic SAR (PSAR), and volume moving averages to create a versatile trading system suitable for various markets. It includes an array of customizable settings that allow traders to adapt the strategy to their preferences and market conditions.
Key Features
Dynamic Moving Averages: Choose between a standard SMA, EMA, or RMA, and explore dynamic versions for adaptive smoothing and trend detection.
Parabolic SAR: Incorporates both standard and adaptive PSAR for trend reversal signals. The adaptive PSAR settings can be fine-tuned for sensitivity and responsiveness.
Volume MA: Enhances trade confirmation with volume moving averages, offering multiple types for a comprehensive market analysis.
Filter Integration: Includes ATR for volatility filtering, ADX for trend strength, RSI for momentum, and MACD for trend confirmation, each with customizable parameters.
Settings Overview
Trend Settings: Choose your preferred MA type and length for trend analysis.
PSAR Settings: Adjust the PSAR start, increment, and maximum values for tailored trend reversal signals.
Adaptive PSAR Settings: Fine-tune the adaptive PSAR with various modes, smoothing periods, and thresholds for enhanced flexibility.
Volume & Volatility Filters: Set up volume MA type and length, and utilize the ATR filter for volatility-based decision-making.
Exit/Entry Conditions: Select from SMA100, PSAR, or Adaptive PSAR for exit conditions, and customize entry conditions with PSAR settings.
Strategy Implementation
The strategy triggers long positions when the price is above the selected MA, accompanied by a favorable PSAR signal and volume exceeding its MA. Short positions are considered under the inverse conditions. Filters such as ADX, RSI, and MACD are applied to refine entry points, while dynamic exit conditions based on the chosen setting ensure disciplined risk management.
Visualization:
SMA and PSAR plots provide a visual representation of the trend and potential reversal points.
Color-coded bars and shapes indicate trading signals and market sentiment.
Designed for versatility, this strategy aims to cater to both novice and experienced traders seeking a robust framework for their trading endeavors. Customize to your heart's content and adapt to the rhythm of the markets with the Adaptive MA PSAR Strategy.
RSI Strategy with Manual TP and SL 19/03/2024This TradingView script implements a simple RSI (Relative Strength Index) strategy with manual take profit (TP) and stop-loss (SL) levels. Let's break down the script and analyze its components:
RSI Calculation: The script calculates the RSI using the specified length parameter. RSI is a momentum oscillator that measures the speed and change of price movements. It ranges from 0 to 100 and typically values above 70 indicate overbought conditions while values below 30 indicate oversold conditions.
Strategy Parameters:
length: Length of the RSI period.
overSold: Threshold for oversold condition.
overBought: Threshold for overbought condition.
trail_profit_pct: Percentage for trailing profit.
Entry Conditions:
For a long position: RSI crosses above 30 and the daily close is above 70% of the highest close in the last 50 bars.
For a short position: RSI crosses below 70 and the daily close is below 130% of the lowest close in the last 50 bars.
Entry Signals:
Long entry is signaled when both conditions for a long position are met.
Short entry is signaled when both conditions for a short position are met.
Manual TP and SL:
Take profit and stop-loss levels are calculated based on the entry price and the specified percentage.
For long positions, the take profit level is set above the entry price and the stop-loss level is set below the entry price.
For short positions, the take profit level is set below the entry price and the stop-loss level is set above the entry price.
Strategy Exits:
Exit conditions are defined for both long and short positions using the calculated take profit and stop-loss levels.
Chart Analysis:
This strategy aims to capitalize on short-term momentum shifts indicated by RSI crossings combined with daily price movements.
It utilizes manual TP and SL levels, providing traders with flexibility in managing their positions.
The strategy may perform well in ranging or oscillating markets where RSI signals are more reliable.
However, it may encounter challenges in trending markets where RSI can remain overbought or oversold for extended periods.
Traders should backtest this strategy thoroughly on historical data and consider optimizing parameters to suit different market conditions.
Risk management is crucial, so traders should carefully adjust TP and SL percentages based on their risk tolerance and market volatility.
Overall, this strategy provides a structured approach to trading based on RSI signals while allowing traders to customize their risk management. However, like any trading strategy, it should be used judiciously and in conjunction with other forms of analysis and risk management techniques.
NASDAQ 100 Peak Hours StrategyNASDAQ 100 Peak Hours Trading Strategy
Description
Our NASDAQ 100 Peak Hours Trading Strategy leverages a carefully designed algorithm to trade within specific hours of high market activity, particularly focusing on the first two hours of the trading session from 09:30 AM to 11:30 AM GMT-5. This period is identified for its increased volatility and liquidity, offering numerous trading opportunities.
The strategy incorporates a blend of technical indicators to identify entry and exit points for both long and short positions. These indicators include:
Exponential Moving Averages (EMAs) : A short-term 9-period EMA and a longer-term 21-period EMA to determine the market trend and momentum.
Relative Strength Index (RSI) : A 14-period RSI to gauge the market's momentum.
Average True Range (ATR) : A 14-period ATR to assess market volatility and to set dynamic stop losses and trailing stops.
Volume Weighted Average Price (VWAP) : To identify the market's average price weighted by volume, serving as a benchmark for the trading day.
Our strategy uniquely applies a volatility filter using the ATR, ensuring trades are only executed in conditions that favor our setup. Additionally, we consider the direction of the EMAs to confirm the market's trend before entering trades.
Originality and Usefulness
This strategy stands out by combining these indicators within the NASDAQ 100's peak hours, exploiting the specific market conditions that prevail during these times. The inclusion of a volatility filter and dynamic stop-loss mechanisms based on the ATR provides a robust method for managing risk.
By focusing on the early trading hours, the strategy aims to capture the initial market movements driven by overnight news and the opening rush, often characterized by higher volatility. This approach is particularly useful for traders looking to maximize gains from short-term fluctuations while limiting exposure to longer-term market uncertainty.
Strategy Results
To ensure the strategy's effectiveness and reliability, it has undergone rigorous backtesting over a significant dataset to produce a sample size of more than 100 trades. This testing phase helps in identifying the strategy's potential in various market conditions, its consistency, and its risk-to-reward ratio.
Our backtesting adheres to realistic trading conditions, accounting for slippage and commission to reflect actual trading scenarios accurately. The strategy is designed with a conservative approach to risk management, advising not to risk more than 5-10% of equity on a single trade. The default settings in the script align with these principles, ensuring that users can replicate our tested conditions.
Using the Strategy
The strategy is designed for simplicity and ease of use:
Trade Hours : Focuses on 09:30 AM to 11:30 AM GMT-5, during the NASDAQ 100's peak activity hours.
Entry Conditions : Trades are initiated based on the alignment of EMAs, RSI, VWAP, and the ATR's volatility filter within the designated time frame.
Exit Conditions : Includes dynamic trailing stops based on ATR, a predefined time exit strategy, and a trend reversal exit condition for risk management.
This script is a powerful tool for traders looking to leverage the NASDAQ 100's peak hours, providing a structured approach to navigating the early market hours with a robust set of criteria for making informed trading decisions.
Strategy - Plus / Connectable [Azullian]Discover the advanced capabilities of Strategy Plus, an essential component of the connectable indicator system designed for fast-paced strategy testing, visualization, and building within TradingView. This enhanced version of our foundational connectable strategy indicator seamlessly integrates with all connectable indicators . By utilizing the TradingView input source as a signal connector , it facilitates the linking of indicators to form a cohesive strategy. Each connectable indicator within the system sends signal weight to the next node, culminating in a comprehensive strategy that incorporates advanced customization options, sophisticated signal interpretation, and elaborate backtest labeling. Strategy Plus stands out by offering improved position management and extensive alert messaging capabilities, ensuring effective strategy refinement and backend integration.
█ DISTINCTIVE FEATURES
The Connectable Strategy Plus enhances risk mitigation within the connectable system through its advanced features and capabilities:
• Refined Signal Input Management: Tailor and precisely connect up to two signal filters with enhanced input flexibility, gain control, and strategic direction settings.
• Strategic Position Investment Control: Optimize positioning with versatile investment bases, custom investment percentages, and direction-specific investments for effective risk management.
• Advanced Exit Stop Loss Configuration: Implement custom stop loss tactics with diverse base modes and trailing options for tailored risk management.
• Strategic Exit Take Profit Settings: Apply precision-driven take profit strategies with various calculation modes and dynamic trailing functionality.
• Calibrated Entry Position Allocation: Optimize investment distribution for entry positions, including DCA and BRO trades, for strategic market response.
• Refined Order Setting Customization: Ensure exchange compliance with adjustable order settings, enhancing backtest accuracy and strategy reliability.
• Comprehensive Condition Settings: Define precise conditions for strategy execution, including date range filtering and order/loss limitations.
• Intuitive Visualization: Enhance strategy clarity with customizable visual elements and trade visualization features.
• Advanced Alert Configurations: Stay informed with comprehensive and customizable alerts for effective backend integration.
• Backend Integration With JSON Format: Leverage elaborate and structured data in JSON format for advanced analytics, enhancing decision-making and strategy optimization outside TradingView.
Let's review the separate parts of this indicator.
█ STRATEGY INPUTS
We've provided 2 inputs for connecting a signal filter or indicators or chains (1→, 2→) which are all set to 'Close' by default.
An input has several controls:
• Enable disable: Toggle the entire input on or off
• Input: Connect indicators or signal filter here, choose indicators with a compatible : Signal connector.
• G - Gain: Increase or reduce the strength of the incoming signal by a factor.
• SM - Signal Mode: Choose a trading direction compatible with the settings in your signal filter
• XM - Exit Mode: Determine when to allow to exit your open trade
○ Always: Doesn't take the restrictions into account, this ignores all the settings chosen in ML or MP
○ Restricted: Use both ML and MP conditions
○ Loss: Use the ML condition only, for example: Position will be exited and the exit signal will be allowed only when the loss exceeds the ML parameter
○ Profit: Use the MP condition only for example: Exits will only be allowed when the profit of the position exceeds the condition of the MP parameter
█ 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.
• XINVB - Custom Profit Investment Base: Choose which base to use to determine the investment percentage when the strategy is above a custom profit threshold (XT).
○ Equity: Use the equity as the base for percentage calculation.
○ Initial capital: Use the initial capital as the base for percentage calculation.
• XINV% - Custom Profit Investment Percentage: Set a percentage of the chosen investment base as the investment for a new position.
○ For example, when 100% in profit, exceeding the XT threshold of 50%, and an initial capital of $100, and the investment base is set to equity with a percentage of 50%, your investment will be 50% of $200, $100.
• XT% - Custom Profit Threshold: Determine how much profit triggers these custom profit investment settings.
• ELIB% - Entry Long Investment Base: Following previous settings, you can further restrict the investment according to the long trading direction.
○ For instance, if the previous calculation resulted in $45 to be used as an investment, and you've set the ELIB% to 50%, your long position will use 50% of $45, which is $22.5.
• ESIB% - Entry Short Investment Base: Following previous settings, you can further restrict the investment according to the short trading direction.
○ For example, if the previous calculation resulted in $45 to be used as an investment, and you've set the ESIB% to 50%, your short position will use 50% of $45, which is $22.5.
• 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.
• SLLB - Stop Loss Long Base: Choose a stop loss mode for calculating stop loss prices in long positions.
○ Risk: Determines the price using the Risk parameter (RISK%) and maximum leverage (MXLVG). In this case, SLLB% will not have any impact.
○ Price Entry + Offset: Calculates the stop loss price based on a offset percentage (SLLB%) from the entry price of the position.
○ Source: Computes the stop loss price based on an external indicator defined in SLLSRC.
- If this results in an invalid price, the calculation will revert to using the price entry + offset.
○ Source + Offset: Determines the stop loss price based on a positive or negative offset percentage (SLLB%) from an external indicator defined in SLLSRC.
- If this results in an invalid price, the calculation will fall back to using the price entry + offset.
• SLLB% - Stop Loss Long Base Percentage: Define an offset percentage that will be applied in the price entry + offset and source + offset stop loss modes.
• SLLSRC - Stop Loss Long Source: Connect an external indicator as the source for stop loss (only those providing price values eg: bollinger bands, moving averages...).
• SLLT - Stop Loss Long Trailing:
○ Fixed: The initial stop loss will be kept and no trailing stop loss will be applied.
○ Trail Stop: Takes into account all settings defined in SLLB and SLLB% and recalculates them with each candle.
- If a better stop loss is computed, it replaces the existing stop loss. In this mode SLLT% will be disregarded.
○ Trail Stop till BE: Similar to trailing stop mode, but it stops trailing when the stop loss reaches the break-even point.
○ Trail Stop from BE: Similar to trailing stop mode, but it starts trailing when the stop loss reaches the break-even point.
○ Trail Price: Computes the trailing stop loss price based on an offset percentage (SLLT%) 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 Price till BE: Similar to the Trail Price mode, but it stops trailing when the stop loss reaches the break-even point.
○ Trail Price from BE: Similar to Trail Price mode, but it starts trailing when the stop loss reaches the break-even point.
○ Trail Incr: Adapts the trailing stop loss price based on the offset percentage (SLLT%).
- Each price change in favor of your position will incrementally adapt the trailing stop loss with SLLT%.
○ Trail Incr till BE: Similar to the Trail Incr mode, but it stops trailing when the stop loss reaches the break-even point.
• SLLT% - Stop Loss Long Trailing Percentage: This percentage serves as an offset or increment depending on your chosen trailing mode.
• SLSB - Stop Loss Short Base: Functions similarly to SLLB but for short positions.
• SLSB% - Stop Loss Short Base Percentage: Functions similarly to SLLB% but for short positions.
• SLSSRC - Stop Loss Short Source: Functions similarly to SLLSRC but for short positions.
• SLST - Stop Loss Short Trailing: Functions similarly to SLLT but for short positions.
• SLST% - Stop Loss Short Trailing Percentage: Functions similarly to SLLT% but for short positions.
█ EXIT TAKE PROFIT
Determine the Take Profit price based on your selected configuration.
• TPLB - Take Profit Long Base: Choose a take profit mode for calculating take profit prices in long positions.
○ Reward: Determines the take profit price using the Risk parameter (RISK%) and the calculated Stop Loss price and the set reward percentage (TPLB%).
- For example: Risk 1%, Calculated Stop loss price: $90, Entry price: $100, Reward (TPLB%): 2%, will result in a take profit price on $120.
○ Price Entry + Offset: Calculates the take profit price based on a offset percentage (TPLB%) from the entry price of the position.
- For example: Entry price: $100, Offset (TPLB%): 2%, will result in a take profit price on $102.
○ Source: Computes the take profit price based on an external input from another indicator defined in TPLSRC.
- If this results in an invalid price, the calculation will revert to using the price entry + offset.
○ Source + Offset: Determines the take profit price based on a positive or negative offset percentage (TPLB%) from an external indicator inpuy defined in TPLSRC.
- If this results in an invalid price, the calculation will fall back to using the price entry + offset.
• TPLB% - Take Profit Long Base Percentage: Define an offset percentage that will be applied in the price entry + offset and source + offset take profit modes.
• TPLSRC - Take Profit Long Source: Choose to connect an external indicator as the source for take profit (of course only those which provide price values eg: bollinger bands, moving averages... but not oscillators).
• TPLT - Take Profit Long Trailing:
○ Fixed: The initial take profit will be kept and no trailing take profit will be applied.
○ Trail Profit: Takes into account all settings defined in TPLB and TPLB% and recalculates them with each candle.
- If an applicable take profit is computed, it replaces the existing take profit. In this mode TPLT% will be disregarded.
○ Trail Profit till BE: Similar to trailing profit mode, but it stops trailing when the take profit reaches the break-even point.
○ Trail Profit from BE: Similar to trailing profit mode, but it starts trailing when the take profit reaches the break-even point.
○ Trail Price: Computes the trailing take profit price based on an offset percentage (TPLT%) 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 Price till BE: Similar to the Trail Price mode, but it stops trailing when the take profit reaches the break-even point.
○ Trail Price from BE: Similar to Trail Price mode, but it starts trailing when the take profit reaches the break-even point.
○ Trail Incr: Adapts the trailing take profit price based on the offset percentage (TPLT%). Each price change against your position will incrementally adapt the trailing take profit with TPLT%.
○ Trail Incr till BE: Similar to the Trail Incr mode, but it stops trailing when the take profit reaches the break-even point.
• TPLT% - Take Profit Long Trailing Percentage: This percentage serves as an offset or increment depending on your chosen trailing mode.
• TPSB - Take Profit Short Base: Functions similarly to TPLB but for short positions.
• TPSB% - Take Profit Short Base Percentage: Functions similarly to TPLB% but for short positions.
• TPSSRC - Take Profit Short Source: Functions similarly to TPLSRC but for short positions.
• TPST - Take Profit Short Trailing: Functions similarly to TPLT but for short positions.
• TPST% - Take Profit Short Trailing Percentage: Functions similarly to TPLT% but for short positions.
█ ENTRY INVESTMENT DISTRIBUTION
Based on your position investment calculation you can distribute the position investment accross the initial opening trade of the position (SIG%) or the follow up Dollar Cost Averaging (DCA%) or Break Out (BRO%) trades.
For example: SIG%: 10%, DCA%: 45%, BRO%: 45% and the calculated Position Investment is $100, then the initial trade will receive $10, DCA will receive $45, and BRO will receive $45 to work with. Disable BRO and or DCA by setting them to 0%. Keep in mind that the sum of SIG, BRO and DCA may not exceed 100%.
• SIG% - Initial order investment percentage based on the signal: The percentage of the position investment distributed over normal trades.
• DCA% - Dollar Cost Averaging investment percentage: The percentage of the position investment distributed to DCA trades.
• BRO% - Break Out investment percentage: The percentage of the position investment distributed to BRO trades.
█ ENTRY DCA
DCA (Dollar-Cost Averaging) is a risk mitigation strategy where the allocated DCA% budget from the Entry Investment Distribution is distributed among x levels (DCA#) based on calculated prices (DPLM) and order sizes (DOSM), when prices move against your position.
• DCA# - Maximum DCA levels: Set the maximum number of DCA levels.
• DPLM - DCA Price Level Mode: Choose a price level mode that determines at which prices the additional purchases are distributed:
○ Linear: Entry prices are evenly spaced at regular intervals.
○ QuadIn: Entry prices are front-loaded, with more at the beginning and fewer later.
○ QuadOut: Entry prices are back-loaded, with fewer at the beginning and more later.
○ QuadInOut: Entry prices start front-loaded, then become back-loaded.
○ CubicIn: Similar to QuadIn but with a smoother front-loaded distribution.
○ CubicOut: Similar to QuadOut but with a smoother back-loaded distribution.
○ ExpoIn: Entry prices are exponentially increasing, starting small and growing.
○ ExpoOut: Entry prices are exponentially decreasing, starting large and reducing.
○ ExpoInOut: Entry prices start exponentially increasing, then decrease exponentially.
• DOSM - DCA Order Size Mode: Choose a DCA budget distribution mode for order sizes:
○ Linear: Order sizes are evenly spaced at regular intervals.
○ QuadIn: Order sizes are front-loaded, with larger orders at the beginning and smaller ones later.
○ QuadOut: Order sizes are back-loaded, with smaller orders at the beginning and larger ones later.
○ QuadInOut: Order sizes start front-loaded and transition to back-loaded.
○ CubicIn: Similar to QuadIn but with a smoother front-loaded distribution of order sizes.
○ CubicOut: Similar to QuadOut but with a smoother back-loaded distribution of order sizes.
○ ExpoIn: Order sizes exponentially increase, starting small and growing.
○ ExpoOut: Order sizes exponentially decrease, starting large and reducing.
○ ExpoInOut: Order sizes start exponentially increasing, then decrease exponentially.
For a visual representation of the price or order size distribution modes, refer to online easing curves.
█ ENTRY BRO
BRO (Break Out) is a risk mitigation strategy where the allocated BRO% budget from the Entry Investment Distribution is distributed among x levels (BRO#) based on calculated prices (BPLM) and order sizes (BOSM), when prices move in favor of your position.
• BRO# - Maximum BRO levels: Set the maximum number of BRO levels.
• BPLM - BRO Price Level Mode: Choose a price level mode that determines at which prices the additional purchases are distributed:
○ Distribution easing modes work similar as the DCA easing modes.
• BOSM - BRO Order Size Mode: Choose a BRO budget distribution mode for order sizes:
○ Distribution easing modes work similar as the DCA easing modes.
█ ORDER SETTINGS
Fine-tune accuracy to match your exchange's trading constraints, enhancing backtest precision with these settings, default settings are least restrictive for crypto trading pairs.
• MINP - Mininmum Position Notional Value: Exchange-defined minimum notional value for positions:
○ Calculated based on your exchange's rules and is the minimum total value your position must hold to meet their requirements It is calculated by multiplying Quantity with price and leverage.
○ It helps ensure your trades align with your exchange's standards.
• MAXP - Maximum Position Notional Value: Exchange-defined maximum notional value for positions:
○ Similar to MINP, this value is calculated based on your exchange's rules and represents the maximum total value allowed for your position.
• MINQ - Mininmum Order Quantity: Least permissible order quantity based on exchange rules:
○ This is the smallest quantity of an asset that your exchange allows you to trade in a single order.
• MAXQ - Maximum Order Quantity: Highest permissible order quantity according to exchange rules:
○ Opposite of MINQ, this is the largest quantity of an asset you can trade in a single order as defined by your exchange.
• DECP - Decimals in Order Price: Allowed decimal places in order prices as per exchange specifications:
○ This value specifies the number of decimal places you can use when specifying the price of an order.
• DECQ - Decimals in Order Quantity: Permitted decimal places in order quantities according to exchange specifications:
○ Similar to DECP, this value indicates the number of decimal places you can use when specifying the quantity of an asset in an order.
█ 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.
• IDO - Maximum Intraday Orders: Limit the number of orders the strategy can place within a single trading day. Upon reaching this limit, the strategy temporarily halts further entries for the day.
• DL% - Maximum Intraday Loss%: Set a threshold for the maximum allowable intraday loss as a percentage of equity. When exceeded, the strategy temporarily suspends trading for the day.
• CLD - Maximum Consecutive Loss Days: Define the maximum number of consecutive days the strategy can incur losses. Upon reaching this limit, the strategy halts trading and avoids new entries.
• DD% - Maximum Drawdown: Specify the maximum permissible drawdown as a percentage of equity. If this limit is met, the strategy halts trading and refrains from placing additional entries.
• TP% - Total Profit %: Establish a target for the total profit percentage the strategy aims to achieve. Once this target is attained, the strategy halts trading and refrains from initiating new entries.
• TL% - Total Loss %: Define a limit for the total loss percentage relative to the initial capital. If this limit is exceeded, the strategy discontinues trading and refrains from placing further entries.
■ 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:
○ EL-SIG0-124: Enter Long - Signal 0 - Position 124
○ EL-BRO1-130: Enter Long - BRO1 - Position 130
○ EL-BRO2-130: Enter Long - BRO2 - Position 130
○ ES-DCA1-140: Enter Short - DCA1 - Position 140
○ XS-DCA2-140: Exit Short - DCA2 - Position 140
○ 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
○ XS-CND-165: Exit Short - Strategy Condition - Max intraday loss - Position 165
■ ALERT SETTINGS
For developers and those who wish to integrate TradingView alerts into their backend systems, we offer comprehensive labeling options.
• ALID: A unique identifier you've assigned to your alert.
• NAME: A structured name you've given to this strategy.
• LAYOUT: The layout key of the strategy, allowing direct chart linking from your backend.
• SYMBOL: The symbol on which the strategy operates.
○ ONCE: You can choose to include this information only in the first message to reduce message size and repetition in follow-up messages. (max. 4096 characters)
• TICK: The ticker for the strategy.
• CHART: The chart parameter containing the timeframe.period and timeframe.multiplier.
○ ONCE: You can choose to include this information only in the first message to reduce message size and repetition in follow-up messages. (max. 4096 characters)
• BAR: Includes bar information in the alert message.
• STRATEGY: Adds strategy inputs to the alert message.
○ ONCE: You can choose to include this information only in the first message to reduce message size and repetition in follow-up messages. (max. 4096 characters)
• PERFORMANCE: Incorporates strategy performance data into the alert message.
• SIGNAL: Appends received signal weights (EL, XL, ES, XS) to the alert message.
• ORDERS: Includes order details in the alert message.
• TAGS: Adds up to 6 tags and their corresponding values to the alert message.
○ ONCE: You can choose to include this information only in the first message to reduce message size and repetition in follow-up messages. (max. 4096 characters)
Of course we can't neglect letting you in on how this juicy JSON would look (without the // comments):
{
"id": 20726, // Message Id
"t": "2023-11-01T10:35:00Z", // Message Time
"al": { // Alert
"id": "639bfa9a-5f01-4031-8880-7ec01e972055", // Alert Id
"n": "TEST04", // Name
"l": "ABC123" // Layout
},
"sym": { // Symbol
"typ": "crypto", // Type
"r": "DOGEUSD.PM", // Root
"pre": "KRAKEN", // Prefix
"tc": "DOGEUSD.PM", // Ticker
"bc": "DOGE", // BaseCurrency
"c": "USD", // Currency
"d": "DOGEUSD Multi Collateral Perpetual Futures Contract", // Description
"mtc": 0.000001, // MinTick
"pv": 1, // PointValue
"ct": "PF_DOGEUSD" // CustomTicker
},
"ch": { // Chart
"pd": "1", // Period
"mul": 1 // Multiplier
},
"bar": { // Bar
"id": 20725, // Index
"t": "2023-11-01T10:33:00Z", // Time
"o": 0.066799, // Open
"h": 0.066799, // High
"l": 0.066799, // Low
"c": 0.066799, // Close
"v": 2924 // Vol
},
"strat": { // Strategy
"n": "Strategy - Plus / Connectable ", // Name
"sig": { // Signal
"c1e": true, // Connector1Enabled
"c1s": 500500.500501, // Connector1Source
"c1g": 1, // Connector1Gain
"c2e": false, // Connector2Enabled
"c2s": 0.067043, // Connector2Source
"c2g": 1, // Connector2Gain
"sm": "Swing (EL, ES)", // SignalMode
"xm": "Always", // ExitMode
"mlp": 0.01, // ExitModeMinPercLoss
"mpp": 0.01 // ExitModeMinPercProfit
},
"inv": { // Investment
"lb": "Equity", // LossBase
"lp": 50, // LossPerc
"pb": "Equity", // ProfitBase
"pp": 100, // ProfitPerc
"pcb": "Equity", // ProfitCustomBase
"pcp": 100, // ProfitCustomPerc
"pct": 10000, // ProfitCustomThreshold
"elp": 100, // LongPerc
"esp": 100, // ShortPerc
"rsk": 1, // MaxRisk
"lvg": 10 // MaxLeverage
},
"sl": { // StopLoss
"lb": "Price Entry + Offset", // LongBase
"lp": 0.2, // LongPerc
"lsrc": 0.067043, // LongSource
"lt": "Trail Stop", // LongTrailMode
"ltp": 0.2, // LongTrailPerc
"sb": "Price Entry + Offset", // ShortBase
"sp": 0.2, // ShortPerc
"ssrc": 0.067043, // ShortSource
"st": "Trail Stop", // ShortTrailMode
"stp": 0.2 // ShortTrailPerc
},
"tp": { // TakeProfit
"lb": "Price Entry + Offset", // LongBase
"lp": 1, // LongPerc
"lsrc": 0.067043, // LongSource
"lt": "Fixed", // LongTrailMode
"ltp": 1, // LongTrailPerc
"sb": "Price Entry + Offset", // ShortBase
"sp": 1, // ShortPerc
"ssrc": 0.067043, // ShortSource
"st": "Fixed", // ShortTrailMode
"stp": 1 // ShortTrailPerc
},
"dis": { // Distribution
"sigp": 10, // SignalPerc
"dcap": 0, // DCAPerc
"brop": 90 // BROPerc
},
"dca": { // DCA
"lvl": 3, // Levels
"pl": "linear", // ModePriceLevel
"os": "linear" // ModeOrderSize
},
"bro": { // BRO
"lvl": 3, // Levels
"pl": "expoIn", // ModePriceLevel
"os": "cubicOut" // ModeOrderSize
},
"ord": { // OrderSettings
"pmin": 5, // PNVMin
"pmax": 30000000, // PNVMax
"qmin": 0, // QtyMin
"qmax": 1000000000, // QtyMax
"dp": 6, // DecPrice
"dq": 6 // DecQty
},
"cnd": { // Conditions
"de": true, // DateRangeEnabled
"start": "2023-11-01T10:30:00Z", // StartTime
"end": "2024-12-31T23:30:00Z", // EndTime
"idoe": false, // MaxIntradayOrdersEnabled
"ido": 100, // MaxIntradayOrders
"dle": false, // MaxIntradayLossEnabled
"dl": 10, // MaxIntradayLossPerc
"clde": false, // MaxConsLossDaysEnabled
"cld": false, // MaxConsLossDays
"dde": false, // MaxDrawdownEnabled
"dd": 100, // MaxDrawdownPerc
"mpe": false, // MaxProfitEnabled
"mp": 200, // MaxProfitPerc
"mle": false, // MaxLossEnabled
"ml": -50 // MaxLossPerc
}
},
"perf": { // Performance
"ic": 1000, // InitialCapital
"eq": 1000, // Equity
"np": 0, // NetProfit
"op": 0, // OpenProfit
"ct": 0, // ClosedTrades
"ot": 0, // OpenTrades
"p": "FLAT", // MarketPosition
"ps": 0, // MarketPositionSize
"pp": "FLAT", // PreviousMarketPosition
"pps": 0 // PreviousMarketPositionSize
},
"sig": { // Signal
"el": 0, // EL
"xl": 0, // XL
"es": 6, // ES
"xs": 0 // XS
},
"ord": ,
"tag":
}
█ 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 this indicator with signals and a signal filter
The indicator provides visual cues based on signal conditions. However, its weight system is best utilized when paired with a connectable signal filter, monitor, or strategy .
Let's connect the Strategy - Plus to a connectable signal filter and connectable indicators :
1. Load all relevant indicators
• Load MA - Plus / Connectable
• Load Signal filter - Plus / Connectable
• Load Strategy - Plus / Connectable
2. Signal Filter Plus: Connect the MA - Plus to the Signal Filter
• Open the signal filter settings
• Choose one of the five input dropdowns (1→, 2→, 3→, 4→, 5→) and choose : MA - Plus / Connectable: Signal Connector
• Toggle the enable box before the connected input to enable the incoming signal
3. Signal Filter: Update the filter settings if needed
• The default filter mode for the trading direction is SWING, and is compatible with the default settings in the strategy and indicators.
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 is 'ABOVE' Threshold 1 (TH1) and Threshold 2 (TH2), both set at 5. This allows each occurrence to score, as the default score is 1 point above the threshold.
5. Strategy Plus: Connect one of the strategy plus inputs to the signal filters signal connector in the strategy settings
• Select a strategy input → and select the Signal filter - Plus: Signal connector
6. Strateg Plus: Enable filter compatible directions
• As the default setting of the filter is SWING, we should also set the SM (Strategy mode) to SWING.
7. Strateg Plus: You're ready to start optimizing
• Dive into all parameters and start optimizing your backtesting results.
█ 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, CLARIFICATIONS AND TIPS
• 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'.
• Hide attributes: As connectable indicators send through quite some information you'll notice all the arguments are taking up some screenwidth and cause some visual clutter. You can disable arguments in Chart Settings / Status line.
• 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.
• Inputs: Connecting a connectable indicator directly to the strategy delivers the raw signal without a weight threshold, meaning every signal will trigger a trade.
• Layout and Abbreviations: Abbreviations streamline structure and input identification. Although they may seem complex initially, inline tooltips provide explanations, facilitating quick acclimatization.
• Total Trade Limit Error & Date-Time Filter: For deep backtesting, be mindful of the total trade limit. Utilize the date-time filter to narrow the test scope and avoid TradingView order limits.
• Calculation Timeout: Encounter a timeout? Adjust any parameter slightly to restart the calculation process.
• Message Character Limit: To stay within message character limits, consider turning off certain features or setting some to 'once'.
• Direct Indicator-to-Strategy Connection: When connecting an indicator directly to a strategy without thresholds, the strategy will default to long if weights are equally assigned.
• Pyramid Enabling with DCA and BRO: Activate pyramid orders, enabling you to optimize your strategy during Dollar Cost Averaging and Break Out trades.
• Recalculate & Fill Orders Properties: Adjusting these default settings in strategy properties tab may lead to unexpected behavior when backtesting. Approach with caution.
• Optimized for Crypto: Our indicators have been optimized and tested primarily on cryptocurrency markets. Results in other markets may vary.
• Inline Tooltips Documentation: Detailed documentation and guidance are available via inline tooltips for immediate assistance.
• Strategy Settings Margin: Set margin to 1 to be able to apply leverage.
• Styling Panel: Explore the styling panel to disable labels or any other visual cues to reduce clutter on busy charts, enhancing visual clarity and personalization.
• Applying Leverage on Spot Markets: Ensure that maximum leverage on spot markets is configured to 1.
• Unrealistic Order Sizes: Verify that the order book can accommodate your backtested order sizes.
█ 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.
FlowHello, everyone,
Recently I found a useful indicator for the short-term minute-level trading called Liquidity Sweeps. This is a technical indicator that studies the resistance and support levels of candle patterns.
The strategy takes into account the following market factors:
Lql -> resistance formed by a rapid rise or support formed by a rapid rise
Sweep Area -> potential entry point
The inspiration of this strategy comes mostly from Liquidity Sweeps (LuxAlgo), but I have also optimized it based on my own trading experience.
What are the differences from the original strategy?
The Only Outbreaks & Retest option has been removed, and the formation of Wicks is enough to prevent conflicting signals.
The P&L ratio of the strategy has been set, which allows more combinations of the appropriate strategy parameters to match different characteristics of trading pairs.
Signals
1. Enter the trade when three consecutive bars are formed in the Wicks block (resistance or support) and set the stop-loss/stop-profit
2. The condition is not met when three bars are formed in the Wicks block, and the Wicks index is reset when the price returns.
Risk Management
1. Use the P&L ratio, plus appropriate ATR volatility to prevent false breakouts.
2. When the signal is reversed.
3. The strategy is suitable for the short-term level, not for the trend market.
Now, for the inexperienced reader, a series of knowledge. ATR: Like Boolean channel and ADX, Average True Rage is an indicator used to measure price volatility. But unlike these two indicators, it can reflect the price volatility more accurately because of the factors such as gaps added in its calculation process. For this reason, it is called "true" volatility.
Sincerely,
Special thanks to @LuxAlgo for sharing.
Yeong RRGThe code outlines a trading strategy that leverages Relative Strength (RS) and Rate of Change (RoC) to make trading decisions. Here's a detailed breakdown of the tactic described by the code:
Ticker and Period Selection: The strategy begins by selecting a stock ticker symbol and defining a period (len) for the calculations, which defaults to 14 but can be adjusted by the user.
Stock and Index Data Retrieval: It fetches the closing price (stock_close) of the chosen stock and calculates its 25-period exponential moving average (stock_ema). Additionally, it retrieves the closing price of the S&P 500 Index (index_close), used as a benchmark for calculating Relative Strength.
Relative Strength Calculation: The Relative Strength (rs) is computed by dividing the stock's closing price by the index's closing price, then multiplying by 100 to scale the result. This metric is used to assess the stock's performance relative to the broader market.
Moving RS Ratio and Rate of Change: The strategy calculates a Simple Moving Average (sma) of the RS over the specified period to get the RS Ratio (rs_ratio). It then computes the Rate of Change (roc) of this RS Ratio over the same period to get the RM Ratio (rm_ratio).
Normalization: The RS Ratio and RM Ratio are normalized using a formula that adjusts their values based on the mean and standard deviation of their respective series over the specified window. This normalization process helps in standardizing the indicators, making them easier to interpret and compare.
Indicator Plotting: The normalized RS Ratio (jdk_rs_ratio) and RM Ratio (jdk_rm_ratio) are plotted on the chart with different colors for visual analysis. A horizontal line (hline) at 100 serves as a reference point, indicating a neutral level for the indicators.
State Color Logic: The script includes a logic to determine the state color (statecolor) based on the previous state color and the current values of jdk_rs_ratio and jdk_rm_ratio. This color coding is intended to visually represent different market states: green for bullish, red for bearish, yellow for hold, and blue for watch conditions.
Signal Generation: The strategy generates buy, sell, hold, and watch signals based on the state color and the indicators' values relative to 100. For example, a buy signal is generated when both jdk_rs_ratio and jdk_rm_ratio are above 100, and the background color is set to green to reflect this bullish condition.
Trade Execution: Finally, the strategy executes trades based on the generated signals. A "BUY" trade is entered when a buy signal is present, and it is closed when a sell signal occurs.
Overall, the strategy uses a combination of RS and RoC indicators, normalized for better comparison, to identify potential buy and sell opportunities based on the stock's performance relative to the market and its momentum.
Kyrie Crossover ( @zaytradellc )Unlocking Market Dynamics: Kyrie Crossover Script by @zaytradellc
personalized trading success with the "Kyrie Crossover" script, meticulously crafted by @zaytrade. This innovative Pine Script, tailored to the birthdays of Kyrie and the script creator, combines the power of technical analysis with a touch of personalization to revolutionize your trading experience.
**Exponential Moving Average (EMA) Crossover Strategy:**
At the heart of the "Kyrie Crossover" script lies a sophisticated EMA crossover strategy. By utilizing a 10-period EMA and a 323-period EMA (symbolizing long term price action ), the strategy effectively captures market trends with precision and insight.
- **Short-Term EMA (10-period):** This EMA reacts swiftly to recent price changes, offering heightened sensitivity to short-term fluctuations. It excels in identifying immediate shifts in market sentiment, making it invaluable for pinpointing short-lived trends and potential reversal points.
- **Long-Term EMA (323-period):** In contrast, the long-term EMA provides a broader perspective by smoothing out short-term noise and focusing on longer-term trend direction. Its extended length filters out market noise effectively, providing a clear representation of the underlying trend's momentum and sustainability.
**Directional Movement Index (DMI) Metrics:**
The "Kyrie Crossover" script goes beyond traditional indicators by incorporating DMI metrics across multiple timeframes. By assessing trend strength and direction, traders gain valuable insights into market dynamics, allowing for informed decision-making.
**Simple Instructions to Profit:**
1. **Identify EMA Crossovers:** Look for instances where the short-term EMA (10-period) crosses above the long-term EMA (323-period) for a bullish signal, indicating a potential buying opportunity. Conversely, a crossover where the short-term EMA crosses below the long-term EMA signals a bearish trend and a potential selling opportunity.
2. **Confirm with DMI Metrics:** Validate EMA crossovers by checking DMI metrics across different timeframes (5 minutes, 15 minutes, 30 minutes, and 1 hour). Pay attention to color-coded indicators, with green indicating a bullish trend, red indicating a bearish trend, and white indicating no clear trend.
3. **Manage Risk:** Implement proper risk management techniques, such as setting stop-loss orders and position sizing based on your risk tolerance and trading objectives.
4. **Stay Informed:** Regularly monitor market conditions and adjust your trading strategy accordingly based on new signals and emerging trends.
Bitcoin 5A Strategy@LilibtcIn our long-term strategy, we have deeply explored the key factors influencing the price of Bitcoin. By precisely calculating the correlation between these factors and the price of Bitcoin, we found that they are closely linked to the value of Bitcoin. To more effectively predict the fair price of Bitcoin, we have built a predictive model and adjusted our investment strategy accordingly based on this model. In practice, the prediction results of this model correspond quite high with actual values, fully demonstrating its reliability in predicting price fluctuations.
When the future is uncertain and the outlook is unclear, people often choose to hold back and avoid risks, or even abandon their original plans. However, the prediction of Bitcoin is full of challenges, but we have taken the first step in exploring.
Table of contents:
Usage Guide
Step 1: Identify the factors that have the greatest impact on Bitcoin price
Step 2: Build a Bitcoin price prediction model
Step 3: Find indicators for warning of bear market bottoms and bull market tops
Step 4: Predict Bitcoin Price in 2025
Step 5: Develop a Bitcoin 5A strategy
Step 6: Verify the performance of the Bitcoin 5A strategy
Usage Restrictions
🦮Usage Guide:
1. On the main interface, modify the code, find the BTCUSD trading pair, and select the BITSTAMP exchange for trading.
2. Set the time period to the daily chart.
3. Select a logarithmic chart in the chart type to better identify price trends.
4. In the strategy settings, adjust the options according to personal needs, including language, display indicators, display strategies, display performance, display optimizations, sell alerts, buy prompts, opening days, backtesting start year, backtesting start month, and backtesting start date.
🏃Step 1: Identify the factors that have the greatest impact on Bitcoin price
📖Correlation Coefficient: A mathematical concept for measuring influence
In order to predict the price trend of Bitcoin, we need to delve into the factors that have the greatest impact on its price. These factors or variables can be expressed in mathematical or statistical correlation coefficients. The correlation coefficient is an indicator of the degree of association between two variables, ranging from -1 to 1. A value of 1 indicates a perfect positive correlation, while a value of -1 indicates a perfect negative correlation.
For example, if the price of corn rises, the price of live pigs usually rises accordingly, because corn is the main feed source for pig breeding. In this case, the correlation coefficient between corn and live pig prices is approximately 0.3. This means that corn is a factor affecting the price of live pigs. On the other hand, if a shooter's performance improves while another shooter's performance deteriorates due to increased psychological pressure, we can say that the former is a factor affecting the latter's performance.
Therefore, in order to identify the factors that have the greatest impact on the price of Bitcoin, we need to find the factors with the highest correlation coefficients with the price of Bitcoin. If, through the analysis of the correlation between the price of Bitcoin and the data on the chain, we find that a certain data factor on the chain has the highest correlation coefficient with the price of Bitcoin, then this data factor on the chain can be identified as the factor that has the greatest impact on the price of Bitcoin. Through calculation, we found that the 🔵number of Bitcoin blocks is one of the factors that has the greatest impact on the price of Bitcoin. From historical data, it can be clearly seen that the growth rate of the 🔵number of Bitcoin blocks is basically consistent with the movement direction of the price of Bitcoin. By analyzing the past ten years of data, we obtained a daily correlation coefficient of 0.93 between the number of Bitcoin blocks and the price of Bitcoin.
🏃Step 2: Build a Bitcoin price prediction model
📖Predictive Model: What formula is used to predict the price of Bitcoin?
Among various prediction models, the linear function is the preferred model due to its high accuracy. Take the standard weight as an example, its linear function graph is a straight line, which is why we choose the linear function model. However, the growth rate of the price of Bitcoin and the number of blocks is extremely fast, which does not conform to the characteristics of the linear function. Therefore, in order to make them more in line with the characteristics of the linear function, we first take the logarithm of both. By observing the logarithmic graph of the price of Bitcoin and the number of blocks, we can find that after the logarithm transformation, the two are more in line with the characteristics of the linear function. Based on this feature, we choose the linear regression model to establish the prediction model.
From the graph below, we can see that the actual red and green K-line fluctuates around the predicted blue and 🟢green line. These predicted values are based on fundamental factors of Bitcoin, which support its value and reflect its reasonable value. This picture is consistent with the theory proposed by Marx in "Das Kapital" that "prices fluctuate around values."
The predicted logarithm of the market cap of Bitcoin is calculated through the model. The specific calculation formula of the Bitcoin price prediction value is as follows:
btc_predicted_marketcap = math.exp(btc_predicted_marketcap_log)
btc_predicted_price = btc_predicted_marketcap / btc_supply
🏃Step 3: Find indicators for early warning of bear market bottoms and bull market tops
📖Warning Indicator: How to Determine Whether the Bitcoin Price has Reached the Bear Market Bottom or the Bull Market Top?
By observing the Bitcoin price logarithmic prediction chart mentioned above, we notice that the actual price often falls below the predicted value at the bottom of a bear market; during the peak of a bull market, the actual price exceeds the predicted price. This pattern indicates that the deviation between the actual price and the predicted price can serve as an early warning signal. When the 🔴 Bitcoin price deviation is very low, as shown by the chart with 🟩green background, it usually means that we are at the bottom of the bear market; Conversely, when the 🔴 Bitcoin price deviation is very high, the chart with a 🟥red background indicates that we are at the peak of the bull market.
This pattern has been validated through six bull and bear markets, and the deviation value indeed serves as an early warning signal, which can be used as an important reference for us to judge market trends.
🏃Step 4:Predict Bitcoin Price in 2025
📖Price Upper Limit
According to the data calculated on February 25, 2024, the 🟠upper limit of the Bitcoin price is $194,287, which is the price ceiling of this bull market. The peak of the last bull market was on November 9, 2021, at $68,664. The bull-bear market cycle is 4 years, so the highest point of this bull market is expected in 2025. That is where you should sell the Bitcoin. and the upper limit of the Bitcoin price will exceed $190,000. The closing price of Bitcoin on February 25, 2024, was $51,729, with an expected increase of 2.7 times.
🏃Step 5: Bitcoin 5A Strategy Formulation
📖Strategy: When to buy or sell, and how many to choose?
We introduce the Bitcoin 5A strategy. This strategy requires us to generate trading signals based on the critical values of the warning indicators, simulate the trades, and collect performance data for evaluation. In the Bitcoin 5A strategy, there are three key parameters: buying warning indicator, batch trading days, and selling warning indicator. Batch trading days are set to ensure that we can make purchases in batches after the trading signal is sent, thus buying at a lower price, selling at a higher price, and reducing the trading impact cost.
In order to find the optimal warning indicator critical value and batch trading days, we need to adjust these parameters repeatedly and perform backtesting. Backtesting is a method established by observing historical data, which can help us better understand market trends and trading opportunities.
Specifically, we can find the key trading points by watching the Bitcoin price log and the Bitcoin price deviation chart. For example, on August 25, 2015, the 🔴 Bitcoin price deviation was at its lowest value of -1.11; on December 17, 2017, the 🔴 Bitcoin price deviation was at its highest value at the time, 1.69; on March 16, 2020, the 🔴 Bitcoin price deviation was at its lowest value at the time, -0.91; on March 13, 2021, the 🔴 Bitcoin price deviation was at its highest value at the time, 1.1; on December 31, 2022, the 🔴 Bitcoin price deviation was at its lowest value at the time, -1.
To ensure that all five key trading points generate trading signals, we set the warning indicator Bitcoin price deviation to the larger of the three lowest values, -0.9, and the smallest of the two highest values, 1. Then, we buy when the warning indicator Bitcoin price deviation is below -0.9, and sell when it is above 1.
In addition, we set the batch trading days as 25 days to implement a strategy that averages purchases and sales. Within these 25 days, we will invest all funds into the market evenly, buying once a day. At the same time, we also sell positions at the same pace, selling once a day.
📖Adjusting the threshold: a key step to optimizing trading strategy
Adjusting the threshold is an indispensable step for better performance. Here are some suggestions for adjusting the batch trading days and critical values of warning indicators:
• Batch trading days: Try different days like 25 to see how it affects overall performance.
• Buy and sell critical values for warning indicators: iteratively fine-tune the buy threshold value of -0.9 and the sell threshold value of 1 exhaustively to find the best combination of threshold values.
Through such careful adjustments, we may find an optimized approach with a lower maximum drawdown rate (e.g., 11%) and a higher cumulative return rate for closed trades (e.g., 474 times). The chart below is a backtest optimization chart for the Bitcoin 5A strategy, providing an intuitive display of strategy adjustments and optimizations.
In this way, we can better grasp market trends and trading opportunities, thereby achieving a more robust and efficient trading strategy.
🏃Step 6: Validating the performance of the Bitcoin 5A Strategy
📖Model interpretability validation: How to explain the Bitcoin price model?
The interpretability of the model is represented by the coefficient of determination R squared, which reflects the degree of match between the predicted value and the actual value. I divided all the historical data from August 18, 2015 into two groups, and used the data from August 18, 2011 to August 18, 2015 as training data to generate the model. The calculation result shows that the coefficient of determination R squared during the 2011-2015 training period is as high as 0.81, which shows that the interpretability of this model is quite high. From the Bitcoin price logarithmic prediction chart in the figure below, we can see that the deviation between the predicted value and the actual value is not far, which means that most of the predicted values can explain the actual value well.
The calculation formula for the coefficient of determination R squared is as follows:
residual = btc_close_log - btc_predicted_price_log
residual_square = residual * residual
train_residual_square_sum = math.sum(residual_square, train_days)
train_mse = train_residual_square_sum / train_days
train_r2 = 1 - train_mse / ta.variance(btc_close_log, train_days)
📖Model stability verification: How to affirm the stability of the Bitcoin price model when new data is available?
Model stability is achieved through model verification. I set the last day of the training period to February 2, 2024 as the "verification group" and used it as verification data to verify the stability of the model. This means that after generating the model if there is new data, I will use these new data together with the model for prediction, and then evaluate the interpretability of the model. If the coefficient of determination when using verification data is close to the previous training one and both remain at a high level, then we can consider this model as stability. The coefficient of determination calculated from the validation period data and model prediction results is as high as 0.83, which is close to the previous 0.81, further proving the stability of this model.
📖Performance evaluation: How to accurately evaluate historical backtesting results?
After detailed strategy testing, to ensure the accuracy and reliability of the results, we need to carry out a detailed performance evaluation on the backtest results. The key evaluation indices include:
• Net value curve: As shown in the rose line, it intuitively reflects the growth of the account net value. By observing the net value curve, we can understand the overall performance and profitability of the strategy.
The basic attributes of this strategy are as follows:
Trading range: 2015-8-19 to 2024-2-18, backtest range: 2011-8-18 to 2024-2-18
Initial capital: 1000USD, order size: 1 contract, pyramid: 50 orders, commission rate: 0.2%, slippage: 20 markers.
In the strategy tester overview chart, we also obtained the following key data:
• Net profit rate of closed trades: as high as 474 times, far exceeding the benchmark, as shown in the strategy tester performance summary chart, Bitcoin buys and holds 210 times.
• Number of closed trades and winning percentage: 100 trades were all profitable, showing the stability and reliability of the strategy.
• Drawdown rate & win-loose ratio: The maximum drawdown rate is only 11%, far lower than Bitcoin's 78%. Profit factor, or win-loose ratio, reached 500, further proving the advantage of the strategy.
Through these detailed evaluations, we can see clearly the excellent balance between risk and return of the Bitcoin 5A strategy.
⚠️Usage Restrictions: Strategy Application in Specific Situations
Please note that this strategy is designed specifically for Bitcoin and should not be applied to other assets or markets without authorization. In actual operations, we should make careful decisions according to our risk tolerance and investment goals.
KT Litmus2
Hello everyone,
Recently I saw a very good indicator on TV called Ichimoku Oscillator. This is a K-line convergence and divergence indicator similar to MACD. After backtesting research, this indicator performs well on long-term trends.
Since it is an indicator, it is made into a strategy category. Several optimizations have also been made.
This strategy takes into account the following market factors:
EMA -> Trend
Fast line - slow line -> moving average
EMA Squeeze -> Momentum Conversion, Trend
ATR -> Noise Reduction
How does it compare to the original indicator?
Optimized background display so the canvas doesn't feel cluttered with excessive colors.
Optimized part of the position reduction logic so that too many trading signals will not affect the performance of the strategy.
NOTE: As you can see, there are potential improvements that can be made by merging volumes.
Signal
Input level -> Kinetic energy enhancement, +4 long, -4 short
Partial exit level -> moving average (EMA | fast and slow line) crossing, trend unchanged
All exit levels -> trend conversion
Risk Management
"Trend Stop Loss" and "Momentum Take Profit" are used here.
Trend stop loss: Use the conversion of the strategy trend parameter wave range to close the order.
Momentum take profit: take advantage of the weakening or reverse trend momentum of the strategy to take profit.
As described, the strategy has obvious advantages in trend trading, but in volatile markets, stop loss may be triggered due to frequent signals.
Now, a set of knowledge is provided for the inexperienced reader.
MACD usually consists of three components. The MACD line is the fast exponential moving average (usually taken on the 12th day) minus the slow exponential moving average (usually taken on the 26th day), generally called the difference (DIF). The second line is the signal line, which is the exponential moving average of DIF (usually 9 days), generally called DEA. The last component is the MACD histogram, whose value is the difference between DIF and DEA. However, the time value of the MACD indicator can also be adjusted according to the trader's preference and trading category.
The underlying logic of DIF is that the short-term exponential moving average reflects current price movements, while the long-term EMA reflects earlier price movements. Therefore, if there is a large gap between these two EMAs, then the market is trending up or down. While the MACD histogram is oscillating around the zero line, indicating the strength of the trend.
EMA: Exponential Moving Average; similar to a simple moving average but exponentially weights the input data.
Sincerely,
salute
---
Acknowledgments:
@LonesomeTheBlue
renew
March 14
Strategies for increasing Python version
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.
FreedX Backtest Plus█ Our new FreedX Backtest PLUS template enhances TradingView backtesting with smart features like Mean Reversion, Flexible Volatility, Liquidation Filter, and Better Trend Filtering, making strategies more effective. It lets users set up automated alerts easily. This guide explains how to make the most of these improved features.
The Trading Date Settings feature in our TradingView script allows you to refine their backtesting parameters by specifying trading dates and hours. This feature enhances the accuracy of the backtest by aligning it with specific time frames and days, ensuring that the strategy is tested under relevant market conditions.
Features:
⚙️ Enable Trading Between Specific Dates:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific date range.
💡 How to Use:
→ Input the Start Date and End Date for the backtest period.
→ The script will execute the strategy only within this specified date range.
⚙️ Enable Trading Between Specific Hours:
🎯 Purpose:
→ Allows you to limit the backtesting of their strategy to a specific hour range.
💡 How to Use:
→ Input the start and end hour for in Trading Session section.
→ The script will execute the strategy only within this specified hour range.
⚙️ Enable Trading on Specified Days of the Week:
🎯 Purpose:
→ Gives you the option to conduct backtesting on selected days of the week, tailoring the strategy to particular market behaviours that may occur on these days.
💡 How to Use:
→ Select the days of the week for the backtest.
→ The script will activate the trading strategy only on these chosen days.
█ BUY/SELL TRIGGER SETTINGS
The Buy/Sell Trigger Settings feature is designed to provide users with flexibility in defining the conditions for 'LONG' and 'SHORT' signals based on various indicator types. This customization is crucial for tailoring strategies to different trading styles and market conditions.
Features:
⚙️ Single-Line Plotted Indicators :
🎯 Purpose:
→ Enables you to select a single-line plotted indicator as a source for backtesting. You can define specific levels to trigger 'LONG' or 'SHORT' signals.
💡 How to Use:
→ Choose a Single-Line Plotted indicator as the source.
→ Set the top and bottom levels for the indicator.
→ The script triggers 'LONG' signals at the bottom level and 'SHORT' signals at the top level.
⚙️ Two-Line Plotted Indicators :
🎯 Purpose:
→ Allows backtesting with two-line cross plot sources. Signals are generated based on the crossover of these lines.
💡 How to Use:
→ Select two lines as 'Source 1' and 'Source 2' for the indicator.
→ The script triggers a 'LONG' signal when 'Source 1' crosses above 'Source 2'.
→ Conversely, a 'SHORT' signal is triggered when 'Source 2' crosses above 'Source 1'.
⚙️ Custom Signals :
🎯 Purpose:
→ This setting enables users to define their own criteria for LONG, SHORT, and CLOSE signals based on custom indicator outputs.
💡 How to Use:
→ Select the custom source for your signals.
→ Define the output values that correspond to each signal type (e.g., “1” for 'LONG', “-1” for SHORT, and “0” for CLOSE).
→ The script will trigger signals according to these custom-defined values.
█ TP/SL SETTINGS
The TP/SL (Take Profit/Stop Loss) Settings feature is designed to give users control over their profit securing and risk mitigation strategies. This feature allows for setting custom TP and SL levels, which can be critical in managing trades effectively.
Features:
Custom TP/SL Levels for Long/Short Signals:
🎯 Purpose:
→ Enables users to set specific percentage levels for Take Profit and Stop Loss on long and short signals.
💡 How to Use:
→ In the TP/SL Settings, input the desired percentage for Take Profit (TP) and Stop Loss (SL).
→ For example, to secure a profit at a 10% price increase on LONG signals, set the “Long TP Percentage” to “10”.
█ STRATEGY SETTINGS
Strategy Settings provide a range of options to customize the trading strategy. These settings include leverage, position direction changes, and more, allowing users to tailor their strategy to their risk tolerance and market view.
Features:
⚙️ Enable Reverse Position:
🎯 Purpose:
→ Automatically closes a current position and opens a new one in the opposite direction upon detecting a signal for a market trend change.
🎯 Example:
→ If a LONG signal is received while in a SHORT position, the script will close the SHORT position and open a LONG position.
💡 How to Use:
→ Activate this feature in the Strategy Settings.
⚙️ Enable Spot Mode:
🎯 Purpose:
→ Disables short orders, using short signals only for closing long positions.
💡 How to Use:
→ Select the 'Spot Mode' option in the Strategy Settings.
⚙️ Enable Invert Signals:
🎯 Purpose:
→ Inverts all indicator signals, changing LONG signals to SHORT and vice versa.
💡 How to Use:
→ Opt for the 'Invert Signals' feature in the Strategy Settings.
⚙️ Enable Trailing Stop:
🎯 Purpose:
→ Triggers a trailing stop order on the exchange instead of a standard stop market order.
☢️ Caution:
→ The backtesting of this feature on TradingView may not accurately reflect actual strategy performance due to discrepancies between TradingView and exchange mechanisms.
💡 How to Use:
→ Select 'Trailing Stop' in the Strategy Settings.
⚙️ Enable Realistic TP & SL:
🎯 Purpose:
→ Goal is protect the user from unrealistic stop loss and take profit prices in live exchange trading conditions.
→ That feature continuously checks the take profit, stop loss and move stop loss prices to prevent unrealistic values. It changes their values according to (minimum realistic percent %)
💡 How to Use:
→ Select 'Enable Realistic TP & SL' in the Strategy Settings. Write min allowed percents.
█ LIMITER SETTINGS
Limiter Settings provide a range of options to customize the trading strategy. These settings include drawdown limits,contract limit, tradable ratio, for allowing users to tailor their strategy to their risk tolerance and market view.
⚙️ Leverage :
🎯 Purpose:
→ Allows users to apply leverage to their trades.
☢️ Caution:
→ High leverage can significantly increase the risk of liquidation.
→ High leverage and a high stop-loss price may override your fixed stoploss percentage, adjusting the stop-loss to the liquidation price.
💡 How to Use:
→ Set the desired leverage ratio in the Strategy Settings.
⚙️ Drawdown Limit:
🎯 Purpose:
→ Sets a maximum drawdown limit, automatically halting the strategy if this limit is reached, thereby controlling risk.
💡 How to Use:
→ Input the maximum drawdown limit (default: 100, min: 0, max: 100).
⚙️ Contract Limit:
🎯 Purpose:
→ Sets a maximum contract limit, beyond which the compound effect cannot be used. This is important to prevent market manipulation through large-volume orders.
💡 How to Use:
→ Input the maximum contract limit (min: 0).
⚙️ Tradable Ratio:
🎯 Purpose:
→ Sets a tradable ratio, it uses that ratio calculating entry cost for position. Main purpose is cash-out and cash-in according to balance change.
💡 How to Use:
→ Input the tradable ratio percent (default: 98, min: 0.1, max: 100).
█ CASH-OUT SETTINGS
Cash-Out Settings offer a money-saving mechanism that prevents entering positions with the entire balance due to cashed-out funds. It functions with a webhook alerts, but the 'Override Allocation %' option must be enabled.
⚙️ Cash-out Threshold %:
🎯 Purpose:
→ It is cash-out mechanism, it saves money with a target threshold.
💡 How to Use:
→ Input the threshold (min: 0).
⚙️ Cash-out Per Profitable Trades %:
🎯 Purpose:
→ It is cash-out mechanism, it saves money from every trade with a percent like commission.
💡 How to Use:
→ Input save percent% (min: 0).
█ ADAPTIVE VOLATILITY STRATEGY SETTINGS
Advanced Strategy Settings offer sophisticated methods for managing Stop Loss (SL) and Take Profit (TP) using the Average True Range (ATR). These settings are ideal for traders who want to incorporate volatility into their exit strategies.
Features:
⚙️ Enable ATR Stop Loss:
🎯 Purpose:
→ Automatically sets the Stop Loss price using the Average True Range at the time of entry.
💡 How to Use:
→ Activate 'ATR Stop Loss' to have the SL price calculated based on the current ATR.
⛓ Enable ATR Trailing Stop:
→ Dynamically updates the Stop Loss price with each new bar, according to the Average True Range.
→ Activate 'ATR Trailing Stop'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
⚙️ Enable ATR Take Profit:
🎯 Purpose:
→ Sets the Take Profit price based on the Average True Range at the time of entry.
💡 How to Use:
→ Choose 'ATR Take Profit' for TP price determination using ATR.
⚙️ Enable ATR Limit Entry:
🎯 Purpose:
→ Trade can not open in candle close price. Price should hit target price that based on average true range value.
💡 How to Use:
→ Choose 'ATR Limit Entry' for entry price determination using ATR.
⛓ Enable ATR Limit Entry Trailing Price:
→ Dynamically updates the entry price with each new bar, according to the Average True Range.
→ Activate 'ATR Limit Entry Trailing Price'.
→ Set the ATR Period to define the number of bars for ATR calculation.
→ Adjust the ATR SL Multiplier to determine the stop loss distance.
→ Modify the ATR TP Multiplier for setting the take profit distance.
█ TREND FILTERING SETTINGS
Trend Filtering Settings are designed to align trading strategies with the prevailing market trend, enhancing the precision of trade entries and exits. These settings utilize moving averages for trend analysis and decision-making.
Features:
⚙️ Enable Moving Average Filtering:
🎯 Purpose:
→ Limits trades based on moving average trends, blocking short trades in an uptrend and vice versa.
💡 How to Use:
→ Enable 'Trend Filtering'.
→ Set Fast and Slow MA Lengths for trend analysis.
→ Select the Timeframe for moving averages.
→ Choose the Moving Average Type for trend filtering.
🎯 Note:
→ Be cautious with timeframe selections; lower timeframes than the base may cause inconsistencies.
⛓ Exit on Trend Reversal:
→ Automatically closes a position when a market trend reversal is detected.
→ Turn on 'Exit on Trend Reversal' in the settings.
⛓ Ignore Counter Signals:
→ Ignores counter signals during trending market way.
→ If the trend way is long. All short signals will ignore and vice versa.
⛓ Enable Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Activate 'Drawing On Chart' to see the trend filter overlaid on the trading chart.
⚙️ Enable Adx Filtering:
🎯 Purpose:
→ Limits trades based on adx value, blocking trades if trend strength is not enough or vice versa for invert mode.
💡 How to Use:
→ Enable 'Adx Filtering'.
→ Set Smoothing and Lengths for adx trend analysis.
→ Select level barrier for trend strength.
⚙️ Enable Custom Filtering:
🎯 Purpose:
→ Limits trades based on custom sources, blocking trades according to custom trades.
💡 How to Use:
→ Enable 'Custom Filtering'.
→ Select fast source.
→ Select slow source.
→ Enable lag mode.
█ MEAN REVERSION FILTERING SETTINGS
Mean Reversion Filtering Settings are designed to align trading strategies during accumulation market conditions. They set a distance from a line to permit trading. The purpose is to ensure that when the price strays too far from the mean line, it should revert back. In accumulation markets, price movements are generally horizontal. In such situations, mean reversion will operate like a grid, enabling profitable trades with low drawdown. However, when the market structure begins to trend, mean reversion filters may not be as profitable as in accumulation markets. For instance, let's say the price is rising and we are shorting the market until it reaches the mean price line. As the price goes up and the mean also rises, we will end up closing the position at a higher price, rendering the mean reversion system non-profitable. Therefore, consider this filter wisely; greater distances might work better in trending markets.
Features:
⚙️ Enable Kairi Filter:
🎯 Purpose:
→ Blocks trades based on distance percent between price and moving average.
💡 How to Use:
→ Enable 'Kairi Filter'.
→ Set Length and Distance Percent.
⛓ Enable Trend Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Enable 'Drawing On Chart' to see the allowed regions overlaid on the trading chart with arrows.
⚙️ Enable VWAP Filter:
🎯 Purpose:
→ Blocks trades based on distance percent between price and volume weighted average price.
💡 How to Use:
→ Enable 'VWAP Filter'.
→ Set Timeframe as minutes and distance as percent.
⛓ Exit on Crossing with VWAP:
→ Automatically closes a position when the closing price of a candle crosses the VWAP.
→ Choose "Enable", 'Exit on Crossing with VWAP' in the settings.
⛓ Enable Drawing On Chart:
→ Visually represents the trend filter directly on the chart for easy reference.
→ Enable 'Drawing On Chart' to see the allowed regions overlaid on the trading chart with arrows.
█ LIQUIDATION FILTER SETTINGS
Liquidation filter compares the volume data of futures and spot markets.
Large differences in volume indicate unexpected market conditions, such as massive trading activities, which may signal liquidations.
Features:
⚙️ Enable Liquidation Filter:
🎯 Purpose:
→ Blocks trades based on extra ordinary volume differences in spot and futures market.
💡 How to Use:
→ Enable 'Liquidation Filter'.
→ Set behavior to react during that market conditions.
→ Set base amount to filter volume. This amount changes according to timeframe, you should find right amounts.
→ Liquidation candle count means, it is sum of liquidated candle count in last 20 bars.If you set 0, it means feature is disabled.
→ Detection, try to select the spot and perpetual symbols automatically, symbol names varies, it do not support all symbols, you should choose manually in that situation.
█ AUTOMATED ALERT SETTINGS
Automated Alert Settings are designed to integrate your TradingView script with webhook alerts. These settings allow for enhanced strategy execution and management.
Features:
Enable Webhook Alerts:
🎯 Purpose:
→ Trigger BUY, SELL, CHANGE_DIRECTION or MOVE_STOP_LOSS .
💡 How to Use:
→ Enable 'Webhook Alerts' in the settings.
→ Enter your Strategy Key.
→ Optionally, activate 'Override Allocation Percentage' to bypass the preset allocation percentage.
☢️ Caution:
→ Overriding the allocation percentage may result in trade entry errors due to misalignment between entry cost and available balance.
Enable Custom Alerts:
🎯 Purpose:
→ User can produce unique messages for different purposes.
💡 How to Use:
→ Enable 'Custom Alerts' in the settings.
→ Enter your message format type.
█ DEBUGGING SETTINGS
Debugging Settings are crucial for users who want to analyze and optimize their strategies. These settings provide tools for visualizing alerts on charts and accessing detailed data outputs.
Features:
⚙️ Enable Alert Plotting:
🎯 Purpose:
→ Allows users to visualize trading alerts directly on the chart, aiding in strategy analysis and refinement.
💡 How to Use:
→ Activate 'Alert Plotting' to draw alerts on the chart.
☢️ Caution:
→ It is recommended to disable this feature when creating actual trading alerts, as it can cause latency in signal processing.
⚙️ Enable Debugger Mode:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Data Window.
💡 How to Use:
→ Turn on 'Debugger Mode' to access real-time data and metrics relevant to your strategy.
⚙️ Enable Table:
🎯 Purpose:
→ Facilitates strategy debugging by providing detailed data output in the TradingView Table on chart.
💡 How to Use:
→ Turn on 'Table' to access last closed candle data and metrics relevant to your strategy.
█ ADDITIONAL SETTINGS
⚙️ Enable Bar Magnifier
⚙️ Enable Using standard OHLC
CVD Divergence Strategy.1.mmThis is the matching Strategy version of Indicator of the same name.
As a member of the K1m6a Lions discussion community we often use versions of the Cumulative Volume Delta indicator
as one of our primary tools along with RSI, RSI Divergences, Open interest, Volume Profile, TPO and Fibonacci levels.
We also discuss visual interpretations of CVD Divergences across multiple time frames much like RSI divergences.
RSI Divergences can be identified as possible Bullish reversal areas when the RSI is making higher low points while
the price is making lower low points.
RSI Divergences can be identified as possible Bearish reversal areas when the RSI is making lower high points while
the price is making higher high points.
CVD Divergences can also be identified the same way on any timeframe as possible reversal signals. As with RSI, these Divergences
often occur as a trend's momentum is giving way to lower volume and areas when profits are being taken signaling a possible reversal
of the current trending price movement.
Hidden Divergences are identified as calculations that may be signaling a continuation of the current trend.
Having not found any public domain versions of a CVD Divergence indicator I have combined some public code to create this
indicator and matching strategy. The calculations for the Cumulative Volume Delta keep a running total for the differences between
the positive changes in volume in relation to the negative changes in volume. A relative upward spike in CVD is created when
there is a large increase in buying vs a low amount of selling. A relative downward spike in CVD is created when
there is a large increase in selling vs a low amount of buying.
In the settings menu, the is a drop down to be used to view the results in alternate timeframes while the chart remains on current timeframe. The Lookback settings can be adjusted so that the divs show on a more local, spontaneous level if set at 1,1,60,1. For a deeper, wider view of the divs, they can be set higher like 7,7,60,7. Adjust them all to suit your view of the divs.
To create this indicator/strategy I used a portion of the code from "Cumulative Volume Delta" by @ contrerae which calculates
the CVD from aggregate volume of many top exchanges and plots the continuous changes on a non-overlay indicator.
For the identification and plotting of the Divergences, I used similar code from the Tradingview Technical "RSI Divergence Indicator"
This indicator should not be used as a stand-alone but as an additional tool to help identify Bullish and Bearish Divergences and
also Bullish and Bearish Hidden Divergences which, as opposed to regular divergences, may indicate a continuation.
Bitcoin 5A Strategy - Price Upper & Lower Limit@LilibtcIn our long-term strategy, we have deeply explored the key factors influencing the price of Bitcoin. By precisely calculating the correlation between these factors and the price of Bitcoin, we found that they are closely linked to the value of Bitcoin. To more effectively predict the fair price of Bitcoin, we have built a predictive model and adjusted our investment strategy accordingly based on this model. In practice, the prediction results of this model correspond quite high with actual values, fully demonstrating its reliability in predicting price fluctuations.
When the future is uncertain and the outlook is unclear, people often choose to hold back and avoid risks, or even abandon their original plans. However, the prediction of Bitcoin is full of challenges, but we have taken the first step in exploring.
Table of contents:
Usage Guide
Step 1: Identify the factors that have the greatest impact on Bitcoin price
Step 2: Build a Bitcoin price prediction model
Step 3: Find indicators for warning of bear market bottoms and bull market tops
Step 4: Predict Bitcoin Price in 2025
Step 5: Develop a Bitcoin 5A strategy
Step 6: Verify the performance of the Bitcoin 5A strategy
Usage Restrictions
🦮Usage Guide:
1. On the main interface, modify the code, find the BTCUSD trading pair, and select the BITSTAMP exchange for trading.
2. Set the time period to the daily chart.
3. Select a logarithmic chart in the chart type to better identify price trends.
4. In the strategy settings, adjust the options according to personal needs, including language, display indicators, display strategies, display performance, display optimizations, sell alerts, buy prompts, opening days, backtesting start year, backtesting start month, and backtesting start date.
🏃Step 1: Identify the factors that have the greatest impact on Bitcoin price
📖Correlation Coefficient: A mathematical concept for measuring influence
In order to predict the price trend of Bitcoin, we need to delve into the factors that have the greatest impact on its price. These factors or variables can be expressed in mathematical or statistical correlation coefficients. The correlation coefficient is an indicator of the degree of association between two variables, ranging from -1 to 1. A value of 1 indicates a perfect positive correlation, while a value of -1 indicates a perfect negative correlation.
For example, if the price of corn rises, the price of live pigs usually rises accordingly, because corn is the main feed source for pig breeding. In this case, the correlation coefficient between corn and live pig prices is approximately 0.3. This means that corn is a factor affecting the price of live pigs. On the other hand, if a shooter's performance improves while another shooter's performance deteriorates due to increased psychological pressure, we can say that the former is a factor affecting the latter's performance.
Therefore, in order to identify the factors that have the greatest impact on the price of Bitcoin, we need to find the factors with the highest correlation coefficients with the price of Bitcoin. If, through the analysis of the correlation between the price of Bitcoin and the data on the chain, we find that a certain data factor on the chain has the highest correlation coefficient with the price of Bitcoin, then this data factor on the chain can be identified as the factor that has the greatest impact on the price of Bitcoin. Through calculation, we found that the 🔵 number of Bitcoin blocks is one of the factors that has the greatest impact on the price of Bitcoin. From historical data, it can be clearly seen that the growth rate of the 🔵 number of Bitcoin blocks is basically consistent with the movement direction of the price of Bitcoin. By analyzing the past ten years of data, we obtained a daily correlation coefficient of 0.93 between the number of Bitcoin blocks and the price of Bitcoin.
🏃Step 2: Build a Bitcoin price prediction model
📖Predictive Model: What formula is used to predict the price of Bitcoin?
Among various prediction models, the linear function is the preferred model due to its high accuracy. Take the standard weight as an example, its linear function graph is a straight line, which is why we choose the linear function model. However, the growth rate of the price of Bitcoin and the number of blocks is extremely fast, which does not conform to the characteristics of the linear function. Therefore, in order to make them more in line with the characteristics of the linear function, we first take the logarithm of both. By observing the logarithmic graph of the price of Bitcoin and the number of blocks, we can find that after the logarithm transformation, the two are more in line with the characteristics of the linear function. Based on this feature, we choose the linear regression model to establish the prediction model.
From the graph below, we can see that the actual red and green K-line fluctuates around the predicted blue and 🟢green line. These predicted values are based on fundamental factors of Bitcoin, which support its value and reflect its reasonable value. This picture is consistent with the theory proposed by Marx in "Das Kapital" that "prices fluctuate around values."
The predicted logarithm of the market cap of Bitcoin is calculated through the model. The specific calculation formula of the Bitcoin price prediction value is as follows:
btc_predicted_marketcap = math.exp(btc_predicted_marketcap_log)
btc_predicted_price = btc_predicted_marketcap / btc_supply
🏃Step 3: Find indicators for early warning of bear market bottoms and bull market tops
📖Warning Indicator: How to Determine Whether the Bitcoin Price has Reached the Bear Market Bottom or the Bull Market Top?
By observing the Bitcoin price logarithmic prediction chart mentioned above, we notice that the actual price often falls below the predicted value at the bottom of a bear market; during the peak of a bull market, the actual price exceeds the predicted price. This pattern indicates that the deviation between the actual price and the predicted price can serve as an early warning signal. When the 🔴 Bitcoin price deviation is very low, as shown by the chart with 🟩green background, it usually means that we are at the bottom of the bear market; Conversely, when the 🔴 Bitcoin price deviation is very high, the chart with a 🟥red background indicates that we are at the peak of the bull market.
This pattern has been validated through six bull and bear markets, and the deviation value indeed serves as an early warning signal, which can be used as an important reference for us to judge market trends.
🏃Step 4:Predict Bitcoin Price in 2025
📖Price Upper Limit
According to the data calculated on March 10, 2023(If you want to check latest data, please contact with author), the 🟠upper limit of the Bitcoin price is $132,453, which is the price ceiling of this bull market. The peak of the last bull market was on November 9, 2021, at $68,664. The bull-bear market cycle is 4 years, so the highest point of this bull market is expected in 2025, and the 🟠upper limit of the Bitcoin price will exceed $130,000. The closing price of Bitcoin on March 10, 2024, was $68,515, with an expected increase of 90%.
🏃Step 5: Bitcoin 5A Strategy Formulation
📖Strategy: When to buy or sell, and how many to choose?
We introduce the Bitcoin 5A strategy. This strategy requires us to generate trading signals based on the critical values of the warning indicators, simulate the trades, and collect performance data for evaluation. In the Bitcoin 5A strategy, there are three key parameters: buying warning indicator, batch trading days, and selling warning indicator. Batch trading days are set to ensure that we can make purchases in batches after the trading signal is sent, thus buying at a lower price, selling at a higher price, and reducing the trading impact cost.
In order to find the optimal warning indicator critical value and batch trading days, we need to adjust these parameters repeatedly and perform backtesting. Backtesting is a method established by observing historical data, which can help us better understand market trends and trading opportunities.
Specifically, we can find the key trading points by watching the Bitcoin price log and the Bitcoin price deviation chart. For example, on August 25, 2015, the 🔴 Bitcoin price deviation was at its lowest value of -1.11; on December 17, 2017, the 🔴 Bitcoin price deviation was at its highest value at the time, 1.69; on March 16, 2020, the 🔴 Bitcoin price deviation was at its lowest value at the time, -0.91; on March 13, 2021, the 🔴 Bitcoin price deviation was at its highest value at the time, 1.1; on December 31, 2022, the 🔴 Bitcoin price deviation was at its lowest value at the time, -1.
To ensure that all five key trading points generate trading signals, we set the warning indicator Bitcoin price deviation to the larger of the three lowest values, -0.9, and the smallest of the two highest values, 1. Then, we buy when the warning indicator Bitcoin price deviation is below -0.9, and sell when it is above 1.
In addition, we set the batch trading days as 25 days to implement a strategy that averages purchases and sales. Within these 25 days, we will invest all funds into the market evenly, buying once a day. At the same time, we also sell positions at the same pace, selling once a day.
📖Adjusting the threshold: a key step to optimizing trading strategy
Adjusting the threshold is an indispensable step for better performance. Here are some suggestions for adjusting the batch trading days and critical values of warning indicators:
• Batch trading days: Try different days like 25 to see how it affects overall performance.
• Buy and sell critical values for warning indicators: iteratively fine-tune the buy threshold value of -0.9 and the sell threshold value of 1 exhaustively to find the best combination of threshold values.
Through such careful adjustments, we may find an optimized approach with a lower maximum drawdown rate (e.g., 11%) and a higher cumulative return rate for closed trades (e.g., 474 times). The chart below is a backtest optimization chart for the Bitcoin 5A strategy, providing an intuitive display of strategy adjustments and optimizations.
In this way, we can better grasp market trends and trading opportunities, thereby achieving a more robust and efficient trading strategy.
🏃Step 6: Validating the performance of the Bitcoin 5A Strategy
📖Model accuracy validation: How to judge the accuracy of the Bitcoin price model?
The accuracy of the model is represented by the coefficient of determination R square, which reflects the degree of match between the predicted value and the actual value. I divided all the historical data from August 18, 2015 into two groups, and used the data from August 18, 2011 to August 18, 2015 as training data to generate the model. The calculation result shows that the coefficient of determination R squared during the 2011-2015 training period is as high as 0.81, which shows that the accuracy of this model is quite high. From the Bitcoin price logarithmic prediction chart in the figure below, we can see that the deviation between the predicted value and the actual value is not far, which means that most of the predicted values can explain the actual value well.
The calculation formula for the coefficient of determination R square is as follows:
residual = btc_close_log - btc_predicted_price_log
residual_square = residual * residual
train_residual_square_sum = math.sum(residual_square, train_days)
train_mse = train_residual_square_sum / train_days
train_r2 = 1 - train_mse / ta.variance(btc_close_log, train_days)
📖Model reliability verification: How to affirm the reliability of the Bitcoin price model when new data is available?
Model reliability is achieved through model verification. I set the last day of the training period to February 2, 2024 as the "verification group" and used it as verification data to verify the reliability of the model. This means that after generating the model if there is new data, I will use these new data together with the model for prediction, and then evaluate the accuracy of the model. If the coefficient of determination when using verification data is close to the previous training one and both remain at a high level, then we can consider this model as reliable. The coefficient of determination calculated from the validation period data and model prediction results is as high as 0.83, which is close to the previous 0.81, further proving the reliability of this model.
📖Performance evaluation: How to accurately evaluate historical backtesting results?
After detailed strategy testing, to ensure the accuracy and reliability of the results, we need to carry out a detailed performance evaluation on the backtest results. The key evaluation indices include:
• Net value curve: As shown in the rose line, it intuitively reflects the growth of the account net value. By observing the net value curve, we can understand the overall performance and profitability of the strategy.
The basic attributes of this strategy are as follows:
Trading range: 2015-8-19 to 2024-2-18, backtest range: 2011-8-18 to 2024-2-18
Initial capital: 1000USD, order size: 1 contract, pyramid: 50 orders, commission rate: 0.2%, slippage: 20 markers.
In the strategy tester overview chart, we also obtained the following key data:
• Net profit rate of closed trades: as high as 474 times, far exceeding the benchmark, as shown in the strategy tester performance summary chart, Bitcoin buys and holds 210 times.
• Number of closed trades and winning percentage: 100 trades were all profitable, showing the stability and reliability of the strategy.
• Drawdown rate & win-loose ratio: The maximum drawdown rate is only 11%, far lower than Bitcoin's 78%. Profit factor, or win-loose ratio, reached 500, further proving the advantage of the strategy.
Through these detailed evaluations, we can see clearly the excellent balance between risk and return of the Bitcoin 5A strategy.
⚠️Usage Restrictions: Strategy Application in Specific Situations
Please note that this strategy is designed specifically for Bitcoin and should not be applied to other assets or markets without authorization. In actual operations, we should make careful decisions according to our risk tolerance and investment goals.
Bitcoin Momentum StrategyThis is a very simple long-only strategy I've used since December 2022 to manage my Bitcoin position.
I'm sharing it as an open-source script for other traders to learn from the code and adapt it to their liking if they find the system concept interesting.
General Overview
Always do your own research and backtesting - this script is not intended to be traded blindly (no script should be) and I've done limited testing on other markets beyond Ethereum and BTC, it's just a template to tweak and play with and make into one's own.
The results shown in the strategy tester are from Bitcoin's inception so as to get a large sample size of trades, and potential returns have diminished significantly as BTC has grown to become a mega cap asset, but the script includes a date filter for backtesting and it has still performed solidly in recent years (speaking from personal experience using it myself - DYOR with the date filter).
The main advantage of this system in my opinion is in limiting the max drawdown significantly versus buy & hodl. Theoretically much better returns can be made by just holding, but that's also a good way to lose 70%+ of your capital in the inevitable bear markets (also speaking from experience).
In saying all of that, the future is fundamentally unknowable and past results in no way guarantee future performance.
System Concept:
Capture as much Bitcoin upside volatility as possible while side-stepping downside volatility as quickly as possible.
The system uses a simple but clever momentum-style trailing stop technique I learned from one of my trading mentors who uses this approach on momentum/trend-following stock market systems.
Basically, the system "ratchets" up the stop-loss to be much tighter during high bearish volatility to protect open profits from downside moves, but loosens the stop loss during sustained bullish momentum to let the position ride.
It is invested most of the time, unless BTC is trading below its 20-week EMA in which case it stays in cash/USDT to avoid holding through bear markets. It only trades one position (no pyramiding) and does not trade short, but can easily be tweaked to do whatever you like if you know what you're doing in Pine.
Default parameters:
HTF: Weekly Chart
EMA: 20-Period
ATR: 5-period
Bar Lookback: 7
Entry Rule #1:
Bitcoin's current price must be trading above its higher-timeframe EMA (Weekly 20 EMA).
Entry Rule #2:
Bitcoin must not be in 'caution' condition (no large bearish volatility swings recently).
Enter at next bar's open if conditions are met and we are not already involved in a trade.
"Caution" Condition:
Defined as true if BTC's recent 7-bar swing high minus current bar's low is > 1.5x ATR, or Daily close < Daily 20-EMA.
Trailing Stop:
Stop is trailed 1 ATR from recent swing high, or 20% of ATR if in caution condition (ie. 0.2 ATR).
Exit on next bar open upon a close below stop loss.
I typically use a limit order to open & exit trades as close to the open price as possible to reduce slippage, but the strategy script uses market orders.
I've never had any issues getting filled on limit orders close to the market price with BTC on the Daily timeframe, but if the exchange has relatively low slippage I've found market orders work fine too without much impact on the results particularly since BTC has consistently remained above $20k and highly liquid.
Cost of Trading:
The script uses no leverage and a default total round-trip commission of 0.3% which is what I pay on my exchange based on their tier structure, but this can vary widely from exchange to exchange and higher commission fees will have a significantly negative impact on realized gains so make sure to always input the correct theoretical commission cost when backtesting any script.
Static slippage is difficult to estimate in the strategy tester given the wide range of prices & liquidity BTC has experienced over the years and it largely depends on position size, I set it to 150 points per buy or sell as BTC is currently very liquid on the exchange I trade and I use limit orders where possible to enter/exit positions as close as possible to the market's open price as it significantly limits my slippage.
But again, this can vary a lot from exchange to exchange (for better or worse) and if BTC volatility is high at the time of execution this can have a negative impact on slippage and therefore real performance, so make sure to adjust it according to your exchange's tendencies.
Tax considerations should also be made based on short-term trade frequency if crypto profits are treated as a CGT event in your region.
Summary:
A simple, but effective and fairly robust system that achieves the goals I set for it.
From my preliminary testing it appears it may also work on altcoins but it might need a bit of tweaking/loosening with the trailing stop distance as the default parameters are designed to work with Bitcoin which obviously behaves very differently to smaller cap assets.
Good luck out there!
Inside Candle StrategyIntroduction
The Inside Candle Breakout Strategy leverages the concept of inside candles as a primary signal for potential breakouts. Unlike common trend-following or scalping strategies, this method focuses on the volatility squeeze indicated by inside candles and aims to capture the momentum that follows these periods of consolidation. The strategy's originality lies in its specific integration of timeframes for signal detection and its application across diverse market conditions without relying on conventional trend indicators.
Strategy Description and Mechanics
Inside Candle Identification: At the heart of this strategy is the detection of inside candles, defined as candles fully contained within the range of the preceding candle. This pattern signifies a temporary balance between buyers and sellers, often preceding significant price movements. The strategy scans for these candles within a user-specified timeframe in the input section of the settings of the strategy, allowing for tailored signal generation based on individual trading preferences.
Entry Points and Market Entries: Upon identifying an inside candle and only once this candle closes, the strategy prepares to enter a trade in the direction of the breakout. Trades are executed in the timeframe selected on the chart, ensuring that entry points are aligned with real-time market movements. This process highlights the strategy's adaptability, making it suitable for various trading styles, from day trading to swing trading.
Overlay Indicator for Enhanced Market Analysis: Accompanying the breakout signals is an overlay indicator comprising two moving averages and a volatility cloud. This feature serves as a secondary tool for market analysis, offering insights into the prevailing market trend and volatility levels. While it doesn't influence the entry or exit signals directly, it provides traders with additional context for refining their decisions, enhancing the strategy's utility. This assistance tool is composed by one moving average and a second line which is calculated adding or subtracting the historical volatility of the asset on the moving average, depending on his momentum.
Strategy Results and Commitment to Realism
Backtesting Protocol: In our commitment to transparency and realism, backtesting results are derived from a dataset that ensures a sufficient number of trades (over 100) to validate the strategy's effectiveness. This approach underscores our dedication to providing traders with reliable and actionable insights.
Risk Management and Trade Sizing: Recognizing the importance of sustainable trading practices, the strategy incorporates strict risk management guidelines. Trades are sized to ensure that only a small percentage of equity is risked on a single trade, adhering to widely accepted risk tolerance levels. The initial account size for this script is set to 10000$.
Strategy Defaults and Justification: The default properties of the strategy, including the risk-reward ratio, average length for moving averages, and other parameters, are carefully chosen based on extensive testing and analysis. These settings represent a balanced approach, aiming to optimize the strategy's performance across a variety of market conditions.
Strategy Components:
- Inside Candles: An inside candle occurs when a candle's high and low are completely contained within the high and low of the previous candle. This pattern indicates a period of consolidation or indecision in the market, often preceding a significant price movement. The strategy detects inside candles based on the user-selected timeframe, allowing traders to capture potential breakouts.
Indicator Overlays:
- Moving Average: A simple moving average (SMA) is calculated over a user-defined length (`Average Length`), providing a dynamic baseline to gauge the market's direction. The strategy offers an option (`Show Moving Average`) to display or hide this moving average on the chart, giving traders control over the visual complexity.
- Volatility Measurement: Alongside the moving average, the strategy assesses market volatility using the standard deviation of the closing prices over the same period defined by the `Average Length`. The moving average is adjusted upwards or downwards by this volatility measure, creating a dynamic channel that reflects the current market conditions.
- Color Gradients for Volatility: The strategy uses a color gradient to fill the area between the moving average and its volatility-adjusted counterpart. This gradient visually represents the volatility level, transitioning from gray (low volatility) to a lighter shade (higher volatility), aiding in the assessment of market sentiment and volatility.
Trading Entries:
- Long Entry: A long position is triggered when the closing price exceeds the high of an inside candle, indicating potential bullish momentum. The strategy places a stop-loss at the low of the inside candle and sets a take-profit level based on the predefined risk-reward ratio (`RR Ratio`).
- Short Entry: Conversely, a short position is initiated when the closing price falls below the low of an inside candle, suggesting bearish pressure. A stop-loss is set at the high of the inside candle, with the take-profit level adjusted according to the risk-reward ratio.
Customization Settings:
- Timeframe: Traders can select the desired timeframe for inside candle detection, tailoring the strategy to fit various trading styles and time horizons.
- RR Ratio: The risk-reward ratio is adjustable, allowing traders to manage the potential risk and return of each trade according to their risk tolerance.
- Average Length: This setting determines the period over which the moving average and volatility are calculated, affecting the sensitivity of the strategy to price movements.
- Visual Settings: Users can customize the appearance of the strategy on their charts, including the colors of the moving average and volatility lines, as well as the line width, enhancing chart readability and personal preference adherence.
Disclaimer
Trading involves significant risk, and it is crucial for traders to conduct their own due diligence before engaging with any strategy. The Inside Candle Breakout Strategy is presented for informational purposes only and does not constitute financial advice.
DCA StrategyIntroducing the DCA Strategy, a powerful tool for identifying long entry and exit opportunities in uptrending assets like cryptocurrencies, stocks, and gold. This strategy leverages the Heikin Ashi candlestick pattern and the RSI indicator to navigate potential price swings.
Core Functionality:
Buy Signal : A buy signal is generated when a bullish (green) Heikin Ashi candle appears after a bearish (red) one, indicating a potential reversal in a downtrend. Additionally, the RSI must be below a user-defined threshold (default: 85) to prevent buying overbought assets.
Sell Signal : The strategy exits the trade when the RSI surpasses the user-defined exit level (default: 85), suggesting the asset might be overbought.
Backtesting Flexibility : Users can customize the backtesting period by specifying the start and end years.
Key Advantages:
Trend-Following: Designed specifically for uptrending assets, aiming to capture profitable price movements.
Dynamic RSI Integration: The RSI indicator helps refine entry signals by avoiding overbought situations.
User-Defined Parameters: Allows customization of exit thresholds and backtesting periods to suit individual trading preferences.
Commission and Slippage: The script factors in realistic commission fees (0.1%) and slippage (2%) for a more accurate backtesting experience.
Beats Buy-and-Hold: Backtesting suggests this strategy outperforms a simple buy-and-hold approach in uptrending markets.
Overall, the DCA Strategy offers a valuable approach for traders seeking to capitalize on long opportunities in trending markets with the help of Heikin Ashi candles and RSI confirmation.
Self Optimizing ROC [Starbots]Self Optimizing Rate of Change (ROC) Strategy. (non-repainting)
Script constantly tests 15 different ROC parameter combinations for maximum profitability and trades based on the best performing combination.
You will notice that signal lines switch after a bar close sometimes, this is when the strategy optimizes to the better combination and change plots, strategy is dynamic.
---------------------------------------------------------------------------------------------------------
The Rate-of-Change (ROC) indicator, which is also referred to as Momentum, is a pure momentum oscillator that measures the percent change in price from one period to the next. The ROC calculation compares the current price with the price “n” periods ago. The plot forms an oscillator that fluctuates above and below the zero line as the rate of change moves from positive to negative. As a momentum oscillator, ROC signals include centerline crossovers, divergences, and overbought-oversold readings.
ROC = (Close - Close n periods ago) / (Close n periods ago) * 100
-----------------------------------------------------------------------------------------------------------
The logic of self - optimizing:
This script is always backtesting 15 different combinations of ROC settings in the background and saves the net. profit gained for every single one of them, then strategy selects and use the best performing combination of settings currently available for you to trade.
It's recalculating on every bar close - if one of the parameters starts performing better than others - have a higher net profit gain (it's literally like running 15 backtests with different settings in the background) strategy switches to that parameter and continues trading like that until one of the other indicator parameters starts performing better again and switches to that settings.
We are optimizing our strategy based on 15 different 'lengths' or also called 'periods' of ROC.
Inputs (ROC period) : (you don't need to change them, you have a nice wide variety of periods)
🔴Roc (default=9) = 5
🟢Roc2 = 6
🔵Roc3 = 7
🟡Roc4 = 8
🟣Roc5 = 9
🟠Roc6 = 10
🔴Roc7 = 11
🟢Roc8 = 12
🔵Roc9 = 13
🟡Roc10 = 14
🟣Roc11 = 15
🟠Roc12 = 16
🟡Roc13 = 17
🟣Roc14 = 18
🟠Roc15 = 20
Backtester in the background works like this:
backtest ROC1 => save net. profit
backtest ROC2 => save net. profit ;
backtest ROC3 => save net. profit ;
..........
..........
backtest ROC15 => save net. profit ;
=>
It will backtest 15 different ROC parameters and save their profits.
Your strategy then trades based on the best performing (highest net.profit) ROC Setting currently available. It will check the calculations and backtest them on every new bar close - it's like running 15 strategies at time, and manually selecting the best performing one.
________________________________________________________________________
If you wish to use it as INDICATOR - turn on 'Recalculate after every tick' in Properties tab to have this script updating constantly and use it as a normal Indicator tool for manual trading.
-- Noise Filter - This will punish the tiny trades made by certain parameters and give more advantage to big average trades. It's basically normal fee calculation, it will deduct 0.xx % fee from every trade when optimizing. You usually want it to have the same number as your fees on exchange. Large number will choose big long swing trades, small number will prioritize small scalping trades.
-- Turn on ROC Combination Profits and spot the worst/best performing combination. You can change periods to get the best performance after checking this table stats.
-- Backtesting Range - backtest within your desired time window. Example: 'from 01 / 01 /2020 to 01 / 01 /2023'.
-- Optimizing range - you can decrease the amount of bars/data for optimizing script. This way you can keep it up to date to more recent market by selecting optimizing range to optimize it just from the recent 3-6months of data for example. Strategy before this selected range will normally trade (backtest) based on the first ROC period ( 'Roc(default=9)' Input) parameter in your menu if you have Optimizing Range turned on.
**** I recommend 'Optimizing Range' to be turned off, use max amount of available bars in your history for optimization script.
-- Strategy is trading on the bar close without repaint. You can trade Long-Sell or Long- Short. Alerts available, insert webhook messages.
-- Turn on Profit Calendar for better overview of how your strategy performs monthly/annualy
-- Recommended ROC periods: from 5 to 24.
-- Recommended Sources : close, hlc3, hlcc4
-- Recommended Chart Timeframe : 4h +
-- Notes window : add your custom comments here or save your webhook messages inside here
-- Trading Session: in a session, you have to specify the time range for every day. It will trade only within this window and close trades when it's out. Session from 9am to 5pm will look like that: 0900-1700 or 7am to 4:30pm 0700-1630. After the colon, you can specify days of the week for your trading session. 1234567 trading all days, 23456 – Monday to Friday ('1 is Sunday here'). 0000-0000:1234567 by default will trade every day nonstop. 00.00am to 00.00pm and 1234567 every day of the week for example - Cryptocurrencies.
This script is simple to use for any trader as it saves a lot of time for searching good parameters on your own. It's self-optimizing and adjusting to the markets on the go.
BabyShark VWAP Strategy What the code does:
This Pine Script implements a trading strategy based on two indicators: Volume Weighted Average Price (VWAP) and On Balance Volume (OBV) Relative Strength Index (RSI). The strategy aims to identify potential buy and sell signals based on deviations from VWAP and OBV RSI crossing certain threshold levels.
How it does it:
**VWAP Calculation**: The script calculates the VWAP using either standard deviation or average deviation over a specified length. It then plots the VWAP and its upper and lower deviation bands.
**OBV RSI Calculation**: It computes the OBV and then calculates the RSI using the cumulative changes in OBV. The RSI is plotted and compared against predefined levels.
**Table Visibility and Occurrence Counting**: It allows the user to display a table showing the number of occurrences where the price is above Upper Dev 2, below Lower Dev 2, crosses above a higher RSI level, or crosses below a lower RSI level.
**Entries**: Long and short entry conditions are defined based on the position of the price relative to the VWAP deviation bands and the color of the OBV RSI. Entries are made when specific conditions are met, and there hasn't been a recent entry.
**Exit Conditions**: The script includes stop-loss and take-profit mechanisms. It exits positions based on price crossing the VWAP or a certain percentage, and it prevents further trading after a certain number of consecutive losses.
What traders can use it for:
**Trend Identification**: Traders can use the VWAP and its deviation bands to identify potential trend reversals or continuations.
**Volume Confirmation**: The inclusion of OBV RSI provides confirmation of price movements based on volume changes.
**Entry and Exit Signals**: The script generates buy and sell signals based on the specified conditions, allowing traders to enter and exit positions with defined stop-loss and take-profit levels.
**Statistical Analysis**: The visibility of occurrence counts in the table allows traders to perform statistical analysis on the frequency of price movements relative to the VWAP and OBV RSI levels.
INFINITY ALGO🆕Meet the updated version of our flagship indicator, now it's INFINITY ALGO!
🏃🏻 QUICK START
In very simple terms, our indicator generates complex trading signals on your chart (buy/sell), including Entry Point, Take Profit levels, Stop Loss level
To start, you need to add our indicator to your chart , choose a timeframe (we recommend 13min,15min and 4h but you can try any, these only have the best results) and set up notifications (how to do it told below) and that's it, you can work with it even without changing the settings!
Of course, to improve the accuracy of signals you will have to choose the optimal settings of the script for each trading pair and timeframe (you can find a guide below)
📊 SIGNALS
This script will generate complex trading recommendations, both Long and Short (signals); signals include:
- Entry Point:
Calculated based on pivot levels with confirmation by EMA/SMA (you can select this in the settings); also bullish/bearish cup is checked to confirm the entry.
Additionally, in the settings you can enable Heiken Ashi calculation mode (it shows much better on some trading pairs).
Why do we mashup these components and how they work together?
- The main indicator in our script is pivot levels, it is enabled by default and cannot be disabled. Auxiliary indicators (which you can switch on and off in the script settings) are EMA/SMA and Heiken Ashi. We have used pivot levels, which mark potential support and resistance zones based on previous price action. We have also used EMA/SMA that smooth out price fluctuations and show the direction of the trend. We have added an option to use Heiken Ashi that filters out noise and highlights the trend. We have also checked for bullish/bearish cup patterns, which are reversal patterns that indicate a change in momentum. By combining these indicators, we have created a more robust entry point that considers multiple factors such as price levels, trend, noise, and momentum.
- 6 Take Profit levels:
It is also possible to change in the settings (It is also possible to change the values for Short or Long positions separately), it will be fixed values in % (The default Take Profits for Long&Short are as follows: TP1-0.3%; TP2-1%; TP3-2%; TP4-3%; TP5-7.5%; TP6-16.5%)
- Stop Loss Level:
As with Take Profits, this is a fixed % value that you can customise to suit your risk management needs (It is also possible to change the values for Short or Long positions separately, by default is 4.5% for Long&Short positions)
*When trading on these signals, we strongly recommend that you exit the position in parts at each take profit or close your entire position at one particular take profit. Our script was designed specifically for exiting a position on take profits
⚙️ SETTINGS
Now let's talk about the settings of this script, which allow you to customise the signals quite a lot. In general, we recommend selecting the settings for each trading pair and timeframe separately, this will allow you to achieve better targets accuracy (the default settings are universal, you can trade with them without changing them if you want)
-> IMAGE <-
1. Period - minimum value of 2. Increasing this parameter will increase the accuracy of signals, but will reduce their number (accordingly, lowering the parameter will do the opposite). For the majority of trading pairs and timeframes the optimal period will be between 5 and 10 (the default value is 5).
2. Maximum Breakout length (in bars) - for most trading pairs you can set the value from 200 to 300 and it will be optimal. Below 200 is not recommended
3. T hreshold Rate % - this value also affects the accuracy and the number of signals - the higher this value is, the more often signals will be generated, but it can negatively affect the accuracy. The minimum value is 3, and the maximum value is 10. We recommend to try values in the range from 4 to 7 for most tickers
4. Minimum Number of tests - the number of level checks is required, we recommend to try 2, and only for some timeframes increase to 3
5. MA type & MA filter - The shorter the length of moving averages, the faster they react to trend changes, and show more local trends than global ones. If the length of MAs is longer, more global trends are shown. By default, the most optimal values are set.
By the way, you can ask us for a ready-made preset for any pair and we will be happy to help you!
📄 BACKTESTING
Now let's talk about how to properly test the settings and evaluate their effectiveness. Our script has a c ustom built-in backtester that shows statistics on the current trading pair and allows you to calculate the accuracy of each take profit target, as well as calculate values such as Gross profit/loss, net profit, and the ratio of initial deposit to profit. (you can enable/disable backtester "statistics" label in main settings)
In the main settings you can change the values for: initial deposit (Deposit $), trade size $ and leverage (by the way, it also affects the display of the label "Peak profit", which is calculated with this leverage)
-> IMAGE <-
Now let's look at the backtester - it shows detailed statistics for each Take Profit level, including: accuracy in % and number of trades; gross profit & loss; net profit in % and $ (based on selected settings); deposit to profit ratio in % and $.
Why did we choose such properties in the backtest for publication?
- Well, as the initial capital we took 5000$ and deposit 3% (150$) of the initial capital in each trade. For the fee was taken the value from the exchange Binance, which is 0.06% per trade (Taker + Maker, for a user without VIP on Binance and without taking into account additional fees such as funding, leverage fees, etc).
- Please also take a look at our inbuilt backtester ( IMAGE ) which counts the accuracy to each Take Profit. Also note that our inbuilt backtester does not take any fees into account. Pay attention to the last field "Deposit with Profit" it shows the value if you would close all positions at a certain target. For example, we can see that the most optimal is TP3 at these settings for this trading pair and timeframe, as the deposit to profit ratio will be +61.2%
- Also the script is more designed for swing and long term trading, so on most trading pairs you will be able to see statistics for 60-90 trades dataset
*disclaimer: please note that past results does not guarantee future performance! The accuracy of take profit targets in our backtester is calculated on past results, keep this in mind please
📥 NOTIFICATIONS
We have provided notifications that will deliver the latest signals to you in a convenient format in TradingView. The notification looks like this: It contains the entry point, Take Profits, Stop Loss, and a bit of advice on risk management. -> IMAGE <-
To set up notifications:
1. Select the script settings, trading pair and timeframe
2. Click "add alert on InfinityAlgo", then select "alert () function calls only" in the settings
-> IMAGE <-
3. That's it, now all that's left is to wait for a fresh alert
🔑 HOW TO GET ACCESS
We hope you will like this script :) We are always ready to help you with customisation, just let us know! To learn more about our scripts & get access - check out the “Author’s instructions” below 👇🏼
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!
How to force strategies fire exit alerts not reversalsPineScript has gone a long way, from very simple and little-capable scripting language to a robust coding platform with reliable execution endpoints. However, this one small intuitivity glitch is still there and is likely to stay, because it is traditionally justified and quite intuitive for significant group of traders. I'm sharing this workaround in response to frequent inquiries about it.
What's the glitch? When setting alerts on strategies to be synchronized with TradingView's Strategy Tester events, using simple alert messages such as "buy" or "sell" based on entry direction seems straightforward by inserting {{strategy.order.action}} into the Create Alert's "Message" field. Because "buy" or "sell" are exactly the strings produced by {{strategy.order.action}} placeholder. However, complications arise when attempting to EXIT positions without reversing, whether triggered by price levels like Stop Loss or Take Profit, or logical conditions to close trades. Those bricks fall apart, because on such events {{strategy.order.action}} sends the same "sell" for exiting buy positions and "buy" for exiting sell positions, instead of something more differentiating like "closebuy" or "closesell". As a result reversal trades are opened, instead of simply closing the open ones.
This convention harkens back to traditional stock market practices, where traders either bought shares to enter positions or sold them to exit. However, modern trading encompasses diverse instruments like CFDs, indices, and Forex, alongside advanced features such as Stop Loss, reshaping the landscape. Despite these advancements, the traditional nomenclature persists.
And is poised to stay on TradingView as well, so we need a workaround to get a simple strategy going. Luckily it is here and is called alert_message . It is a parameter, which needs to be added into each strategy.entry() / strategy.exit() / strategy.close() function call - each call, which causes Strategy Tester to produce entry or exit orders. As in this example script:
line 12: strategy.entry(... alert_message ="buy")
line 14: strategy.entry(... alert_message ="sell")
line 19: strategy.exit(... alert_message ="closebuy")
line 20: strategy.exit(... alert_message ="closesell")
line 24: strategy.close(... alert_message ="closebuy")
line 26: strategy.close(... alert_message ="closesell")
These alert messages are compatible with the Alerts Syntax of TradingConnector - a tool facilitating auto-execution of TradingView alerts in MetaTrader 4 or 5. Yes, simple alert messages like "buy" / "sell" / "closebuy" / "closesell" suffice to carry the execution of simple strategy, without complex JSON files with multiple ids and such. Other parameters can be added (actually plenty), but they are only option and that's not a part of this story :)
Last thing left to do is to replace "Message" in Create Alert popup with {{strategy.order.alert_message}} . This placeholder transmits the string defined in the PineScript alert_message= parameter, as outlined in this publication. With this workaround, executing closing alerts becomes seamless within PineScript strategies on TradingView.
Disclaimer: this content is purely educational, especially please don't pay attention to backtest results on any timeframe/ticker.