20

📋 Regras de trading

Regras de trading automáticas e alertas

1. O que são Regras de Trading?

Regras de trading são condições predefinidas que ajudam você a negociar de forma disciplinada. O sistema monitora automaticamente suas posições e envia alertas quando uma regra é acionada. Assim você nunca esquece uma ação importante.

O Sistema de Regras de Trading:
• Lembra automaticamente de regras importantes
• Avisa sobre violações de limites de risco
• Ajuda a documentar e analisar o cumprimento das regras
• Suporta diferentes estilos de trading (opções, ações, etc.)

2. Por que as Regras são Importantes?

A maioria dos traders tem regras na cabeça, mas as esquece no calor do momento. Exemplo: "Fechar com 50% de lucro" - mas então você espera mais e perde a saída. As regras de trading lembram você automaticamente!

"Planeje seu trade, execute seu plano" - Com o sistema de regras, esse princípio se torna realidade.

Arquitetura: As Duas Dimensões

O sistema de regras é baseado em duas dimensões fundamentais:

┌─────────────────────────────────────────────────────────────────┐
│                        DIMENSÕES DA REGRA                       │
├─────────────────────────────────────────────────────────────────┤
│                                                                 │
│  FONTE                         ESCOPO (Aplicabilidade)          │
│  ┌──────────────┐              ┌──────────────────────────┐    │
│  │ Sistema      │              │ 🎯 Posição               │    │
│  │ (Predefinido)│              │    Uma posição           │    │
│  ├──────────────┤              │    específica            │    │
│  │ Usuário      │              ├──────────────────────────┤    │
│  │ (Personaliz.)│              │ 🏦 Conta                 │    │
│  └──────────────┘              │    Uma conta de          │    │
│                                │    corretora             │    │
│                                ├──────────────────────────┤    │
│                                │ 💼 Portfólio             │    │
│                                │    Todas as contas       │    │
│                                └──────────────────────────┘    │
│                                                                 │
└─────────────────────────────────────────────────────────────────┘

4. Dimensão 1: Fonte da Regra

🔧 Predefinições do Sistema
Regras predefinidas do sistema que você pode ativar com um clique. Estas são baseadas em práticas de trading comprovadas e mantidas pela equipe do Singularity Trader.

Exemplos:
• "Lucro de 50%" - Fechar com 50% do lucro máximo
• "Gestão de 21 DTE" - Avisar com 21 dias restantes
• "Stop Loss de 200%" - Fechar com perda 2x o prêmio

✏️ Definidas pelo Usuário (Personalizadas)
Suas próprias regras que você cria para corresponder exatamente ao seu estilo de trading. Você define o nome, condição e ação você mesmo.

5. Dimensão 2: Escopo (Aplicabilidade)

Cada regra tem um escopo que determina a quais posições ela se aplica:

EscopoRegra de ExemploCaso de Uso
🎯 Posição"Vender esta posição AAPL em +20%"Plano individual de trade
🏦 Conta"Máx. 30% do poder de compra nesta conta"Conta IRA conservadora
💼 Portfólio"Nunca mais de 5% em uma posição"Regra geral de risco

6. 🎯 Regras de Posição em Detalhes

Regras de posição se aplicam a uma posição específica. Elas permitem que você defina um plano individual para cada trade.

Regras de Posição Típicas:
• Preço Stop-Loss - ex.: "Vender se o preço cair abaixo de $150"
• Meta de Take-Profit - ex.: "Fechar em +20%"
• Baseado em DTE - ex.: "Fechar em 14 DTE"
• Aviso de ITM - ex.: "Fazer roll se a opção for ITM"
• Plano individual de trade

Caso de Uso: Você abre um trade e imediatamente define quando fechar ou ajustar. O sistema lembra você quando a condição é atendida.

7. 🏦 Regras de Conta em Detalhes

Regras de conta se aplicam a uma conta de corretora. Elas ajudam você a executar diferentes estratégias por conta.

Regras de Conta Típicas:
• % Máximo de Uso do Poder de Compra - ex.: "Nunca acima de 50%"
• Máximo de Posições Abertas - ex.: "Máx. 10 posições"
• Classes de Ativos Permitidas - ex.: "Somente ações, sem opções"
• Tamanho Máximo de Posição nesta conta
• Regras de margem específicas da conta

Caso de Uso: Você tem uma conta IRA conservadora e uma conta de trading agressiva. As regras de conta garantem que você siga diferentes perfis de risco.

8. 💼 Regras de Portfólio em Detalhes

Regras de portfólio se aplicam em todas as contas. Elas protegem seu patrimônio total.

Regras de Portfólio Típicas:
• Limite de Exposição Total - ex.: "Máx. 200% do capital"
• Diversificação por Setor - ex.: "Máx. 20% em Tecnologia"
• Tamanho Máximo de Posição (total) - ex.: "Máx. 5% em uma ação"
• Limites de Correlação - ex.: "Aviso se trades similares demais"
• Regras gerais de risco

Caso de Uso: Não importa quantas contas você tem, essas regras garantem que seu portfólio total permaneça seguro.

9. Categorias de Regras

As regras são organizadas por categoria com base em quando se aplicam:

📥 Regras de Entrada (antes de abrir)
Verificações antes de abrir uma posição:
• Entrada com 45 DTE - Opções com ~45 dias restantes
• Delta 0.30 - Short puts no delta 0.30
• IV Rank > 50 - Apenas vender quando IV está alto
• Evitar Resultados - Sem trades sobre resultados

📤 Regras de Saída/Gestão
Quando fechar ou ajustar posições:
• Lucro de 50% - Fechar com 50% do ganho máximo
• Gestão de 21 DTE - Avisar com 21 dias restantes
• Stop Loss de 200% - Fechar com perda 2x o prêmio
• Roll no ITM

⚠️ Regras de Risco
Limites em todo o portfólio:
• Regra de 1-2% - Risco máximo por trade
• Tamanho de Posição de 5% - Máximo por posição
• Poder de Compra de 50% - Nunca exceder

🧠 Regras de Psicologia
Proteção contra trading emocional:
• 3 Perdas = Pausa
• Sem Revenge Trading
• Planejar Antes do Trade

10. Arquitetura do Sistema: O Motor de Regras

O motor de regras é o coração do sistema. Ele monitora continuamente todas as suas posições e verifica se as regras são acionadas:

┌─────────────────────────────────────────────────────────────────┐
│                        MOTOR DE REGRAS                          │
├─────────────────────────────────────────────────────────────────┤
│  Definição de Regra (Admin/Usuário)                             │
│  • Nome, Descrição                                              │
│  • Tipo: Entrada / Saída / Gestão / Risco                       │
│  • Condição (ex.: DTE <= 21)                                    │
│  • Ação: Alerta / Aviso / Bloqueio                              │
│  • Tipo de Ativo: Opção / Ação / Todos                          │
│  • Escopo: Posição / Conta / Portfólio                          │
├─────────────────────────────────────────────────────────────────┤
│                              ↓                                  │
│  ┌───────────┐  ┌───────────┐  ┌───────────┐  ┌───────────┐    │
│  │ Dashboard │  │   Lista   │  │  Verif.   │  │  Sistema  │    │
│  │  Widget   │  │  Obs.Sig. │  │  Entrada  │  │  Alertas  │    │
│  └───────────┘  └───────────┘  └───────────┘  └───────────┘    │
└─────────────────────────────────────────────────────────────────┘

O motor verifica regularmente todas as regras ativas e aciona a ação apropriada quando as condições são atendidas.

11. Integração na Plataforma

As regras de trading são integradas em vários lugares na plataforma:

PáginaIntegração
DashboardWidget "Ação Necessária" com alertas de regras ativas
Detalhe de PosiçãoMostrar regras ativas para esta posição
Entrada de TradeVerificação antes de abrir (regras de risco)
Lista de ObservaçãoColuna de sinais baseada em regras de entrada
NotificaçõesPush/E-mail quando regra aciona
Diário de TradingPontuação de cumprimento de regras por trade

12. Tipos de Condição

Estes tipos de condição estão disponíveis para regras:

TipoDescriçãoAtivo
PROFIT_PCTLucro em %Todos
LOSS_PCTPerda em %Todos
DTEDias até ExpiraçãoOpções
DELTAValor DeltaOpções
IV_RANKIV Rank/PercentilOpções
POSITION_SIZE_PCTPosição > X% do portfólioRisco
BUYING_POWER_PCTUso do BP > X%Risco
EARNINGS_DTEResultados em X diasTodos

13. Status: Conceito

⚠️ Nota: O sistema de Regras de Trading está atualmente em fase de conceito. Os recursos descritos aqui serão implementados em versões futuras.

Seu feedback é bem-vindo para ajudar a moldar os recursos de forma otimizada! A documentação técnica detalhada pode ser encontrada em docs/concepts/TRADING-RULES.md.

14. UI Preview: Create a Custom Rule

Here is how to create your own individual rule:

┌─────────────────────────────────────────────────────────┐
│ ➕ New Rule                                              │
├─────────────────────────────────────────────────────────┤
│                                                         │
│ Name: [My Stop-Loss Rule____________________]           │
│                                                         │
│ Scope:                                                  │
│ ○ 💼 Portfolio (all accounts)                          │
│ ● 🏦 Account: [Interactive Brokers ▼]                  │
│ ○ 🎯 Position: [Select position...]                    │
│                                                         │
│ When:                                                   │
│ [Loss %_____▼] [>=] [15__] [%]                         │
│                                                         │
│ Then:                                                   │
│ [🔔 Send Alert___▼]                                    │
│                                                         │
│ Asset Type: ○ All  ● Stocks  ○ Options                 │
│                                                         │
│              [Cancel]  [💾 Save]                       │
└─────────────────────────────────────────────────────────┘

You define: Name, Scope, Condition (When…), Action (Then…) and Asset Type.

15. UI Preview: Dashboard Widget "Action Required"

On the dashboard you see all positions where a rule has been triggered:

┌─────────────────────────────────────────────────────────┐
│ ⚠️ Action Required (3)                                  │
├─────────────────────────────────────────────────────────┤
│                                                         │
│ 🟡 AAPL 180 PUT         50% profit reached (52%)       │
│    Rule: 50% Profit Take                                │
│    [Close] [Ignore]                                     │
│                                                         │
│ 🔴 MSFT 400 CALL        21 DTE reached (18 days)       │
│    Rule: 21 DTE Management                              │
│    [Roll] [Close] [Ignore]                              │
│                                                         │
│ 🟡 TSLA Stock           Stop-loss nearly reached (-9%) │
│    Rule: 10% Stop-Loss                                  │
│    [Sell] [Adjust Stop] [Ignore]                        │
│                                                         │
└─────────────────────────────────────────────────────────┘

Each alert shows: Symbol, rule name, current value, and action buttons. The color (🟡 yellow, 🔴 red) indicates urgency.

16. UI Preview: Position Detail with Rules

In the detail view of a position you see which rules are active:

┌─────────────────────────────────────────────────────────┐
│ AAPL 180 PUT 2025-01-17                                 │
├─────────────────────────────────────────────────────────┤
│ ...Position Details...                                  │
│                                                         │
│ 📋 RULES FOR THIS POSITION                             │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ ✅ Portfolio: 50% Profit Take (active)             │ │
│ │ ✅ Portfolio: 21 DTE Management (active)           │ │
│ │ ➕ Add rule for this position...                    │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────────────────────────────────────────┘

You see all rules that apply to this position (portfolio-wide, account-wide, or position-specific). With ➕ you can directly create a new rule for this position.

17. Condition Types

The following condition types are available for rules:

TypeDescriptionAsset
PROFIT_PCTProfit in %All
LOSS_PCTLoss in %All
DTEDays to ExpirationOptions
DELTADelta valueOptions
IV_RANKIV Rank/PercentileOptions
POSITION_SIZE_PCTPosition > X% of portfolioRisk
BUYING_POWER_PCTBP Usage > X%Risk
EARNINGS_DTEEarnings in X daysAll

18. Data Architecture (Simplified)

For the technically curious: the system stores rules in three tables:

1. trading_rule_presets (System Presets)
Admin-defined rules that all users can enable.

2. user_trading_rules (User Rules)
Contains activated presets and custom rules for each user, with scope assignment.

3. trading_rule_triggers (Trigger Log)
Logs when which rule was triggered and how the user responded (closed, ignored, etc.).

This structure enables:
• Fast checking of all active rules
• Analysis of rule compliance over time
• Compliance reporting in the trade journal

19. Wheel Strategy Rules

For the popular Wheel Strategy there are special rules:

RuleDescription
Only Stocks You Want to OwnOnly run the Wheel on stocks you would hold long-term
Cash-SecuredAlways keep enough cash for assignment
CC at ResistancePlace Covered Calls at technical resistance
CC Not Below Cost BasisNever sell Covered Calls below your purchase price

20. Implementation Phases

The Trading Rules system will be developed in phases:

Phase 1: Foundation
• Create database tables
• Define system presets
• Admin page for preset management

Phase 2: User Rules
• User rules UI
• Activation of system presets
• Create custom rules

Phase 3: Rule Engine
• Automatic checking of all rules
• Trigger detection
• Logging of all activations

Phase 4: Alerts & Notifications
• Dashboard widget "Action Required"
• Email notifications
• Push notifications (optional)

Phase 5: Integration
• Position detail: show active rules
• Trade entry: risk checks
• Trade journal: compliance analysis

21. Open Questions & Feedback

We want to design the system optimally and welcome your feedback on these questions:

1. Auto-Execution: Should rules also be able to execute trades automatically (e.g., auto-close)?

2. Check Interval: How often should the rule engine run (real-time vs. every 5 min vs. hourly)?

3. Community Rules: Should rules be shareable between users?

4. Which Presets: Which rules should be included as system presets?

Send your feedback to the support team or in the forum!

Status: Concept

⚠️ Note: The Trading Rules system is currently in concept phase. The features described here will be implemented in future versions.

Your feedback is welcome to help shape the features optimally! Detailed technical documentation can be found at docs/concepts/TRADING-RULES.md.

23. Trading Lights — Traffic Light System Before the Trade

Trading Lights is your market status dashboard in green/yellow/red. You'll find it on the dashboard and as a sidebar widget. It shows at a glance whether current market conditions are favorable for new trades.

What is displayed?
Three categories, each with its own traffic light (green/yellow/red):

Macro Environment — Fear & Greed Index, VIX, and NYSE Market Breadth as a third indicator (see next section).
Sector Context — your underlying's sector compared to the overall market (RSI, SMA200 status).
Underlying Status — the specific market you're looking at (trend, volatility, recent movements).

Majority logic instead of "worst indicator wins": Each category summarizes its indicators by majority — if 2 of 3 are green, the category is green. This prevents a single red outlier from negating an entire category.

Clicking on a traffic light opens a modal with beginner-friendly explanations for each indicator — what the value means, how it compares historically, and what actions are suggested.

24. NYSE Market Breadth — "How Many Stocks Are Actually Rising?"

Market breadth measures whether a market move is driven by many stocks or just a few heavyweights. An S&P 500 rising because 7 mega-caps are up is less healthy than one rising because 400 stocks are up.

Singularity Trader automatically calculates four NYSE breadth indicators every 3 hours:

A/D Ratio (Advance/Decline) — ratio of advancing to declining stocks on the NYSE. Values > 2.0 = broadly supported rally; < 0.5 = broad selloff.
McClellan Oscillator — smoothed breadth momentum indicator. Positive = broad upward thrust, negative = broad downward thrust. Zero-line crossings are classic signals.
NYSE > 50d MA — percentage of NYSE stocks above their 50-day average. > 70% = hot (risk of overheating), < 30% = cold (potential setup environment).
High/Low Ratio — ratio of new 52-week highs to lows. Divergences from the index are often early warning signals.

Where you see this:
• In the Trading Lights modal as the third macro indicator
• In the Markets tab as its own metric row
• On the dashboard under "Market Context"
• As a detail heatmap on the market analysis page

In one sentence: Breadth green = "The market is carrying you"; breadth red = "You're swimming against the current".

25. COT Analysis — What the Big Players Are Actually Doing

The COT Report (Commitments of Traders) is published weekly by the CFTC and shows net positions of large institutional traders in futures markets. Singularity Trader imports this data automatically and presents it in structured form.

Why is this interesting?
If Commercial Hedgers (e.g., gold mines, oil companies) are rarely this long historically — it's often a signal they expect a bottom. If Large Speculators are extremely bullish, a trend reversal is often imminent.

What you'll find:
Heatmap overview — all available futures markets (Gold, Oil, S&P, EUR, Bitcoin, …) with their current COT status
COT Index (52 weeks) — normalized: 0% = extreme bearish, 100% = extreme bullish in 1-year history
Detail view per market — historical charts of Commercial, Large Speculator, and Small Trader positions with price chart overlay
Related instruments — e.g., Gold COT also shows Silver, Platinum, GLD ETF flows
Signal labels — "Commercial Extreme Long" / "Speculator Extreme Short" etc., when a market hits its 5-year extreme

Data is updated every Friday evening (after CFTC release). Accessible via sidebar Market Analysis → COT.