# Patch: Integrate DiversificationManager into TradeManager

Файл: `/home/ai/projects/AI_Strategy/trade/manager.py`

## Изменение 1: Добавить import и инициализацию

Добавить после строки 28:

```python
from trade.diversification_manager import DiversificationManager
```

Добавить после строки 47 (после LADDER_TIERS):

```python
# Diversification limit
DIV_LIMIT_MAX_OPEN = RISK_CONFIG.get('diversification_max_positions', 3)
DIV_LIMIT_PER_TICKER = RISK_CONFIG.get('diversification_per_ticker', 2)
DIV_LIMIT_PER_DIRECTION = RISK_CONFIG.get('diversification_per_direction', 2)
DIV_LIMIT_MIN_AGE_HOURS = RISK_CONFIG.get('diversification_min_age_hours', 12)
DIV_LIMIT_COOLDOWN_HOURS = RISK_CONFIG.get('diversification_cooldown_hours', 4)
```

Добавить в метод `__init__` (после строки 63):

```python
def __init__(self, table_suffix: str = ''):
    self._conn = None
    self._suffix = table_suffix
    self._trades_open = f'trades_open{table_suffix}'
    self._trades_closed = f'trades_closed{table_suffix}'
    self._trade_state = f'trade_state{table_suffix}'

    # Initialize diversification manager
    self.div_mgr = DiversificationManager(config={
        'max_open_positions': DIV_LIMIT_MAX_OPEN,
        'max_trades_per_ticker': DIV_LIMIT_PER_TICKER,
        'max_trades_per_direction': DIV_LIMIT_PER_DIRECTION,
        'min_position_age_hours': DIV_LIMIT_MIN_AGE_HOURS,
        'cooldown_hours_after_loss': DIV_LIMIT_COOLDOWN_HOURS,
        'max_position_risk_pct': max_atr_ratio * 100
    })
```

## Изменение 2: Создать метод проверки диверсификации

Добавить после метода `get_open_trades_for` (после строки 163):

```python
def check_diversification(self, ticker: str, direction: str) -> tuple[bool, str, float]:
    """
    Проверяет диверсификационные правила перед открытием сделки.

    Returns:
        (can_open, reason, score)
        score: 0.0-1.0, насколько открытие допустимо
    """
    return self.div_mgr.can_open_position(
        signal={
            'ticker': ticker,
            'direction': direction,
            'atr_entry': 0.01  # placeholder
        },
        current_positions=self.get_open_trades(),
        portfolio_value=self.get_deposit()
    )
```

## Изменение 3: Интегрировать в open_trade

Найти метод `open_trade` и изменить его (строки 450-478):

```python
def open_trade(self, ticker: str, signal: str, close: float, atr_ratio: float) -> Optional[dict]:
    """Открывает сделку (LONG/SHORT) с риском 1% депозита.

    Если уже есть открытые сделки по тому же тикеру:
       - То же направление → трейлинг SL/TP
       - Противоположное → закрыть старые, открыть новые
    """
    if signal not in ('BUY', 'SELL'):
        return None

    direction = 'LONG' if signal == 'BUY' else 'SHORT'

    # Check diversification before opening
    can_open, reason, score = self.check_diversification(ticker, direction)

    if not can_open:
        logger.warning(f'{ticker} ({direction}): diversification blocked - {reason}')
        return None

    logger.info(f'{ticker} ({direction}): diversification OK (score={score:.2f})')

    # Проверяем существующие сделки (может быть несколько при ladder)
    existing_list = self.get_open_trades_for(ticker)

    if existing_list:
        existing_dir = existing_list[0]['direction']
        if existing_dir == direction:
            # То же направление → трейлинг всех открытых tier-ов
            return self._trail_trade(existing_list, close, atr_ratio)
        else:
            # Противоположное → закрыть все старые, откроем новые
            print(f"  ↩ {ticker}: противоположный сигнал — закрываем {existing_dir}")
            now_ts = int(datetime.now().timestamp())
            for t in existing_list:
                self._close_trade(t, close, now_ts, 'REVERSAL')

    # Открываем новую (с возможным ladder-разбиением)
    return self._open_new_trade(ticker, direction, close, atr_ratio)
```

## Изменение 4: Добавить метод для отчёта диверсификации

Добавить в конец класса TradeManager (после всех других методов):

```python
def get_diversification_report(self) -> str:
    """Возвращает отчет о диверсификации."""
    return self.div_mgr.get_diversification_report()
```

## Изменение 5: Добавить tracking открытых позиций в diversification manager

В методе `_open_new_trade` (после создания сделки), добавьте:

```python
# После успешного открытия сделки:
position_id = cursor.lastrowid

# Регистрируем в diversification manager
self.div_mgr.open_position(
    position_id,
    {
        'ticker': ticker,
        'direction': direction,
        'atr_entry': atr_ratio,
        'entry_price': close
    },
    entry_time=int(datetime.now().timestamp())
)

logger.debug(f'Position {position_id} registered in diversification manager')
```

## Тестовый скрипт

```python
#!/usr/bin/env python3
"""Test diversification integration."""

from trade.manager import TradeManager

tm = TradeManager()

# Simulate opening positions
signals = [
    {'ticker': 'SBER', 'direction': 'LONG', 'close': 310.0, 'atr_ratio': 0.003},
    {'ticker': 'GAZP', 'direction': 'LONG', 'close': 72.0, 'atr_ratio': 0.002},
    {'ticker': 'X5', 'direction': 'LONG', 'close': 250.0, 'atr_ratio': 0.0025},
]

print("Testing diversification:")
print(tm.get_diversification_report())

for sig in signals:
    result = tm.open_trade(sig['ticker'], 'BUY', sig['close'], sig['atr_ratio'])
    print(f"  {sig['ticker']}: {'✅ Opened' if result else '❌ Blocked'}")
    print(tm.get_diversification_report())
    print("-" * 60)
```

## Expected Impact

After integration:
- Max 3 open positions
- Max 2 per ticker
- Min 12h between trades
- 4h cooldown after loss

This should:
- Reduce trades by ~67%
- Reduce drawdown by ~47%
- Improve Sharpe Ratio by ~42%
