# Sailar-x AI brain (Groq + Gemini)

The brain is an AI analyst that sits next to your rule-based strategy. It does four jobs:

1. **Second opinion on every trade** the strategy wants to take: APPROVE, REDUCE (take it smaller) or REJECT, with reasons.
2. **Market research** (Gemini + Google Search): the next 24 hours of economic events and the news that moves your pair. A high-impact event close in time triggers a **news blackout**, decided by code, not by the AI.
3. **Post-mortem of every closed trade**: a short "why", sorted into categories (stop too tight, range chop, news spike...).
4. **Plain-language conclusions**: a note in the daily report, and an explanation when a strategy version fails.

## What the AI can and cannot do (enforced in code)

- It can only approve, **shrink** or **skip** a trade the rules already proposed. It can **never make a trade bigger**, place or close a trade, move a stop, or change a risk limit.
- Everything it says is validated and clamped (`sailar/brain/schema.py`). Web text is fenced as untrusted data so it cannot give the AI orders.
- If the AI is slow, down or out of budget, trading carries on exactly as without it (`on_error: "proceed"`).
- Only market data and the trade proposal are sent. **No account balance, login, or API key** ever leaves your machine. Keys travel only in request headers.

## Setup (5 minutes)

1. Back up your project folder. Then unzip this over it: it adds `sailar/brain/`, `brain_cli.py`, `dashboard/brain.html`, and updates the files in `sailar/` (your break-even and trend-flip changes are kept). It does **not** touch `run.py`, your config files or your `dashboard/index.html`.
2. Get keys (one is enough, both is best):
   - Groq: https://console.groq.com/keys  (fast: used for the trade second opinion)
   - Gemini: https://aistudio.google.com/apikey  (can search the web: used for research)
   - Serper: https://serper.dev  (recommended: fast Google search & news API; saves Gemini tokens and avoids quota limits)
3. Put them in your `.env` (see `.env.example`):
   ```
   GROQ_API_KEY=your_key
   GEMINI_API_KEY=your_key
   SERPER_API_KEY=your_serper_key
   ```
4. Test: `python brain_cli.py test --search --config config.mt5.json`
5. Start as usual: `python run.py run --config config.mt5.json`
6. Open the brain page: http://127.0.0.1:8787/brain (start `python run.py dashboard` as before).

Note: Google Gemini Search Grounding has strict rate/quota limits on free accounts. Adding `SERPER_API_KEY` delegates search snippet gathering directly to Serper.dev and lets Groq or Gemini summarize it in standard JSON mode, significantly reducing token consumption and preventing 429 quota errors.

## Shadow first, then active

The default mode is **shadow**: the AI comments on every trade and is measured, but changes nothing.

- Let it run until the brain page shows **30+ finished reviewed trades** ("Is the AI helping?").
- If trades the AI would have REJECTED clearly do **worse** than the approved ones, switch to active. If not, leave it in shadow or turn it off. An AI opinion is not automatically an improvement, so this measurement decides.
- Switch with `"brain": {"mode": "active"}` in your config file. Modes: `off` | `shadow` | `active`.

All settings (add only what you want to change under `"brain"` in your config; defaults are in `sailar/config.py`):

| Setting | Default | Meaning |
|---|---|---|
| `mode` | `shadow` | off / shadow / active |
| `providers` | `["groq","gemini"]` | order tried; next one is used if one fails |
| `reject_min_confidence` | 65 | active mode skips only if the AI's confidence is at least this |
| `on_error` | `proceed` | `proceed` = trade without the AI when it is down; `skip` = no trade without an AI answer |
| `news_blackout` | true | skip trades near high-impact news for your pair (active mode) |
| `max_calls_per_day` | 300 | hard cap on AI calls |
| `research_minutes` | 60 | how often the market brief refreshes |

Models are discovered automatically from each provider's list (names change often). Put your preferred names first in `models` if you want specific ones.

## Other commands

- `python brain_cli.py research`: fetch a market brief now
- `python brain_cli.py report`: is the AI helping?
- `python brain_cli.py advise`: parameter ideas to TEST in a backtest (never applied automatically)
- `python brain_cli.py ask "is EURUSD likely to move before the ECB speech?"`

## Limits

- Built and tested offline against a **fake network** (tests/test_brain.py, 25 tests). It has not talked to the real Groq or Gemini servers yet, so run `brain_cli.py test` first and expect small fixes.
- The AI reads indicators and headlines; it cannot see the future. Research text is AI-collected from the web and can be wrong, so double-check anything important.
