OPEN-SOURCE SCRIPT

[3Commas] HA & MA

314
HA & MA

🔷What it does: This tool is designed to test a trend-following strategy using Heikin Ashi candles and moving averages. It enters trades after pullbacks, aiming to let profits run once the risk-to-reward ratio reaches 1:1 while securing the position.

🔷Who is it for: It is ideal for traders looking to compare final results using fixed versus dynamic take profits by adjusting parameters and trade direction—a concept applicable to most trading strategies.

🔷How does it work: We use moving averages to define the market trend, then wait for opposite Heikin Ashi candles to form against it. Once these candles reverse in favor of the trend, we enter the trade, using the last swing created by the pullback as the stop loss. By applying the breakeven ratio, we protect the trade and let it run, using the slower moving average as a trailing stop.

A buy signal is generated when:
  • The previous candle is bearish (ha_bear[1]), indicating a pullback.
  • The fast moving average (ma1) is above the slow moving average (ma2), confirming an uptrend.
  • The current candle is bullish (ha_bull), showing trend continuation.
  • The Heikin Ashi close is above the fast moving average (ma1), reinforcing the bullish bias.
  • The real price close is above the open (close > open), ensuring bullish momentum in actual price data.
  • The signal is confirmed on the closed candle (barstate.isconfirmed) to avoid premature signals.
  • dir is undefined (na(dir)), preventing repeated signals in the same direction.

A sell signal is generated when:
  • The previous candle is bullish (ha_bull[1]), indicating a temporary upward move before a potential reversal.
  • The fast moving average (ma1) is below the slow moving average (ma2), confirming a downtrend.
  • The current candle is bearish (ha_bear), showing trend continuation to the downside.
  • The Heikin Ashi close is below the fast moving average (ma1), reinforcing bearish pressure.
  • The real price close is below the open (close < open), confirming bearish momentum in actual price data.
  • The signal is confirmed after the candle closes (barstate.isconfirmed), avoiding premature entries.
  • dir is undefined (na(dir)), preventing consecutive signals in the same direction.

In simple terms, this setup looks for trend continuation after a pullback, confirming entries with both Heikin Ashi and real price action, supported by moving average alignment to avoid false signals.

If the price reaches a 1:1 risk-to-reward ratio, the stop will be moved to the entry point. However, if the slow moving average surpasses this level, it will become the new exit point, acting as a trailing stop

🔷Why It’s Unique
  • Easily visualizes the benefits of using risk-to-reward ratios when trading instead of fixed percentages.
  • Provides a simple and straightforward approach to trading, embracing the "keep it simple" concept.
  • Offers clear visualization of DCA Bot entry and exit points based on user preferences.
  • Includes an option to review the message format before sending signals to bots, with compatibility for multi-pair and futures contract pairs.

🔷 Considerations Before Using the Indicator

⚠️Very important: The indicator must be used on charts with real price data, such as Japanese candlesticks, line charts, etc. Do not use it on Heikin Ashi charts, as this may lead to unrealistic results.

🔸Since this is a trend-following strategy, use it on timeframes above 4 hours, where market noise is reduced and trends are clearer. Also, carefully review the statistics before using it, focusing on pairs that tend to have long periods of well-defined trends.

🔸Disadvantages:
  • False Signals in Ranges: Consolidating markets can generate unreliable signals.
  • Lagging Indicator: Being based on moving averages, it may react late to sudden price movements.

🔸Advantages:
  • Trend Focused: Simplifies the identification of trending markets.
  • Noise Reduction: Uses Heikin Ashi candles to identify trend continuation after pullbacks.
  • Broad Applicability: Suitable for forex, crypto, stocks, and commodities.

🔸The strategy provides a systematic way to analyze markets but does not guarantee successful outcomes. Use it as an additional tool rather than relying solely on an automated system.
Trading results depend on various factors, including market conditions, trader discipline, and risk management. Past performance does not ensure future success, so always approach the market cautiously.

🔸Risk Management: Define stop-loss levels, position sizes, and profit targets before entering any trade. Be prepared for potential losses and ensure your approach aligns with your overall trading plan.

🔷 STRATEGY PROPERTIES
  • Symbol: BINANCE:BTCUSDT (Spot).
  • Timeframe: 4h.
  • Test Period: All historical data available.
  • Initial Capital: 10000 USDT.
  • Order Size per Trade: 1% of Capital, you can use a higher value e.g. 5%, be cautious that the Max Drawdown does not exceed 10%, as it would indicate a very risky trading approach.
  • Commission: Binance commission 0.1%, adjust according to the exchange being used, lower numbers will generate unrealistic results. By using low values e.g. 5%, it allows us to adapt over time and check the functioning of the strategy.
  • Slippage: 5 ticks, for pairs with low liquidity or very large orders, this number should be increased as the order may not be filled at the desired level.
  • Margin for Long and Short Positions: 100%.
  • Indicator Settings: Default Configuration.
    • MA1 Length: 9.
    • MA2 Length: 18.
    • MA Calculations: EMA.
    • Take Profit Ratio: Disable. Ratio 1:4.
    • Breakeven Ratio: Enable, Ratio 1:1.
    • Strategy: Long & Short.

🔷 STRATEGY RESULTS
  • ⚠️Remember, past results do not guarantee future performance.
  • Net Profit: +324.88 USDT (+3.25%).
  • Max Drawdown: -81.18 USDT (-0.78%).
  • Total Closed Trades: 672.
  • Percent Profitable: 35.57%.
  • Profit Factor: 1.347.
  • Average Trade: +0.48 USDT (+0.48%).
  • Average # Bars in Trades: 13.


🔷 HOW TO USE

🔸 Adjust Settings:
The default values—MA1 (9) and MA2 (18) with EMA calculation—generally work well. However, you can increase these values, such as 20 and 40, to better identify stronger trends.

🔸 Choose a Symbol that Typically Trends:
Select an asset that tends to form clear trends. Keep in mind that the Strategy Tester results may show poor performance for certain assets, making them less suitable for sending signals to bots.

🔸 Experiment with Ratios:
Test different take profit and breakeven ratios to compare various scenarios—especially to observe how the strategy performs when only the trade is protected.

🔸This is an example of how protecting the trade works: once the price moves in favor of the position with a 1:1 risk-to-reward ratio, the stop loss is moved to the entry price. If the Slow MA surpasses this level, it will act as a trailing stop, aiming to follow the trend and maximize potential gains. snapshot

🔸In contrast, in this example, for the same trade, if we set a take profit at a 1:3 risk-to-reward ratio—which is generally considered a good risk-reward relationship—we can see how a significant portion of the upward move is left on the table. snapshot

🔸Results Review:
It is important to check the Max Drawdown. This value should ideally not exceed 10% of your capital. Consider adjusting the trade size to ensure this threshold is not surpassed.

Remember to include the correct values for commission and slippage according to the symbol and exchange where you are conducting the tests. Otherwise, the results will not be realistic.

If you are satisfied with the results, you may consider automating your trades. However, it is strongly recommended to use a small amount of capital or a demo account to test proper execution before committing real funds.

🔸Create alerts to trigger the DCA Bot:
  • Verify Messages: Ensure the message matches the one specified by the DCA Bot.
  • Multi-Pair Configuration: For multi-pair setups, enable the option to add the symbol in the correct format.
  • Signal Settings: Enable whether you want to receive long or short signals (Entry | TP | SL), copy and paste the the messages for the DCA Bots configured.
  • Alert Setup:
  • When creating an alert, set the condition to the indicator and choose "alert() function call only.
  • Enter any desired Alert Name.
  • Open the Notifications tab, enable Webhook URL, and paste the Webhook URL.
  • For more details, refer to the section: "How to use TradingView Custom Signals".
  • Finalize Alerts: Click Create, you're done! Alerts will now be sent automatically in the correct format.

🔷 INDICATOR SETTINGS
  • MA 1: Fast MA Length
  • MA 2: Slow MA Length
  • MA Calc: MA's Calculations (SMA,EMA, RMA,WMA)
  • TP Ratio: This is the take profit ratio relative to the stop loss, where the trade will be closed in profit.
  • BE Ratio: This is the breakeven ratio relative to the stop loss, where the stop loss will be updated to breakeven or if the MA2 is greater than this level.
  • Strategy: Order Type direction in which trades are executed.
  • Use Custom Test Period: When enabled signals only works in the selected time window. If disabled it will use all historical data available on the chart.
  • Test Start and End: Once the Custom Test Period is enabled, here you select the start and end date that you want to analyze.
  • Check Messages: Enable the table to review the messages to be sent to the bot.
  • Entry | TP | SL: Enable this options to send Buy Entry, Take Profit (TP), and Stop Loss (SL) signals.
  • Deal Entry and Deal Exit : Copy and paste the message for the deal start signal and close order at Market Price of the DCA Bot. This is the message that will be sent with the alert to the Bot, you must verify that it is the same as the bot so that it can process properly so that it executes and starts the trade.
  • DCA Bot Multi-Pair: You must activate it if you want to use the signals in a DCA Bot Multi-pair in the text box you must enter (using the correct format) the symbol in which you are creating the alert, you can check the format of each symbol when you create the bot.


👨🏻‍💻💭 We hope this tool helps enhance your trading. Your feedback is invaluable, so feel free to share any suggestions for improvements or new features you'd like to see implemented.

__
The information and publications within the 3Commas TradingView account are not meant to be and do not constitute financial, investment, trading, or other types of advice or recommendations supplied or endorsed by 3Commas and any of the parties acting on behalf of 3Commas, including its employees, contractors, ambassadors, etc.

Wyłączenie odpowiedzialności

Informacje i publikacje przygotowane przez TradingView lub jego użytkowników, prezentowane na tej stronie, nie stanowią rekomendacji ani porad handlowych, inwestycyjnych i finansowych i nie powinny być w ten sposób traktowane ani wykorzystywane. Więcej informacji na ten temat znajdziesz w naszym Regulaminie.