INVITE-ONLY SCRIPT
Mis à jour

- Trading Bot - Pyramidal Candle RSI (Pro) - Robot Strategy -

401
OVERVIEW

The Pyramidal Candle RSI (Pro) strategy is an automation-first multi-entry mean-reversion system that combines candle pattern confirmation with RSI momentum filtering to build pyramidal positions. It is designed from the ground up to be operated by a trading bot: every signal, every parameter, and every piece of information needed to place an order is transmitted in real time through TradingView's alert system via invisible plot() outputs embedded in a JSON webhook payload. The bot receives the trade direction, quantity type, leverage, position amount, and stop-loss levels with every alert — enabling fully autonomous order execution.

Unlike standard RSI strategies that enter once on an oversold/overbought signal, this strategy opens multiple incremental positions on successive candles that confirm the ongoing move, then exits the entire position when the average entry price reaches a configurable profit threshold. This pyramidal accumulation approach — buying each successive dip or selling each successive rally — creates a dollar-cost-averaging effect that significantly improves the average entry price compared to a single-entry approach.


BUILT FOR AUTOMATION — JSON WEBHOOK INTEGRATION

A core differentiator of this strategy is its complete automation-readiness. The script does not simply generate buy/sell alerts — it transmits a full set of structured trading parameters on every signal, designed to be consumed by a webhook-based trading bot.

The strategy uses Pine Script's plot() function with display=display.none to create invisible data channels. These plots do not appear on the chart but are accessible via TradingView's {{plot("PlotName")}} placeholder in alert messages. Combined with TradingView's built-in variables ({{ticker}}, {{strategy.order.comment}}, {{interval}}), this enables the construction of a complete JSON payload such as:

Pine Script®


What each field transmits:
  • comment: The order action — ENTER_LONG, EXIT_LONG, ENTER_SHORT, or EXIT_SHORT — telling the bot exactly what to do.
  • ticker: The asset symbol, so a single bot instance can manage multiple assets.
  • interval: The chart timeframe, allowing the bot to validate that the signal matches the expected configuration.
  • trading_mode: A numeric code indicating the active trading mode.
  • qty_type: A numeric code indicating the position sizing method (1=Percent Available, 2=Percent Total, 3=Cash).
  • leverage: The configured leverage multiplier, so the bot can place correctly sized orders on the exchange.
  • amount_pct: The configured amount (% or $) per entry.
  • stop_loss_long_pct / stop_loss_short_pct: The stop-loss percentages for each direction (100 = disabled).

This architecture means the bot does not need to be separately configured with position sizes or risk parameters — everything is defined once in the TradingView strategy settings and automatically transmitted with every alert. Changing a parameter in the strategy immediately updates what the bot receives, ensuring permanent synchronization between backtest settings and live execution.


WHAT MAKES THIS STRATEGY ORIGINAL
  • Pyramidal candle-by-candle accumulation: The strategy enters additional positions on each new candle that closes in the signal direction, up to a configurable maximum (default: 4, configurable up to 20). This is fundamentally different from standard scripts that enter a single position on an RSI signal. The progressive accumulation creates a natural dollar-cost-averaging effect.
  • Consecutive candle confirmation for initial entry: The first entry requires a configurable number of consecutive candles closing in the expected direction (default: 1). Increasing this value provides stronger entry confirmation by filtering out isolated candles.
  • Average-price-based exit threshold: Exits are not based on RSI returning to a neutral zone or crossing a fixed level. Instead, the strategy closes all positions when the current price exceeds the average entry price by a configurable percentage (default: 1% for both longs and shorts). This provides a consistent and predictable profit target tied to the actual cost basis of the accumulated position.
  • RSI slope filter (not level-based): The RSI filter does not use traditional overbought/oversold levels. Instead, it checks whether the RSI value is rising compared to the previous bar (for longs) or falling (for shorts). This confirms that momentum is beginning to shift in favor of the trade direction. By default, the RSI is calculated on the HIGH price source rather than CLOSE, which detects momentum shifts earlier.
  • Direct capital allocation per entry: The configured amount (in $ or %) is used directly for each individual entry — what you set is what each order uses. This gives the user full control over position sizing: for example, setting 20% with 5 entries means each entry invests 20% of the balance, for a total exposure of 100% when all entries are filled. The user decides how to distribute capital across entries.
  • Confirmed-bar-only execution: All entries and exits use barstate.isconfirmed, ensuring that signals are only processed on fully closed candles. This completely eliminates repainting — a critical requirement for live automation.


HOW THE STRATEGY WORKS — DETAILED METHODOLOGY

1. Candle Direction Detection

On each confirmed bar, the strategy classifies the candle as bullish (close > open) or bearish (close < open). For the very first entry (when no position is open), a sequence of consecutive candles in the expected direction is required (configurable). For subsequent pyramidal entries (when a position is already open), a single candle in the direction is sufficient.

2. Entry Logic (Long Positions)

The long entry system uses a counter-trend accumulation approach:
  • When no position is open, the strategy waits for the configured number of consecutive bearish candles (buying the dip after confirmed downward pressure).
  • Once the first entry is placed, each subsequent bearish candle on a confirmed bar triggers an additional long entry, up to the maximum number of entries.
  • The RSI filter (enabled by default) requires that RSI(14, source=high) is rising — meaning rsi_value > rsi_value[1]. Despite the bearish candle, this confirms that momentum is beginning to shift upward, reducing the risk of catching a falling knife.
  • The optional SMA filter (disabled by default) requires the close price to be above a 50-period SMA, restricting entries to bullish trend contexts.
  • The strategy checks that the current number of open trades is below the maximum allowed, preventing over-accumulation.

3. Entry Logic (Short Positions)

The short entry logic mirrors the long logic:
  • Initial entry after consecutive bullish candles (selling the rally after confirmed upward pressure).
  • Additional entries on each subsequent bullish candle.
  • RSI must be falling (rsi_value < rsi_value[1]) to confirm downward momentum shift.
  • Optional SMA filter requires price below the SMA.

4. Position Sizing

The user configures a capital amount per entry (default: 25% of total balance). The strategy calculates:
  • allocated_capital = equity * qty_amount / 100
  • unit_size = (capital_alloue * leverage) / close


The configured amount is applied directly to each entry without any automatic division. The user is responsible for sizing each entry appropriately relative to the number of pyramid entries configured.

5. Exit Logic (Primary Exit)

The strategy continuously tracks the average entry price across all open positions (strategy.position_avg_price). The exit multiplier is calculated as 1 + (threshold% / 100) for longs, or 1 - (threshold% / 100) for shorts.

For long exits: when a bullish candle closes at or above the target price (average_price * exit_multiplier), all positions are closed. For short exits: when a bearish candle closes at or below the target price. The bullish/bearish candle requirement adds confirmation to the exit, preventing premature exits on wicks.

6. Take-Profit and Stop-Loss (Optional)

An optional take-profit (default: 5%, disabled) and stop-loss (default: 10%, enabled) are calculated from the average entry price and monitored via strategy.exit(). The stop-loss provides a safety net against extended adverse moves that could exhaust the pyramiding capacity.


DEFAULT STRATEGY PROPERTIES
  • Initial Capital: $10,000
  • Pyramiding: 20 (maximum capacity; default limited to 4 entries via input)
  • Commission: 0.10% per trade
  • calc_on_every_tick: false (no repainting)
  • Default Mode: Long Only
  • Maximum Entries: 4
  • Consecutive Candles Required for First Entry: 1
  • Long Exit Threshold: 1% above average entry price
  • Short Exit Threshold: 1% below average entry price
  • RSI Filter: Enabled (14-period, source: HIGH, slope-based)
  • SMA Filter: Disabled by default (50-period when enabled)
  • Take-Profit: Disabled (5% when enabled)
  • Stop-Loss: Enabled at 10%
  • Quantity: 25% of total balance per entry
  • Leverage: 2x (for backtesting purposes only)


HOW TO USE THIS STRATEGY
  1. Select your trading direction: Long Only or Short Only.
  2. Set the maximum number of entries. More entries improve the average entry price via dollar-cost-averaging but increase total capital commitment and exposure. Values between 3 and 8 work well for most assets.
  3. Adjust the consecutive candle requirement for the initial entry. A value of 1 is the most responsive. Values of 2 or 3 provide stronger confirmation but reduce trade frequency.
  4. Configure the exit threshold percentage. A value of 1% provides frequent small profits. Higher values (2-3%) allow trades to capture larger moves but increase holding time and risk.
  5. Enable or disable the RSI filter. When enabled, it adds momentum shift confirmation — the RSI must be turning in the trade direction despite the candle closing against it. Adjust the RSI length and source as needed.
  6. Enable or disable the SMA filter to restrict entries to the dominant trend direction.
  7. Set your capital allocation per entry and leverage. The configured amount is used directly for each entry — plan your sizing according to the number of entries you allow.
  8. Optionally configure the take-profit and stop-loss percentages. The stop-loss is recommended to limit worst-case scenarios.
  9. Use the built-in spread calculator to estimate actual trading costs and enter them in Strategy Properties.
  10. Enable the on-chart information tables to monitor active settings, filter status, entry count, exit thresholds, and performance.


WHY THIS STRATEGY IS INVITE-ONLY
  • The pyramidal candle accumulation system — automatically building positions across multiple entries with user-controlled capital allocation per entry — is a unique architecture not found in standard open-source RSI or candle-based scripts.
  • The combination of candle sequence confirmation, RSI slope filtering (using HIGH source for early detection), and average-price-based exit thresholds creates a multi-factor system that is significantly more sophisticated than simple RSI overbought/oversold entries.
  • The use of barstate.isconfirmed on all entries and exits guarantees zero repainting — essential for reliable live automation.
  • Full bot-automation readiness with structured alert messages (ENTER_LONG, EXIT_LONG, ENTER_SHORT, EXIT_SHORT) and invisible plot outputs for webhook-based JSON systems.
  • Comprehensive on-chart parameter display with real-time performance monitoring, including average entry price line, filter status, and detailed statistics.
  • The strategy represents original work combining candle pattern analysis, momentum filtering, direct capital allocation, and pyramidal position management into a cohesive automated system.


LIMITATIONS AND IMPORTANT NOTES
  • Pyramidal accumulation strategies progressively increase exposure as the market moves against the position. Extended adverse moves can produce significant drawdowns before the average price exit threshold is reached.
  • The effectiveness of the candle confirmation and RSI slope filter varies across assets and timeframes. Thorough backtesting on your specific target is essential.
  • Past backtest performance does not guarantee future results. Market conditions change and past patterns may not repeat.
  • Default parameters are starting points. Optimization for each specific asset and timeframe is required for best results.
  • Ensure that your trading bot's pyramiding and position sizing settings match the strategy configuration to avoid unintended behavior.
  • Non-standard chart types (Heikin Ashi, Renko, Kagi, Point and Figure, Range) should not be used for backtesting as they produce unrealistic results.


DISCLAIMER

This script is provided for educational and informational purposes only. It does not constitute financial advice. Trading financial instruments involves substantial risk of loss. Past performance is not indicative of future results. Always conduct your own research and consult with a qualified financial advisor before making any investment decisions. Use this strategy at your own risk.
Notes de version
Upgrade to PineScript version 6
Notes de version
Protection adjustments (division by zero of quantities is now prohibited)

Clause de non-responsabilité

Les informations et publications ne sont pas destinées à être, et ne constituent pas, des conseils ou recommandations financiers, d'investissement, de trading ou autres fournis ou approuvés par TradingView. Pour en savoir plus, consultez les Conditions d'utilisation.