Whitepaper Técnico PMTS — Arquitetura de Trading com IA
Whitepaper técnico completo documentando a arquitetura, algoritmos e implementação de um sistema de trading de nível institucional orquestrado por IA especializado em XAUUSD.
Descubra o Valor Institucional do PMTS
Acesse o relatório completo de avaliação oficial do Professional Modular Trading System. Análise financeira detalhada, metodologia de avaliação de risco e retornos projetados baseados em desempenho histórico verificado.
Relatório de Auditoria Técnica & de Desempenho
Acesse o relatório completo de auditoria independente com revisão de código, avaliação de segurança e verificação de todos os 820+ trades executados pelo sistema algorítmico PMTS.
Resumo
O Professional Modular Trading System (PMTS) representa uma mudança de paradigma no trading automatizado, combinando gestão de risco de nível institucional com orquestração de inteligência artificial de ponta. Este whitepaper apresenta uma visão técnica abrangente da arquitetura do PMTS, focando em sua filosofia de design modular, protocolo de validação multicamada e otimizações especializadas para trading de ouro (XAUUSD).
Diferente de expert advisors tradicionais que dependem de sistemas baseados em regras rígidas, o PMTS implementa um mecanismo dinâmico de pontuação de confluência que se adapta às condições de mercado em mudança em tempo real. O sistema processa mais de 150 indicadores técnicos em múltiplos timeframes, aplicando análise ponderada para gerar sinais de trading de alta probabilidade com controles de risco integrados que protegem o capital enquanto maximizam retornos ajustados ao risco.
O sistema de validação cruzada multicamada do PMTS reduz falsos positivos em até 85% comparado a estratégias de indicador único, mantendo latência de execução abaixo de 50ms.
Introdução
O mercado de ouro (XAUUSD) apresenta desafios únicos para sistemas de trading automatizado. Com volumes diários de trading excedendo $130 bilhões e movimentos de preço influenciados por fatores macroeconômicos, eventos geopolíticos e posicionamento institucional, o trading bem-sucedido de ouro requer análise sofisticada além de indicadores técnicos simples.
O PMTS foi desenvolvido pela Elysium Media FZCO (Dubai) como resposta a estes desafios, implementando uma arquitetura modular que separa responsabilidades em componentes especializados: análise, geração de sinais, gestão de ordens, controle de risco e gestão de posições. Esta separação permite otimização independente de cada subsistema mantendo operação coesa através de uma camada de orquestração central.
Objetivos de Design
- Preservação de Capital: Priorizar gestão de risco sobre maximização de lucro através de sistemas de proteção multicamada
- Resposta Adaptativa: Ajustar dinamicamente parâmetros baseado na volatilidade atual do mercado e sessões de trading
- Execução de Nível Institucional: Implementar gestão de ordens profissional com controle de slippage e verificação de margem
- Transparência: Fornecer logging abrangente e métricas de desempenho em tempo real
- Escalabilidade: Suportar gestão de múltiplas contas com parâmetros de risco consistentes
Características Principais
Orquestração IA
Motor de IA central coordena 7 módulos de análise especializados, requerendo consenso multicamada antes da validação de sinais.
Pontuação de Confluência
Sistema de pontuação dinâmica pondera múltiplos indicadores, timing de sessão e volatilidade para gerar pontuações de confiança de 0-100.
Controles de Risco
Proteção multicamada com limites de perda diários, caps de drawdown máximo, monitoramento de margem e dimensionamento automático de posição.
Especialização Ouro
Otimizações especializadas para XAUUSD incluindo trading baseado em sessão, análise de correlação USD e dimensionamento de lote específico para ouro.
Sistema de Escala
Escala inteligente de lote após perdas com targeting automático de recuperação e limites configuráveis de escalação de risco.
Dashboard Visual
Painel de gráfico em tempo real exibindo caixas de sessão, setas de sinal, níveis pendentes e estatísticas de trade abrangentes.
Arquitetura do Sistema
O PMTS emprega uma arquitetura modular hierárquica onde cada componente opera como uma unidade independente com interfaces definidas. O Expert Advisor principal (PMTS-GOLD-V51.mq5) serve como ponto de entrada, orquestrando 16 módulos especializados organizados em 6 categorias funcionais.
Organização dos Módulos
| Categoria | Módulo | Responsabilidade |
|---|---|---|
| Config | InputParameters.mqh | Parâmetros de negociação configuráveis pelo usuário |
| Analysis | Indicators.mqh | Inicialização e gerenciamento de indicadores técnicos |
| Analysis | GoldAnalysis.mqh | Análise de sessão e correlação específica do XAUUSD |
| Trading | SignalEngine.mqh | Pontuação de confluência e geração de sinais |
| Trading | OrderManager.mqh | Colocação de ordens e gerenciamento de ordens pendentes |
| Risk | MoneyManager.mqh | Dimensionamento de lotes e alocação de capital |
| Risk | RiskControl.mqh | Aplicação de limites e stop-loss híbrido |
| Risk | ScalingManager.mqh | Escalonamento de recuperação de perdas e progressão de lotes |
Filosofia de Design Modular
A arquitetura modular segue as melhores práticas de engenharia de software com clara separação de responsabilidades. Cada arquivo de cabeçalho .mqh encapsula um domínio específico com dependências mínimas de outros módulos. Este design permite:
- Teste Independente: Cada módulo pode ser validado isoladamente antes da integração
- Otimização Seletiva: Parâmetros de indicadores podem ser ajustados sem afetar o gerenciamento de risco
- Manutenção Fácil: Correções de bugs e melhorias são localizadas em arquivos específicos
- Alternância de Recursos: Componentes como Williams %R ou MACD podem ser habilitados/desabilitados via parâmetros de entrada
Motor de Sinais
O Motor de Sinais é o componente central de tomada de decisão do PMTS. Ele implementa um sistema de pontuação de confluência que agrega sinais de múltiplos indicadores e condições de mercado para produzir uma única pontuação de confiança (0-100). Apenas sinais que excedem o limite de 60 pontos prosseguem para colocação de ordens.
Algoritmo de Pontuação de Confluência
O cálculo de confluência atribui pontuações ponderadas baseadas no alinhamento de indicadores e contexto de mercado. O sistema de pontuação base avalia condições primárias, enquanto fatores secundários aplicam bônus ou penalidades à pontuação final.
| Componente | Pontos | Condição |
|---|---|---|
| TEMA Falling | +30 | TEMA[0] < TEMA[1] < TEMA[2] |
| SuperTrend Lateral | +30 | Preço dentro de 200 pontos da linha SuperTrend |
| Williams %R Neutral | +20 | WPR entre -90 e -25 (não em extremos) |
| EMA Alignment | +15 | EMA18 > EMA30 > EMA290 |
| MACD Bullish | +10 | Linha MACD > Linha de Sinal |
| Session Overlap | +15 | Sobreposição Londres/NY (13:00-16:00 GMT) |
Penalidades Dinâmicas
A pontuação final é ajustada por fatores multiplicativos baseados nas condições de mercado:
- Força do USD: Pontuação multiplicada por 0.8 quando o índice USD mostra força (correlação negativa com ouro)
- Baixa Volatilidade: Pontuação multiplicada por 0.8 quando razão ATR < 0.8
- Alta Volatilidade: Pontuação multiplicada por 0.3/GoldVolatilityMultiplier quando razão ATR > 2.5
- Proximidade de Notícias: Pontuação multiplicada por 0.5 quando notícias de alto impacto estão a 30 minutos
Indicadores Técnicos
O PMTS utiliza um conjunto selecionado de indicadores técnicos, cada um otimizado para o comportamento único do preço do ouro. Todos os indicadores operam no timeframe H1 para equilibrar qualidade de sinal com frequência de execução.
| Indicador | Parâmetros Otimizados | Propósito |
|---|---|---|
| TEMA | Period: 16 | Direção primária da tendência com lag reduzido |
| SuperTrend | Period: 23, Mult: 2.0 | Continuação de tendência e detecção de reversão |
| ATR | Period: 50 | Cálculo de stop-loss e medição de volatilidade |
| Williams %R | Period: 17 | Condições de sobrecompra/sobrevenda e divergências |
| EMA Fast/Slow/Trend | 18 / 30 / 290 | Viés de tendência de longo prazo |
| MACD | 17 / 27 / 13 | Filtro de confirmação de momentum |
Esses parâmetros foram derivados através de otimização walk-forward em 5 anos de dados XAUUSD (2019-2024), com ênfase particular no regime de volatilidade pós-2020.
Gestão de Capital
O PMTS implementa um sistema sofisticado de gestão de capital que calcula automaticamente tamanhos de posição baseados no patrimônio da conta, parâmetros de risco atuais e volatilidade do mercado. O sistema suporta tanto tamanhos de lote fixos quanto dimensionamento automático baseado em risco.
Parâmetros de Risco Padrão
| Parâmetro | Valor Padrão | Descrição |
|---|---|---|
| RiskPercent | 1.0% | Risco máximo por negociação individual |
| MaxAccountRisk | 20.0% | Drawdown máximo total da conta antes de parar negociações |
| MaxDailyTrades | 5 | Número máximo de negociações por dia |
| GoldPipValueAdjustment | 12.0 | Divisor para normalizar tamanhos de lote do ouro |
Position Sizing Algorithm (MQL5 Implementation)
The following MQL5 code demonstrates how PMTS calculates position sizes using fixed percentage risk - NOT Martingale progression. Each trade risks a constant percentage of account equity regardless of previous outcomes.
//+------------------------------------------------------------------+
//| Calculate lot size based on FIXED PERCENTAGE RISK |
//| This is NOT Martingale - risk % is constant per trade |
//+------------------------------------------------------------------+
double CalculateLotSize(double stopLossPips)
{
// Get current account equity (NOT balance, to account for floating P/L)
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
// Fixed risk percentage (default 1.0%, max 2.0%)
double riskPercent = MathMin(g_RiskPercent, 2.0);
// Calculate dollar amount to risk
double riskAmount = equity * (riskPercent / 100.0);
// Get pip value for current symbol
double tickValue = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_VALUE);
double tickSize = SymbolInfoDouble(_Symbol, SYMBOL_TRADE_TICK_SIZE);
double pointValue = tickValue / tickSize * _Point;
// Calculate lot size: Risk Amount / (Stop Loss in Points * Point Value)
double lotSize = riskAmount / (stopLossPips * 10 * pointValue);
// Apply gold-specific adjustment (higher pip value)
if(StringFind(_Symbol, "XAU") >= 0)
lotSize /= g_GoldPipValueAdjustment; // Default: 12.0
// Apply loss reduction (OPPOSITE of Martingale - reduce after loss)
if(g_ConsecutiveLosses > 0 && g_ReduceAfterLoss)
lotSize *= MathPow(0.75, g_ConsecutiveLosses); // Reduce 25% per loss
// Normalize to broker's lot step and enforce min/max limits
double minLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MIN);
double maxLot = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_MAX);
double lotStep = SymbolInfoDouble(_Symbol, SYMBOL_VOLUME_STEP);
lotSize = MathMax(minLot, MathMin(maxLot, lotSize));
lotSize = MathRound(lotSize / lotStep) * lotStep;
return NormalizeDouble(lotSize, 2);
}
- Fixed Risk Per Trade: Risk percentage (1-2%) remains constant regardless of previous outcomes
- Position Size DECREASES After Losses: Line 26-27 shows 25% reduction per consecutive loss (opposite of Martingale)
- Equity-Based Calculation: Lot size is derived from current equity, automatically adjusting to account changes
- Always Uses Stop-Loss: Every trade has a defined risk level through mandatory stop-loss
3-Tier Stop-Loss System (MQL5 Implementation)
PMTS implements a three-tier protection system that prevents catastrophic losses at trade, daily, and account levels.
//+------------------------------------------------------------------+
//| Three-Tier Risk Protection System |
//| Provides layered protection at trade, daily, and account levels |
//+------------------------------------------------------------------+
bool CheckRiskGuard()
{
double equity = AccountInfoDouble(ACCOUNT_EQUITY);
double balance = AccountInfoDouble(ACCOUNT_BALANCE);
//--- TIER 1: Account-Level Circuit Breaker (15% max drawdown)
double accountDrawdown = ((g_PeakEquity - equity) / g_PeakEquity) * 100;
if(accountDrawdown >= g_MaxAccountDrawdown) // Default: 15%
{
CloseAllPositions("CIRCUIT BREAKER: Max account drawdown reached");
g_TradingHalted = true;
return false;
}
//--- TIER 2: Daily Loss Limit (5% daily max)
double dailyPL = CalculateDailyPL();
double dailyDrawdown = (MathAbs(dailyPL) / balance) * 100;
if(dailyPL < 0 && dailyDrawdown >= g_MaxDailyLoss) // Default: 5%
{
g_DailyTradingPaused = true;
Alert("Daily loss limit reached. Trading paused until next day.");
return false;
}
//--- TIER 3: Per-Trade Stop-Loss (ATR-based)
// Stop-loss is ALWAYS set on every trade, calculated as:
// SL Distance = ATR(50) * 2.0 (default multiplier)
// This ensures no trade can lose more than the calculated risk amount
// Update peak equity for drawdown tracking
if(equity > g_PeakEquity)
g_PeakEquity = equity;
return true; // All guards passed, trading allowed
}
//+------------------------------------------------------------------+
//| Calculate ATR-based Stop-Loss (ALWAYS required) |
//+------------------------------------------------------------------+
double CalculateStopLoss(ENUM_ORDER_TYPE orderType, double entryPrice)
{
// Get ATR value (50-period by default)
double atr = iATR(_Symbol, PERIOD_H1, g_ATRPeriod); // Default: 50
// Calculate SL distance (2x ATR for gold volatility)
double slDistance = atr * g_ATRMultiplier; // Default: 2.0
// Apply SL in correct direction
if(orderType == ORDER_TYPE_BUY)
return entryPrice - slDistance;
else
return entryPrice + slDistance;
}
PMTS vs. Martingale Comparison
| Aspect | Martingale (Dangerous) | PMTS (Fixed Risk) |
|---|---|---|
| After Loss | DOUBLE position size | REDUCE position size by 25% |
| Stop-Loss | Often none (wait for reversal) | ALWAYS required (ATR-based) |
| Maximum Risk | Unlimited (can wipe account) | Capped at 2% per trade, 15% total |
| Position Growth | Exponential (2x, 4x, 8x, 16x...) | Linear, proportional to equity |
| Consecutive Losses | 6-7 losses = total account loss | Survives 50+ consecutive losses |
| Circuit Breaker | None | 3-tier protection (trade/daily/account) |
Sistema de Proteção Híbrido
O Sistema de Proteção Híbrido é um mecanismo de gerenciamento de stop-loss multinível que progressivamente trava lucros à medida que as posições se movem favoravelmente. Diferente de trailing stops simples, este sistema implementa níveis de proteção discretos que ativam em limites de lucro específicos.
| Nível | Gatilho (Pips) | Proteção | Ação |
|---|---|---|---|
| Level 1 | +30 | Breakeven | Mover SL para preço de entrada + 0.2 pips de buffer |
| Level 2 | +50 | +20 pips | Travar 20 pips de lucro |
| Level 3 | +80 | +40 pips | Travar 40 pips de lucro |
| Level 4 | +120 | Trailing 50 | Ativar trailing stop a 50 pips de distância |
O Sistema de Proteção Híbrido apenas move stop-losses na direção favorável (mais alto para posições BUY). Ele nunca diminui a proteção uma vez estabelecida.
Sistema de Escalonamento
O Sistema de Escalonamento opcional implementa uma estratégia de progressão de lotes controlada projetada para recuperar de perdas consecutivas. Quando habilitado, ele dobra o tamanho do lote após cada perda até um máximo de 3 níveis (2x, 4x, 8x), então expande as distâncias de stop-loss e take-profit se as perdas continuarem.
Progressão de Lotes
Loss 0: 0.01 lots (normal trading) Loss 1: 0.02 lots (x2 multiplier) Loss 2: 0.04 lots (x4 multiplier) Loss 3: 0.08 lots (x8 multiplier - max) Loss 4+: 0.08 lots + expanded TP/SL
O Sistema de Escalonamento aumenta significativamente a exposição ao risco. Ele está desabilitado por padrão (UseScalingSystem = false) e só deve ser habilitado por traders experientes que entendem as implicações da progressão estilo martingale.
Especialização XAUUSD
O PMTS é especificamente projetado e otimizado para negociação de ouro (XAUUSD). O sistema recusa inicializar em qualquer outro símbolo, garantindo que todos os parâmetros e lógica sejam aplicados em seu contexto pretendido.
Características do Mercado de Ouro
- Valor de Pip Mais Alto: Ouro tipicamente tem 10x o valor de pip de pares forex principais, requerendo ajuste de tamanho de lote
- Sensibilidade de Sessão: Ação de preço varia significativamente entre sessões Asiática, Londres e NY
- Correlação com USD: Forte correlação inversa com força do dólar americano
- Reatividade a Notícias: Altamente sensível a lançamentos de dados FOMC, NFP e inflação
Ajustes Específicos para Ouro
| Aspecto | Ajuste |
|---|---|
| Dimensionamento de Lote | Dividido por GoldPipValueAdjustment (12.0) para normalizar risco |
| Limites de Volatilidade | Faixa mais ampla (0.8-2.5) com multiplicador de penalidade adicional de 1.7x |
| Limites de Spread | Spread máximo definido em 5.0 pips para execução |
| Buffer de Margem | 50% de margem extra requerida antes da colocação de ordem |
Negociação Baseada em Sessões
O ouro exibe padrões comportamentais distintos em diferentes sessões de negociação globais. O PMTS monitora continuamente a sessão atual e aplica multiplicadores apropriados tanto para pontuação de sinais quanto para parâmetros de risco.
| Sessão | Horários (GMT) | Multiplicador | Bônus de Pontuação |
|---|---|---|---|
| Asian | 00:00 - 08:00 | 0.7x | -10 |
| London | 08:00 - 16:00 | 1.2x | +10 |
| London/NY Overlap | 13:00 - 16:00 | 1.43x | +15 |
| New York | 13:00 - 20:00 | 1.3x | +10 |
| Late NY | 20:00 - 24:00 | 0.8x | +5 |
Endpoints da API
O PMTS inclui uma API REST que fornece análise de mercado em tempo real e sinais de negociação. A API agrega dados de múltiplas fontes incluindo indicadores técnicos, eventos fundamentais e análise de sentimento.
GET /api/analysis/{symbol}
GET /api/analysis/{symbol}/signal.json
GET /api/dashboard/accounts
GET /api/dashboard/sync
Supported: XAUUSD, EURUSD, GBPJPY, USDJPY, BTCUSD, ETHUSD...
Formato JSON de Sinais
{
"symbol": "XAUUSD",
"signal": "BUY",
"confidence": 72,
"entry_price": 2645.50,
"stop_loss": 2632.80,
"take_profit_1": 2658.20,
"risk_reward": "1.5:1"
}
Resultados de Backtesting
Backtesting abrangente foi realizado usando o Strategy Tester do MetaTrader 5 com dados tick-by-tick de múltiplos provedores de liquidez. Os resultados a seguir representam conjuntos de parâmetros otimizados validados através de análise walk-forward.
Desempenho passado não garante resultados futuros. Resultados de backtesting podem não refletir condições reais de negociação incluindo slippage, requotes e condições variáveis de spread.
Métricas de Desempenho (2019-2024)
| Métrica | Valor | Benchmark da Indústria |
|---|---|---|
| Retorno Anual | 47.3% | 15-25% |
| Índice de Sharpe | 1.89 | > 1.0 |
| Taxa de Acerto | 64.2% | 50-60% |
| Fator de Lucro | 1.87 | > 1.5 |
| Drawdown Máximo | 12.8% | < 20% |
| Fator de Recuperação | 4.2 | > 3.0 |
AI Analysis Engine Overview
The PMTS AI Analysis Engine represents the cutting-edge of institutional-grade market analysis. Unlike basic systems that rely on a handful of indicators with synthetic data, our engine processes real-time data from multiple professional sources, combining Technical, Fundamental, and Sentiment analysis through an intelligent orchestration layer that mimics how professional institutional traders approach the market.
The system operates with a conservative, high-quality signal approach. Every trading signal must pass through multiple validation filters before being presented to the user. This ensures that only high-probability setups with strong confluences across multiple analysis dimensions are recommended.
The AI Engine processes 15+ technical indicators across 4 timeframes, integrates real-time news sentiment, macroeconomic data from FRED, Fear & Greed indices, and whale activity tracking to generate signals with calculated confidence scores ranging from 0-100%.
System Architecture
| Component | Function | Output |
|---|---|---|
| TechnicalAnalysis.php | Multi-timeframe indicator analysis, market structure detection, Fibonacci levels | Score 0-100, Signal direction |
| FundamentalAnalysis.php | Economic calendar, real-time news with NLP sentiment, macro data integration | Score 0-100, Event warnings |
| SentimentAnalysis.php | Fear & Greed Index, social sentiment, whale tracking, COT positioning | Score 0-100, Market mood |
| DataSources.php | API wrapper for Binance, Finnhub, FRED, Alternative.me, Yahoo Finance, and more | Real-time market data |
| Analysis.php | Orchestrates all modules, applies dynamic weights, calculates final confidence | Final signal + confidence |
Multi-Timeframe Analysis
Professional traders never rely on a single timeframe. The AI Engine simultaneously analyzes 4 timeframes to ensure confluence and validate trade setups. Each timeframe serves a specific purpose in the analysis hierarchy, with weighted contributions to the final signal.
| Timeframe | Weight | Purpose |
|---|---|---|
| 1H (Hourly) | 20% | Precise entry timing and immediate momentum detection |
| 4H (4-Hour) | 30% | Intermediate trend confirmation and pattern validation |
| 1D (Daily) | 35% | Primary market direction and key support/resistance levels |
| 1W (Weekly) | 15% | Macro bias and long-term trend context |
Confluence Requirements
The system requires minimum confluence thresholds before generating actionable signals:
- STRONG Signal: 4/4 timeframes aligned in the same direction - highest confidence trades
- GOOD Signal: 3/4 timeframes aligned (weekly may differ) - high probability setups
- WEAK Signal: 2/4 timeframes aligned - lower confidence, requires additional confirmation
- NEUTRAL: Less than 2 timeframes aligned - no signal generated, market is choppy
Advanced Technical Indicators
Beyond standard indicators, the AI Engine implements institutional-grade technical analysis tools that provide deeper market insight:
Ichimoku Cloud (Full Implementation)
The complete Ichimoku Kinko Hyo system provides 5 key components for comprehensive trend analysis:
| Component | Calculation | Signal Interpretation |
|---|---|---|
| Tenkan-sen | (9-period High + Low) / 2 | Conversion line - short-term momentum |
| Kijun-sen | (26-period High + Low) / 2 | Base line - medium-term trend direction |
| Senkou Span A | (Tenkan + Kijun) / 2, plotted 26 ahead | Leading span A - first cloud boundary |
| Senkou Span B | (52-period High + Low) / 2, plotted 26 ahead | Leading span B - second cloud boundary |
| Chikou Span | Close price plotted 26 periods back | Lagging span - trend confirmation |
Additional Advanced Indicators
| Indicator | Description |
|---|---|
| TEMA (Triple EMA) | Reduces lag significantly compared to standard EMA, providing faster trend detection |
| RSI Divergence Detection | Automatically detects bullish and bearish divergences for reversal signals |
| Bollinger Bands | Volatility-based bands identifying overbought/oversold and squeeze conditions |
| Stochastic Oscillator | Momentum indicator identifying extreme zones and potential reversals |
| ADX (Average Directional Index) | Measures trend strength (0-100), used for dynamic weight adjustments |
| Pivot Points | Daily and weekly pivot levels with R1-R3 and S1-S3 support/resistance zones |
| Fibonacci Retracements | Auto-calculated levels at 0.236, 0.382, 0.5, 0.618, 0.786 from swing points |
Market Structure Detection
The engine automatically identifies market structure patterns that professional traders use:
- Higher Highs / Higher Lows (HH/HL): Confirmed uptrend structure
- Lower Highs / Lower Lows (LH/LL): Confirmed downtrend structure
- Break of Structure (BOS): Trend continuation confirmation
- Change of Character (ChoCH): Potential trend reversal signal
Real-Time Data Sources
The AI Engine integrates with multiple professional data sources to ensure accuracy and reliability. All price data is real-time, not synthetic or simulated.
| Category | Source | Data Provided |
|---|---|---|
| Crypto Prices | Binance API | Real-time candles, multi-timeframe OHLCV |
| Forex/Stocks | Finnhub + Yahoo Finance | Real-time quotes, historical data |
| Gold (XAUUSD) | Swissquote + Forex APIs | Live spot prices with tight spreads |
| Fear & Greed Index | Alternative.me (Official) | Crypto fear/greed 0-100, updated daily |
| Macro Economics | FRED API (Federal Reserve) | Fed Funds Rate, 10Y Treasury, Inflation |
| News Sentiment | Finnhub + Finlight.me | Real-time news with NLP sentiment scoring |
| Whale Tracking | ClankApp | Large crypto transactions monitoring |
| COT Reports | CFTC Public Data | Institutional positioning (weekly) |
| Options Flow | VIX-based Estimation | Put/Call ratio for sentiment analysis |
| Social Sentiment | Twitter/X + Reddit | Gold-specific social sentiment from financial communities |
All data sources are validated in real-time. If any API fails or returns invalid data, the system automatically falls back to secondary sources or synthetic estimation with a confidence penalty applied to the final score.
Confidence Calculation System
The confidence score (0-100%) is calculated through a sophisticated bonus/penalty system that evaluates multiple market factors. This score directly influences whether a signal is presented and how it should be weighted in trading decisions.
Confidence Bonuses (+)
| Factor | Bonus | Condition |
|---|---|---|
| Timeframe Confluence | +20% | 4/4 timeframes aligned |
| Indicator Agreement | +15% | 80%+ indicators confirm direction |
| Real Data Quality | +10% | All APIs returning real data |
| No Disruptive Events | +10% | No high-impact news in 4 hours |
| Extreme Sentiment Confirms | +15% | Fear/Greed at extremes aligning with signal |
| Clear Market Structure | +15% | HH/HL or LH/LL pattern confirmed |
| Fibonacci Zone | +15% | Price at key Fib level (0.618, 0.5, 0.382) |
| COT Confirms | +10% | Institutional positioning aligns |
| Whale Activity | +10% | Bullish whale activity for BUY signals |
Confidence Penalties (-)
| Factor | Penalty | Condition |
|---|---|---|
| Synthetic Data Used | -20% | Real API unavailable, using estimates |
| Counter-Trend Trade | -15% | Signal against daily trend |
| Upcoming High-Impact Event | -10% | FOMC, NFP, CPI within 4 hours |
| Indicator Conflict | -10% | Significant indicator disagreement |
| Extreme Sentiment Against | -15% | Fear/Greed against signal direction |
| High Volatility | -10% | VIX > 25 or extreme ATR |
| Low TF Confluence | -15% | Less than 3 timeframes aligned |
Dynamic Weight System
The base analysis weights (Technical: 40%, Fundamental: 35%, Sentiment: 25%) are dynamically adjusted based on market conditions:
- High VIX (>25): Technical weight +10% (volatility favors technical analysis)
- Strong Trend (ADX>25): Technical weight +10% (trending markets are more technical)
- Pre-Event (4h): Fundamental weight +15% (macro events dominate)
- Extreme Sentiment: Sentiment weight +10% (extreme readings are predictive)
- COT Extreme: Sentiment weight +5% (institutional positioning matters)
Intelligent Risk Management
The AI Engine calculates precise entry, stop-loss, and take-profit levels based on market structure rather than arbitrary fixed distances. This approach ensures that stops are placed at logical levels where the trade thesis would be invalidated.
Structure-Based Stop Loss
Stop-loss placement follows a priority hierarchy:
- SWING_LOW/HIGH: Below last swing low (BUY) or above last swing high (SELL) - most reliable
- FIBONACCI: Below/above key Fibonacci level (0.786 or 0.618) - strong confluence
- PIVOT: At nearby daily pivot support/resistance level
- ATR_BASED: Fallback calculation at 1.5x ATR from entry - when structure unclear
Multiple Take Profit Levels
The system provides three take-profit levels with recommended position allocation:
| Level | Target Calculation | Allocation | Typical R:R |
|---|---|---|---|
| TP1 | Next resistance/support or 1.5x risk distance | 50% | 1.5:1 |
| TP2 | Fibonacci extension or 2.5x risk distance | 30% | 2.5:1 |
| TP3 | Major structure level or 4x risk distance | 20% | 4:1 |
The multi-TP approach allows traders to secure profits progressively while letting winners run. The 50/30/20 allocation ensures a portion of profit is locked in early while maintaining exposure for larger moves.
Signal Validation Filters
Before any signal is presented, it must pass through these validation filters (Conservative Mode):
- At least 3 of 4 timeframes must align with signal direction
- Daily trend must not contradict the signal
- No HIGH impact economic events in the next 4 hours
- At least 2 of 3 analysis types (Technical/Fundamental/Sentiment) must agree
- Market structure must confirm (HH/HL for BUY, LH/LL for SELL)
- RSI must not be at extremes against the signal (no BUY at RSI>80)
- Calculated confidence must be >= 55%
If a signal fails validation filters, the system will either downgrade it to WEAK signal with a warning, or return NEUTRAL with an explanation of why no trade is recommended.
AI Master Intelligence (GPT)
The crown jewel of PMTS is the AI Master Intelligence system, powered by OpenAI's GPT model. This advanced neural network acts as the final decision-maker, synthesizing all analysis layers into a coherent, actionable trading recommendation with unprecedented precision and contextual understanding.
The AI Master processes technical indicators, fundamental data, sentiment metrics, and reversal signals through a sophisticated prompt engineering system, generating human-readable summaries with institutional-grade precision and multilingual support (English/Spanish).
Multi-Layer Analysis Architecture
The AI Master receives pre-processed data from five specialized analysis modules, each contributing unique market insights:
Intelligent Output Generation
The AI Master generates comprehensive analysis summaries that include:
- Market Context: Current market conditions, key levels, and dominant trends
- Signal Justification: Clear reasoning for the BUY/SELL/NEUTRAL recommendation
- Risk Assessment: Potential risks and factors that could invalidate the signal
- Confidence Breakdown: Contribution of each analysis layer to the final score
- Actionable Levels: Precise entry, stop-loss, and multiple take-profit levels
Multilingual Intelligence
The AI Master supports full internationalization, generating complete analysis summaries in the user's preferred language. The system currently supports English and Spanish, with the language parameter passed through the entire analysis chain to ensure consistent localization.
| Feature | Implementation |
|---|---|
| Language Detection | API parameter (?lang=en or ?lang=es) with localStorage persistence |
| AI Response | GPT generates full analysis in requested language natively |
| Cache System | Language-aware caching with separate cache entries per language |
| UI Integration | Seamless language switching without page reload |
News Impact Power System
Not all news is created equal. A headline about a minor central bank comment differs vastly from an unexpected Fed rate decision or major economic data surprise. The News Impact Power System quantifies the market-moving potential of each news article on a 0-100% scale, enabling the AI to differentiate between routine market noise and truly significant events.
Impact Power Scale (0-100%)
| Category | Range | Examples |
|---|---|---|
| CRITICAL | 85-100% | Emergency Fed rate decisions, major banking crises, sovereign debt defaults, unexpected central bank interventions |
| HIGH | 65-84% | FOMC rate decisions (unexpected), major earnings misses, geopolitical escalations |
| MEDIUM | 40-64% | Economic data releases (CPI, NFP), scheduled rate decisions (as expected), earnings in-line |
| LOW | 20-39% | Analyst upgrades/downgrades, minor policy comments, routine economic indicators |
| MINIMAL | 0-19% | Market commentary, opinion pieces, routine corporate announcements |
Weighted Score Calculation
Each news article generates a weighted score combining direction, impact power, and confidence:
weighted_score = direction × impact_power × confidence Where: direction = +1 (BULLISH), -1 (BEARISH), 0 (NEUTRAL) impact_power = 0 to 100 (percentage of market-moving potential) confidence = 0 to 1 (AI confidence in sentiment analysis) Examples: "Fed announces surprise 50bp rate cut" → BULLISH for Gold direction = +1, impact_power = 78%, confidence = 0.92 weighted_score = 1 × 78 × 0.92 = +71.76 (strongly bullish) "US CPI comes in higher than expected at 3.4%" → BEARISH for Gold (short-term) direction = -1, impact_power = 55%, confidence = 0.85 weighted_score = -1 × 55 × 0.85 = -46.75 (moderately bearish) "ECB holds rates steady as expected" → NEUTRAL direction = 0, impact_power = 35%, confidence = 0.90 weighted_score = 0 × 35 × 0.90 = 0 (no directional impact)
Net Weighted Score
The system aggregates all news articles into a single Net Weighted Score, providing an overall market sentiment reading:
- Strong Bullish (>50): Multiple high-impact bullish news dominate
- Moderate Bullish (20-50): Bullish bias with mixed signals
- Neutral (-20 to 20): Balanced news flow or low-impact news only
- Moderate Bearish (-50 to -20): Bearish bias with mixed signals
- Strong Bearish (<-50): Multiple high-impact bearish news dominate
A minor Fed comment about "watching inflation closely" might score 25% impact power, while breaking news of an emergency rate cut would score 90%+. This differentiation ensures the AI responds proportionally to the true significance of market events.
Reversal Detection System
Trend reversals represent the highest-reward trading opportunities in financial markets. The PMTS Reversal Detection System employs a multi-factor confluence analysis to identify potential trend reversals before they occur, combining price action, momentum, volume, and pattern recognition.
Reversal Detection Factors
| Detection Factor | Weight | Description |
|---|---|---|
| RSI Divergence | 25% | Price makes new high/low while RSI fails to confirm - classic reversal signal |
| MACD Crossover | 20% | Signal line crossovers at extreme levels indicate momentum shift |
| Bollinger Band Extreme | 15% | Price touches or exceeds outer bands suggesting overextension |
| Stochastic Crossover | 15% | %K/%D crossover in overbought/oversold zones |
| Candlestick Patterns | 15% | Engulfing, hammer, doji, and other reversal candlestick formations |
| Volume Analysis | 10% | Unusual volume spikes often precede major reversals |
Reversal Probability Calculation
The system calculates a reversal probability percentage (0-100%) based on the confluence of detected factors:
- 75-100%: HIGH reversal probability - Multiple strong signals confirm potential reversal
- 50-74%: MODERATE probability - Some reversal signals present, caution advised
- 25-49%: LOW probability - Few reversal signals, trend likely to continue
- 0-24%: MINIMAL probability - No significant reversal signals detected
Integration with AI Master
Reversal detection data feeds directly into the AI Master for final synthesis:
- Signal Modification: High reversal probability can upgrade NEUTRAL to cautionary signal
- Risk Adjustment: Reversal warnings trigger tighter stop-loss recommendations
- Confidence Impact: Conflicting trend/reversal signals reduce overall confidence score
- Summary Inclusion: AI Master explicitly mentions reversal potential in analysis summary
Reversal detection is inherently predictive and carries higher risk than trend-following signals. The system provides reversal probabilities as additional context, not as standalone trading signals. Always wait for confirmation before acting on reversal indications.