OPEN-SOURCE SCRIPT

OB/OS adaptative v1.1

87
# OB/OS Adaptative v1.1 - Multi-Timeframe Adaptive Overbought/Oversold Indicator

## Overview
The `tradingview_indicator_emas.pine` script is a sophisticated multi-timeframe indicator designed to identify dynamic overbought and oversold levels in financial markets. It combines EMA (Exponential Moving Average) crossovers and Bollinger Bands across monthly, weekly, and daily timeframes to create adaptive support and resistance levels that adjust to changing market conditions.

## Core Functionality

### Multi-Timeframe Analysis
The indicator analyzes three timeframes simultaneously:
- **Monthly (M)**: Long-term trend identification
- **Weekly (W)**: Intermediate-term trend identification
- **Daily (D)**: Short-term volatility measurement

### Technical Indicators Used
- **EMA 9 and EMA 20**: For trend identification and momentum assessment
- **Bollinger Bands (20-period)**: For volatility measurement and extreme level identification
- **Price action**: For confirmation of level validity and signal generation

## Key Features

### Adaptive Level Calculation
The indicator dynamically determines overbought and oversold levels based on market structure and trend bias:

#### Monthly Level Logic
- **Bullish Bias** (when monthly open > EMA20):
- Oversold = lower of EMA9 or EMA20
- Overbought = upper of EMA9 or Bollinger Upper Band
- **Bearish/Neutral Bias** (when monthly open ≤ EMA20):
- Oversold = Bollinger Lower Band
- Overbought = upper of EMA20 or EMA9

#### Weekly Level Logic
- **Bullish Bias** (when weekly open > EMA20):
- Oversold = lower of EMA9 or EMA20
- Overbought = Bollinger Upper Band
- **Bearish/Neutral Bias** (when weekly open ≤ EMA20):
- Oversold = Bollinger Lower Band
- Overbought = upper of EMA20 or EMA9

#### Daily Level Logic
- Simple Bollinger Bands:
- Oversold = Bollinger Lower Band
- Overbought = Bollinger Upper Band

### Final Level Determination
The indicator combines all three timeframes through a weighted averaging process:
1. Calculates initial values as the average of monthly, weekly, and daily levels
2. Ensures mathematical consistency by enforcing overbought_final ≥ oversold_final using min/max functions
3. Calculates a midpoint average level as the center of the range

### Visual Elements
- **Dynamic Lines**: Draws horizontal lines for current and previous period overbought, oversold, and average levels
- **Labels**: Places clear textual labels at the start of each period
- **Color Coding**:
- Red for overbought levels (resistance)
- Green for oversold levels (support)
- Blue for average levels (pivot point)
- **Transparency**: Previous period lines use semi-transparent colors to distinguish between current and historical levels

### Update Mechanism
- **Calculation Day**: User-defined day of the week (default: Monday)
- On the specified calculation day, the indicator:
- Updates all levels based on previous bar's data
- Draws new lines extending forward for a user-defined number of days
- Maintains previous period lines for comparison and trend analysis
- Automatically deletes and recreates lines to ensure clean visualization

### Proximity Detection
- Alerts when price approaches overbought/oversold levels (configurable distance in percentage)
- Helps identify potential reversal zones before actual crossovers occur
- Distance thresholds are user-configurable for both overbought and oversold conditions

### Alert Conditions
The indicator provides four distinct alert types:
1. **Cross below oversold**: Triggered when price crosses below the oversold level
2. **Cross above overbought**: Triggered when price crosses above the overbought level
3. **Near oversold**: Triggered when price approaches the oversold level within the configured distance
4. **Near overbought**: Triggered when price approaches the overbought level within the configured distance

### Debug Mode
When enabled, displays comprehensive debug information including:
- Current values for all levels (oversold, overbought, average)
- Timeframe-specific calculations and raw data points
- System status information (current day, calculation day, etc.)
- Lines existence and timing information
- Organized in multiple labels at different price levels to avoid overlap

## Configuration Parameters

| Parameter | Default Value | Description |
|---------|---------------|-------------|
| Short EMA (9) | 9 | Length for short-term EMA calculation |
| Long EMA (20) | 20 | Length for long-term EMA calculation |
| BB Length | 20 | Period for Bollinger Bands calculation |
| Std Dev | 2.0 | Standard deviation multiplier for Bollinger Bands |
| Distance to overbought (%) | 0.5 | Percentage threshold for "near overbought" alerts |
| Distance to oversold (%) | 0.5 | Percentage threshold for "near oversold" alerts |
| Calculation day | Monday | Day of week when levels are recalculated |
| Lookback days | 7 | Number of days to extend previous period lines backward |
| Forward days | 7 | Number of days to extend current period lines forward |
| Show Debug Labels | false | Toggle for comprehensive debug information display |

## Trading Applications

### Primary Use Cases
1. **Reversal Trading**: Identify potential reversal zones when price approaches overbought/oversold levels
2. **Trend Confirmation**: Use the adaptive nature of levels to confirm trend strength and direction
3. **Position Sizing**: Adjust position size based on distance from key levels
4. **Stop Placement**: Use opposite levels as dynamic stop-loss references

### Strategic Advantages
- **Adaptive Nature**: Levels adjust to changing market volatility and trend structure
- **Multi-Timeframe Confirmation**: Signals are validated across multiple timeframes
- **Visual Clarity**: Clear color-coded lines and labels enhance decision-making
- **Proactive Alerts**: "Near" conditions provide early warnings before crossovers

## Implementation Details

### Data Security
Uses `request.security()` function to fetch data from higher timeframes (monthly, weekly) while maintaining proper bar indexing with `[1]` offset for open prices.

### Performance Optimization
- Uses `var` keyword to declare persistent variables that maintain state across bars
- Efficient line and label management with proper deletion before recreation
- Conditional execution of debug code to minimize performance impact

### Error Handling
- Comprehensive NA (not available) checks throughout the code
- Graceful degradation when data is unavailable for higher timeframes
- Mathematical safeguards to prevent invalid level calculations

## Conclusion
The OB/OS Adaptative v1.1 indicator represents a sophisticated approach to identifying market extremes by combining multiple technical analysis concepts. Its adaptive nature makes it particularly useful in trending markets where static levels may be less effective. The multi-timeframe approach provides a comprehensive view of market structure, while the visual elements and alert system enhance its practical utility for active traders.

Feragatname

Bilgiler ve yayınlar, TradingView tarafından sağlanan veya onaylanan finansal, yatırım, işlem veya diğer türden tavsiye veya tavsiyeler anlamına gelmez ve teşkil etmez. Kullanım Şartları'nda daha fazlasını okuyun.