INVITE-ONLY SCRIPT
Mis à jour

- Trading Bot - TopBot + Bollinger Anomaly - Robot Strategy -

447
OVERVIEW

The TopBot / Bollinger Anomaly strategy is an automation-first mean-reversion system that combines two powerful anomaly detection engines into a single, unified script. With a simple selector at the top of the settings panel, the trader can instantly switch between two distinct approaches — TopBot Anomaly (pure SMA-based deviations) and Bollinger Anomaly (Bollinger Band-based deviations) — without changing scripts, losing configuration, or reconfiguring alerts. Every signal, every parameter, and every piece of information needed to place an order is transmitted in real time through TradingView's alert system, enabling fully autonomous bot execution regardless of the selected mode.

The strategy uses a multi-layered entry system with up to 10 independent deviation levels for both long and short positions, combined with deviation-based exits, a multi-timeframe trend filter, and a post-stop-loss cooldown mechanism. It supports five distinct trading modes — Long Only, Short Only, Both (Exit on MA), Both (Exit on Deviations), and Swing Trading — providing comprehensive flexibility for different market conditions.

This unified architecture means traders can test both anomaly detection approaches on the same asset, with the same parameters, on the same chart — and compare results instantly by toggling the strategy mode selector. No need to maintain two separate scripts: one strategy, two engines, zero compromise.

The strategy uses LIMIT triggers at predetermined price levels, allowing immediate entry and exit of positions without waiting for the next candle.


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 (Long Only, Short Only, Both, Swing).
  • 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. The JSON payload structure is identical in both TopBot and Bollinger modes, so a trading bot works seamlessly with either engine without any reconfiguration.


WHAT MAKES THIS STRATEGY ORIGINAL
  • Two anomaly detection engines in one script: The strategy selector at the top of the settings panel lets the trader instantly switch between TopBot Anomaly (pure SMA-based deviations) and Bollinger Anomaly (Bollinger Band volatility-adjusted deviations). All other parameters — entry levels, exit levels, trading mode, quantity, leverage, stop-loss, cooldown — are shared between both modes. This allows direct A/B comparison on the same asset with zero overhead.
  • TopBot mode — SMA-based anomaly detection: Entry levels are calculated as direct percentage deviations from the central moving average. This creates a simpler but often more robust reference framework that is less sensitive to volatility spikes, producing consistent entry zones regardless of market conditions.
  • Bollinger mode — volatility-adaptive anomaly detection: Entry levels are calculated as percentage deviations from the Bollinger Bands (upper and lower), which themselves adapt to market volatility through standard deviation. This creates entry zones that automatically widen in high-volatility conditions and tighten in low-volatility periods.
  • Up to 10 independent pyramidal entry levels: Each entry level is individually configurable as a percentage deviation. Long entries trigger below the reference line (buying dips); short entries trigger above (selling rallies). Up to 10 entries can be stacked, allowing deep position building during extended anomalies.
  • Five distinct trading modes in a single script: Long Only, Short Only, Both with MA-based exit (positions close when price crosses the reference), Both with deviation-based exit (separate exit thresholds for longs and shorts), and Swing Trading mode (automatic directional flipping at configurable boundaries). Each mode uses dedicated logic paths, not just parameter changes.
  • Separate entry and exit MA types (Bollinger mode): In Bollinger mode, the entry MA and exit MA can be configured independently — for instance, using SMA for entries with Bollinger Bands and ZLEMA for faster exit detection. This decouples entry timing from exit timing for maximum flexibility.
  • Deviation-based exit logic: Positions exit when price returns to a configurable percentage above (longs) or below (shorts) the reference level. This provides predictable profit targets independent of band or MA behavior.
  • Multi-timeframe trend filter: An optional trend MA (configurable type and length, default: 200-period on 15-minute timeframe) restricts entries to the dominant trend direction. Supports SMA, EMA, HMA, PCMA, WMA, DEMA, and ZLEMA types with independent data source selection.
  • Post-stop-loss cooldown with MA cross re-entry: After a stop-loss, the strategy enforces a configurable bar-based cooldown and optionally requires price to cross the main MA before allowing a new entry. This also cancels all pending limit orders in the stopped direction.
  • Swing Trading with stop-loss direction lock: In Swing mode, an optional setting prevents re-entry in the same direction after a stop-loss, forcing the strategy to wait for the opposite signal before re-engaging.


HOW THE STRATEGY WORKS — DETAILED METHODOLOGY

1. Strategy Mode Selection

The first parameter in the settings panel determines the anomaly detection engine:
  • TopBot Anomaly: All entry and exit levels are computed as percentage deviations directly from the central moving average. The MA serves as both the reference for entries and exits. This mode displays the ground MA on the chart with colored fill zones between anomaly levels.
  • Bollinger Anomaly: Entry levels are computed as percentage deviations from the Bollinger Bands (lower band for longs, upper band for shorts). Exit levels use a separate, independently configurable exit MA. This mode displays the exit MA on the chart with individual anomaly level lines.

All other parameters — trading mode, quantity, leverage, stop-loss, cooldown, trend filter — work identically in both modes. Switching modes recalculates all entry and exit levels automatically.

2. Moving Average and Bollinger Band Calculation

The strategy computes a central moving average using a user-selected MA type (default: SMA) over a configurable length (default: 16) with the ohlc4 data source. The MA type can be set to SMA, EMA, HMA, PCMA, WMA, DEMA, or ZLEMA.

In Bollinger mode, standard deviation bands are calculated using a configurable multiplier (default: 2.0). These bands define the upper and lower reference points for entry calculations. A separate exit MA (configurable type and length, default: ZLEMA 14) provides the reference for exit level calculations.

3. Anomaly Level Calculation

Each of the 10 entry levels is defined as a percentage deviation from the reference:

TopBot mode:
  • For longs: entry_price = SMA * (1 - deviation%)
  • For shorts: entry_price = SMA * (1 + deviation%)

Bollinger mode:
  • For longs: entry_price = Lower_Band * (1 - deviation%)
  • For shorts: entry_price = Upper_Band * (1 + deviation%)

Each level is independently configurable. Setting a level to 0% disables it. Levels should be configured in ascending order (e.g., 8.7%, 11%, 14%) to create a structured grid.


4. Entry Logic (Classic Mode)

In Classic mode (Long Only, Short Only, Both), the strategy monitors each enabled deviation level. When the price crosses below a long entry level or above a short entry level, a limit order is placed at that level. Each fill adds to the position (pyramiding up to 10).

An entry block prevents new positions from opening on the same bar where the previous position was just closed.

Position sizes are calculated per entry level using the configured quantity type (Cash, Percent Available, or Percent Total). In "Percent (Available Balance)" mode, each entry is sized on remaining equity.


5. Exit Logic (Classic Mode)
  • Exit on Deviations: All positions close when the price exceeds the reference level by the configured exit deviation (default: 2% for longs, 3.1% for shorts). In TopBot mode, the reference is the central MA. In Bollinger mode, the reference is the exit MA.
  • Exit on MA: In "Both (Exit on MA)" mode, positions close when price crosses the reference level (central MA in TopBot mode, exit MA in Bollinger mode).


6. Swing Trading Mode

In Swing Trading mode, the strategy monitors two thresholds around the reference:
  • When price exceeds the reference by the swing high threshold (default: 2.8%), any long is closed and a short position is opened.
  • When price falls below the reference by the swing low threshold (default: 2.8%), any short is closed and a long position is opened.

In TopBot mode, thresholds are relative to the SMA. In Bollinger mode, they are relative to the upper and lower bands respectively. This creates continuous market exposure with automatic directional switching. The optional direction lock after stop-loss prevents immediate re-entry in the stopped direction.


7. Trend Filter

The optional trend filter calculates a configurable MA (default: 200-period EMA) on a higher timeframe (default: 15-minute) using request.security(). For longs, entries are permitted only when price is above this filter MA. For shorts, only when below. The filter MA type, data source, and timeframe are all independently configurable. The trend filter works identically in both strategy modes.


8. Stop-Loss and Cooldown

Optional percentage-based stop-losses (default: disabled at 100%) trigger from the average entry price. When hit, the cooldown system:
  • Blocks new entries in the stopped direction for a configurable number of bars (default: 1).
  • Cancels all pending limit orders in that direction (entries 2 through 10 and swing entries).
  • Optionally requires a price-MA cross before re-entry permission is granted.


DEFAULT STRATEGY PROPERTIES
  • Initial Capital: $10,000
  • Pyramiding: 10 (matching the 10 available entry levels)
  • Commission: 0.20% per trade (applied on each entry and exit)
  • calc_on_every_tick: false (no repainting)
  • Default Mode: TopBot Anomaly, Long Only
  • MA Length: 16 (SMA)
  • Bollinger Standard Deviation Multiplier: 2.0 (used in Bollinger mode only)
  • Exit MA: ZLEMA 14 (used in Bollinger mode only)
  • Default Long Entry Deviation: 8.7%
  • Default Short Entry Deviation: 9.7%
  • Default Long Exit Deviation: 2%
  • Default Short Exit Deviation: 3.1%
  • Swing High/Low Thresholds: 2.8% each
  • Trend Filter: Disabled by default (200 EMA on 15min when enabled)
  • Stop-Loss: Disabled by default (set to 100%)
  • Cooldown After Stop-Loss: Enabled (1 bar + MA cross required)
  • Swing Direction Lock After SL: Disabled by default
  • Quantity: 25% of available balance per entry
  • Leverage: 2x (for backtesting purposes only)
  • Data Source: ohlc4


HOW TO USE THIS STRATEGY
  1. Start by selecting the strategy mode: TopBot Anomaly for pure SMA-based deviation entries, or Bollinger Anomaly for volatility-adaptive entries based on Bollinger Bands. You can switch between them at any time to compare results on the same asset.
  2. Select your trading mode from the five available options. Start with Long Only or Short Only for initial testing, then explore Both or Swing modes once familiar with the behavior.
  3. Set the MA length for your asset and timeframe. This is the most important parameter. Test values between 10 and 40, starting at 16.
  4. If using Bollinger mode, adjust the standard deviation multiplier (default 2.0) and optionally configure the exit MA type and length independently.
  5. Configure your main entry deviation level (Level 1) — this drives most of the strategy's performance. Then optionally add entries at deeper levels (spaced at least 2% apart) for pyramiding.
  6. Set exit deviation levels. Higher values (3-5%) produce longer trades with larger average profits but more drawdown. Lower values (1-2%) produce faster exits.
  7. Optionally enable the trend filter to restrict entries to the dominant trend. Configure the MA type, length, timeframe, and data source.
  8. For Swing mode, set the high and low reversal thresholds. Symmetric values (e.g., 2.8% both) produce balanced behavior.
  9. Set your quantity type and amount. For pyramiding strategies, "Percent (Available Balance)" is recommended to prevent over-allocation.
  10. Configure stop-loss and cooldown if desired. The cooldown with MA cross requirement is recommended when using stop-losses.
  11. Optionally adjust the MA type for entries (SMA, EMA, HMA, PCMA, WMA, DEMA, ZLEMA) in the Advanced settings.
  12. Use the spread calculator to estimate true trading costs and adjust the commission field in Strategy Properties.
  13. Review on-chart information tables for comprehensive real-time parameter display, level visualization, and performance tracking.


WHY THIS STRATEGY IS INVITE-ONLY
  • Two distinct anomaly detection engines — SMA-based and Bollinger-based — unified in a single script with instant switching. No other published strategy offers this dual-engine approach, enabling direct A/B comparison on any asset.
  • A 10-level independent anomaly detection system with separate long and short entry grids creates a highly configurable position-building framework not found in any standard open-source script.
  • Five distinct trading modes (Long Only, Short Only, Both Exit-on-MA, Both Exit-on-Deviations, Swing Trading) each with dedicated logic paths in a single script — offering unmatched versatility.
  • Independent MA configuration for entries and exits (in Bollinger mode), with seven selectable MA types, separate data sources, and separate timeframes — enabling precision-tuned entry and exit timing.
  • The post-stop-loss cooldown system with pending order cancellation and optional MA-cross re-entry condition protects capital in adverse conditions.
  • Full bot-automation readiness with structured alert messages (ENTER_LONG, EXIT_LONG, ENTER_SHORT, EXIT_SHORT), invisible plot outputs for JSON webhook integration, and quantity/leverage metadata — working identically in both strategy modes with zero bot reconfiguration.
  • Comprehensive three-tier on-chart information display (full, minimal, or hidden) with mode-adaptive visualization: colored fill zones in TopBot mode, clean anomaly level lines in Bollinger mode. Real-time parameter monitoring, spread calculation, and detailed performance statistics included.
  • The strategy represents the most complete implementation of the anomaly detection framework, combining months of development and testing from two independently proven strategies into a single, unified tool.


TOPBOT VS BOLLINGER — WHICH MODE TO USE

Both modes share the same core logic, parameters, and automation architecture. The key difference is how entry and exit zones are calculated:
  • TopBot Anomaly uses fixed percentage deviations from the SMA. Entry zones remain consistent regardless of volatility. Best suited for assets with relatively stable price behavior, or when the trader wants predictable, volatility-independent entry levels.
  • Bollinger Anomaly uses percentage deviations from the Bollinger Bands, which themselves expand and contract with volatility. Entry zones adapt automatically to market conditions. Best suited for assets with variable volatility, or when the trader wants entries that account for current market dynamics.

The recommended approach is to test both modes on your target asset and timeframe with the same parameters, then select the mode that produces the best risk-adjusted returns. The unified script makes this comparison effortless.


LIMITATIONS AND IMPORTANT NOTES
  • Mean-reversion strategies are inherently exposed to prolonged directional moves. The pyramiding approach can lead to significant drawdowns if the market does not revert to the mean.
  • Past backtest performance does not guarantee future results. Always test on multiple assets and timeframes before live deployment.
  • Default parameters are starting points. Extensive optimization for each asset and timeframe is required.
  • When using leverage, ensure your exchange and bot configuration matches the strategy settings to avoid position size mismatches.
  • The strategy uses calc_on_every_tick=false — entries are confirmed on bar close. Live trading results may differ due to slippage and execution latency.
  • Higher pyramid depths and wider deviation spreads increase capital requirements and drawdown risk. Size positions conservatively.
  • Non-standard chart types (Heikin Ashi, Renko, Kagi, Point and Figure, Range) should not be used for backtesting as they produce unrealistic results.
  • In Swing mode, continuous market exposure means the strategy is always exposed to overnight/weekend gaps and black swan events.
  • Bollinger-specific parameters (standard deviation multiplier, exit MA type/length) have no effect in TopBot mode. They remain visible in the settings for convenience when switching between modes.


DISCLAIMER

This script is provided for educational and informational purposes only. It does not constitute financial advice. Trading cryptocurrencies and other 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

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.