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 
7f335a2
 
 
0a38476
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f335a2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
# 📚 Referência de APIs e Interfaces

## Visão Geral

Este documento descreve todas as APIs, interfaces e contratos entre os módulos do Vampire Trading Bot. Cada seção inclui exemplos de uso, parâmetros esperados e formatos de resposta.

## Estrutura de Módulos

### Core
- `advanced_market_processing.py`: Processamento avançado de dados de mercado
  - **Classe**: `AdvancedMarketProcessor`
  - **Importação**: `from src.core.advanced_market_processing import AdvancedMarketProcessor`
- `database_logger.py`: Sistema de logging em banco de dados
- `log_parser.py`: Parser de logs do Vampire Bot
- `performance_monitor.py`: Monitor de performance do sistema

### AI
- `voting_system.py`: Sistema de votação inteligente para ensemble
  - **Classe**: `VotingStrategy` (Enum)
  - **Função**: `intelligent_vote()`
  - **Importação**: `from src.ai.voting_system import VotingStrategy, intelligent_vote`
- `ensemble_ai.py`: Sistema ensemble de IA
  - **Função**: `ensemble_ai()`
  - **Classe**: `EnsembleResult`
  - **Importação**: `from src.ai.ensemble_ai import ensemble_ai, EnsembleResult`

## 🔧 Core Engines

### Funções Utilitárias de Análise Técnica

#### calculate_rsi(prices: list, period: int = 14) -> float
```python
def calculate_rsi(prices: list, period: int = 14) -> float:
    """Calcula o RSI (Relative Strength Index).
    
    Args:
        prices (list): Lista de preços históricos
        period (int): Período para cálculo (padrão: 14)
        
    Returns:
        float: Valor do RSI (0-100)
    """
```

#### calculate_bollinger_bands(prices: list, period: int = 20, std_dev: float = 2.0) -> dict
```python
def calculate_bollinger_bands(prices: list, period: int = 20, std_dev: float = 2.0) -> dict:
    """Calcula as Bandas de Bollinger.
    
    Args:
        prices (list): Lista de preços históricos
        period (int): Período para média móvel (padrão: 20)
        std_dev (float): Multiplicador do desvio padrão (padrão: 2.0)
        
    Returns:
        dict: {'upper': float, 'middle': float, 'lower': float}
    """
```

#### calculate_ema(prices: list, period: int) -> float
```python
def calculate_ema(prices: list, period: int) -> float:
    """Calcula a EMA (Exponential Moving Average).
    
    Args:
        prices (list): Lista de preços históricos
        period (int): Período para cálculo da EMA
        
    Returns:
        float: Valor da EMA
    """
```

#### format_number(value: float, decimals: int = 2) -> str
```python
def format_number(value: float, decimals: int = 2) -> str:
    """Formata um número para exibição.
    
    Args:
        value (float): Valor a ser formatado
        decimals (int): Número de casas decimais (padrão: 2)
        
    Returns:
        str: Número formatado
    """
```

### TechnicalAnalysisEngine

#### Classe Principal
```python
class TechnicalAnalysisEngine:
    def __init__(self):
        """Inicializa o engine de análise técnica."""
    
    def analyze_market_data(self, market_text: str) -> Dict[str, Any]:
        """Analisa dados de mercado a partir de texto.
        
        Args:
            market_text (str): Texto contendo dados de mercado
            
        Returns:
            Dict[str, Any]: Resultado da análise técnica
            {
                'market_data': MarketData,
                'technical_signals': List[TechnicalSignal],
                'scalping_setups': List[ScalpingSetup],
                'risk_analysis': RiskAnalysis,
                'overall_signal': str,
                'confidence': float
            }
        """
```

#### Estruturas de Dados

```python
@dataclass
class MarketData:
    """Dados básicos de mercado."""
    symbol: str              # Símbolo do ativo
    current_price: float     # Preço atual
    variation: float         # Variação absoluta
    variation_percent: float # Variação percentual
    high: float             # Máxima do período
    low: float              # Mínima do período
    volume: float           # Volume negociado
    timestamp: str          # Timestamp da cotação

@dataclass
class TechnicalSignal:
    """Sinal de indicador técnico."""
    indicator: str          # Nome do indicador (RSI, EMA, etc.)
    value: float           # Valor atual do indicador
    signal: str            # Sinal gerado (COMPRAR, VENDER, NEUTRO)
    confidence: float      # Confiança do sinal (0-100)
    description: str       # Descrição detalhada
    timestamp: str         # Timestamp do cálculo

@dataclass
class ScalpingSetup:
    """Setup de scalping detectado."""
    name: str              # Nome do setup
    entry_price: float     # Preço de entrada
    stop_loss: float       # Stop loss
    take_profit: float     # Take profit
    risk_reward: float     # Relação risco/recompensa
    confidence: float      # Confiança do setup
    timeframe: str         # Timeframe recomendado
```

#### Exemplo de Uso

```python
engine = TechnicalAnalysisEngine()

market_text = """
📊 DADOS DE MERCADO - WINV25
Preço Atual: 140135.00000 ↗
Variação: +5.00000 (+0.00%)
Máxima: 140155.00000
Mínima: 140075.00000
Volume: 5023
"""

result = engine.analyze_market_data(market_text)
print(f"Sinal geral: {result['overall_signal']}")
print(f"Confiança: {result['confidence']}%")
```

### SentimentAnalysisEngine

#### Classe Principal
```python
class SentimentAnalysisEngine:
    def __init__(self, model_name: str = None):
        """Inicializa o engine de análise de sentimento.
        
        Args:
            model_name (str, optional): Nome do modelo a usar
        """
    
    def analyze_sentiment(self, text: str) -> SentimentResult:
        """Analisa sentimento de um texto.
        
        Args:
            text (str): Texto para análise (max 512 tokens)
            
        Returns:
            SentimentResult: Resultado da análise
        """
    
    def batch_analyze(self, texts: List[str]) -> List[SentimentResult]:
        """Analisa múltiplos textos em lote.
        
        Args:
            texts (List[str]): Lista de textos
            
        Returns:
            List[SentimentResult]: Lista de resultados
        """
```

#### Estruturas de Dados

```python
@dataclass
class SentimentResult:
    """Resultado de análise de sentimento."""
    text: str                    # Texto original
    sentiment: str               # POSITIVO, NEGATIVO, NEUTRO
    confidence: float            # Confiança (0-100)
    scores: Dict[str, float]     # Scores detalhados por classe
    keywords: List[str]          # Palavras-chave extraídas
    financial_indicators: List[str] # Indicadores financeiros detectados
    timestamp: str               # Timestamp da análise
    model_used: str             # Modelo utilizado
```

#### Exemplo de Uso

```python
engine = SentimentAnalysisEngine()

text = "O mercado está muito otimista hoje, com forte alta nos índices."
result = engine.analyze_sentiment(text)

print(f"Sentimento: {result.sentiment}")
print(f"Confiança: {result.confidence}%")
print(f"Palavras-chave: {result.keywords}")
```

### AdvancedFibonacciEngine

#### Classe Principal
```python
class AdvancedFibonacciEngine:
    def __init__(self):
        """Inicializa o engine de análise de Fibonacci."""
    
    def perform_advanced_analysis(
        self,
        swing_high: float,
        swing_low: float,
        current_price: float,
        historical_data: Optional[pd.DataFrame] = None
    ) -> AdvancedFibonacciAnalysis:
        """Realiza análise avançada de Fibonacci.
        
        Args:
            swing_high (float): Preço do swing high
            swing_low (float): Preço do swing low
            current_price (float): Preço atual
            historical_data (pd.DataFrame, optional): Dados históricos
            
        Returns:
            AdvancedFibonacciAnalysis: Análise completa
        """
```

#### Estruturas de Dados

```python
@dataclass
class FibonacciLevel:
    """Nível de Fibonacci."""
    level: float                 # Nível (0.236, 0.382, etc.)
    price: float                # Preço do nível
    type: str                   # 'retracement', 'extension', 'projection'
    ratio: float                # Ratio de Fibonacci
    distance_from_current: float # Distância do preço atual
    strength: float             # Força do nível (0-100)

@dataclass
class ConfluenceZone:
    """Zona de confluência."""
    price_range: Tuple[float, float] # Faixa de preços
    levels_count: int               # Número de níveis na zona
    strength: float                 # Força da zona
    types: List[str]               # Tipos de níveis presentes

@dataclass
class AdvancedFibonacciAnalysis:
    """Análise completa de Fibonacci."""
    swing_high: float
    swing_low: float
    current_price: float
    swing_range: float
    retracement_levels: List[FibonacciLevel]
    extension_levels: List[FibonacciLevel]
    projection_levels: List[FibonacciLevel]
    confluence_zones: List[ConfluenceZone]
    harmonic_patterns: List[HarmonicPattern]
    key_support: float
    key_resistance: float
    trend_direction: str
    fibonacci_zone: str
    overall_strength: float
    trading_signal: str
    alerts_count: int
```

## 🔄 Real-time Integration

### RealTimeIntegration

#### Classe Principal
```python
class RealTimeIntegration:
    def __init__(self, log_file_path: str):
        """Inicializa integração em tempo real.
        
        Args:
            log_file_path (str): Caminho para arquivo de log
        """
    
    def start(self):
        """Inicia monitoramento em tempo real."""
    
    def stop(self):
        """Para monitoramento."""
    
    def subscribe(self, callback: Callable[[BotEvent], None]):
        """Inscreve callback para eventos.
        
        Args:
            callback: Função a ser chamada para cada evento
        """
```

#### Estruturas de Dados

```python
@dataclass
class BotEvent:
    """Evento do bot em tempo real."""
    timestamp: datetime
    event_type: str              # 'new_analysis', 'fibonacci_alert', etc.
    data: Dict[str, Any]        # Dados do evento
    priority: str               # 'low', 'normal', 'high', 'critical'

@dataclass
class RealTimeConfig:
    """Configuração de tempo real."""
    log_file_path: str
    check_interval: float        # Intervalo de verificação (segundos)
    max_queue_size: int         # Tamanho máximo da fila
    enable_notifications: bool   # Habilitar notificações
    auto_analysis: bool         # Análise automática
    backup_logs: bool           # Backup de logs
```

## 📊 Performance Monitor

### PerformanceMonitor

#### Classe Principal
```python
class PerformanceMonitor:
    def __init__(self, max_metrics_history: int = 1000):
        """Inicializa monitor de performance."""
    
    def start_monitoring(self, interval: float = 5.0):
        """Inicia monitoramento.
        
        Args:
            interval (float): Intervalo entre coletas (segundos)
        """
    
    def record_analysis_time(self, analysis_time: float):
        """Registra tempo de análise.
        
        Args:
            analysis_time (float): Tempo em segundos
        """
    
    def get_performance_summary(self) -> Dict[str, Any]:
        """Retorna resumo de performance.
        
        Returns:
            Dict com métricas de performance
        """
```

#### Estruturas de Dados

```python
@dataclass
class PerformanceMetrics:
    """Métricas de performance."""
    timestamp: datetime
    cpu_usage: float            # Uso de CPU (%)
    memory_usage: float         # Uso de memória (%)
    memory_available: float     # Memória disponível (MB)
    disk_usage: float          # Uso de disco (%)
    analysis_time: float       # Tempo de análise (s)
    events_processed: int      # Eventos processados
    errors_count: int          # Contagem de erros
    bot_signals_count: int     # Sinais do bot
    fibonacci_alerts_count: int # Alertas de Fibonacci
```

## 🔍 Log Parser

### VampireBotLogParser

#### Classe Principal
```python
class VampireBotLogParser:
    def __init__(self):
        """Inicializa parser de logs."""
    
    def parse_log_content(self, log_content: str) -> Optional[BotAnalysis]:
        """Faz parse de conteúdo de log.
        
        Args:
            log_content (str): Conteúdo do log
            
        Returns:
            BotAnalysis ou None se parsing falhar
        """
    
    def parse_log_file(self, file_path: str) -> Optional[BotAnalysis]:
        """Faz parse de arquivo de log.
        
        Args:
            file_path (str): Caminho do arquivo
            
        Returns:
            BotAnalysis ou None se parsing falhar
        """
```

#### Estruturas de Dados

```python
@dataclass
class BotAnalysis:
    """Análise completa do bot."""
    analysis_number: int
    timestamp: str
    market_data: MarketData
    technical_indicators: TechnicalIndicators
    fibonacci_analysis: FibonacciAnalysis
    performance_time: Optional[float] = None

@dataclass
class TechnicalIndicators:
    """Indicadores técnicos do log."""
    rsi: float
    rsi_status: str
    ema_fast: float
    ema_slow: float
    ema_trend: str
    bollinger_status: str
    bollinger_upper: float
    bollinger_lower: float
    atr: float
    volatility: str
    volatility_multiplier: float
```

## 🎨 UI Interface

### GradioInterface

#### Classe Principal
```python
class GradioInterface:
    def __init__(self):
        """Inicializa interface Gradio."""
    
    def create_interface(self) -> gr.Blocks:
        """Cria interface completa.
        
        Returns:
            gr.Blocks: Interface Gradio configurada
        """
    
    def launch(self, **kwargs):
        """Lança a interface com configurações otimizadas.
        
        Args:
            **kwargs: Argumentos para gr.launch()
            
        Configurações padrão para HF Spaces:
            - server_name: "0.0.0.0"
            - server_port: 7860
            - share: False
            - show_error: True
            - max_threads: 10
            - ssr_mode: False (para compatibilidade HF Spaces)
            - show_api: False
        """
```

#### Configurações HF Spaces

```python
from hf_spaces_config import HuggingFaceSpacesConfig

# Uso automático das configurações HF Spaces
config = HuggingFaceSpacesConfig()
launch_config = config.get_launch_config()
demo.launch(**launch_config)

# Configuração manual para HF Spaces
demo.launch(
    server_name="0.0.0.0",
    server_port=7860,
    share=False,
    show_error=True,
    max_threads=10,
    ssr_mode=False,  # CRÍTICO: Evita erro 500 no HF Spaces
    show_api=False
)
```

#### Componentes da Interface

```python
class UIComponents:
    """Componentes reutilizáveis da UI."""
    
    @staticmethod
    def create_market_input() -> gr.Textbox:
        """Cria campo de entrada de dados de mercado."""
    
    @staticmethod
    def create_sentiment_input() -> gr.Textbox:
        """Cria campo de entrada para análise de sentimento."""
    
    @staticmethod
    def create_fibonacci_inputs() -> Tuple[gr.Number, gr.Number, gr.Number]:
        """Cria campos para análise de Fibonacci."""
```

## 🛠️ Utilities

### Utilitários de Validação

```python
class ValidationUtils:
    @staticmethod
    def validate_market_data(data: Dict[str, Any]) -> bool:
        """Valida dados de mercado.
        
        Args:
            data: Dicionário com dados de mercado
            
        Returns:
            bool: True se válido
        """
    
    @staticmethod
    def validate_text_input(text: str) -> bool:
        """Valida entrada de texto.
        
        Args:
            text: Texto a validar
            
        Returns:
            bool: True se válido
        """
```

### Utilitários de Formatação

```python
class FormatUtils:
    @staticmethod
    def format_price(price: float) -> str:
        """Formata preço com separadores."""
    
    @staticmethod
    def format_percentage(value: float) -> str:
        """Formata porcentagem com sinal."""
    
    @staticmethod
    def format_analysis_result(result: Dict[str, Any]) -> str:
        """Formata resultado de análise para exibição."""
```

## 📋 Códigos de Erro

### Códigos de Sistema
- `SYS_001`: Erro de inicialização
- `SYS_002`: Erro de configuração
- `SYS_003`: Erro de memória insuficiente

### Códigos de Análise
- `ANA_001`: Dados de mercado inválidos
- `ANA_002`: Erro no modelo de IA
- `ANA_003`: Timeout de análise
- `ANA_004`: Erro de parsing de texto

### Códigos de Interface
- `UI_001`: Erro de renderização
- `UI_002`: Entrada inválida
- `UI_003`: Erro de comunicação

## 🔧 Configuração de APIs

### Variáveis de Ambiente

```bash
# Configurações de modelo
FINBERT_MODEL_PATH=/path/to/model
MAX_TEXT_LENGTH=512

# Configurações de performance
MAX_WORKERS=4
CACHE_SIZE=1000

# Configurações de logging
LOG_LEVEL=INFO
LOG_FILE_PATH=/path/to/logs
```

### Configuração via Arquivo

```python
# config.py
class APIConfig:
    MAX_TEXT_LENGTH = 512
    TIMEOUT_SECONDS = 30
    RETRY_ATTEMPTS = 3
    CACHE_TTL = 3600
```

## 📝 Exemplos de Integração

### Exemplo Completo

```python
from market_analysis import TechnicalAnalysisEngine
from sentiment_analysis import SentimentAnalysisEngine
from fibonacci_analysis import AdvancedFibonacciEngine

# Inicializar engines
tech_engine = TechnicalAnalysisEngine()
sentiment_engine = SentimentAnalysisEngine()
fib_engine = AdvancedFibonacciEngine()

# Dados de entrada
market_text = "Preço: 140135, Variação: +5"
sentiment_text = "Mercado muito otimista hoje"

# Análises
tech_result = tech_engine.analyze_market_data(market_text)
sentiment_result = sentiment_engine.analyze_sentiment(sentiment_text)
fib_result = fib_engine.perform_advanced_analysis(140570, 139540, 140135)

# Consolidar resultados
final_result = {
    'technical': tech_result,
    'sentiment': sentiment_result,
    'fibonacci': fib_result,
    'timestamp': datetime.now().isoformat()
}

print(json.dumps(final_result, indent=2, default=str))
```

## 🚀 Próximas Versões da API

### v2.0 (Planejado)
- REST API completa
- WebSocket para tempo real
- Autenticação e autorização
- Rate limiting
- Documentação OpenAPI/Swagger

### v3.0 (Futuro)
- GraphQL API
- Microserviços
- API Gateway
- Métricas avançadas
- Multi-tenancy