Spaces:
Sleeping
Sleeping
| # 📚 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 |