OPEN-SOURCE SCRIPT
Optimized ADX DI CCI Strategy

### Key Features:
- Combines ADX, DI+/-, CCI, and RSI for signal generation.
- Supports customizable timeframes for indicators.
- Offers multiple exit conditions (Moving Average cross, ADX change, performance-based stop-loss).
- Tracks and displays trade statistics (e.g., win rate, capital growth, profit factor).
- Visualizes trades with labels and optional background coloring.
- Allows countertrading (opening an opposite trade after closing one).
1. **Indicator Calculation**:
- **ADX and DI+/-**: Calculated using the `ta.dmi` function with user-defined lengths for DI and ADX smoothing.
- **CCI**: Computed using the `ta.cci` function with a configurable source (default: `hlc3`) and length.
- **RSI (optional)**: Calculated using the `ta.rsi` function to filter overbought/oversold conditions.
- **Moving Averages**: Used for CCI signal smoothing and trade exits, with support for SMA, EMA, SMMA (RMA), WMA, and VWMA.
2. **Signal Generation**:
- **Buy Signal**: Triggered when DI+ > DI- (or DI+ crosses over DI-), CCI > MA (or CCI crosses over MA), and optional ADX/RSI filters are satisfied.
- **Sell Signal**: Triggered when DI+ < DI- (or DI- crosses over DI+), CCI < MA (or CCI crosses under MA), and optional ADX/RSI filters are satisfied.
3. **Trade Execution**:
- **Entry**: Long or short trades are opened using `strategy.entry` when signals are detected, provided trading is allowed (`allow_long`/`allow_short`) and equity is positive.
- **Exit**: Trades can be closed based on:
- Opposite signal (if no other exit conditions are used).
- MA cross (price crossing below/above the exit MA for long/short trades).
- ADX percentage change exceeding a threshold.
- Performance-based stop-loss (trade loss exceeding a percentage).
- **Countertrading**: If enabled, closing a trade triggers an opposite trade (e.g., closing a long opens a short).
4. **Visualization**:
- Labels are plotted at trade entries/exits (e.g., "BUY," "SELL," arrows).
- Optional background coloring highlights open trades (green for long, red for short).
- A statistics table displays real-time metrics (e.g., capital, win rates).
5. **Trade Tracking**:
- Tracks the number of long/short trades, wins, and overall performance.
- Monitors equity to prevent trading if it falls to zero.
### 2.3 Key Components
- **Indicator Calculations**: Uses `request.security` to fetch indicator data for the specified timeframe.
- **MA Function**: A custom `ma_func` handles different MA types for CCI and exit conditions.
- **Signal Logic**: Combines crossover/under checks with recent bar windows for flexibility.
- **Exit Conditions**: Multiple configurable exit strategies for risk management.
- **Statistics Table**: Updates dynamically with trade and capital metrics.
## 3. Configuration Options
The script provides extensive customization through input parameters, grouped for clarity in the TradingView settings panel. Below is a detailed breakdown of each setting and its impact.
### 3.1 Strategy Settings (Global)
- **Initial Capital**: Default `10000`. Sets the starting capital for backtesting.
- **Effect**: Determines the base equity for calculating position sizes and performance metrics.
- **Default Quantity Type**: `strategy.percent_of_equity` (50% of equity).
- **Effect**: Controls the size of each trade as a percentage of available equity.
- **Pyramiding**: Default `2`. Allows up to 2 simultaneous trades in the same direction.
- **Effect**: Enables multiple entries if conditions are met, increasing exposure.
- **Commission**: 0.2% per trade.
- **Effect**: Simulates trading fees, reducing net profit in backtesting.
- **Margin**: 100% for long and short trades.
- **Effect**: Assumes no leverage; adjust for margin trading simulations.
- **Calc on Every Tick**: `true`.
- **Effect**: Ensures real-time signal updates for precise execution.
### 3.2 Indicator Settings
- **Indicator Timeframe** (`indicator_timeframe`):
- **Options**: `""` (chart timeframe), `1`, `5`, `15`, `30`, `60`, `240`, `D`, `W`.
- **Default**: `""` (uses chart timeframe).
- **Effect**: Determines the timeframe for ADX, DI, CCI, and RSI calculations. A higher timeframe reduces noise but may delay signals.
### 3.3 ADX & DI Settings
- **DI Length** (`adx_di_len`):
- **Default**: `30`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for calculating DI+ and DI-. Longer periods smooth trends but reduce sensitivity.
- **ADX Smoothing Length** (`adx_smooth_len`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Smooths the ADX calculation. Longer periods produce smoother ADX values.
- **Use ADX Filter** (`use_adx_filter`):
- **Default**: `false`.
- **Effect**: If `true`, requires ADX to exceed the threshold for signals to be valid, filtering out weak trends.
- **ADX Threshold** (`adx_threshold`):
- **Default**: `25`.
- **Range**: Minimum `0`.
- **Effect**: Sets the minimum ADX value for valid signals when the filter is enabled. Higher values restrict trades to stronger trends.
### 3.4 CCI Settings
- **CCI Length** (`cci_length`):
- **Default**: `20`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for CCI calculation. Longer periods reduce noise but may lag.
- **CCI Source** (`cci_src`):
- **Default**: `hlc3` (average of high, low, close).
- **Effect**: Defines the price data for CCI. `hlc3` is standard, but users can choose other sources (e.g., `close`).
- **CCI MA Type** (`ma_type`):
- **Options**: `SMA`, `EMA`, `SMMA (RMA)`, `WMA`, `VWMA`.
- **Default**: `SMA`.
- **Effect**: Determines the moving average type for CCI signal smoothing. EMA is more responsive; VWMA weights by volume.
- **CCI MA Length** (`ma_length`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for the CCI MA. Longer periods smooth the MA but may delay signals.
### 3.5 RSI Filter Settings
- **Use RSI Filter** (`use_rsi_filter`):
- **Default**: `false`.
- **Effect**: If `true`, applies RSI-based overbought/oversold filters to signals.
- **RSI Length** (`rsi_length`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for RSI calculation. Longer periods reduce sensitivity.
- **RSI Lower Limit** (`rsi_lower_limit`):
- **Default**: `30`.
- **Range**: `0` to `100`.
- **Effect**: Defines the oversold threshold for buy signals. Lower values allow trades in more extreme conditions.
- **RSI Upper Limit** (`rsi_upper_limit`):
- **Default**: `70`.
- **Range**: `0` to `100`.
- **Effect**: Defines the overbought threshold for sell signals. Higher values allow trades in more extreme conditions.
### 3.6 Signal Settings
- **Cross Window** (`cross_window`):
- **Default**: `0`.
- **Range**: `0` to `5` bars.
- **Effect**: Specifies the lookback period for detecting DI+/- or CCI crosses. `0` requires crosses on the current bar; higher values allow recent crosses, increasing signal frequency.
- **Allow Long Trades** (`allow_long`):
- **Default**: `true`.
- **Effect**: Enables/disables new long trades. If `false`, only closing existing longs is allowed.
- **Allow Short Trades** (`allow_short`):
- **Default**: `true`.
- **Effect**: Enables/disables new short trades. If `false`, only closing existing shorts is allowed.
- **Require DI+/DI- Cross for Buy** (`buy_di_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a DI+ crossover DI- for buy signals; if `false`, DI+ > DI- is sufficient.
- **Require CCI Cross for Buy** (`buy_cci_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a CCI crossover MA for buy signals; if `false`, CCI > MA is sufficient.
- **Require DI+/DI- Cross for Sell** (`sell_di_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a DI- crossover DI+ for sell signals; if `false`, DI+ < DI- is sufficient.
- **Require CCI Cross for Sell** (`sell_cci_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a CCI crossunder MA for sell signals; if `false`, CCI < MA is sufficient.
- **Countertrade** (`countertrade`):
- **Default**: `true`.
- **Effect**: If `true`, closing a trade triggers an opposite trade (e.g., close long, open short) if allowed.
- **Color Background for Open Trades** (`color_background`):
- **Default**: `true`.
- **Effect**: If `true`, colors the chart background green for long trades and red for short trades.
### 3.7 Exit Settings
- **Use MA Cross for Exit** (`use_ma_exit`):
- **Default**: `true`.
- **Effect**: If `true`, closes trades when the price crosses the exit MA (below for long, above for short).
- **MA Length for Exit** (`ma_exit_length`):
- **Default**: `20`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for the exit MA. Longer periods delay exits.
- **MA Type for Exit** (`ma_exit_type`):
- **Options**: `SMA`, `EMA`, `SMMA (RMA)`, `WMA`, `VWMA`.
- **Default**: `SMA`.
- **Effect**: Determines the MA type for exit signals. EMA is more responsive; VWMA weights by volume.
- **Use ADX Change Stop-Loss** (`use_adx_stop`):
- **Default**: `false`.
- **Effect**: If `true`, closes trades when the ADX changes by a specified percentage.
- **ADX % Change for Stop-Loss** (`adx_change_percent`):
- **Default**: `5.0`.
- **Range**: Minimum `0.0`, step `0.1`.
- **Effect**: Specifies the percentage change in ADX (vs. previous bar) that triggers a stop-loss. Higher values reduce premature exits.
- **Use Performance Stop-Loss** (`use_perf_stop`):
- **Default**: `false`.
- **Effect**: If `true`, closes trades when the loss exceeds a percentage threshold.
- **Performance Stop-Loss (%)** (`perf_stop_percent`):
- **Default**: `-10.0`.
- **Range**: `-100.0` to `0.0`, step `0.1`.
- **Effect**: Specifies the loss percentage that triggers a stop-loss. More negative values allow larger losses before exiting.
## 4. Visual and Statistical Output
- **Labels**: Displayed at trade entries/exits with arrows (↑ for buy, ↓ for sell) and text ("BUY," "SELL"). A "No Equity" label appears if equity is zero.
- **Background Coloring**: Optionally colors the chart background (green for long, red for short) to indicate open trades.
- **Statistics Table**: Displayed at the top center of the chart, updated on timeframe changes or trade events. Includes:
- **Capital Metrics**: Initial capital, current capital, capital growth (%).
- **Trade Metrics**: Total trades, long/short trades, win rate, long/short win rates, profit factor.
- **Open Trade Status**: Indicates if a long, short, or no trade is open.
## 5. Alerts
- **Buy Signal Alert**: Triggered when `buy_signal` is true ("Cross Buy Signal").
- **Sell Signal Alert**: Triggered when `sell_signal` is true ("Cross Sell Signal").
- **Usage**: Users can set up TradingView alerts to receive notifications for trade signals.
- Combines ADX, DI+/-, CCI, and RSI for signal generation.
- Supports customizable timeframes for indicators.
- Offers multiple exit conditions (Moving Average cross, ADX change, performance-based stop-loss).
- Tracks and displays trade statistics (e.g., win rate, capital growth, profit factor).
- Visualizes trades with labels and optional background coloring.
- Allows countertrading (opening an opposite trade after closing one).
1. **Indicator Calculation**:
- **ADX and DI+/-**: Calculated using the `ta.dmi` function with user-defined lengths for DI and ADX smoothing.
- **CCI**: Computed using the `ta.cci` function with a configurable source (default: `hlc3`) and length.
- **RSI (optional)**: Calculated using the `ta.rsi` function to filter overbought/oversold conditions.
- **Moving Averages**: Used for CCI signal smoothing and trade exits, with support for SMA, EMA, SMMA (RMA), WMA, and VWMA.
2. **Signal Generation**:
- **Buy Signal**: Triggered when DI+ > DI- (or DI+ crosses over DI-), CCI > MA (or CCI crosses over MA), and optional ADX/RSI filters are satisfied.
- **Sell Signal**: Triggered when DI+ < DI- (or DI- crosses over DI+), CCI < MA (or CCI crosses under MA), and optional ADX/RSI filters are satisfied.
3. **Trade Execution**:
- **Entry**: Long or short trades are opened using `strategy.entry` when signals are detected, provided trading is allowed (`allow_long`/`allow_short`) and equity is positive.
- **Exit**: Trades can be closed based on:
- Opposite signal (if no other exit conditions are used).
- MA cross (price crossing below/above the exit MA for long/short trades).
- ADX percentage change exceeding a threshold.
- Performance-based stop-loss (trade loss exceeding a percentage).
- **Countertrading**: If enabled, closing a trade triggers an opposite trade (e.g., closing a long opens a short).
4. **Visualization**:
- Labels are plotted at trade entries/exits (e.g., "BUY," "SELL," arrows).
- Optional background coloring highlights open trades (green for long, red for short).
- A statistics table displays real-time metrics (e.g., capital, win rates).
5. **Trade Tracking**:
- Tracks the number of long/short trades, wins, and overall performance.
- Monitors equity to prevent trading if it falls to zero.
### 2.3 Key Components
- **Indicator Calculations**: Uses `request.security` to fetch indicator data for the specified timeframe.
- **MA Function**: A custom `ma_func` handles different MA types for CCI and exit conditions.
- **Signal Logic**: Combines crossover/under checks with recent bar windows for flexibility.
- **Exit Conditions**: Multiple configurable exit strategies for risk management.
- **Statistics Table**: Updates dynamically with trade and capital metrics.
## 3. Configuration Options
The script provides extensive customization through input parameters, grouped for clarity in the TradingView settings panel. Below is a detailed breakdown of each setting and its impact.
### 3.1 Strategy Settings (Global)
- **Initial Capital**: Default `10000`. Sets the starting capital for backtesting.
- **Effect**: Determines the base equity for calculating position sizes and performance metrics.
- **Default Quantity Type**: `strategy.percent_of_equity` (50% of equity).
- **Effect**: Controls the size of each trade as a percentage of available equity.
- **Pyramiding**: Default `2`. Allows up to 2 simultaneous trades in the same direction.
- **Effect**: Enables multiple entries if conditions are met, increasing exposure.
- **Commission**: 0.2% per trade.
- **Effect**: Simulates trading fees, reducing net profit in backtesting.
- **Margin**: 100% for long and short trades.
- **Effect**: Assumes no leverage; adjust for margin trading simulations.
- **Calc on Every Tick**: `true`.
- **Effect**: Ensures real-time signal updates for precise execution.
### 3.2 Indicator Settings
- **Indicator Timeframe** (`indicator_timeframe`):
- **Options**: `""` (chart timeframe), `1`, `5`, `15`, `30`, `60`, `240`, `D`, `W`.
- **Default**: `""` (uses chart timeframe).
- **Effect**: Determines the timeframe for ADX, DI, CCI, and RSI calculations. A higher timeframe reduces noise but may delay signals.
### 3.3 ADX & DI Settings
- **DI Length** (`adx_di_len`):
- **Default**: `30`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for calculating DI+ and DI-. Longer periods smooth trends but reduce sensitivity.
- **ADX Smoothing Length** (`adx_smooth_len`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Smooths the ADX calculation. Longer periods produce smoother ADX values.
- **Use ADX Filter** (`use_adx_filter`):
- **Default**: `false`.
- **Effect**: If `true`, requires ADX to exceed the threshold for signals to be valid, filtering out weak trends.
- **ADX Threshold** (`adx_threshold`):
- **Default**: `25`.
- **Range**: Minimum `0`.
- **Effect**: Sets the minimum ADX value for valid signals when the filter is enabled. Higher values restrict trades to stronger trends.
### 3.4 CCI Settings
- **CCI Length** (`cci_length`):
- **Default**: `20`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for CCI calculation. Longer periods reduce noise but may lag.
- **CCI Source** (`cci_src`):
- **Default**: `hlc3` (average of high, low, close).
- **Effect**: Defines the price data for CCI. `hlc3` is standard, but users can choose other sources (e.g., `close`).
- **CCI MA Type** (`ma_type`):
- **Options**: `SMA`, `EMA`, `SMMA (RMA)`, `WMA`, `VWMA`.
- **Default**: `SMA`.
- **Effect**: Determines the moving average type for CCI signal smoothing. EMA is more responsive; VWMA weights by volume.
- **CCI MA Length** (`ma_length`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for the CCI MA. Longer periods smooth the MA but may delay signals.
### 3.5 RSI Filter Settings
- **Use RSI Filter** (`use_rsi_filter`):
- **Default**: `false`.
- **Effect**: If `true`, applies RSI-based overbought/oversold filters to signals.
- **RSI Length** (`rsi_length`):
- **Default**: `14`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for RSI calculation. Longer periods reduce sensitivity.
- **RSI Lower Limit** (`rsi_lower_limit`):
- **Default**: `30`.
- **Range**: `0` to `100`.
- **Effect**: Defines the oversold threshold for buy signals. Lower values allow trades in more extreme conditions.
- **RSI Upper Limit** (`rsi_upper_limit`):
- **Default**: `70`.
- **Range**: `0` to `100`.
- **Effect**: Defines the overbought threshold for sell signals. Higher values allow trades in more extreme conditions.
### 3.6 Signal Settings
- **Cross Window** (`cross_window`):
- **Default**: `0`.
- **Range**: `0` to `5` bars.
- **Effect**: Specifies the lookback period for detecting DI+/- or CCI crosses. `0` requires crosses on the current bar; higher values allow recent crosses, increasing signal frequency.
- **Allow Long Trades** (`allow_long`):
- **Default**: `true`.
- **Effect**: Enables/disables new long trades. If `false`, only closing existing longs is allowed.
- **Allow Short Trades** (`allow_short`):
- **Default**: `true`.
- **Effect**: Enables/disables new short trades. If `false`, only closing existing shorts is allowed.
- **Require DI+/DI- Cross for Buy** (`buy_di_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a DI+ crossover DI- for buy signals; if `false`, DI+ > DI- is sufficient.
- **Require CCI Cross for Buy** (`buy_cci_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a CCI crossover MA for buy signals; if `false`, CCI > MA is sufficient.
- **Require DI+/DI- Cross for Sell** (`sell_di_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a DI- crossover DI+ for sell signals; if `false`, DI+ < DI- is sufficient.
- **Require CCI Cross for Sell** (`sell_cci_cross`):
- **Default**: `true`.
- **Effect**: If `true`, requires a CCI crossunder MA for sell signals; if `false`, CCI < MA is sufficient.
- **Countertrade** (`countertrade`):
- **Default**: `true`.
- **Effect**: If `true`, closing a trade triggers an opposite trade (e.g., close long, open short) if allowed.
- **Color Background for Open Trades** (`color_background`):
- **Default**: `true`.
- **Effect**: If `true`, colors the chart background green for long trades and red for short trades.
### 3.7 Exit Settings
- **Use MA Cross for Exit** (`use_ma_exit`):
- **Default**: `true`.
- **Effect**: If `true`, closes trades when the price crosses the exit MA (below for long, above for short).
- **MA Length for Exit** (`ma_exit_length`):
- **Default**: `20`.
- **Range**: Minimum `1`.
- **Effect**: Sets the period for the exit MA. Longer periods delay exits.
- **MA Type for Exit** (`ma_exit_type`):
- **Options**: `SMA`, `EMA`, `SMMA (RMA)`, `WMA`, `VWMA`.
- **Default**: `SMA`.
- **Effect**: Determines the MA type for exit signals. EMA is more responsive; VWMA weights by volume.
- **Use ADX Change Stop-Loss** (`use_adx_stop`):
- **Default**: `false`.
- **Effect**: If `true`, closes trades when the ADX changes by a specified percentage.
- **ADX % Change for Stop-Loss** (`adx_change_percent`):
- **Default**: `5.0`.
- **Range**: Minimum `0.0`, step `0.1`.
- **Effect**: Specifies the percentage change in ADX (vs. previous bar) that triggers a stop-loss. Higher values reduce premature exits.
- **Use Performance Stop-Loss** (`use_perf_stop`):
- **Default**: `false`.
- **Effect**: If `true`, closes trades when the loss exceeds a percentage threshold.
- **Performance Stop-Loss (%)** (`perf_stop_percent`):
- **Default**: `-10.0`.
- **Range**: `-100.0` to `0.0`, step `0.1`.
- **Effect**: Specifies the loss percentage that triggers a stop-loss. More negative values allow larger losses before exiting.
## 4. Visual and Statistical Output
- **Labels**: Displayed at trade entries/exits with arrows (↑ for buy, ↓ for sell) and text ("BUY," "SELL"). A "No Equity" label appears if equity is zero.
- **Background Coloring**: Optionally colors the chart background (green for long, red for short) to indicate open trades.
- **Statistics Table**: Displayed at the top center of the chart, updated on timeframe changes or trade events. Includes:
- **Capital Metrics**: Initial capital, current capital, capital growth (%).
- **Trade Metrics**: Total trades, long/short trades, win rate, long/short win rates, profit factor.
- **Open Trade Status**: Indicates if a long, short, or no trade is open.
## 5. Alerts
- **Buy Signal Alert**: Triggered when `buy_signal` is true ("Cross Buy Signal").
- **Sell Signal Alert**: Triggered when `sell_signal` is true ("Cross Sell Signal").
- **Usage**: Users can set up TradingView alerts to receive notifications for trade signals.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.
Open-source Skript
Ganz im Sinne von TradingView hat dieser Autor sein/ihr Script als Open-Source veröffentlicht. Auf diese Weise können nun auch andere Trader das Script rezensieren und die Funktionalität überprüfen. Vielen Dank an den Autor! Sie können das Script kostenlos verwenden, aber eine Wiederveröffentlichung des Codes unterliegt unseren Hausregeln.
Haftungsausschluss
Die Informationen und Veröffentlichungen sind nicht als Finanz-, Anlage-, Handels- oder andere Arten von Ratschlägen oder Empfehlungen gedacht, die von TradingView bereitgestellt oder gebilligt werden, und stellen diese nicht dar. Lesen Sie mehr in den Nutzungsbedingungen.