xtrader

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 17, 2026 License: MIT Imports: 22 Imported by: 0

README

XTrader

English | Português

Go React TypeScript PostgreSQL Docker MetaTrader 5 LLM Telegram

An automated trading platform in Go for MetaTrader 5 symbols (Exness). A controller launches and supervises agents:

  • agents that trade the decisions of a language model (OpenAI or Anthropic), each with its own prompt;
  • classic strategy agents, without an LLM, in four families: trend, momentum, breakout and intraday.

The controller also serves the web dashboard, the Telegram bot and XTrader AI, a language model that watches every agent and only acts to reduce risk. All the operational configuration and the records live in PostgreSQL.

[!WARNING] Automated trading carries a real risk of loss. XTrader is not investment advice, and no strategy, prompt or agent in it has been shown to be profitable. Validate any agent in a backtest and on a demo account before a real account. A real account is only accepted with the Permitir conta real (Allow real account) option turned on in the agent and in the MT5 account. Read the Risk disclaimer before using it.

[!NOTE] English is not supported in the application yet: the web dashboard, the Telegram bot and the messages of the application are only in Brazilian Portuguese for now. English support is coming soon.

Contents

Screens

The screenshots below come from the real dashboard running on a mock API: the accounts, agents, trades and values are fictitious.

LLM agents

Besides the chart and the orders, the dashboard of an LLM agent shows the market sentiment read by the model, the analysis drawn on the chart (supply and demand zones, liquidity, markers) and the last decision. Each decision opens with its context, rationale and drawings; the Decisões do LLM (LLM decisions) tab lists them all, including the ones where the model was not even consulted, with the reason.

List of the model's decisions, with the origin of each consultation, the action, the confidence, the result and the rationale, and the Reanalisar agora (Reanalyze now) button

Strategy agents

The agents without an LLM use the same dashboard, with the strategy's indicators on the chart (here, the Fibonacci levels of the current impulse).

Agent settings

The agents are in Configurações › Agentes (Settings › Agents), the LLM ones apart from the strategies, which are grouped by family. Each card turns the agent on and off, switches the prompt on the spot and opens the secrets, the results, the protection and the daily limit.

Editing an LLM agent Editing a strategy agent

The Parametrizador global (global parameter editor) changes or removes a parameter on every agent at once:

XTrader AI

XTrader AI chats through the dashboard's floating button: it answers with the current data and turns requests for action into proposals that only take effect once the user confirms them. The periodic analyses, the actions and the armed protections are in Configurações › XTrader AI (Settings › XTrader AI).

Performance

The summary of the live trades as the MT5 accounts recorded them, in the style of Profit's "Resumo de Performance" (Performance Summary), and the charts of equity, result per trade, per period, per asset, per agent and of efficiency (MFE/MAE).

Backtesting

Backtests run several agents at once over the broker's history, with costs, trading hours, agents per asset and out-of-sample validation, and compare the results under the same conditions.

Accounts, limits and news

Prompts
Editing the smc_ict prompt, with the header lines that configure the agent
List of prompts Editing a prompt
Telegram, users, layout and configuration file

Login, light theme and phone

Login screen

Dashboard in the light theme

The dashboard, the agents and the performance on a phone

Features

LLM agent

The agents/llm/llmagent agent asks the model for a decision and applies it within risk rules.

  • Context sent to the model:
    • candles and indicators;
    • price structure and levels;
    • higher timeframes;
    • market session;
    • correlated markets;
    • economic calendar;
    • memory of the latest decisions and trades. Each decision counts by the time it was made: the consultations on the forming candle (interval, reanalysis) see the earlier ones of the same candle. After a restart, the memory comes from the journal, also by the time of each decision;
    • open position, with the candles closed since the entry (candles_held), or since the bot started tracking it. The count goes by the candle times, so it includes the closes that the consultation interval skips and does not count the time the market is closed (weekend).
  • Possible decisions: enter, exit, hold, move the stop loss and take profit, or wait. Each entry carries a stop loss (and a take profit, depending on the prompt) on the order itself. A prompt can also allow pending orders and drawings on the chart (see SMC/ICT, pending orders and drawings).
  • Rationale: two or three short sentences, in the language of -llm-language: the scenario read and the evidence for the decision, the main contrary evidence and, on an entry, what invalidates it; on a wait, what is missing and what would change the decision.
  • Market sentiment: besides the decision, every model answer carries its reading of the asset's market (sentiment), from 0 (very bearish) to 100 (very bullish), 50 neutral, whatever the action. It is informational only: it does not change the action, does not go through the rules or the minimum confidence, and does not send orders. A value outside 0 to 100, or a missing one, is left out with a note, and the decision is kept. It is stored with the decision (in the database, in the decision_sentiments table; in paper, in memory) and shows on the dashboard's gauge and in the decision dialog; the decisions made before this feature, the failures and the analyses not consulted have no reading.
  • Exit that fails (market closed, quote refused, bridge down, bot stopped): the position is not left without stop loss and take profit.
    • On MT5, the close order goes out with them in place. They go away together with the position, and a refused close does not touch them.
    • In paper, the legs reserve the position: they are canceled before the close and, if it fails, placed again at the same levels.
    • The close is retried, without consulting the model, at every candle close and on the ticks, with a growing interval (30s, 1 min, 2 min... up to 15 min).
    • The failure, a position left without protection and the completed close are reported on the dashboard and on Telegram.
    • On a restart, the pending exit is not resumed: the position keeps its protection, and the model is consulted again.
  • When to consult: only on the schedule of llm-consult-interval (for example, every 5 min), required in live and paper, plus the start of the agent and the on-demand reanalysis, from the dashboard or Telegram, with a note for the model. The model is never consulted on a candle close; an LLM agent without the interval does not start (the error shows in the log and on the dashboard). Only the backtest, which has no candles in progress, consults on the closes: those on the schedule, or all of them without the interval.
  • Agent start: on (re)start, the assets are analyzed at once, in parallel, with the same rules as the other analyses: an asset with no possible entry (for example, when the higher trend is required and it is mixed) is not consulted, and the analysis shows on the dashboard as "Não consultado" (Not consulted), with the reason. Each decision is applied on the asset's next tick, at that tick's price.
  • Repeated "Não consultado": the analyses of an asset that do not consult the model for the same reason, in sequence (on the consultation interval, with the same position and the same prompt), are kept in a single record: the first one. A note on the record says how many there were, the triggers and the last one, with its time, price and detail when it changes. For example, an asset blocked by news with a consultation every 10 s produces one record, not 360 per hour. A different reason, a model decision, the start of the agent or a reanalysis starts another record.
  • Entry checked at the time of applying it: the model answers some time after the context is read (up to llm-timeout; the start decision, on a later tick). Before sending the entry, the agent reads the position and the price again:
    • if the asset already has a position (for example, a position opened by hand on MT5 during the consultation), the entry is refused;
    • the decision is validated again at the current price, with the same rules as the context: stop and target on the right side, distances, minimum stop distance and risk:reward net of the spread. In live, the price comes from the broker (on MT5, the bid of the last tick), with the spread of the last candle; in the backtest, it is the candle's;
    • if the price cannot be read, the entry is refused too.
    • The refused decision shows as "Recusada pelas regras" (Refused by the rules), with the reason. This also applies to the refusals by the daily limit and by news at the time of applying.
  • Model answer (Anthropic): the decision is requested through a forced call of the trading_decision tool. A model that refuses the forced call (for example, claude-opus-5-5, which answers HTTP 400 "tool_choice ... not supported") gets the tool unforced, with a request to answer with it:
    • only that refusal switches the mode; any other 400 error fails the consultation and the next one stays forced. The forced call is tried again once an hour and applies again if the model accepts it;
    • with the unforced tool, if the model answers with text only, the decision JSON is read from the text and goes through the same validations. More than one decision in the text, or none, is an invalid answer;
    • these models think before answering, and the thinking counts toward the token limit: without llm-max-tokens, the limit of the unforced answer is 16000 (4096 on the forced call);
    • a cut-off answer (token limit, the model's context window) or a paused one is a consultation failure, with no decision, even when the tool call is complete.
  • Momentary provider failure: an answer that the API does not charge for, because it did not run the request (429, except the exhausted quota insufficient_quota; 503; 529, Anthropic overloaded), is resent once, after its Retry-After or after 1 s, only if the wait is at most 10 s and 5 s of llm-timeout are left after it. Otherwise, or if the resend fails, the consultation fails as before and the agent pauses the consultations for the Retry-After. The other errors (500, 502, 400 etc.) are never resent.
  • Reasoning effort (llm-reasoning, OpenAI only): none, minimal, low, medium, high or xhigh, as the model accepts (the newer ones accept none and xhigh, and some do not accept minimal). A value the model does not accept is refused by the API (HTTP 400), and the error names the parameter (the param reasoning_effort) and gives the API's message. The database accepts these six.
  • Token usage: each answer logs the input tokens (including those read from the cache), those written to the cache (Anthropic, cache_creation_input_tokens, charged separately and not part of the input), the output tokens and the reasoning tokens (OpenAI), and the day's total (UTC, reset on every restart). A 2xx answer that is not valid JSON, or has another format, still counts the tokens when its usage object can be read. The cost in money is not calculated: there is no price table in the code.
  • Prompts: editable and switched while the agent runs. The switch takes effect from the next analysis, and each decision records the prompt and the version used.
  • Protections:
    • minimum confidence. On a reanalysis with a note from the trader, a decision that reduces the position's risk (EXIT, or the stop moved closer to the price) is applied even below it. The decision records this in its notes ("the min confidence ... waived"), together with the trader's message;
    • minimum risk:reward;
    • maximum spread in ATR;
    • minimum stop distance;
    • blocking near news, in the global window of the News tab, the same as for the other agents;
    • daily gain and loss limits per asset, defined in the prompt (see Daily limits).
  • History of the day: the context carries the asset's positions and orders in the trading day (daily_history), with the result of each position.
  • Economic calendar: read from the MT5 terminal's MCP server, with the address, the token, the switch and the blocking window of the News tab, the same for every agent (each agent's calendar-* parameters still apply to the window of the model's context).
    • With news disabled, or without the token, no query is made. The context tells the model that the calendar was not read and why (status: disabled, missing_token, unauthorized for the token refused by the server, unavailable for the service down), and no entry is blocked by news: the lack of a query never counts as an absence of releases.
    • The news in the context (minutes_from_now and the value already published) and the blocking of entries use the time of the analysis. In live, it is the current time, including in the consultations on the forming candle (interval, reanalysis and agent start); in the backtest, the candle close.
    • The news block is checked again at the time of applying the entry, like the daily limit: a decision applied inside the news window (a slow model answer, or the start decision applied on a later tick) is refused.
    • Calendar unavailable: the context tells the model that it could not be read (and why), the log warns every 15 min and entries are not blocked by news; with news disabled, only the change is logged. This applies to the server down, a tool with an error, or no currency of the pair with events in the calendar.
    • A tool error (e.g., terminal busy) is retried once, half a second later, and the next reading queries again. Only a currency the calendar does not know goes 1 h without being queried.
    • Unknown currency: any error in the query of a code that is not a currency of the MT5 calendar (e.g., XTI from XTIUSD). A currency of the MT5 calendar is only taken as unknown when the server refuses the parameter of the call itself (JSON-RPC -32602, invalid parameter). The tool's error message is never enough, whatever its text (e.g., currency EUR not available, Calendar data for currency EUR not available yet), because it may be transient (e.g., the terminal's calendar still syncing): it counts as a transient error. The currencies of the MT5 calendar are those of the countries in CalendarCountries (USD, EUR, JPY, GBP, CAD, AUD, NZD, CHF, CNY, BRL, KRW, HKD, SGD, MXN, ZAR, INR, NOK, SEK and ALL).
    • Skipped currency: the unknown one, or one the calendar returns without any event (queried again on the next reading), produces a warning in the log, at most one per currency per hour.
    • In a two-currency pair (e.g., EURUSD), the unknown currency is skipped and the other one's news stays in the context and in the block. A transient error on one of them, however, leaves the whole pair's calendar unavailable on that reading, with no partial events.
    • Reading the days: each server day is read at once (up to 5000 events). If the server says it cut the answer (truncated), the day is read again in halves, down to 15-min intervals; a 15-min interval that is still cut leaves the calendar unavailable on that reading, instead of missing news. An event outside the requested interval, such as one at midnight on a server that includes the end of the interval, is left out, and the same event (ID and time) never enters twice.
    • Cache: the days in progress are read again every 5 min; the finished ones stay in the cache for 24 h and then leave it (a late revision is read again, and a long backtest does not pile up every day in memory).
    • Events without a time: the event's time_mode is read. An all-day event (Event takes all day), one with no time (no time) or a tentative one (tentative, only the day known) comes from the calendar at 00:00 server time, which is not its time. It never blocks entries and shows in the context the whole day, with time_mode (all_day, no_time or tentative) and the published value only after the end of the day. A tentative or no-time event whose time the calendar already gives (other than 00:00) counts as a timed event, including in the block. Without time_mode, the event counts as a timed one, as before.
    • An MCP session that fails to open is discarded, and the next call opens another. The SSE answer is read up to the event that answers the call, without waiting for the server to close the stream (up to 16 MiB).
SMC/ICT, pending orders and drawings

The smc_ict prompt (initial agent llm-smc) analyzes the market with Smart Money Concepts / ICT. The features it uses are turned on by lines in the prompt header and work with any prompt; prompts without these lines work exactly as before (same instructions, same schema, same context).

Header line Effect
# Pending orders: limit, stop enables the pending orders of the listed types (limit: BUY_LIMIT/SELL_LIMIT; stop: BUY_STOP/SELL_STOP), plus MODIFY_PENDING and CANCEL_PENDING
# Drawings: on the model returns the drawings of its analysis (drawings), the only ones drawn on the chart: the prompt defines what appears, without the S/R lines (levels)
# Context: smc the context gains smc, the structure in SMC concepts computed by the code, on the decision timeframe and the higher ones

An unknown value in one of these lines rejects the prompt, as with the daily limits.

  • smc_ict setups: only two, both in favor of the bias of the higher timeframes (the direction of their most recent break of structure):
    1. Liquidity sweep + CHoCH: the liquidity on one side is taken (a wick beyond a swing, the previous day's or week's high/low, or the Asian range, closing back), a displacement closes beyond the last swing on the other side (CHoCH), and the entry is the price's return to the FVG or the order block of that leg, in the discount (buy) or the premium (sell) of the dealing range.
    2. BOS + retracement: with the bias, a new break of structure (BOS) with displacement, and the entry on the retracement to the FVG or the order block of the leg, in the discount or the premium.
    • Confirmation: the bias, the break by a close on the decision timeframe (after the sweep, in setup 1), the entry zone intact, and room to the target (the opposite liquidity) for llm-min-rr. Without any one of them, WAIT.
    • Entry: a limit at the edge of the zone the price returns through; at market, with the same stop and target, when the closed candle already rejects the zone.
    • Stop: beyond the point that invalidates the scenario (the extreme of the sweep, or the origin of the leg of the break), never inside the zone; target: just before the opposite liquidity.
    • Invalidation (the model cancels the pending order): a close beyond the extreme protected by the stop, the zone filled or broken, the bias flipped, a break against the trade before the fill, the target reached before the fill.
    • Management: keeps the position while the structure holds; on each new BOS in favor, moves the stop behind the swing that supports it; exits on a CHoCH against; protects before high-impact news.
    • The prompt sets no risk values: it uses the agent's llm-min-rr, llm-min-stop-atr, llm-max-level-atr and llm-pending-expiry. The buffer beyond the stop, a break-even, the killzones and the validity of the pending orders are left for the operator to define.
  • smc context (mechanical definitions over the 3-candle swings of the structure, with no invented size limit: the model weighs each item by its size in ATR):
    • structure_breaks: closes beyond the last unbroken swing, bos (same direction as the previous break) or choch (opposite direction), the 4 most recent;
    • fair_value_gaps: three-candle gaps not yet filled (the remaining part, how much has already been taken, size and distance in ATR), the 3 closest on each side;
    • order_blocks: the last opposite candle before the leg that broke the structure, marked as mitigated when the price came back to it and discarded when a close goes through it, the 2 closest on each side;
    • liquidity_sweeps: wicks beyond a swing that closed back without breaking it, the 3 most recent;
    • dealing_range: the leg of the last break, with the equilibrium (50%) and the price's position (below 0.5, discount; above, premium).
  • Pending orders:
    • They go in through the core's protected order APIs (CreateOrderLimitProtected/CreateOrderStopProtected), with the stop loss and take profit on the order itself; on MT5, the pending order carries the SL/TP at the broker and is valid until canceled (GTC).
    • Validated as entries, measured from the pending order's price: the type's side of the market (buy limit below the ask, buy stop above it; sell limit above the bid, sell stop below it), stop and target on the correct sides of the entry, distances up to llm-max-level-atr, risk:reward (llm-min-rr) and stop room (llm-min-stop-atr, net of the spread). The minimum confidence, the setup, the direction, the higher-timeframe trend filter, the maximum spread, the daily limit and the news block also apply, checked again at the price of the moment the decision is applied.
    • One pending order per asset, only with no position. While it waits, the model sees it in the context (pending_order: type, prices, size, candles waited and who placed it) and can only keep it (WAIT), modify it (MODIFY_PENDING, with all the new levels; the ones that already exist are moved, never added or removed) or cancel it (CANCEL_PENDING).
    • Modification: the limit and the legs are moved at the broker, in the order that keeps each level on the correct side at every step. Brokers cannot move the trigger of a stop order: the stop order is canceled and placed again at the new levels.
    • Canceled by the agent itself, without asking the model, when an entry of its type is no longer allowed (daily limit, news, higher-timeframe trend, spread, direction, or a prompt without that type), when a position appears on the asset (it would add to the position), and after llm-pending-expiry candles, if set. The news window is also watched on ticks. The reason goes in the analysis notes, and a cancellation on ticks is notified on the dashboard and on Telegram.
    • Once filled, it becomes the tracked position, with its legs; partially filled, the rest is canceled. Expired, rejected or canceled outside the agent, it leaves tracking, with a note.
    • After a restart, the asset's open pending order (only of a type the prompt uses) is tracked again from the stored orders, with its legs and with placed_by read from the decision link. A pending order opened by hand on MT5, under the agent's magic number, is also tracked, like the positions opened outside; with a prompt without pending orders, those pending orders stay untouched, as before.
  • Drawings: zones (from low to high), supply (supply) and demand (demand) zones, levels and markers, each with an id, label, bias, timeframe and times (from, and to when it ended), linked to the decision that drew them (decisions[].drawings). They are validated before being drawn: known type, unique id, label, the decision timeframe or a higher timeframe of the context, times in RFC 3339 up to the last candle, positive prices; an invalid drawing is discarded (up to 20 per decision) with the reason in the notes, without rejecting the decision. Each answered analysis replaces the drawings of the previous one, even when rejected or ignored; a query that failed or was skipped keeps the previous ones. The model receives the current drawings (chart_drawings) so it keeps the ids of the ones still valid and leaves out the invalidated ones.
  • What is drawn: a prompt without # Drawings: gets, from the system instructions, the request for the supports and resistances of the analysis (levels, up to 8), drawn as dotted S/R lines across the whole chart. With # Drawings: on, that request and the levels field leave the instructions and the schema: the chart shows only the drawings the model returns, as the prompt text says (smc_ict, for example, draws the nearest liquidity as BSL and SSL levels). A levels sent anyway is discarded, with a note on the decision.
  • Supply and demand: the supply zone is the base the price fell from strongly, the demand zone the base it rose from strongly, with the state (state) the model identified: fresh (the price has not come back to it), tested (it came back and the zone held) or broken (a candle of its timeframe closed beyond the far edge: above supply, below demand). The code checks the consistency before drawing and discards, with the reason in the notes: a fresh or tested zone with an end (to), or already broken by the last close of its timeframe in the context; a broken one without the candle that broke it (to); an unknown state; and the same zone (type, timeframe, low and high) repeated under another id. Each zone is linked to the asset, the timeframe it was read on and the decision that drew it, and the next analysis replaces it (kept by its id while valid, left out when invalidated).
Family Binary Strategies
Trend agents/trendagent trendconfluence, matrend, emapullback, fibonacci, trendpullback, emacross, ema200, ribbon, supertrend, emasupertrend, psarema, atrtrailing, ichimoku, ichimokuadx, mtftrend, mtfema, consensus
Momentum agents/momentumagent adxema, macdtrend, emamacd, emarsiadx, rsitrend, stochpullback, papullback, rsi2
Breakout agents/breakoutagent atrbreakout, fimathe, squeezebreakout, donchian, channel, adxdonchian, donchianatr, bbbreakout, keltner, volumebreakout, highlow, momentumbreakout
Intraday agents/intradayagent orb, asialondon, vwap, sweep, zscore, meanreversion, scalp1m, scalp1mbtc, newsbreakout, seasonality, volumeprofile, cmegap, pairs

Each agent runs in live mode (launched by the controller) or paper mode. From the command line, it also runs backtests.

  • Strategy flags: a strategy flag is accepted only with a strategy that uses it. A flag that no strategy of the agent uses is rejected at startup, with an error (before, it was accepted and ignored, like -trailing-atr on intradayagent). An agent saved in the controller with such a flag does not start until the flag is removed from its settings: the reason goes in the controller log (e.g., -trailing-atr is an input of no strategy of the agent, on the agent's line), the dashboard shows the last exit (exit status 1) and, with Reiniciar se cair (Restart if it goes down), the new attempts follow the supervision's growing wait (from 5 s up to 1 min).

    • -max-risk-pct: accepted by every strategy of the four agents except pairs, which sets no stop: with it, an agent running pairs does not start. It rejects the entry that would lose more than this % of the free margin at its stop (both in the account currency, the loss by the point value; see Account currency): the strategy's stop (in ATR, beyond the SMA 200 on matrend, the Fibonacci or Fimathe levels) or the fixed-value one (-stop-value). On trendconfluence, it counts the tightest of the configured stops, and one must be configured (-stop-atr, -trailing-atr, -broker-stop-atr, -broker-trailing-atr or -stop-value), or the agent does not start. The rejected entry goes in the log with the computed loss. Default 0 (no limit): the agents trade as before until they get the parameter. On fimathe, the default is 3 (a rule of the methodology), and -fimathe-max-risk-pct is still accepted as the same limit (not both together).
    • -stop-atr and -take-profit-atr (stop and target in ATR 14 from the entry): accepted by every strategy of the four agents except pairs, whose two legs protect each other.
      • On the strategies with stop and target in ATR (the signal ones, orb, vwap, consensus...), they change the multiple, as before.
      • On the ones that compute their own levels (fibonacci, fimathe, squeezebreakout, meanreversion, trendpullback, scalp1m, scalp1mbtc), they apply only when set: the initial stop and target are placed at these multiples of the ATR from the entry (from the limit price, on limit entries), instead of the strategy's levels. The other exits remain: the stop moved by R or by the channel, the time exit, the opposite signal. Without them, nothing changes.
      • On matrend, -stop-atr puts the stop at the broker at this multiple from the entry, instead of the stop beyond the SMA 200, and it is then moved by the strategy's trailing; -take-profit-atr sets a target, which it did not have.
      • On trendconfluence, -stop-atr is still the stop checked at the close (the broker stop is -broker-stop-atr), and -take-profit-atr sets a target at the broker with the entry.
      • On volumeprofile, -stop-atr is still the room beyond the session extreme, and -take-profit-atr replaces the target at the other edge of the value area. On cmegap, the stop was already in ATR from the entry, and -take-profit-atr replaces the target at the reference.
      • The fixed values (-stop-value, -take-profit-value) are still accepted and, together, still take precedence over the ATR ones.
    • -trailing-atr: accepted and applied, as before, by trendconfluence and matrend, and now also by fibonacci and consensus (trendagent), by donchianatr (breakoutagent, the only signal strategy that moves the stop by default) and by every strategy of momentumagent (now declared in them). Still rejected with the other strategies of trendagent and breakoutagent (emapullback, atrbreakout and the other signals). On intradayagent, no strategy moves the stop: once accepted and ignored, it is now rejected.
  • Entry filter (regime, equity-curve, meta-model, intermarket-symbol; every strategy agent, no LLM): filters the entries of any strategy of the four agents without changing its rules. A rejected entry becomes a block for the strategy, like the controller's blocks, and goes to the log once per reason and asset ([FILTER] … entries refused: …); exits always pass. Without these parameters, the agent trades exactly as before. A filter still without data (not enough candles, the reference missing or stale, the model without the indicators) rejects the entries. A parameter of a filter without the filter turned on (e.g., regime-len without regime) keeps the agent from starting, with the error. The filters do not apply to pairs (the agent does not start with them): each leg would be judged on its own, and the filter would reject one leg after the other had opened. The default numbers are ours, except where the source is stated. Defaults, all changeable through the parameters:

    • Regime: regime (trend or range; off by default) lets entries in only with the market trending, or only with it ranging, as measured by regime-method:
      • er (default), Kaufman's efficiency ratio ("Trading Systems and Methods"), |C[t] − C[t−n]| / Σ|C[i] − C[i−1]|: regime-len 10 (the period of Kaufman's adaptive moving average) and a trend from regime-threshold 0.30 up (a common threshold for the ratio, not checked against the book: take it as ours);
      • adx, Wilder's ADX ("New Concepts in Technical Trading Systems", 1978): 14 (Wilder's period) and 25 (the usual reading of the index; Wilder talks about the ADXR);
      • hurst, the Hurst exponent by rescaled range (Hurst, 1951; Mandelbrot and Wallis, 1969), with the Anis and Lloyd (1976) correction for small samples: 100 returns (ours) and 0.5 (the random walk of the theory). Without the correction, the calculation overestimates H in short windows (a random walk of 100 returns gives about 0.6) and almost everything would look like a trend; with it, random walks stay at 0.5, above is persistent (trend) and below, reversion.
      • Use trend on the trend, breakout and momentum agents and range on the reversion ones (zscore, meanreversion, vwap). regime-max-atr-pct (default 0, off) rejects entries while the ATR 14 is above this percentile of the previous regime-atr-window (100, ours) candles (extreme volatility), with or without regime.
      • On the chart: a pane with the value of er or adx.
    • Equity curve: no published source (trading the equity curve is a common idea among traders; the rule and the numbers are ours). equity-curve N (default 0, off; at least 2) pauses entries while the curve of the strategy's theoretical trades, in R, is below the average of its last N points, and only judges after N closed trades.
      • Each entry attempt with a stop becomes a theoretical trade, one at a time per asset, even when rejected: that is how the curve rises again and releases the entries.
      • It closes at the stop (−1R), at the target (+target/risk R), at the stop when both are hit on the same candle, at the close after equity-curve-max-bars (100) candles, or when its real position goes flat.
      • It is kept only in memory: it starts from zero on every agent restart. In the backtest, it starts empty at the start of the period, as in live: the warm-up attempts do not go into it.
    • Meta-labeling (López de Prado, "Advances in Financial Machine Learning": the triple-barrier labels, the purging and the secondary model over the primary model's signals): a model estimates the chance of each strategy signal ending positive, and lets entries in only above a threshold. The 18 indicators, the logistic regression with L2 (the book does not prescribe the model), the 70/30 split, the L2 of 1, the threshold of 0.5 and the 100 candles are ours.
      • meta-record (JSONL file, e.g., data/meta/matrend.jsonl) records each entry attempt with 18 indicators of the moment (ATR, ADX, efficiency, RSI, distance and slope of the EMA 50, Bollinger width, 10-candle return, relative volume, hour and weekday, side) and, when known, the triple-barrier label: 1 with the target before the stop, 0 with the opposite; when it expires at meta-max-bars (100) candles or is closed by the strategy, the sign of the result. In the controller's backtests, it records from the start of each segment: run a backtest with it to collect the samples. Each sample says where it came from (source: live, paper or backtest; in the backtest, also the run and the segment, fit or validation).
      • The command xtrader metalabel --samples data/meta/matrend.jsonl --out data/meta/matrend.json discards the repeated samples (the same attempt recorded by two backtests of the same period), shows how many came from each source and trains a logistic regression with L2 regularization, split by time (the oldest 70% for training, the rest for testing, purging the training samples that end inside the test), and shows the training and test AUC and, for each threshold from 0.40 to 0.70, how many entries it would let through and their precision. It also accepts --agent, --strategy, --pair, --source (live, paper, backtest, comma-separated), --segment (fit, validation), --train-share (0.7), --l2 (1), --threshold (0.5) and --json. In production, run it as the agents' user, or the model is unreadable to them: docker exec -u trader -w /app xtrader-controller-1 /app/bin/xtrader metalabel …, with the paths relative to /app.
      • meta-model (the model file) lets entries in only with a probability of a positive result (the label above: the target before the stop, or a positive result at expiry or at the strategy's close) ≥ meta-threshold (default: the model's, 0.5). An unreadable model keeps the agent from starting. The model stores how far the training samples go (trained_through): a backtest with it that starts before that date is rejected, because the period would be in sample; test it on periods after the training.
    • Intermarket: intermarket-symbol (e.g., DXYm, read and never traded) allows the buy or the sell depending on how the reference closes against its own intermarket-ema (50) EMA:
      • intermarket-mode = inverse (default): buys only with the reference below the EMA and sells only with it above (the dollar against gold); direct is the opposite.
      • Only on the pairs of intermarket-pairs (default all, e.g., XAUUSDm).
      • It uses only the reference candles already closed at the pair's candle, the last one at most 4 candles behind (the EMA 50, the 4 candles and the inverse mode as the default are ours). A pair of intermarket-pairs that the agent does not trade keeps the agent from starting (a typo would turn the filter off silently).
      • It works in paper, in live and in the controller's backtests, which read the reference candles of the same period; it is rejected in the backtest by -csv.
  • Fibonacci (fibonacci, trendagent, no LLM): trades the pullback of each impulse in the impulse's direction, at the Fibonacci retracements: buys on the pullback of a rally, sells on the pullback of a drop, one position at a time per asset. The levels are retracements of the impulse, from 0 (the extreme) to 1 (the origin). Defaults, all changeable through the parameters:

    • Impulse: fib-swing = pivot, from one pivot to the next opposite pivot, each pivot with fib-pivot = 5 candles on each side (it is only known 5 candles later). The most recent top, from the low since the previous bottom, is the buy impulse; the most recent bottom, from the high since the previous top, the sell impulse. With fib-swing = range, the impulse goes from the low to the high of the last fib-lookback candles (default 300). A minimum of fib-min-impulse-atr = 3 ATR at the extreme's candle. The impulse stops being valid at a price beyond the extreme (it continued; the next pivot forms another one) or at a close beyond the origin, and each impulse is traded once (an agent restart forgets the ones already traded). fib-trend-ema = 200 trades only in the direction of the EMA 200 (default 0, off).
    • Entry: fib-trigger = close, at market at the close of the candle that rejects the zone from fib-entry-low = 0.5 to fib-entry-high = 0.618: the wick reaches 50%, the candle closes in the impulse's direction (above the open on a buy) and the close does not go past 61.8%. With fib-trigger = limit, a limit order at fib-limit-level (default 0.618, inside the zone), placed while the price is on the extreme's side and canceled when the impulse stops being valid, when a position appears on the asset, or after fib-pending-bars candles (default 20; 0 for only by the impulse). A limit placed before a restart is no longer tracked: the position it opens is, like the others, but canceling the limit is up to the operator.
    • Stop: at fib-stop-level = 0.786, plus fib-stop-buffer-atr = 0.25 ATR beyond it (fib-stop-level = 1 places it at the origin).
    • Target: fib-target = extreme, at the extreme of the impulse; extension, at fib-target-level (default 1.272) times the impulse from the origin; rr, fib-reward-risk (default 2) times the distance to the stop; none, no take profit, which requires trailing-atr.
    • Also accepts: trailing-atr, max-bars, min-atr-pct, stop-value and take-profit-value (the fixed values replace the Fibonacci stop and target, and are rejected together with fib-stop-level/fib-stop-buffer-atr and with fib-target/fib-target-level/fib-reward-risk), stop-atr and take-profit-atr (when set, the stop and target at these multiples of the ATR from the entry, instead of the Fibonacci levels).
    • On the chart: the levels of the current impulse (0, the zone, the stop, 1 and the target extension) from the origin on, the pivots and the ATR.
  • Fimathe (fimathe, breakoutagent, no LLM): the first trend entry of each mapping of the reference channel of the Fimathe technique (Fimathe 4.0, lesson 3), as the official robot automates it. With the defaults:

    • Mapping: at the start of each week (Sunday, 00:00 UTC), with the 1h bars closed before it: the trend from the last two tops and bottoms, the reference channel from the last bottom to the last top (wick, or body if too wide, between 1 and 8 ATR), the neutral zone on the other side of the trend.
    • Entry at the close of a 15m candle: back beyond the channel's 50% (price below it or in the neutral zone), or beyond the channel's edge (price that stayed beyond the 50%). A close beyond the neutral zone (reversal zone) ends the mapping. One entry per mapping and per asset, also counting the ones from before a restart.
    • Exit: a stop beyond the neutral zone, moved by the subcycle (the channel of the 15m candles before the entry): 0x0 in the first 50% and one step every 50%; no target, or a target at 2 channel heights with the stop locked at 0x0. At most 3% of the free balance lost at the stop (max-risk-pct, or fimathe-max-risk-pct). With stop-atr and take-profit-atr set, the initial stop and target are at these multiples of the ATR from the entry, instead of the channel levels, and the subcycle keeps moving the stop; the fixed values are still rejected.
    • On the chart: the channel, the neutral zone, the 50%, the expansions, the reversal zone, the planned entry (dashed, not an order), the entry made, the subcycle and the stop moves, with the legend "Fimathe".
  • The rules of the LLM agent's prompts (meanreversion, scalp1m, scalp1mbtc, trendpullback, squeezebreakout, no LLM): the rules of the prompts mean_reversion, scalp_1m, scalp_1m_btc, default (the trend_pullback setup; free, the free-weighing one, does not become code) and breakout, with the approved numbers where the prompt was vague. What the candles do not carry is left out: the economic calendar, the levels of the higher timeframes and the spread, in whose place min-atr-pct applies. Each one computes its own stop and target and measures them in R, the profit of a close in units of the initial risk (from the entry to the first stop): it moves the stop to the entry (break-even, without the spread) and, further on, behind the price, never backward, and closes a stalled trade on time. They accept min-atr-pct, the sizing flags (lot, max-risk-pct...) and stop-atr and take-profit-atr: when set, the initial stop and target are at these multiples of the ATR from the entry, and R is measured from that stop; max-bars and trailing-atr are rejected. Short mirrors long:

    • meanreversion (15m): a ranging market (ADX 14 below 20 and not rising, EMA 9 and 21 less than 0.25 ATR apart, the close crossing the Bollinger 20 middle band at least 2 times in 20 candles); a low at the lower band (20, 2) with RSI 14 below 30 on the candle or the previous one, the candle closing back inside, bullish, with a lower wick of at least 50%. Stop 0.5 ATR below the lowest low of 5 candles, target at the middle band, minimum 1.2R. Exits at the middle band, with ADX above 25 and the DI against, or on a close outside the band again; break-even at 0.7R; exits after 8 candles below 0.2R. The filters can be loosened through agent parameters: meanreversion-oversold and meanreversion-overbought (the RSI, 30/70), meanreversion-max-adx (20), meanreversion-flat-atr (0.25) and meanreversion-wick-pct (0.5); without them, these numbers apply.
    • scalp1m (1m): volume ≥ 0.8× the 20-candle average, ADX above 18, London or New York open (08:00 to 17:00 in each city), EMA 9 and 21 separated by ≥ 0.1 ATR and sloping in favor over 3 candles, the close beyond both, the 15m and 1h EMAs 9/21 not opposed; a pullback of up to 5 candles to the EMA 9 without closing beyond the EMA 21, and the candle closing beyond the EMA 9 and the previous high with the MACD histogram in favor or the RSI crossing 50. It does not enter after 3 strong candles in a row (body ≥ 0.5 ATR), more than 1 ATR from the EMA 9, or with RSI above 75. Stop below the pullback, between 1 and 1.5 ATR; target 1.5R, before the 20-candle high; minimum 1.2R. Break-even at 0.8R, trailing of 1 ATR from 1.5R, exit on a close beyond the EMA 21 and after 10 candles without 0.5R.
    • scalp1mbtc (1m): only the strong impulses: ADX above 20 and rising with the DI in favor, volume ≥ 1.2× the average, the close beyond the SMA 200, no 60-candle high less than 3 ATR ahead; a pullback of up to 3 candles to the EMA 9 without closing beyond it, the candle closing beyond the previous high with the MACD histogram growing. It does not enter after 4 strong candles, more than 1.5 ATR from the EMA 9, or with RSI above 78. Stop between 1.5 and 2 ATR; target 2R, at least 3 ATR away. Break-even at 1R, trailing of 1.5 ATR from 1.5R, exit beyond the EMA 21 or with the ADX falling and the other DI on top, and after 15 candles without 0.5R.
    • trendpullback (1h): EMA 9 above the 21, the close above the SMA 200, ADX ≥ 20; a pullback of up to 5 candles to the EMA 9 without closing below the SMA 200; the candle closing above the EMA 9 with the MACD histogram turning in favor or the RSI crossing 50, RSI ≤ 70. Stop below the pullback, at least 1 ATR away; target at the highest high of 50 candles, or 2R without one above; minimum 1.5R. Break-even at 1R; from 2R, trailing behind the last bottom (5-bar pivot) or at 1 ATR, whichever is closer; exits on a close below the EMA 21.
    • squeezebreakout (15m): the box of the 10 candles before the breakout, with a height ≤ 3 ATR and the ATR below the 30th percentile of the last 100; a close beyond the box with a body ≥ 50% of the candle, volume ≥ 1.5× the average (2× against the SMA 200) and ADX rising with the DI in favor. It enters up to 0.5 ATR from the box; further away, it waits up to 5 candles for a retest (within 0.25 ATR of the edge, closing beyond it) and a candle closing beyond the retest candle's high. Stop in the middle of the box, or below the breakout candle if that is tighter and at least 1 ATR away; target at the box height projected from the edge; minimum 2R. Exits on a close back inside the box; break-even at 1R; from 1.5R, trailing by the EMA 9 or the low of the last 2 candles, whichever is closer. With the stop in the middle of the box, the target never reaches 2R: it only enters with the stop below the breakout candle. The filters can be loosened through agent parameters: squeezebreakout-min-rr (2), squeezebreakout-min-volume (1.5), squeezebreakout-max-atr-percentile (30) and squeezebreakout-max-box-atr (3); without them, these numbers apply.
    • After a restart, the position found keeps the strategy's exits, but without the initial risk: the break-even and the trailing by R stop, and the time exit counts only the candles. squeezebreakout also no longer knows the box: the position keeps the broker's stop and target.
  • Consensus (consensus, trendagent, no LLM): votes among the rules of the signal strategies (the same as ema200, supertrend, donchian..., with the classic periods of each): buys when at least consensus-quorum rules signaled a buy in the last consensus-window candles (the current one included) and none signaled a sell in that span; sells in the mirror case. One position at a time per asset. Each rule votes the way it trades on its own: its signal on a candle is the one at that candle's close, computed only from the candles up to it (no look-ahead), and each one computes its own indicators separately (several use the same internal names, e.g. the trend EMA, 200 in ema200 and 50 in adxema). Default timeframe 15m (that of the signal strategies). Defaults, all changeable through the parameters:

    • Rules: consensus-rules = ema200,supertrend,macdtrend,adxema,donchian: a trend rule (the close crossing the rising EMA 200), a volatility trend rule (the flip of the Supertrend 10/3), a momentum rule (the MACD 12/26/9 crossing the signal line beyond zero), a momentum rule with ADX (close beyond the EMA 50 with the ADX 14 above 25 and the DI in favor) and a breakout rule (the close beyond the 20-period Donchian channel). Accepts any names of the signal strategies, separated by commas, at least 2, each one once; the same rule under another name is refused (donchian and donchianatr are the same rule with different exits, and only the rule votes). mtftrend and mtfema were left out of the default: their warm-up (4 and 16 times the timeframe) would become the consensus's warm-up.
    • Entry: at market at the close of the candle on which the consensus forms: consensus-quorum = 3 rules in the same direction within consensus-window = 3 candles, none in the opposite direction (consensus-window = 1: on the same candle). A consensus that still holds on the following candles does not enter again (for example, after the stop), just as each rule fires only on its own event. A rule that signaled both a buy and a sell within the window vetoes both sides.
    • Stop: at stop-atr (1) ATR 14 from the entry, at the broker.
    • Target: at take-profit-atr (1.5) ATR from the entry (take-profit-atr = 0: no target). The opposite consensus closes the position at market and, if it formed on that candle, opens its own side; while it holds, an opposite position found (e.g. after a restart) is closed too.
    • Also accepts: trailing-atr (the stop at the broker following the best price since the entry, never backward, as in donchianatr; default 0, off), max-bars (default 0), min-atr-pct, stop-value, take-profit-value and the sizing flags (lot, max-risk-pct...).
    • Warm-up: that of the longest rule plus the window: 2204 candles with the default rules, about 23 days on 15m.
    • On the chart: each rule's indicators, with the rule's name in the group (e.g. ema200: EMA 200 Trend, adxema: ADX 14), and the ATR 14.
    • Source: the rules are the classic ones of the existing signal strategies; the quorum vote within a window is a combination (ensemble) with no published source. The default rules, the quorum of 3, the window of 3, the 15m timeframe and the exits (those of the signal strategies) are our choices, to be validated in backtests.
  • RSI 2 (rsi2, momentumagent, no LLM): the 2-period RSI strategy of Larry Connors and Cesar Alvarez ("Short Term Trading Strategies That Work", 2008, chapter "The 2-Period RSI: The Trader's Holy Grail of Indicators?"): buys the pullback of a rising market and sells the bounce of a falling market (the book tests both sides), one position at a time per asset, on the book's daily candles (timeframe = 1d). Defaults, all changeable through the parameters:

    • Trend: buys only with the close above the SMA 200 and sells only below it (the book's periods, SMA 200, RSI 2 and SMA 5, are fixed).
    • Entry: at market at the close of the candle on which the (Wilder) RSI 2 closes below rsi2-oversold (10), a buy, or above rsi2-overbought (90), a sell. The level counts, not the cross: with no position, it enters on any close with the RSI beyond it. The book also tests more extreme levels, which both flags accept.
    • Exit: the book's rule, at market on the first close above the SMA 5 (buy) or below it (sell). If the entry on the other side holds on the same close, it is opened (a combination of ours: the book tests each side separately).
    • Stop: Connors's tests use no stop (the book concludes that a stop makes these short-term systems worse). Here the stop sits at the broker only as protection, at stop-atr (1) ATR 14 from the entry: the default of the strategies with a stop and target, not a number from the book. For a system that buys weakness, 1 ATR is tight: test a larger stop-atr in the backtests.
    • Target: also only protection, ours and not the book's, at take-profit-atr (1.5) ATR, which may close before the SMA 5 exit. With take-profit-atr = 0, no target: the exit is only through the SMA 5, closer to the book.
    • Also accepts: max-bars (default 0, no time exit), min-atr-pct, trailing-atr (default 0, off; not a rule of the book, accepted as in every momentumagent strategy), stop-value and take-profit-value, direction (e.g. buy, only the long side, on an asset in a strong uptrend) and the sizing flags (lot, max-risk-pct...).
    • Warm-up: 210 candles: the SMA 200 plus 10 of slack (ours), with the ATR 14 seed (154 candles) inside that window, since the decision reads only the last candle. On 1d, it fits in the year of warm-up that the controller's backtest reads before the period, on gold too (about 260 daily candles per year).
    • After a restart: the position found keeps the SMA 5 exit and the legs at the broker, because the rule keeps no state.
    • On the chart: the SMA 200, the SMA 5 and the RSI 2 in a panel.
    • The edge was measured by the book on US stocks on the daily timeframe; on XAUUSD and BTCUSD it is a hypothesis to be measured in the backtests.
  • Breakout after the news (newsbreakout, intradayagent, no LLM): trades the breakout of the range the price draws right after a scheduled economic release (payroll, CPI, rate decision...), with the orb rules applied to that range in place of the session's opening range (without the orb VWAP filter, on by default there). The rule does not come from a book: it is the opening range breakout (ORB) anchored at the release time, and none of the numbers below has a published source. The releases come from the calendar of the News tab, the same one the news guard uses, delivered to the agent by the controller in live and paper, and, in the backtest, from the period's releases read by the controller: only the time, the event and the importance, never the values, so the backtest does not look into the future. Without a calendar (news off, no token, or the agent running outside the controller), it does not enter, and the log says it is waiting for the releases. Defaults, all changeable through the parameters:

    • Releases: those with an exact time (all-day or to-be-confirmed ones are left out) of importance newsbreakout-importance = high or above (low, medium or high), in the asset's currencies (USD for XAUUSDm and BTCUSDm). newsbreakout-codes (default empty: every event) restricts them to a list of event_code codes from the MQL5 calendar, separated by commas or semicolons, case-insensitive; check the codes on the server, they are not in the code. Releases at the same time count as one. The calendar is read at most every 5 min on the candle clock (the close of the last candle), not on the computer's clock, so the backtest repeats live trading: a to-be-confirmed release that gets a time later shows up on the next read in both. Each read has up to 5 s, and a read that fails keeps the releases already read, with a warning in the log, and is retried 5 min of candles later.
    • Range: the high and low of the candles within newsbreakout-wait = 15m after the release (opened at it or later and closed by the end of the wait; the candle that contains the release time is left out). The 15 minutes and the high importance are the defaults of the News tab guard: the first entry goes out after the guard releases the entries. With a larger "after" window, raise newsbreakout-wait along with it, otherwise the entries inside the window are refused by the guard (a later breakout can still enter). newsbreakout-max-range-atr skips the release whose range is wider than that multiple of the ATR (default 0, off).
    • Entry: at market on the first close beyond the range, with the previous close inside it, by newsbreakout-buffer-atr = 0 ATR or more (ours, the "first close beyond the range"; orb uses 0.1), on a candle that closes before the end of newsbreakout-expiry = 1h after the wait (ours), or before the next release, if it comes first. One entry per release and per asset, also counting those from before a restart, read from the orders stored by the bot (with the same limitation as orb: a manual entry in the window, before the restart, also counts).
    • Stop: at stop-atr (1) ATR 14 from the entry close, as in orb.
    • Target: at take-profit-atr (2) ATR from the entry close, as in orb.
    • Exit: at market on a close back beyond the middle of the range (the breakout failed), or at the end of the window (the end of newsbreakout-expiry, or the next release), as orb closes at the end of the session. With the calendar read, a position found outside the window of a release (opened before a restart, or by hand in MT5) is closed too; without it, the position keeps the stop and the target.
    • Also accepts: timeframe (default 5m), max-bars, min-atr-pct, stop-value, take-profit-value and the sizing flags (lot, max-risk-pct...). trailing-atr is refused.
    • Positions opened by hand: the strategy adopts any position of the asset on its magic number, like orb: one opened by hand in MT5 outside the window of a release is closed on the next candle.
    • Warm-up: 156 candles of 5m (the seeded ATR 14).
    • On the chart: the high and low of each release's range, on the candles where the breakout is valid.
    • Limitations: the backtest does not run the news guard (its blocking and closing in live are not reproduced), and the backtest's releases are those the calendar stores today for the period (a rescheduled release shows up at its final time). Whether the breakout after the news is profitable is a hypothesis to be measured in the backtests.
  • Intraday seasonality (seasonality, intradayagent, no LLM): trades the bias of fixed windows of the day, measured walk-forward on the asset's own history: each window's return on the previous days, at the same time in the market's city, indicates the direction it tends to move in. The basis is the persistence of the returns of the same interval of the day over the following days, which Heston, Korajczyk and Sadka show across stocks ("Intraday Patterns in the Cross-section of Stock Returns", Journal of Finance, 2010: a stock's return in a half hour, relative to the others, predicts that of the same half hour on the following days); using the absolute return of a single asset over time is our hypothesis. For gold, Caminschi and Heaney ("Fixing a Leaky Fixing", Journal of Futures Markets, 2014) show the effect of the London PM fixing, in its old format, replaced by the LBMA electronic auction in 2015; the AM fixing window has no cited study. It is a hypothesis to be measured in the backtests: the candles do not carry the spread, and a bias of a few points may not pay for it. Defaults, all changeable through the parameters:

    • Windows: seasonality-windows = 10:30/60@Europe/London;15:00/60@Europe/London;09:30/60@America/New_York, which are gold's AM and PM fixings (LBMA Gold Price, at 10:30 and 15:00 London time) and the open of the New York stock exchanges (09:30): the times come from the sources, the one-hour duration of each is ours (Heston et al. measure half hours). Each window is HH:MM/minutos@fuso (minutes@time zone, an IANA name), separated by ;, and follows its own city's daylight saving time (10:30 in London is 10:30 UTC in winter and 09:30 UTC in summer). The duration is a multiple of the timeframe, below 23 hours, and the start must fall on a candle open all year round: 10:30 works on 15m, not on 1h, and the agent does not start with such a window.
    • Bias: the window's return, from the open of the first candle to the close of the last, on each of the last seasonality-days = 60 days on which it traded, never that of the day about to be traded. Only a day with the candles at both ends counts: gold's weekend, a holiday or a gap in the data are left out (BTC's weekends count). With at least seasonality-min-days = 20 days, it computes the t statistic t = mean / (deviation / √n), with the sample standard deviation. The 60 and the 20 days are ours.
    • Entry: at market at the close of the candle that ends at the start of the window, when |t| ≥ seasonality-min-t = 2 (near the usual 5% significance level, a statistical convention, not a number from the papers: with the minimum of 20 days, the 5% critical t is about 2.09, and 2 corresponds to p ≈ 0.06; there is also no correction for the number of windows tested). Buys with a positive mean and sells with a negative one; with 0, trades every window by the sign of the mean. One position at a time per asset: a window that starts with another position open is not traded (the New York open, at 14:30 London time for most of the year, overlaps half an hour of the PM fixing). Of windows that start together, the one with the highest |t| wins.
    • Exit: at market at the close of the candle that ends at the end of the window.
    • Stop / Target: safety levels, far from the moves of a window, ours: stop-atr (3) and take-profit-atr (4.5) ATR 14 of the timeframe's candles, from the entry.
    • Timeframe: 15m (ours). The agent keeps the 60 days of candles as if the market traded 24 hours a day, plus the ATR seed: 5,919 candles on 15m, and the backtest reads about 94 days before the period. The limit is 20,000 candles: above that, it measures the days that fit, at least seasonality-min-days. On 1m, the 20 days do not fit and the agent does not start.
    • Also accepts: timeframe, max-bars (closes before the end of the window), min-atr-pct, stop-value, take-profit-value and the sizing flags (lot, max-risk-pct...).
    • Positions opened by hand: the strategy adopts any position of the asset on its magic number: one opened by hand in MT5 outside a window is closed on the next candle.
    • On the chart: each window's t statistic on the entry candle, with the ±seasonality-min-t lines.
    • After a restart: the position found closes at the end of the last window started before its opening (read from the orders stored by the bot), or right away, if that window has already ended.
    • Risks: with 3 windows on 2 assets at |t| ≥ 2, one passes by chance every now and then, and the 60-day samples of consecutive days overlap in 59 days: a window that becomes significant stays so for days, by chance or not. Only out-of-sample backtests can tell. The PM fixing (10:00 New York time) coincides with frequent US releases: the news guard may refuse the entry or close the position within the window.
    • Measure before turning it on: the xtrader seasonality command (cmd/xtrader) measures the same bias on candle files (the CSVs from xtrader download or from the candle cache of the controller's backtests, data/backtests/candles): for each window, the days, the mean and deviation of the return in %, the t statistic, the fraction of up days and the bias (alta (up), baixa (down), - or poucos dias (few days)), and the same table for each hour of the day in the --zone time zone. Unlike the strategy, it measures the file's whole period at once, not the last 60 days of each day. Flags: --csv (one or more files, required), --windows (the format and default of seasonality-windows), --zone (default UTC), --min-t (default 2), --min-days (default 20), --from and --to (days as AAAA-MM-DD (YYYY-MM-DD); --to is the day after the last one) and --json (JSON instead of the tables). E.g.: go run ./cmd/xtrader seasonality --csv xau-15m.csv --from 2026-08-01 --to 2026-11-01.
  • Volume Profile (volumeprofile, intradayagent, no LLM): the "80% rule" of the Market Profile value area (J. Peter Steidlmayer; James Dalton, "Mind Over Markets"), read from the candles' volume. When the session opens outside the previous session's value area and comes back inside it, the rule says the market tends to cross it to the other edge. One position per session and per asset. Only the 70% of the value area (Steidlmayer) and the two 30-minute periods back inside it (Dalton) come from the sources; the other numbers are ours. Defaults, all changeable through the parameters:

    • Session: the CME trading day, from volumeprofile-anchor = 17:00 to 17:00 in the volumeprofile-timezone = America/New_York time zone (the 23-hour Globex day of the gold and bitcoin futures; ours: Steidlmayer and Dalton used the exchange's day session, so the "open" tested here is the 18:00 New York reopen, at a low-liquidity hour), following New York's daylight saving time. Candles join the session by their open time. The previous session is the last one with candles (the previous trading day): a weekend or holiday with no candles is skipped.
    • Profile: the volume of each candle of the previous session (MT5's real volume or, without it, the tick volume; on CFDs, the tick volume) is spread evenly from the candle's low to its high, over volumeprofile-bins = 50 price bands (ours; Market Profile uses tick-sized rows) from the session's low to its high. With no volume at all, each candle weighs the same (time at price, like TPOs). The POC is the band with the most volume; on a tie, the one closest to the middle of the session. The value area starts from the POC and, as in the CBOT method (Dalton), compares the two bands above with the two below and adds the pair with more volume (on a side with only one band left, that band; both pairs on a tie, ours), until it gathers volumeprofile-value-area = 0.70 of the session's volume (Steidlmayer's 70%, about one standard deviation).
    • Entry: at market, at the close of the candle that completes volumeprofile-confirm = 2 consecutive closes inside the value area, after the session opened outside it (reading Dalton's two periods as two closes inside is ours; a common, looser reading is two TPOs inside). The opening candle counts if it closes inside. On the default timeframe, 30m, this gives Dalton's two 30-minute periods. Opened above the area: sell. Opened below: buy. Only on that close: a streak that stays inside does not enter later. It does not enter on the last candle that closes before the end of the session or after it, nor if the session has already traded at the opposite edge (the area has already been filled): these two rules are ours.
    • Stop: stop-atr (1) ATR 14 beyond the session's extreme outside the value area (the high, after opening above; the low, after opening below); Dalton gives no stop, the 1 ATR is ours. It is always farther than the bracket's stop at stop-atr ATR from the close, and may be wide relative to the target (the source sets no minimum risk-reward).
    • Target: the other edge of the value area. A position still open is closed at market at the end of the session in which it entered (ours: the source does not say what to do with it), at the close of the last candle that ends before the end, e.g. at 16:30 New York time on 30m, while gold still trades (the candle that ends at 17:00 would close with the market already closed); if that candle is missing, on the first candle after it.
    • Also accepts: max-bars (default 0, only the end of the session), min-atr-pct, stop-value and take-profit-value (the fixed values replace the profile's stop and target), take-profit-atr (when set, the target at that multiple of the ATR from the entry, in place of the other edge of the value area) and the sizing flags (lot, max-risk-pct...). trailing-atr is refused.
    • Why the CME trading day: anchored at midnight UTC, gold's Friday session (which closes before 00:00 UTC) would never end, and Friday's trade would be carried into the weekend; the Sunday-night stretch would become a short "previous session" for Monday. With another anchor (e.g. volumeprofile-anchor = 00:00 and volumeprofile-timezone = UTC), use max-bars so as not to hold through the weekend.
    • After a restart: the session's position opened before it counts toward the limit of one per session, as in orb's -max-trades, read from the orders stored by the bot, with the same limitation: a manual entry in the session also counts. The position found is closed at the end of the session in which it was opened.
    • On the chart: the high (VAH), the POC and the low (VAL) of the previous session's value area, as points.
    • The "80%" in the name is Dalton's claim, not a result measured here: it is a hypothesis to be measured in the backtests on the real assets.
  • CME gap (cmegap, intradayagent, no LLM): trades against the weekend gap, back to the CME Friday close: sells a gap up, buys a gap down, at most one position per week per asset. The hours are those of CME Globex for the bitcoin (BTC) and gold (GC) futures: Sunday to Friday, 17:00 to 16:00 Chicago time, following Chicago's daylight saving time. The idea that gaps tend to fill is a market belief, not a rule with a source: it is a hypothesis to be measured in the backtests before turning the agent on. Defaults, all changeable through the parameters:

    • Reference: the close of the last candle that ends by the CME Friday close (cmegap-close = 16:00, in cmegap-timezone = America/Chicago). On BTCUSDm, which trades over the weekend, it is the price of BTCUSDm itself at the time the CME futures stopped (not the futures price: the two differ by the basis); on XAUUSDm, which closes over the weekend, it is the market's own last price of the week.
    • Gap: the close of the first candle opened from the Sunday reopen (cmegap-open = 17:00) on, minus the reference. On a market that reopens later, its first candle after that time counts.
    • Entry: at market, at the close of that first candle, when the gap is at least cmegap-min-gap-atr = 0.5 ATR (14) of that candle (ours, no source), against the gap (toward the reference). Only that candle enters: a gap not traded there (smaller than the minimum, or with the entry refused by the trading hours, by a news item or by a daily limit) is not traded later in the week.
    • Stop: stop-atr (1) ATR beyond the entry, on the side opposite the reference (the default of the strategies with a stop and target, ours).
    • Target: the reference (the gap filled).
    • Time exit: cmegap-expiry = 120 hours after the entry (ours, up to the following Friday) or, if it comes first, at the close of the last candle that ends before the next CME Friday close. It does not wait for the candle that ends at the close itself, which may only complete with the gold market already closed. So the position is never carried into the next weekend; with the 120-hour default, the Friday exit always applies.
    • Also accepts: max-bars, min-atr-pct (skips the entry when the ATR is below that % of the price), stop-value and take-profit-value (the fixed values replace the ATR stop and the target at the reference), take-profit-atr (when set, the target at that multiple of the ATR from the entry, in place of the reference) and the sizing flags (lot, max-risk-pct...). trailing-atr is refused. Default timeframe 1h (at most 1 day).
    • On the chart: the week's reference ("CME close"), from the reopen to the Friday close.
    • After a restart: the position found keeps the stop and target that are at the broker. The cmegap-expiry hours count from the opening read from the orders stored by the bot (without it, from the candle on which the position is found), and the exit before Friday still applies.
    • Caveats: the spread at gold's Sunday reopen is wide and the candles are mid-price, so real fills are worse. The global trading hours are in Belém time: Sunday 17:00 in Chicago is 20:00 in Belém during Chicago's winter and 19:00 during its summer; if the configured window does not include Sunday night, the strategy never enters. CME holidays (early close, late reopen) are not known, and if the broker's gold hours do not match CME's, adjust cmegap-close/cmegap-open.
  • Pairs (pairs, intradayagent, no LLM): statistical arbitrage between two cointegrated assets, the agent's two assets (pair, e.g. XAUUSDm;XAGUSDm: the first is leg A, the second leg B; any other number of assets is refused at startup). From the rule of Gatev, Goetzmann and Rouwenhorst ("Pairs Trading: Performance of a Relative-Value Arbitrage Rule", Review of Financial Studies, 2006) come the entry at two deviations, the exit at the crossing and the equal-value legs ("one dollar long and one dollar short"); the spread over a rolling window is ours (the paper uses normalized prices and the fixed estimates of a formation period). In ols mode, the spread is the Engle and Granger (1987) residual, as in Vidyamurthy ("Pairs Trading: Quantitative Methods and Analysis", 2004). Defaults, all changeable through the parameters:

    • Spread: on each candle both assets have (timeframe default 1h, ours: the paper uses daily candles), with pairs-hedge:
      • ratio (default): s = ln A − ln B, the logarithm of the price ratio (β = 1), consistent with the equal-value legs;
      • ols: s = ln A − β·ln B, with β the slope of the (OLS) regression of ln A on ln B, and leg B sized at β times the value of leg A (see Size); a β ≤ 0 is not traded.
      • In both, over the last pairs-len = 250 candles in common (the paper's formation period, there one year of daily candles; on 1h, about 10 days), the Z-Score z = (s − mean) / standard deviation over the same candles. The window rolls forward every candle (the paper fixes the formation estimates for the following trading period). Candles of only one asset (feed failure, market closed) are left out of the computation. The decision for a given time waits for the other asset's candle, and a candle that arrives after the other asset has already moved on to the next one is discarded.
    • Entry: on the candle on which z falls to −pairs-entry-z (default 2, that is, −2) or below (coming from above), buys A and sells B (long spread); on the candle on which it rises to +pairs-entry-z or above, sells A and buys B ("when prices diverge by more than two historical standard deviations", in the paper). It enters on the cross, not on the level (ours: avoids reopening right after a time or stop exit, or entering at startup on an old divergence). Both legs at market, A first; if B fails, A is closed right away. One spread at a time. direction applies to leg A: buy only long spreads, sell only short ones. With pairs-stop-z, a divergence already beyond it is not opened.
    • Exit: both legs at market when z comes back to pairs-exit-z on its side (−pairs-exit-z on the long spread, +pairs-exit-z on the short one; 0, the mean, is our analog of the paper's "next crossing of the prices"), after pairs-max-bars (250) candles in common (ours, one formation window; the paper closes at the end of a 6-month trading period; 0 turns it off), or at |z| ≥ pairs-stop-z (default 0, off; the paper uses no stop). No stop loss or take profit at the broker.
    • Size: with ratio, each leg's lot, which must balance the values of the two (the paper opens "one dollar long and one dollar short"): value = lot × contract size × price. Without lot, each leg is worth half of the position-fraction of the free balance, which then must be below 1 (without position-fraction, the strategy's default, 0.5, ours: a quarter of the free balance in each leg). With ols, leg B is worth β times leg A: with lot, leg A uses its own lot and B is β × the value of A, rounded to the nearest multiple of B's lot (B's lot serves as the step: use the volume step, e.g. 0.01, for the most faithful hedge; the entry is skipped if B rounds to zero); without lot, the position-fraction is split 1/(1+β) and β/(1+β).
    • Reconciliation: on every candle of either asset, a leg open alone (after a close by a stop, by the limits, by hand, or by a close that failed) is closed, and so are two legs on the same side: the position is the spread or nothing.
    • Also accepts: timeframe, direction, lot, position-fraction, leverage and min-position-value. stop-atr, take-profit-atr, max-bars, min-atr-pct and trailing-atr are refused; with stop-value, take-profit-value or max-risk-pct the agent does not start (there is no stop).
    • Positions opened by hand: a lone leg (opened by hand in MT5, or left over from a close) is closed on the next candle of either leg.
    • Protection: the agent's break-even and trailing (Position protection) must stay off: they move and close each leg alone, breaking the hedge (the other leg is closed on the next candle). Do not put a stop or target on a leg by hand in MT5. The news guard and the daily limits can also close one leg before the other.
    • After a restart: the two legs found on opposite sides become the tracked spread again, and pairs-max-bars counts from the opening of leg A.
    • Warm-up: 276 candles in common (the window, the candle before it for the cross, and 10% of slack for candles of only one asset).
    • Limitations: the strategy does not test cointegration: choosing two cointegrated assets is the user's decision. The legs are not atomic, and each round trip pays the spread and fees of both. The backtest report counts each leg as a trade (the win rate is per leg). In a command-line backtest, XAGUSDm and ETHUSDm need -mt5-contract-size (the package does not know their contract size).
    • On the chart: the spread's Z-Score on the recent candles on which both assets have a candle ("Pairs Z-Score" panel).
  • After a restart: the open position the strategy finds is tracked with the legs (stop loss and take profit) that are at the broker, read from the orders stored by the bot.

    • The trailing at the broker continues from them (-trailing-atr of the signal strategies, like donchianatr; matrend -broker-stop; trendconfluence -broker-trailing-atr), counting the best price since the entry from the loaded candles.
    • MaxBars counts the candles since the position's actual opening.
    • The -max-trades of orb and asialondon counts the strategy's own entries in the session and, after a restart, also the positions opened in the session before it, read from the orders stored by the bot (before, the count restarted from zero). Without a restart, a manual trade (opened by hand in MT5) does not count, as always.
    • Limitation: the stored orders do not say who opened the position. So a manual entry made before a restart, in the same session, starts counting after it. Storing the order's origin (a new migration) would close this case; it is a pending decision.
    • The stops on the close (matrend, trendconfluence) are rebuilt from the entry candle, when it is in the loaded window, and never end up wider than the stop at the broker.
    • Without a known opening time (e.g. a position opened outside the bot), the position is tracked from the current candle, as before.
  • Failed exit: as in the LLM agent, the position is not left without stop loss and take profit. On MT5, the close goes out with them in place; in paper, they are canceled first and, if the close fails, placed back at the same levels. The close is retried at every candle close (including that of a matrend and trendconfluence reversal, whose signal has already passed), and a close that leaves the position unprotected is logged as an error.

  • Strategy error (panic): applies to every agent, the LLM one included. A panic in the strategy or in one of its indicators (for example, an index out of range with the day's data) loses only that candle (or that tick of the forming candle) of the asset, and the bot carries on with the next one. The panic goes to the log with the stack and to the dashboard and Telegram as an error, at most one alert every 10 min for the same call (the next one says how many happened in between; those in between go to the log on one line, without the stack).

    • During warm-up (the candles loaded at startup), the panic would repeat at every start: the agent does not start, the error states the asset, the call and the candle, and the controller relaunches it with a growing wait (see Supervision in Controller).
    • In a backtest, the panic ends the backtest with the error, because the result would be wrong.
    • On the dashboard chart, a panic in an indicator leaves only the indicators out; the candle stays on the chart.
  • Candle order: a candle's close always reaches the strategy before the next forming candle, even when they arrive together. Before, one of them could jump ahead and the close was discarded as late (in the LLM agent, without the analysis of that close).

  • Candle closed on MT5: applies to every agent, the LLM one included. A candle closes when the terminal already has the next one. Without it (market idle, closed, or terminal disconnected), it closes 2 s after its end by the agent's clock, but only if the terminal confirms it was connected: a tick of the symbol after the candle's end (by the server clock) or the terminal connected to the server (/health) after the end, read before the candles.

    • Without the confirmation, the candle stays forming, in the warm-up and in the stream, until the terminal has the next candle or reconnects. A terminal disconnected in the middle of the candle no longer delivers the partial candle as closed. After 10 s like this, the log warns once per candle.
    • With the market idle and the terminal connected, the close is delayed by at most one read cycle (1 s).
    • A candle already delivered as closed that the terminal changes later (for example, rebuilt from the server's history on a reconnection) goes to the log with both values. It is not delivered again, because the strategy has already run on it.
    • Agent clock ahead of the server's by more than 2 s (mitigated, not solved): the lead is estimated from the ticks read (the smallest delay between the tick's server time and the read, among the last 20 new ticks read in the last 30 min), and the /health confirmation also waits out that lead, so that the candle closes by the server clock. Without that estimate (right after startup, before new ticks are read, or with no new ticks for more than 30 min) or with a lead above 10 min (treated as the server's time zone, not as clock drift), the agent's clock applies: a candle with no tick after its end can still close early, and the later change shows up in the log, as above. With the clock in sync (up to 2 s of difference), nothing changes, and with the market active the terminal's next candle closes the previous one, as before.
  • Candles kept by the strategy: applies to every agent, the LLM one included. The bot keeps, per asset, the candles of three warm-ups (WarmupPeriod) plus the forming candle, not the whole history since the start. The strategy receives its warm-up at the close, as before. In a strategy that runs on the ticks of the forming candle (the LLM), the indicators run on every tick over these candles, not over a history that grows without limit (in the LLM, about 0.1 ms per tick, versus 4 ms with a month of M1). Recursive indicators (EMA, RSI, ATR, MACD) give the same values they would give over the whole history.

    • Checked before and after the change: the strategies' backtests produced the same orders, and the LLM received the same contexts, including in the interval consultations with the forming candle, except for the last digit of some numbers (sums in talib's order).
  • Protection of several positions on MT5: a stop loss and take profit (OCO) that protects several positions of the asset is placed, moved and canceled position by position. If one of them fails midway, those already changed go back to their previous levels (when placing the OCO, no levels; when canceling, the levels from before; when moving, the old level). So none is left unprotected while the bot tracks the legs, nor at a level different from the leg's.

    • After that, the account is read again, and the error states the levels of each position (as before, CHANGED or WITHOUT PROTECTION) and whether the rollback failed. A position that was not rolled back also goes to the log as an error.
    • A failure on the first position, refused by the broker, has changed nothing: the error is the broker's, as before.
  • Requests to MT5:

    • Closing, protecting or closing by an opposite position (close-by) uses the position's ticket, as MT5 requires. The identifier (the ticket of the order that opened it, which never changes) remains the key of the book and the history. The two differ only when the server reopens the position in a service operation (e.g. a swap charge), in which case a request by the identifier would be refused.
    • With a stops level (trade_stops_level) or a freeze level (trade_freeze_level) on the symbol, the adapter refuses before sending, with an error that states the distances: stop loss/take profit closer to the market than the stops level (for a position, from the bid/ask; for a pending order, from its price); a pending order closer to the market than that level; and a change to a pending order or to a position's levels within the freeze level. Only what changes is checked, and closes and cancellations are never blocked. Without these levels (as on Exness), nothing changes and no extra tick is read. The prices sent are rounded to the symbol's trade_tick_size when it is larger than the point (e.g. 0.25 on an index), besides the digits.
    • Partially filled pending order: it stays PARTIALLY_FILLED with the requested quantity while the rest can still be filled. Fully filled, it becomes FILLED with everything. If the rest is canceled by the bot, canceled in the terminal, or expires, it becomes FILLED with the filled quantity, per the history (without the history after 1 min, from the position's volume), and not CANCELED. The position keeps the order's levels, and the legs keep tracking it. On Exness (CFD), a partial fill is unlikely.
    • Cancellation of a pending order by the bot: after the removal, the adapter reads the asset's positions (one extra read per cancellation, skipped when the book already knows of the partial fill) to find a partial fill the book had not seen yet. With no position from the order, it becomes CANCELED right away, along with the legs. During that read, or if it fails, the order stays PENDING_CANCEL and the legs remain, until the next reads of the account and the history tell what happened: FILLED with the filled part or, if nothing was filled, CANCELED along with the legs. With no position from the order in the account and no history within 1 min, CANCELED applies, as for any pending order that leaves the book without history.
    • Limitation: a position that the terminal listed only after that read (unlikely, because the fill reaches the terminal before the removal) may leave the order CANCELED in the bot, with the legs canceled, although the position stays in the account with the order's levels.
Controller
  • Supervision: launches the enabled agents as child processes, with a new token at each start. With Reiniciar se cair (Restart if it crashes) on, an agent that crashes comes back with the settings it was started with (and the current secrets), after a wait that doubles at each crash (from 5 s up to 1 min, and back to 5 s after 1 min running); with it off, the agent stays stopped (see below). On Linux, the agents and the services stop together with the controller, even when it is killed (see Stopping the controller).
  • Configuration: hands the agents their configuration through an internal API, on loopback only.
  • Records: receives the orders, the decisions and the journal from the agents through a durable outbox. The agent writes locally and sends later, and the strategy flow never waits for the database.
    • Writing to disk: each record goes to the agent's outbox file (data/outbox/<agente>-<id>.db) and is synced (fsync) before the agent moves on. An fsync failure (for example, an I/O error) is a write error, like a full disk: the order is notified and rewritten, and the record is still sent while the agent runs. The file is compacted on open and, while running, when it exceeds 32 MiB and twice its size at the last compaction and no record is pending (so only the set-aside and the held records, which are few, stay in it). Compaction writes a copy, syncs the copy, swaps the file for it and syncs the directory (buntdb's automatic compaction, which syncs none of this, is turned off). The copy is written and synced without holding the agent's writes: a new record waits only for the file swap, which appends to the copy what was written in the meantime and reopens the (small) file, and the log says how long the compaction took. So a power loss loses at most the write in progress, which had not been confirmed yet. The limit is the storage itself: a disk or volume that confirms the fsync without writing (a write cache without a battery, some network or VM volumes) can lose what it confirmed.
    • Sending: in batches, in the order the records were written. A batch the controller cannot read (400, for example too large) is split in half right away, until the unreadable record is alone, and the others go on without waiting for a new order or decision. On stopping, the agent tries to send what is left for up to 10 s and warns in the log how many records were left for the next start.
    • Record refused for good: it is set aside in the outbox file, never resent, with an error in the agent's log, and the following ones are sent. This happens when the controller refuses it (422: unreadable record, invalid data, a database constraint or a PostgreSQL limit, such as an index row that is too large) or when it cannot read it alone (400 or 413) while it reads the records that come after it.
    • Record that alone always fails (503, for example a database error the controller does not treat as a refusal): a batch that fails 5 times in a row (or for 5 min) is split in half at each failure, until the first record is alone. After 5 failures and 5 min alone, each new failure of it is followed by a check, without writing, of the next records of the same type (order, decision, journal or prompt status, among the next 1000): if the controller writes those, it is retried right away, and the new failure counts as proof against it. It is only held (set aside for now) after failing for 30 min with 5 proofs in a row; a check that fails (for example, with an unstable database) resets the proofs. While the controller fails with the records of the same type (for example, with every order), or there is no record of the same type after it to check, nothing is held and the queue waits, and the dashboard shows the sending as failing.
    • Held record: setting aside a record that fails with 503 is a heuristic (a database unstable for a long time can still get a valid record held), so it is not lost. It stays in the outbox file, with an error in the agent's log, and the following ones are sent. It is resent alone when the controller writes records of the same type again and 15 min have passed since the last attempt (the wait doubles at each new failure, up to 4 h; after an agent restart, right after the first record of the same type is written). Once written, it leaves the outbox; refused by the controller (422), it stays set aside for good; if a newer record with the same key is written first (for example, a newer state of the same order or the prompt status), it is discarded, never coming back over the newer one.
    • Memory: the outbox keeps all records in memory, as in the file (the pending, the held and the set-aside ones). No pending record is discarded, because each one is the state of an order, a decision or a model query. So the log warning that the records are not reaching the controller becomes an error when the controller has been down for 1 h or more, or when the outbox exceeds 10000 records or 128 MiB; the error says how many records and how many MiB, and repeats every 5 min. An agent that restarts with the outbox above these limits also logs the error. Set-aside records (refused for good) are kept 7 days for analysis, at most the newest 1000, and then deleted, with a warning in the log. Those set aside by an earlier version, which did not store the time, count the 7 days from the agent's start.
    • Pending records on the dashboard: the agent's card (in Configurações, the Settings page) shows the records that have not reached the database yet when sending is failing or the oldest is more than 1 min old, the set-aside records and the held ones. The age is that of the oldest pending record, reported by the agent at each send (an agent of an earlier version does not report it after a written batch, and it is left out). It is what the agent reported at its last send; a restarted controller only knows it at the next send.
    • Keys: the controller writes each record by the keys of its content (the ID of the order, of the decision or of the journal entry; the prompt status is one per agent). Resending a record duplicates nothing, and a newer state of the same order, decision or status replaces the earlier one (the order never goes back, see below). The sequence (seq) only orders the outbox and restarts when it empties and the agent restarts.
    • Unreadable outbox: the agent does not start, and the log says which file and what to do. With the parameter outbox-quarantine = true, the file is moved to <arquivo>.corrupt-<hora> (kept for analysis) and the agent starts with an empty outbox; if the file opens and only some records are unreadable, only those are set aside. The records of the moved file do not reach the database (for example, the last state of an order). Remove the parameter afterwards. A file cut at the end (the agent killed in the middle of a write) opens with the earlier records, with a warning in the log.
    • Order IDs: the agent reserves the IDs in advance. Without an answer from the controller, it numbers beyond the reservation, and the controller reserves those IDs when it receives the orders. The request for the next reservation is repeated while the controller does not answer, with a warning in the log every 5 min, and stops when the agent stops or the controller refuses the token.
    • An order never goes back in the database or in the agent's memory: a final state (FILLED, CANCELED, REJECTED, EXPIRED) is not replaced by an open one, and a state is not replaced by an older one (updated_at). So the copy of an order written late (for example, that of a limit moved while the order was being filled) does not undo the fill after a restart. A final state replaces an open one even with an earlier time, because the fill time is the broker's and the time of a modification is the agent's. Resending the same state through the outbox changes nothing, and the refused state shows up as a warning in the log.
    • In the bot itself, the writes of an order do not cross. A modification (limit, stop loss, take profit) or a cancellation that the broker answers after the fill does not rewrite the order as open: it stays as it ended, and the modification returns the order in that state (the dashboard shows the order filled). A state read from the broker before a modification is read again in the next cycle (1 s), instead of undoing it. The cancellation writes the order as the bot tracks it (with the moved price), not an old copy. The dashboard and Telegram receive the states of each order in the order they were written, and a slow consumer (sending a notification, for example) does not hold the bot back. In paper and in the backtest, the local storage also never swaps a final state for an open one.
  • Interfaces: serves the web dashboard (login with session and CSRF) and the Telegram bot.
XTrader AI, the supervisor of the agents

XTrader AI is a language model (OpenAI or Anthropic) that watches all agents: it analyzes the whole set periodically, can halt an agent with a rationale and chats through the interface. It only acts through structured tools, which the controller validates and executes with the same protections as the other orders. The model never sends an order, never opens a position or loosens a stop, and never sees secrets.

  • Periodic analysis: off by default. When on (it requires a provider, a model and a key), it runs at each configured interval (from 5 min to 24 h; 15 min in the seed), one at a time: one that coincides with another in progress is recorded as skipped. A model that is down, refuses the key or does not answer in time (timeout_seconds, 2 min in the seed) leaves the analysis as failed, without touching any agent, and the next interval tries again. On start, the controller marks as failed the analysis that was left in progress.

  • What the model receives: a consolidated snapshot, the same as GET /api/supervisor/overview, stored at each analysis:

    • when it was generated, with the time zone, and the result windows (today, the last 24 h and each agent's accounting period), with start and end;
    • the MT5 accounts by alias ("conta 1", that is, account 1), with the currency, the balance, the time of the reading and the reason when they could not be read;
    • the exposure computed in code, per account, currency and pair: buys, sells and how many agents on each side;
    • per agent: name, type, strategy, mode, whether it is enabled and running, restarts, last exit, launch error, outbox, block and stop by the supervisor, pairs, timeframe, the parameters that limit risk (lot, leverage, max-risk-pct, stops etc.), the daily limits of the prompt, the model and prompt of LLM agents, positions (ticket, side, volume, prices, SL/TP, P/L), pending orders, open and realized result per currency, and the last 5 decisions, with the short reason;
    • the gaps: account not read, agent down.

    Money values always come with the account currency, never summed across currencies or converted. Never in the snapshot: keys, tokens, the bridge URL, the account login or the magic number.

  • Criteria: the supervisor's instructions, editable, with the seed's default in three groups: operational (agent down, in a restart loop, outbox failing, position without a stop loss), risk (summed exposure in the same direction, position beyond the agent's own limits) and performance (only with a large enough sample, comparing the agent with itself). The financial limits are those of the daily lock, applied by the system (the supervisor reports the state and does not repeat the action), and those configured in each agent.

  • Actions, always separate:

    • Bloquear novas entradas (Block new entries): the agent does not open or increase positions, and keeps managing those it has (stop, trailing, strategy exits). Nothing is closed or canceled. It applies live, without restarting the agent, and also at the next start of a stopped agent;
    • Parar o agente quando zerado (Stop the agent when flat): blocks entries and cancels the pending entry orders; the agent keeps managing the positions and is only turned off when it has no position and no pending order. No position is liquidated or abandoned;
    • Parar o agente agora (Stop the agent now): only with confirmation, and refused if any position has no stop loss at the broker. The positions keep their stop loss and take profit at the broker;
    • Cancelar pendentes de entrada (Cancel pending entry orders): never the protections (stop loss and take profit) of a position;
    • Fechar posições (Close positions): in the periodic analysis, always a proposal for the user to confirm; in the chat, it runs right away when the user asks explicitly and completely (see Chat). Only the positions of the application's agents (by the magic number), never manual trades;
    • Liberar as entradas (Release entries): only the user;
    • Arm the breakeven or the trailing of a position (protect_position): only on agents that allow the feature ("XTrader AI pode acionar", XTrader AI can trigger), on a position the agent reported, with the agent's trigger kept (before it, the feature only stays armed and the agent applies it when the price gets there). The reason is mandatory and must treat the reversal as a possibility, never as a certainty. On its own, within the cap of actions per analysis; in the chat, when the user asks. The record keeps the reason, the evidence, the position, the earlier stop, the request and what the broker confirmed (see Position protection).
  • Autonomy (configurable): on its own, the supervisor can block entries and stop when flat (the seed's default) and, if turned on, cancel pending entry orders, at most 3 actions per analysis (configurable, up to 10). The rest, and whatever goes past the cap, becomes a proposal for the user, which expires at the next interval. An autonomous action is refused when the snapshot has a gap in the agent or in its account, and the stop only happens when two analyses in a row ask for it for the same agent (the block applies from the first one).

  • Never reactivates: the supervisor has no way to turn on an agent or release entries. Reactivating the agent in the settings also clears the stop mark and the block it created; a block created separately only goes away with Liberar (Release).

  • Chat: a floating button, on every page, opens the XTrader AI panel. It answers using the snapshot (refreshed every 30 s at most) and the user's last 20 messages; the answer shows the time of the data. The answer arrives by streaming (SSE), written as the model writes it, in Markdown (lists, tables, bold, code and http/https links, never HTML). Until the text arrives, an animation says what it is doing: reading the agents, analyzing, querying an agent or building a proposal. An explicit and complete request (the action, the named agents or all of them, and the options, such as "close every position and block every agent") runs right away (execute_action), with no confirmation on screen: the backend builds the scope from a new reading of the accounts, stores the action as requested by the user (with the user's message as evidence), and the result, checked in the account, shows up in the chat written by the system. If an option is missing (cancel the pending orders? keep blocked? stop when flat or now?), the tool refuses and XTrader AI asks. XTrader AI's own suggestions are still proposals, built with the real list of affected agents, positions (tickets) and pending orders, and executed only with Confirmar (Confirm), within 10 min. An ambiguous request (nonexistent agent, more than one agent matching, empty scope) comes back as a question. Through the chat it also reads and sets the daily lock (get_daily_limits, set_daily_limits), always telling one limit for the total of all agents apart from the same limit for each agent, and asking when the request does not make it clear. The history is per user; the action log is a single one, visible to everyone.

  • Reliable execution:

    • a confirmed proposal executes once, even with two clicks or two tabs (the move from "proposed" to "executing" is conditional in the database);
    • actions on the same agent do not cross, and closing several positions is one action at a time;
    • closing for a running agent is done by the agent itself, with "reduce only" orders: if the stop is hit in the middle, the order does not open a new position. An agent that is not running is kept from starting, and the position is closed directly at the bridge, checking before and after that the terminal is on the right account;
    • the result of each item comes from a new reading of the account, repeated for up to 15 s: closed, already closed, still open or unknown. An unknown result (no answer from the broker) is never resent;
    • a position opened after the proposal is not touched; each ticket counts once per account, even with agents on the same account;
    • partial failures stay as Parcial (Partial), with the result of each item;
    • the stop when flat is checked every 15 s: it only turns the agent off with the block confirmed in the agent, no position or pending order in the agent and in the account (read in full), seen that way in readings with at least 10 s between the first and the last, and with nothing pending in the outbox.
  • Record: each analysis (the snapshot sent, the summary, the findings per agent, category and severity, the token usage) and each action (who asked and confirmed, reason, category, evidence, scope and result) are stored in the database. The agent's card and the dashboard bar show the blocked entries and the stop, with who did them (XTrader AI or the user) and the reason.

Position protection: breakeven and trailing stop

Each agent can protect its open positions with breakeven and trailing stop, off by default: without configuring them, the agent behaves as before. XTrader AI can arm each feature on a position, when the agent allows it.

  • Parameters (all in multiples of Wilder's ATR(14) of the closed candles of the agent's timeframe, converted into each asset's price; an agent with XAUUSDm and BTCUSDm uses the same values on both):

    Feature Parameter What it is
    Breakeven gatilho (trigger) favorable move since the entry to activate
    margem (margin) how far beyond the entry the stop goes, added to the known costs
    Trailing stop gatilho (trigger) favorable move since the entry to activate
    distância (distance) how far behind the price the stop stays
    passo (step) least improvement of the stop to send an update to the broker

    Each feature also has Ligado (On) and XTrader AI pode acionar (XTrader AI can trigger), independent of each other. Validation: up to 50 ATR; the breakeven with the trigger above the margin; the trailing with the step up to the distance.

  • Prices: the move and the trailing use the exit price: the bid on a buy, the ask on a sell (the spread of the MT5 candles). The entry is the position's average price, not the candle close.

  • Breakeven: with the move since the entry (the best price reached) at the trigger, the stop goes to the entry + margin + known costs (the entry and exit commissions, the exit one estimated equal to the entry one, and the negative swap, converted into price; in paper, the fee), rounded toward the protection side. This does not guarantee a zero net result: spread and slippage on the exit, and future commission and swap can leave the result negative. Without a known cost, the dashboard says "custos desconhecidos" (unknown costs).

  • Trailing stop: active once the move reaches the trigger; then, at each price, the candidate stop sits the "distância" behind the exit price, rounded away from the market, and is only sent when it tightens the current stop by at least the step (and one tick). Deterministic: no model is queried at each update.

  • Coordination: with protection on or armed in an agent, everything that moves the stop of an open position (the strategy, the LLM agent, the breakeven, the trailing and XTrader AI) goes through the same guard of the order controller: they only tighten, comparing with the live level at the broker, read again under the pair's lock. The most protective stop always wins: a less protective request is refused and whoever asked starts following the stop as it is. llm-widen-stop has no effect. The manual adjustment from the dashboard stays free and can loosen; the trailing tightens again if its rule says so. The legs of a pending entry are not guarded: they follow the entry.

  • Failures: nothing is removed before an update. If the broker refuses it, the stop stays where it was and the next attempt waits 10 s; with the answer lost, MT5 returns the earlier levels and the stop is read again, never resent blindly. At most one update every 2 s per position.

  • Position without a stop: gets one at the feature's level when the trigger is hit (on MT5, keeping the take profit).

  • Restart: the broker's stop is the state; the best price since the entry is read again from the candles. A position adopted after a restart continues from where it was, without loosening.

  • Where it shows: in the chart card, below the header, the state of each feature on the position: waiting for the trigger (how far, in ATR), active (the stop), unavailable (e.g., no ATR yet), the last send (requested, confirmed by the broker or refused, with the stop kept) and, when armed by XTrader AI, its badge with the reason. A stop only shows as applied after the broker confirms it.

  • Only with the agent running: the tracking runs in the agent (paused from the dashboard or with entries blocked, it continues); with the process stopped, the position keeps the stop it has at the broker.

Account currency

All money in the application is in the MT5 account currency, as the broker shows it (BRL on an account in reais, USD on one in dollars), with no exchange conversion by the application. Price is still price, in the pair's quote.

  • Point value: how much a move of 1 in the price is worth, in the account currency, for 1 unit of the asset: the symbol's trade_tick_value ÷ trade_tick_size ÷ trade_contract_size, as MT5 reports it (the tick value already comes in the account currency), read again every minute. It is what turns a price distance into money.
  • Strategies and LLM: the free cash (Position) is the account's. stop-value, take-profit-value, min-position-value and max-risk-pct are in the account currency: "losing 50" with stop-value 50 on a BRL account is the price distance that loses 50 BRL (50 ÷ (units × point value)). The size by fraction of the balance is saldo × fração × alavancagem ÷ (preço × valor do ponto) (balance × fraction × leverage ÷ (price × point value)). The LLM receives the balance, the open P/L and the value_per_price_unit in the account currency (account_currency), and the prices in quote_currency.
  • Dashboard: net profit, the P/L of the orders and of the position, and limits in the account currency. A close still without the broker's value shows as "aguardando a corretora" (waiting for the broker), left out of the sums. The Total column (price × quantity, in the quote) and the core's fee only show in the paper wallet.
  • Telegram: /balance shows the account and /profit sums what the broker recorded (those still waiting, apart). The profit notification waits for the broker's value for up to 60 s; without it, it says it is waiting for the broker.
  • Paper: still simulated in the pair's quote currency (e.g., USD), with a point value of 1, and labeled as a simulation everywhere.
  • Old values: money parameters configured before this change were in the quote (USD); they now count in the account currency. The initial agent matrend uses stop-value 5.4 and take-profit-value 10.8 (BRL, about 1 and 2 in price on one unit of XAUUSDm, with the point value at 5.39 BRL on 2026-10-29).
Daily lock: loss and gain limits

Maximum loss and maximum gain limits for the day, for all agents summed and for each agent. When a limit is hit, the application flattens everything and stops: it closes the positions in scope, cancels the pending entry orders and blocks entries until the day turns. The agents keep running, without opening anything.

  • Scopes:
    • all agents (Configurações › Limites, Settings › Limits): one limit on the summed result, in the accounts' currency, with no conversion. With accounts in different currencies, the same value applies to the result of each currency separately, and when it is hit in any of them, it flattens and blocks all agents;
    • each agent (Configurações › Agentes › Limite diário, Settings › Agents › Daily limit): in the currency of the agent's account. An entry only happens if both the global limit and the agent's allow it.
  • Result of the day:
    • realized since 00:00 (America/Belem, the controller's time zone and the same as the LLM daily limits): the day's exits with swap, commission and fees, plus the commission and fee of the day's entries;
    • plus the open P/L (profit + swap) of the positions open now;
    • read from the deals and positions of the MT5 accounts every 5 s, each trade once per account, even with agents sharing the account;
    • manual positions (without an agent's magic number) do not count and are never touched; agents in paper do not count, but are flattened and blocked with all the others.
  • Trigger: the limit must be hit in two readings in a row, and the lock triggers once per day and scope. The closing:
    1. blocks the agents' entries and waits for the orders being sent to finish;
    2. cancels the pending entry orders and closes the positions: by the agent itself if it is running, directly at the bridge with the launch locked if it is stopped;
    3. checks in the account. A position that still shows up is closed again, up to 3 attempts with 15 s between them; an unknown result is never resent blindly.
  • Least margin for new entries: with a maximum loss set, the new entries of the agents in scope are blocked, without flattening anything, when the margin left until the maximum loss falls below the least margin. The margin is the maximum loss plus the worse of the realized result and the result with the open positions, so that a profit that is still open never lends margin. The least margin is set in each limit (Configurações › Limites and each agent's limit), as a % of the maximum loss: 10% by default, 0 turns it off; the screen shows the value in money.
    • Block: below the least margin in two readings in a row, entries are blocked (waiting for the orders being sent to finish) and the lock is stored (daily_margin_guards, with the trigger and release events in daily_limit_events). The open positions keep their stops, including those of the daily loss. In the dashboard band, Margem mínima atingida: sem novas entradas (Least margin reached: no new entries), in amber, with the reason and the least margin next to the limits.
    • Release: the margin back at the least margin in two readings in a row (for example, with positions closing in profit), the least margin or the limit turned off, or the day turning.
    • Why: on 2026-11-17, the daily loss stop closed a position at −99.99 BRL on a limit of 100. Since the lock only triggers from −100.00, entries stayed released with R$ 0.01 of margin; three agents entered together at 08:30, already negative from the spread, and the day closed at −129.59 by the time it was flattened. With the least margin, entries would have been blocked at 08:16.
    • Limit change: if the change leaves the margin below the least margin, the preview warns; the block comes in the following readings, without confirmation.
  • Stops at the broker (maximum loss): with a maximum loss set and the limit's Proteger com stops na corretora (Protect with stops at the broker) switch on (in each limit, global or the agent's; on by default), protection does not depend only on the flattening done by the application. Every minute, and right away on a limit change, the controller computes for each scope the margin left: the maximum loss plus the result of the day (realized + open), minus the estimated exit costs (the entry commission and fee of each position). Then:
    • Split: the margin is split among the open positions in scope in proportion to each one's loss to its stop now, and the stops move closer to the price in the same proportion. A position without a stop goes in by its exposed value. If the current stops already fit in the margin, nothing changes; a position whose stop is tighter than its share keeps it and leaves the rest to the others. With all agents, each account currency is split separately, like the limit. No position gets the whole margin.
    • Level: each position's share becomes a stop level through the symbol's tick value on the account (trade_tick_value_loss, otherwise trade_tick_value), rounded to the tick toward the price. It stays one tick beyond the broker's minimum distance (trade_stops_level); when that distance forces it, the stop is looser than the share, with a note saying so.
    • Only tightens: a tighter stop (from the strategy, the breakeven, the trailing or an earlier round) stays as it is. The stop is only moved when it tightens by more than 2% of the distance to it (one tick at least). A position covered by both limits (the global one and the agent's) gets the tighter stop.
    • Who applies it: the running agent, through the same path as the breakeven, which answers with the broker's result; while there is a limit stop, the agent's stop guard stays on (the strategy and the LLM do not loosen the stop). A stopped agent, launched by the controller, has its stop adjusted directly at the bridge (TRADE_ACTION_SLTP, the take profit kept, the launch locked), checked in the account afterwards; inside the broker's freeze level (trade_freeze_level), the adjustment waits for the next round. An agent running outside the controller is left out, with the reason.
    • Excluded: the legs of pairs (they protect each other) and an agent with buys and sells on the same asset keep only the flattening.
    • Record: each requested stop, the margin and the position's share, and the last send (confirmed, refused, no answer or not sent, with the reason) are stored in daily_stops; they show in Configurações › Limites › Stops na corretora agora (Settings › Limits › Stops at the broker now) and, on the chart, the position's protection shows Limite diário (Daily limit) with the stop. A requested stop holds while the position is open, the limit and the switch are on and the day does not turn, and it is handed again to an agent that restarts. Turning off the switch or the limit ends the requests; the stops already placed stay at the broker as they are.
    • Limitations: when hit, the stops leave the day near the limit, never exactly at it: slippage and gaps go past the level, and the flattening still applies behind them. With the margin used up (the result at the limit), no new stop is requested: the flattening takes care of the positions.
  • What still applies: stop loss, trailing, breakeven, closes and reductions. The lock does not touch protection or exit orders.
  • What does not get around the lock: restarting the application or the agent, turning the agent back on, Liberar entradas (Release entries), by the user or by XTrader AI, and resetting the balance. The lock is stored (daily_guards) and the entries handed to the agents combine the supervisor's block and the lock's. Only the day turning or an explicit limit change releases it.
  • Limit change: reevaluated right away. If it would trigger or release the lock now, the screen and the chat show the effect and ask for confirmation; each change is recorded (daily_limit_events) with who asked, from where (settings or chat), the reason and the old and new values.
  • Incomplete data: without reading an account in two readings in a row, entries are blocked, without flattening anything, until the reading comes back. What is missing never becomes zero.
  • Where it shows: the Limite diário band at the top of the dashboard, full width, right below the agent bar (the same for any agent shown; the floating XTrader AI panel does not repeat it); and the Limites (Limits) tab in Configurações, which only configures (the global card does not show the state of the day, and the per-agent table shows each agent's). The state and the reason stay in the band: the agent bar and the agents' cards do not repeat the warning. At the top, the band shows the state as a padlock on a badge in the state's color (closed with entries blocked: daily gain or loss reached, or result of the day incomplete; open with them released; the state spelled out on mouse hover and for screen readers) and the flatten button on the right; below, the result of the day highlighted, with the realized and the open, and the limits; last, the limit hit and the time, and until when entries stay blocked (e.g., Perda diária atingida às 10:27: entradas bloqueadas até 00:00 (Belém) (Daily loss reached at 10:27: entries blocked until 00:00 (Belém))), or the reason for an incomplete result, and the agents blocked by their own limit. With a limit hit, it takes the color of a gain (green) or of a loss (red); with the result incomplete, amber. With no limit set, it shows only the label, Sem limite definido (No limit set) and the button below.
  • Zerar + Cancelar ordens (Flatten + Cancel orders): the red button on the right of the band (it flattens every position and cancels the pending orders), different from each agent's ×. It only shows with open positions or pending orders of the agents (while the account reading is not done yet or is incomplete, it shows); on the phone, only the icon. It asks for confirmation in the card itself (saying what it does and what it never touches) and runs an XTrader AI close_positions action over all registered agents, stored as requested by the user.
    • Coordination: a running agent gets a single request, which holds the entries, cancels the pending entry orders and closes all its pairs at market, in that order; a pending order filled while it is being canceled is closed along with them. The agents are served together, up to 8 at a time, and not one after the other (before, a flattening with 5 positions took about 24 s); the result lists each agent in name order. The same applies to the flattening of the daily limit and of the end of a trading hours window, and the × of different agents runs at the same time. The entries stay held for one more candle and are then released: the action never blocks for good, does not disable agents and does not change the limits. A stopped agent has its launch locked, its orders removed at the bridge and then everything it holds closed, including a position opened in the meantime.
    • Protections: the close is at market, reduce-only; the position's stop and target stay until it closes.
    • Scope: only the agents' positions and orders (by the magic number); manual ones and those of other systems are never touched.
    • Result: checked in the accounts, never taken as success just for having been requested: the closed positions, the canceled orders and, under O que resta (What remains), each position or order that is still open, failed or has an unknown result. A close with an unknown result is never resent: it shows up to be checked in the account. The button stays disabled while the action runs; a second request, or an agent's × in the meantime, is refused (409).
  • Limitations: an order sent before the block can be filled (it is flattened right after); the MT5 history lags a few seconds (a position just closed keeps its last open P/L for up to 60 s); between the reading and the close the price moves, so the final result can go a little past the limit.
Trading hours

One schedule for all agents (Configurações › Limites › Horário de operação, Settings › Limits › Trading hours), with one or more windows per day (e.g., 08:00–10:00 and 12:00–14:00), in HH:MM Belém time, the controller's time zone.

  • Windows: up to 24. Each one starts before it ends, within the same day: a window never crosses midnight (to cover the night, use 22:00–23:59 and 00:00–02:00). They cannot overlap or touch (10:00–12:00 and 12:00–14:00 become one). They can be saved in any order and are kept in the order of the day. When on, the schedule needs at least one window. The windows are in trading_hours_windows (migration 40); the first one is also in the columns of trading_hours, for the earlier readers. A single-window schedule saved before still applies as the first window.
  • Agents of each window: each window's agents button picks one or more enabled agents that can open positions in it. With none checked, the window applies to all. With agents checked, the others are blocked during it, with the reason (e.g., Janela 08:00–10:00 só para highlow, matrend (Window 08:00–10:00 only for highlow, matrend)). The agents are in trading_hours_window_agents (migration 41), by id: renaming an agent keeps it in the window. The end actions apply to all agents, whichever agents the window has.
  • Assets of each window: each window's Ativos (Assets) field takes the assets the agents can open positions on in it, as MT5 names them, one chip per asset: once an asset is typed, Enter (or ; or ,) turns it into a chip, as does leaving the field. Several pasted at once (e.g., XAUUSDm;BTCUSDm) become one chip each, a repeated asset does not go in again, a chip's × removes it and Backspace in the empty field removes the last one. A chip that is not an MT5 asset name turns red, with the reason. Empty, the window applies to all assets. With assets, an entry on another asset is refused by the agent's strategy, with the reason (e.g., Janela 08:00–10:00 só para os ativos XAUUSDm, BTCUSDm (Window 08:00–10:00 only for the assets XAUUSDm, BTCUSDm)). Exits, stops and targets always pass, and the end actions apply to all positions. The assets are in trading_hours_window_pairs (migration 42).
    • How it reaches the agents: along with the entries the controller sends (entries_pairs and pairs_reason in agentapi.Entries, in the same revision). The agent keeps the assets in an agentapi.PairGate, which the entry filter (entryfilter) checks before each strategy entry. In an agent with no filter configured, the filter is installed only for this and does not measure or read anything else. The LLM agent checks the same gate when applying a decision, as it does with the daily limit and the news. In the backtest, the batch's schedule updates the gate at each window.
  • Outside the windows: no agent opens a position. The entries of all agents are blocked, as in the daily lock: sent right away to the running agents, waiting for the orders being sent, and applied by the stopped ones when they start. When the next window opens, they are released by the agents' runtime. The reason says until when, e.g., Fim da janela 08:00–10:00: entradas bloqueadas até 12:00 (End of window 08:00–10:00: entries blocked until 12:00).
  • At the end of each window, as checked in it:
    • Zerar posições (Flatten positions): closes the agents' positions (a close_positions action, of automatic origin, with the same path as the Zerar + Cancelar ordens (Flatten + Cancel orders) button: by the agent if it is running, at the bridge with the launch locked if it is stopped, checked in the account);
    • Cancelar ordens pendentes (Cancel pending orders): cancels the pending entry orders (along with the close, under the same hold of the entries, or in a cancel_pending of all agents when only this one is checked).
    • Unchecked, whatever is open stays as it is, with the stops; only new entries are blocked.
    • Only the agents' positions and orders (by the magic number); manual ones are never touched.
  • Once per window: the actions run when the window ends after having been open, with what it had checked when it opened or at the last change made while it was open.
    • With the application stopped at the end of a window, they run when it comes back, even if it is already the next window. In that case, entries stay blocked until the positions are closed, and only then does the next window open.
    • Changing the open window while keeping the current time inside it does nothing (the new end applies); changing it so that the current time falls outside every window counts as its end, right away.
    • Turning the schedule off with a window open releases the entries without flattening anything, and turning it on later outside the windows only blocks.
    • Turning the schedule on outside the windows only blocks entries. Restarting the application does not repeat the actions or release the block.
  • Record: each schedule change, each opening (with the window) and closing, and the end actions of each window (with the window, the action and the result) are stored in trading_hours_events; the id of the last event goes into the revision of the agents' entries.
  • Where it shows: the Horário de operação card on the Limites tab (state and windows) and, on the dashboard's daily limit card, a badge with a clock: Aberto · fecha às 10:00 (Open · closes at 10:00) or Fora do horário · abre às 12:00 (Outside hours · opens at 12:00), with the windows on mouse hover.
Exposure per asset

A maximum of agents with a position on the same asset and in the same direction at the same time, for all agents, set by rules (Configurações › Limites › Exposição por ativo, Settings › Limits › Exposure per asset): with the rule XAUUSDm, BTCUSDm | 2, if trend and orb are already long XAUUSDm, a third agent does not buy XAUUSDm, but can sell it or buy BTCUSDm.

  • Rules: each rule has its Ativos (Assets), as MT5 names them, one chip per asset (typed like the assets of the trading hours windows), and the Máximo de agentes (Maximum agents), from 1 to 100. The maximum applies to each asset of the rule separately, per direction (buys and sells count separately): with USOILm, UKOILm | 4, up to 4 agents long USOILm and up to 4 long UKOILm. Adicionar regra (Add rule) creates another rule, for assets with another maximum; the trash icon removes it. An asset stays in one rule only, and there are at most 50 assets.
  • No rule: an asset without a rule has no limit, and with no rule at all the limit is off. A rule left blank is ignored on save.
  • When opened again: the assets with the same maximum show together in one rule, by name, and the rules by maximum: the controller stores each asset's maximum.
  • Who takes a slot: each agent with a position on the asset and in the direction, read from the MT5 accounts by the magic number, or with a pending entry order on it (the pending order of an agent that already has a position on the asset protects or adds to the position, and does not take another slot). An agent counts once, however many positions it has. Manual positions (without an agent's magic number) and agents in paper do not count.
  • How it is checked: before sending each entry, the agent asks the controller for the slot (POST to agentapi.ExposurePath, with the asset and the side). The controller serves one request at a time, with the accounts read at most 2 s before, and reserves the granted slot for 2 minutes, until the order shows up in the account. So agents entering in the same second never go past the limit together, and the slot of an order that was never sent becomes free again. An agent that is already on the asset and in the direction always gets the slot.
  • Entry refused: the strategy does not send the order and records the reason, e.g., Exposição máxima em XAUUSDm: 2 agentes já estão comprados (orb, trend) (Maximum exposure on XAUUSDm: 2 agents are already long (orb, trend)). Without a reading of some account (bridge not answering, token refused), the entries with a limit are refused (Não foi possível conferir a exposição: sem leitura de … (Could not check the exposure: no reading of …)): nothing goes in blindly.
  • How it reaches the agents: along with the entries the controller sends (exposure in agentapi.Entries). With the limit on, the entry filter (entryfilter) asks for the slot after the other blocks have let the entry through; in an agent with no filter configured, the filter is installed only for this. The LLM agent asks for the slot when applying a decision, after checking the daily limit, the news and the window's assets. A change of the limit applies to the next entries.
  • What is never limited: exits, stops, targets and protection orders. The limit does not close anything already open: if it goes down with more agents on the asset, only the new entries wait.
  • Where it applies: only on agents in live. Agents in paper, which have no positions in the account, are never refused and never take a slot, and the backtest, where each agent runs alone, is not limited.
  • Where it is stored: in exposure_limits (migration 43), a single record, with each asset's maximum in pairs and who changed it last. The max_agents column, from the first version's single maximum for all assets, is no longer read or written (it stays at 0).
Agents per asset

Which agents can open positions on each asset, for all agents, set by rules (Configurações › Limites › Agentes por ativo, Settings › Limits › Agents per asset): with the rule XAUUSDm, XAGUSDm → orb, trend, only orb and trend open positions on XAUUSDm and XAGUSDm; the other agents keep trading their other assets.

  • Rules: each rule has its Ativos (Assets), as MT5 names them, one chip per asset, and the Agentes que podem operar (Agents that can trade), picked in a dialog (at least one). An asset stays in one rule only; there are at most 50 rules. Adicionar regra (Add rule) creates another; the trash icon removes it; a rule left blank is ignored on save.
  • No rule: an asset without a rule is free for all agents that trade it; with no rule at all, nothing changes.
  • How it is applied: the controller computes, for each agent, the agent's assets that the rules allow, crossed with those of the open trading hours window (when the window limits the assets), and sends the list along with the entries (entries_pairs in agentapi.Entries, with the reason in pairs_reason). The strategy (the entry filter) and the LLM agent check the list before each entry, as they already did with the window's assets, and record the reason for the refusal, e.g., Agentes por ativo: XAUUSDm só para os agentes orb, trend (Agents per asset: XAUUSDm only for the agents orb, trend). It applies right away, without restarting.
  • No asset allowed: an agent that cannot trade any of its assets has its entries blocked, with the reason (Nenhum ativo permitido. … (No asset allowed. …)), and trades again when a rule includes it.
  • What is never affected: exits, stops, targets, protection orders and positions already open.
  • Where it applies: on agents in live and in paper. In the backtest, when the batch checks Respeitar os agentes por ativo de Configurações › Limites (Respect the agents per asset of Settings › Limits) (checked by default; see Backtesting).
  • Renaming an agent updates its name in the rules.
  • Where it is stored: in asset_agents (migration 48), a single record, with the rules in rules, a revision that grows at each change (the agents get the newest one) and who changed it last.
Web dashboard
  • Painel (Dashboard):
    • price chart filling the card, with the orders and the stop and take profit lines; in the top corner, inside the chart, the timeframe selector and the buttons for full screen, candles ou linha (candles or line) and the crosshair, which goes back to the current candle and price (on a narrow screen, in a row just above the chart); the legend starts with the asset, before the indicators, and the drawn LLM analysis and the position protection sit in a thin row above it, only when they exist. In line mode, the price is the line of the closes in blue over a gradient area, with the last-price line dotted; the orders, the markers, the draggable lines, the LLM analysis and the price scale are the same as with candles. The choice is kept in the browser;
    • the LLM analysis, when the prompt draws: zones (translucent boxes), levels and markers, colored by bias (bullish, bearish, neutral), behind the candles and with the labels on top; the chart legend says which analysis they belong to (timeframe, time and how many supply and demand zones). The supply zones (red, descending hatching) and demand zones (green, ascending hatching) stand apart from the other zones by the hatching and by the reinforced border on the side the price reaches (the bottom of supply, the top of demand), with the label Oferta (Supply) or Demanda (Demand) followed by the model's label; the state shows in the fill (a tested zone is lighter) and in the decision, and a broken one carries rompida (broken) in the label, faded and dashed up to the candle that broke it. An entry intent that did not become an order (ignored, refused or not executed) appears dashed, with the result in the label. Pending orders appear by type (C LIMIT, V STOP; C = buy, V = sell), with the legs waiting for the fill as SL pend. and TP pend. (long dash); a pending order that ended stays as a segment at its price during the wait, solid if filled and dashed if canceled, expired or rejected. Everything follows the broker's order events and the decisions in real time. In a decision's dialog, Mostrar no gráfico (Show on chart) draws that decision's analysis, with the levels it proposed, until Voltar à análise atual (Back to the current analysis);
    • at the top, the context bar: the agent, the pair (in segmented buttons, up to 6 pairs; in a list beyond that) and the agent's state: the bot (start and stop) and the timeframe and model the strategy runs on;
    • just below, edge to edge, the accounts card of all agents, whatever agent is chosen, with three values side by side, all in each account's currency, as the broker shows it (BRL in an account in reais, USD in one in dollars; accounts in different currencies at the same time give one total per currency, without conversion):
      • P/L em aberto (open P/L): the sum of the profit and swap of the positions open now in the MT5 accounts, read every 5 s;
      • P/L fechado (closed P/L): what the accounts recorded for the agents' positions closed in the period (profit, swap, commission and fees of each exit, the same way each agent's net profit counts a close), read every 15 s. It includes an agent's position closed outside the bot (by hand, by stop out): it belongs to the agent of the entry's magic number. The period appears above the title; a double click on the title (or Enter, with it focused) opens the choice: Hoje (Today, since 00:00), Semana (Week, since Monday), Mês (Month, since the 1st) or Personalizado (Custom, from the first to the last day chosen, up to 400 days), by the browser's time. The chosen period is kept in the browser; without one, Hoje applies;
      • Saldo (Balance): the sum of the balances of the accounts read, each account once by login, and how many there are;
      • each value with its label, the values aligned and a mark on the left that tells them apart: blue the open one (live), orange the closed one (of the chosen period), neutral the balance;
      • below them, after a discreet line (vertical, when the values and the chart sit side by side), the P/L acumulado (cumulative P/L) of the period, with the legend (--- aberto + — fechado) (open + closed): as a solid line, the closed P/L, the sum of the same exits the closed P/L value counts, one after another in the order they happened, starting from zero at the start of the period and moving in steps at each exit, held until now (or until the end of a past period), drawn like the quote card's line (green when positive, red when negative); in a period that has not ended, with open positions, the line continues dashed up to the closed P/L plus the current open P/L, in real time; one chart per currency, without conversion. When the period changes, the chart and the value show the loading and then the new period, never the previous one; with no exits in the period or with a read error, the card says so in place of the chart;
      • separated by a discreet line, one block per agent: on a wide screen, next to the values for up to 8 agents (the chart grows to their height); with more, below, at full width and with more blocks per row, with the values and the chart side by side on top. Each block shows the icon, the name and, one row per asset and direction, an arrow (up for a buy, down for a sell; "Compra em XAUUSDm, 2 posições abertas" (Buy on XAUUSDm, 2 open positions) on mouse hover and for screen readers) and the open P/L of its positions in that asset and direction (e.g. ↑ XAUUSDm: +22,60); an asset bought and sold at the same time appears in two rows, never as a single direction of the agent. Only the assets with an open position appear, and each one is a link: clicking BTCUSDm in the highlow block shows highlow on BTCUSDm in the dashboard (with Ctrl or the middle button, in a new tab); the agent and asset shown are highlighted. An agent not on the dashboard (turned off) has no link. With no open position, the block shows only Sem posição aberta (No open position), plus the closed P/L in the period, without the configured assets; the rows follow the opening and closing of the positions. The sum sits at the top when there is more than one row, and the closed P/L in the period comes last (the closed P/L comes per agent, without the asset). The block's background is slightly green with a positive open P/L, red with a negative one and neutral with zero or no open position; an agent whose account could not be read appears dashed, with Em aberto: sem dados (Open: no data), never as zero. The value and the sign still tell the result, without relying on color; a stopped or disabled agent appears marked, and its positions keep counting. With an open position, the block has a × that closes at once, without confirmation, all of that agent's positions at market: an XTrader AI close_positions action (through the agent, or directly at the bridge when it is stopped), checked in the account and recorded. The other agents are not touched; pending entry orders stay; entries are not blocked (the agent waits one candle). The button spins and stays disabled until the result (repeated clicks do nothing), and the real result appears in the block: the positions closed and what failed or stayed unknown;
      • the controller reads the positions, balances and deals directly from the bridges of the accounts of the live agents, enabled or not, running or not, and recognizes each agent's ones by the magic number (preferring the agent that trades that pair);
      • each position and each deal count once, by the ticket in the account (login), even with several agents or several URLs on the same account; positions without an agent's magic number (manual ones) are left out, as are the agents in paper, which have no real positions;
      • if an account could not be read (bridge not answering, token refused, terminal error), the value shows Incompleto (Incomplete) and the card says which agents' data is missing: they do not count as zero;
    • the quote card: the pair, the last price, the asset's change over the loaded candles (buy & hold) and how many they are, and, at the bottom of the card, edge to edge, the line of those candles' closes;
    • the Sentimento do mercado (Market sentiment) card (LLM analysis): the market reading from the pair's most recent decision that has one (from 0, very bearish, to 100, very bullish), in an arc of the five bands with the reading's band highlighted, the value and the band in the center, the time, and the previous reading (a dot on the arc) with the change since it. Only in LLM agents: in the others, the card does not appear and leaves no space (see LLM cards, below);
    • the results in cards (return with the equity trend and drawdown, with a paper wallet; trades, win rate, net profit, profit factor), with the value as large as the card allows and reduced only when it would not fit whole. Win rate, net profit and profit factor show next to the value their evolution trade by trade, over the same trades as the value (the profit factor from the first loss, infinite before it); the net profit card also shows the open position with its P&L, or "Sem posição aberta" (No open position). With the broker reporting the results (MT5), the net profit is what the account recorded for each close, in the account currency (BRL in an account in reais, USD in one in dollars), with swap, commission and fees; each close is matched to the position it closed the way the core computes it, even after a position closed outside the bot (by hand, by stop out). A close whose value the broker has not recorded yet (the MT5 history arrives seconds later, and is read 60 days back) stays out of the sum, and the card says how many are waiting for the broker: it never becomes a value in another currency. In the paper wallet, the profit is the core's, in the quote currency, labeled as a simulation;
    • in an LLM agent, the model's last decision, below the chart: the action, the rationale, the confidence, the result and access to the full dialog;
    • below, in tabs: the order history; the model's decisions, with each one's context, and the analyses in which the model was not consulted ("Não consultado", Not consulted), with the reason, and the Reanalisar agora (Reanalyze now) button, enabled by the agent's Permitir reanálise (Allow reanalysis) switch; and the equity curve (with a paper wallet). The chosen tab is kept in the browser. The card (Atividade do agente, Agent activity) has a fixed height, whatever its content: that of the news card, measured as it changes (the chart resized, an LLM agent's last decision), or 640 px when the two are on the same row or the news is hidden. The title, the tabs, the summary and the pages stay in place; only the table scrolls when it exceeds the height, with the header visible (on a phone, the row cards scroll inside the card), and the equity curve fills the card's space.
  • Hiding the values: the eye button in the top bar hides, on every page, the balances and money values (P/L, balance, profit, daily limits, the values on the Performance page, the position's P&L on the chart), with ••••• in place of the digits; the same button shows them again. Prices, quantities and percentages stay visible, and so do the gain and loss colors; backtest results, which are simulations, do not change. The choice is kept in the browser, the same in every tab.
  • LLM cards: Sentimento do mercado, Última decisão do LLM (Last LLM decision) and the Decisões do LLM (LLM decisions) tab appear only in LLM agents; the other cards belong to all agents. In an agent of another kind, these cards stay out of the dashboard without leaving space, but do not count as hidden: their position in the saved layout stays the same, even if another card is moved in the meantime, and they return to it when switching to an LLM agent. When switching agents, the dashboard starts from scratch: while the new agent loads, the placeholder blocks already follow its kind (without the sentiment one in an agent without LLM), and nothing from the previous agent stays on screen.
  • Appearance: the cards are glass: translucent over the page's light, with the background blurred behind them, a thin border and a soft shadow, in both themes; the chart is drawn over the glass. What sits on top of them (lists, dialogs, the XTrader AI panel, the full-screen chart) stays opaque. On a phone the blur is lighter; without blur support in the browser, or with reduzir transparência (reduce transparency) or mais contraste (increase contrast) turned on in the system, the cards fall back to the opaque panel.
  • Card layout: the layout button in the top bar (grid icon) opens the dashboard customization. A card that joins the dashboard after the layout was saved (such as the open P/L) appears in a row of its own at the end, without moving the rest; Restaurar padrão (Restore default) puts it in its place in the default layout. The dashboard is made of rows, each row of columns and each column of stacked cards, and any card goes to any row or column:
    • Moving: each card gets a bar above it, dragged with the mouse or a finger. Dropped on the left or right edge of another card, it becomes a column next to that card's column; on the top or bottom edge, it is stacked above or below it; in the middle, the two swap places; in a strip between rows (or at the end), it gets a row of its own; in the empty space of a row, it joins as a column at the end of that row. With the bar focused, the keyboard arrows also move the card: up and down within the column (at its top or bottom, to a row of its own; alone in the row, it swaps the row with the neighboring one) and sideways (it leaves the column for a column of its own on that side; alone in the column, it swaps places with the neighboring column).
    • No reserved space: a column or row left without cards (because the card was moved or hidden) disappears, and the other cards of the row share the width. The ✕ hides the card (display only: the data and functions continue, and it comes back through the Mostrar (Show) button, in the same place).
    • Widths and heights: the columns of a row share the width, each with a minimum (300 px the quote, 240 px the sentiment, 280 px the results, 260 px the decision, 360 px the chart and the activity, never more than an equal share of the row). A column alone in its row takes the whole row. In a row of only compact cards (quote, sentiment, results, decision), they have the same height; next to the chart, the activity or a column of several cards, each one takes the height of its own content.
    • Chart: it is the only card that resizes, by its edges: the bottom bar changes the height (from 280 px up to the window's, or automatic), the right one the width (from 360 px up to its row's, minus the minimum of the row's other columns, or automatic) and the corner, both. The row's other cards adjust while it is dragged. Alone in the row, dragged to the row's end, it goes back to automatic width and takes the whole row, and a card dropped in the space beside it gets the rest. A saved width larger than the screen can fit is reduced down to the minimum of the other cards, without overflowing the page. The cards stacked with it follow the column's width. The chart redraws at the new size, and moving the card does not recreate it: the zoom and position remain (and so does the tab chosen in the activity).
    • Smaller screens: below 1200 px, a row of three or more columns gets two; below 1024 px (tablet), the rows stack, with the chart at screen width (the chosen width does not apply), except the rows of only compact cards (each in its own column), which stay in two columns; on a phone (below 768 px), everything is in one column. The default layout stays as before at every width.
    • Only the bars drag: the buttons, fields and chart of the cards (zoom, dragging the chart, moving orders) keep responding. Outside customization, the dashboard looks as it does without it. The arrangement, the hidden cards and the chart size are stored in localStorage (xtrader.dashboard.layout, version 2; an arrangement saved in the previous format, of areas, is converted into rows) and come back on reload; without a saved arrangement, with an invalid one, or without localStorage, the default layout applies. Configurações › Layout (Settings › Layout) shows what was customized, and Restaurar layout padrão (Restore default layout) removes only that preference, applying the default at once, including on dashboards already open.
  • Chart timeframe: a selector in the corner of the chart shows the asset in 1m, 5m, 15m, 30m, 4h or D (daily), and in the strategy's execution timeframe when it is not among those. The selection changes only the view: the execution timeframe (the agent's timeframe parameter, marked with a dot in the selector) remains the timeframe of the candles the strategy receives, of the LLM analyses and of the decisions; it only changes in the agent's settings, with a restart.
    • In the execution timeframe, the chart is the usual one (candles, indicators, orders and analysis). In the others, the candles come from the agent (GET …/{par}/candles), the orders and the LLM analysis are aligned to the candle that contains each time, the strategy's indicators (computed in the execution timeframe) are not drawn, and the position, the pending orders and the reanalysis stay the same, in real time.
    • Where the candles come from: in an agent connected to the broker (MT5) or in paper, the closed ones are read from the broker (cached for 2 s, one read serving all dashboards) and the forming candle is built by the agent: above the execution timeframe, from its candles (exact); below it, from the prices the chart received (approximate: open at the previous close, high and low of the prices received, no volume), corrected by the broker when it closes. In a backtest, only the timeframes above the execution one, multiples of it, built from the strategy's candles; the others appear disabled.
    • The dashboard rereads the last candles of the timeframe shown every 15 s and when the period of the last one ends, and carries each event's price to the forming candle. A late response from a previous timeframe or asset is discarded: while the new one loads, the chart stays empty with "Carregando candles de …" (Loading candles of …), never with the candles of another timeframe. The chosen timeframe stays in the address (?tf=4h).
  • Slow client: an asset's snapshot is built at once and only then sent, without holding up the agent: a phone downloading slowly (through ngrok, for example) does not delay the orders, the candles or the other requests. The account currency comes from the connection to MT5, without querying the broker on each snapshot. The candles reach the strategy and the chart through separate queues, in order, and a busy chart does not delay the strategy. The queues have no limit, because dropping or merging candles would change what the strategy sees: a queue with 1000 candles or more (a stuck consumer) logs a warning, at most one per minute. Non-finite numbers (NaN, infinity) of an order or of the position go out as 0, and a chart line with them is left out: the asset's snapshot and events do not fail because of them.
  • Chart window: each asset's chart keeps the last 5000 closed candles (about 3 days on M1, 17 on M5 and 7 months on H1), plus the indicators' warm-up before them. So the snapshot and the indicators, recomputed at every close and every snapshot, do not grow with the agent's running time. The orders all remain in the dashboard, for the statistics. An order older than the first kept candle appears on the first candle, as already happened with the orders of previous runs. The "Buy & hold" counts only the chart's candles. A backtest's chart keeps all candles.
  • Reconnection: when the real-time events drop (network, agent restarting) and come back, the dashboard reloads the asset's snapshot, the decisions and the bot state, because what happened during the drop (orders, position, candles) does not arrive through the events. A browser that does not keep up with the events (256 in its queue, for example on a slow network) loses the following ones: the agent ends its event stream, and the dashboard reconnects and reloads the same way, instead of staying out of date. If the connection is refused, the dashboard checks the session: with no session (expired or ended), it goes to the login; with one, or with no answer from the dashboard, it tries again every 5 s.
  • Bot: start and stop each agent's bot in the state at the top of the dashboard, next to the agent and the pair. The button itself tells the state: Parar bot (Stop bot), confirmed in place, with the bot running, Iniciar bot (Start bot) with it stopped; with no bot to control, only desativado (disabled) appears. It applies only to the agent shown: the others keep trading.
    • Stopped stays stopped: the stop (from the dashboard or the Telegram /stop) is recorded in agent_bot_controls (migration 44), with who stopped it and when, as soon as the agent confirms it. If the agent's process restarts (deploy, host reboot, a crash with Reiniciar se cair (Restart if it crashes), the Reiniciar (Restart) button or the Parametrizador global (global parameter editor)), it comes back with the bot stopped: the agent stops the bot as soon as it starts, before the first candle. Only Iniciar bot or /start release it again. Before, a restart came back with the bot running.
    • Bot stopped: no new order from the strategy goes out, neither entry nor exit. The protection of the open positions (the stop and target at the broker, and moving them), the closing of a position by XTrader AI or by Zerar (Flatten) and the cancellation of orders continue. Pending orders already at the broker stay there; use Zerar + Cancelar ordens (Flatten + Cancel orders) first, if needed.
    • Where it shows: the agent's card in Configurações › Agentes (Settings › Agents) shows Bot parado (Bot stopped), with who stopped it, when, and that it stays stopped after a restart.
  • Configurações (Settings), by section (in the top navigation):
    • Agentes (Agents): the LLM ones separate from the strategies, these grouped by family; create, edit, rename, delete, turn on and off, restart and set the secrets.
    • Renomear (Rename, a button on the agent's card): only with the agent disabled and stopped. It changes only the name: the agent keeps its ID, its account (comment and magic number at the broker, so the positions remain its own), the model, the secrets, the orders, the decisions, the results and the queue of records not yet sent (the file data/outbox/<nome>-<id>.db is renamed with it; if the change fails, nothing changes). The old name stays in agent_former_names, so the seeds do not recreate the agent with it, and it is free for another agent. In Telegram, the agent is selected again by the new name (/agent).
    • Resultados (Results, a button on the agent's card): the results by period and their reset. See Resetting the results.
    • Contas MT5 (MT5 accounts): the accounts of each terminal and the coordinated switch of the active account. See MT5 accounts.
    • Limites (Limits): the global daily limit, the trading hours, the exposure per asset, the agents per asset and each agent's limits.
    • Notícias (News): the economic calendar and the blocking window of all agents. See News.
    • Prompts: editor with version history.
    • XTrader AI: see XTrader AI.
    • Telegram: turns the bot on and off, token and authorized IDs.
    • Usuários e papéis (Users and roles): the dashboard users and the permissions by area (see Security).
    • Layout: the arrangement of the dashboard cards in this browser and the Restaurar layout padrão button.
    • Importar e exportar (Import and export): the configuration in a JSON file. See Importing and exporting the configuration.
  • Navigation and layout: the top bar leads to the Painel and to the sections of Configurações in a segmented control (next to the brand on desktop, in a second row below 1200 px, a drawer through the ☰ button on a phone), with each section's count; the Painel link goes back to the agent, pair and timeframe left there. The cards follow one pattern (a short highlighted label over the title, values in a monospaced font) and orange marks what is chosen and the main action. Dark and light theme. On a phone, tables become cards and dialogs open as panels coming from the bottom; in a table too wide for the screen, the actions column stays fixed on the right.
Performance

The Performance page (in the bar, next to Painel (Dashboard); /performance) shows the result of the trades of the live agents, in the style of the "Resumo de Performance" (Performance Summary) of Nelogica's Profit.

  • Source: the deals of the MT5 accounts, the same as the closed P/L card's, in each account's currency, without conversion. With accounts in different currencies, each currency has its own summary (the "Moeda da conta", Account currency, selector). Only the agents' positions count (by the entry's magic number); manual ones and paper agents are left out.
  • Trade: a position whose last close fell in the period and of which nothing stayed open, counted once even if closed in parts. It has asset, agent, side, lots, open time, close time, duration, entry price and average exit price, gross result (the profit of the exits), costs (commission, fee and swap of the entry and the exits) and net. A position opened more than 30 days before the period has no open time and no duration. Unlike the closed P/L card, which sums only the exits, here the net includes the entry commission.
  • Filters: period (Hoje, Semana, Mês or Personalizado, that is Today, Week, Month or Custom; kept in the browser separately from the card's), agent and asset. The numbers are reread every minute and by the Atualizar (Refresh) button.
  • Resumo (Summary):
    • net balance and total balance (before costs), gross profit and gross loss, costs and profit factor (gross profit ÷ gross loss);
    • winning, losing and break-even trades, by the result before costs, and the percentage of winners;
    • average per trade (net), average of the winners and of the losers and the ratio between them, largest gain and largest loss, longest streaks and average times;
    • maximum lots and initial capital (the accounts' balance at the start of the period, rebuilt from the current balance minus everything the account recorded since then, deposits included);
    • return on that capital, maximum equity (the peak of the cumulative net) and percentage of time in the market;
    • maximum drawdown of the cumulative net, in value and in % of the equity at the peak (initial capital + peak). Without the path of each trade, it is measured between closes, so peak-to-trough and trade-by-trade give the same number and only one appears.
  • Gráficos (Charts):
    • equity: the cumulative net, green above and red below zero;
    • the result of each trade;
    • by period: by day up to 31 days, by week up to 180, by month beyond that;
    • by asset and by agent.
  • Operações (Trades): the list, most recent first, with the running total, MFE, MAE and total efficiency, and Baixar CSV (Download CSV), a file separated by ;, with times in UTC, the filters applied and the entry, exit and total efficiencies.
  • Efficiency (the Gráficos › Eficiência view and its group in Resumo): the price path of each trade while it was open, read from the broker's candles (the bridge's /rates), in the smallest timeframe that fits in 5,000 candles (M1 up to ~3.5 days, then M5, M15, H1, H4, D1).
    • MFE/MAE: the maximum in favor and the maximum against, in money in the account currency, valued like the trade itself (the gross result over the price move; with no move, the lots by the symbol's tick value). On the chart, each trade is a bar from MAE to MFE with a dot at the result.
    • Efficiencies (those of TradeStation and Profit, over the price range from low to high): entry, how close to the best price it entered; exit, how close to the best price it exited; total, the result over the range (negative on a loss).
    • In Resumo: average MFE and MAE, the average efficiencies, the "deixado na mesa" (left on the table: how much the winners gave back from the best point) and the largest MAE of a winner (how far a gain went against it, a reference for the stop).
    • Limitations: MT5 candles are bid, and for a short the spread of each candle is added (the price at which it closes); the entry candle and the exit candle may have prices from before or after the trade, and the extremes always include the realized entry and exit. A trade with no known open time has no path. The first access to a period reads the candles of each trade, which can take a few seconds; after that, each trade read stays cached while the controller runs.
Backtesting

The Backtesting page (in the bar, next to Performance; /backtesting) runs the agents' strategies over the history of their assets, several at a time, and compares the results under the same conditions. It serves to decide which agents to turn on; turning them on is still done in Configurações › Agentes (Settings › Agents).

  • Isolation: each run is a separate process of the binary of the agent's kind, in -mode backtest, with a CSV feed and a paper wallet.
    • The process does not receive the agent's token, the account and bridge flags or the bridge tokens (MT5_BRIDGE_TOKEN, MT5_MCP_TOKEN); an LLM agent receives only the key of the model's provider.
    • It never sends an order and never writes to the agents' tables, balances or histories. The controller only reads the candles (/symbol and /rates) from the bridge of the agent's account.
    • The tests prove this with a fake bridge that records the requests: none reaches the agent, and the controller only makes reads.
  • Configure: the agents (the incompatible ones appear disabled, with the reason), the assets (a subset, or all of each agent's), the period (up to backtest.max_period_days), the out-of-sample validation, the timeframe (the agent's or another, which tests a variation), the initial balance, the fee, the fallback spread, the slippage, the daily limits, the trading hours, the agents per asset and the caps of the LLM agents. Before submitting, the page shows the assumptions and the estimate of LLM calls and cost.
  • Runs: queued in the controller, backtest.concurrency at a time. Each has a status (queued, running, done, failed, canceled, interrupted, LLM cap reached), progress, duration and the error. They continue with the page closed; a controller restart marks the ones that were running as interrupted. Canceling stops the process and keeps the partial report.
  • Results: one row per agent, with the fit and the validation side by side.
    • Metrics: return/drawdown, net, return %, maximum drawdown (% and value), profit factor, win rate, trades, open at the end (apart), positive months and the validation.
    • No row is "the best": the default sort is return/drawdown, every column sorts, and there are filters for minimum sample and LLM agents.
    • Robustness badges: small sample (fewer than 30 trades), high drawdown (above 20%), degraded in validation (positive fit and negative validation, or validation return/drawdown below half the fit's), non-deterministic LLM, data with gaps, refused orders.
    • The conditions that differ between rows (assets, timeframes, LLM agents mixed with deterministic ones) appear in a notice.
    • An undefined metric (profit factor without losses, return/drawdown without a drawdown) appears as "—", with the reason on mouse hover.
    • A run's detail opens in a panel on the right, over the page, when clicking the agent (it closes with Esc, the × or a click outside; on a phone, at full width), and has the capital curve, the trades with the reason for the entry and the exit (in the LLM, the model's rationale), the positions open at the end, the warnings and gaps, the configuration snapshot and, in the LLM, the calls.
  • Out-of-sample validation: with a validation of N% (up to 50%), the batch runs each agent twice, on the start of the period (fit) and on the last N% (validation), with the same configuration.
  • Configuration snapshot: each run keeps the agent's effective parameters (the same flags it runs with, without secrets), the protection, the command and the binary's sha256, and, in the LLM, the provider, the model, the caps, the prices and the prompt (name, version, sha256 and content).

Simulation assumptions

  • Data: MT5 bid candles read from the bridge of the agent's account, with each candle's spread (the fallback spread applies only to candles without it), stored in backtest.dir/candles and reused. There is a warm-up before the period: what the agent's strategy asks for (the agent reports the candles and the timeframe with -print-warmup, without connecting to anything), with 50% extra headroom plus one day for weekends and market pauses, up to 365 days; at least 1000 candles of the agent's timeframe (up to 60 days), which is also what applies to LLM agents or when the agent does not report it (with a warning). The engine only delivers candles to the strategy after the full warm-up, so a short warm-up would leave the start of the period without trades (e.g. mtfema, with EMAs of 4x and 16x the timeframe, asks for 8832 candles of 15m, about 140 days). A long period with a long warm-up may run on M5 instead of M1 (up to 200,000 candles per file). If history is still missing, the run warns "aquecimento incompleto" (incomplete warm-up), counted in candles of the strategy's timeframe. Gaps larger than 3 times the timeframe (and than 2 hours) outside the weekend become warnings and are never filled; without enough data, the run fails with the reason.
  • No future data: the strategy, the breakeven/trailing and the LLM context only read candles closed up to the simulated instant, including in higher timeframes.
  • Execution: at the finest resolution the period allows (up to 200,000 candles: M1 when it fits, otherwise M5, M15…). When the broker keeps the finer candles for less time than the period (on the Exness demo, M1 covers only a few months), the run uses the next timeframe that covers the whole period, with a warning, and the detail shows the resolution used; with none, it fails for insufficient data. Buys at the ask (bid + spread), sells at the bid, slippage against the order at market and on stops. A stop with a gap fills at the candle's open.
  • Conservative rule: with stop and target touched in the same candle, the stop wins; an entry filled in a candle that also crosses the stop exits stopped out in it.
  • Lot and margin: the symbol's lot step and minimum lot (an order outside them is refused and counted); the agent's leverage sets the margin.
  • Protection and limits: the agent's breakeven and trailing run on every candle. The batch's daily limits (in the quote currency, America/Belem day) flatten the position and block entries until the day turns. The agents' limits (in the account currency) and the global limit do not apply.
  • Trading hours: the batch can apply trading hours, with one or more windows and, at the end of each, flatten the positions and/or cancel the pending entry orders, as checked in it. They come filled with those from the Limites (Limits) tab and can be changed for the batch only. They run on the candles' clock, in America/Belem time, with the same rule as production: outside the windows, no entry; at the end of a window that was open, its actions, with the positions closed at the candle that closes at the end, and the exit reason Fim do horário (End of hours). Each agent in the batch runs only in the windows that allow it (the ones for everyone and the ones that select it), and a batch with an agent outside every window is refused. They stay in the run's assumptions (hours.windows; the older batches, with start and end, still count as one window).
  • Agents per asset: the batch asks whether it respects the agents per asset of Configurações › Limites (Settings › Limits), through Respeitar os agentes por ativo de Configurações › Limites (Respect the agents per asset of Settings › Limits), checked by default. When checked, each agent runs only on the assets the rules allow it: the others stay out of the run, with a note such as fora pelos agentes por ativo de Configurações › Limites: XAUUSDm (out by the agents per asset of Settings › Limits), and the page shows before submitting what is left out for each agent. An agent with no allowed asset is refused (take it out of the batch or uncheck the option). The rules apply as they were when the batch was queued and stay in the assumptions (asset_agents and asset_rules), shown in the results summary. When unchecked, each agent tests all its assets.
  • Agent parameters: the batch can add parameters to all its agents (nome=valor, separated by ;; a list inside a value uses commas), e.g. the entry filter (regime=trend; equity-curve=20), to compare the same agents with and without a filter without changing their configuration. An agent parameter with the same name is overridden only in the batch. The parameters the backtest itself sets (the assets, the timeframe, the strategy, the mode, the MT5 account ones) and those of LLM agents are refused, and a batch with parameters does not accept LLM agents. They stay in the batch's assumptions.
  • End of period: the open positions are valued at market (close − spread − slippage) and shown apart from the realized result.
  • Currency: the pair's quote currency (USD in XAUUSD and BTCUSD), without conversion: a simulation, not the value in the account currency.

LLM agents

  • They run with a cap on calls and on cost per run (backtest.llm_max_calls and llm_max_cost by default, changeable in the batch). The cost is estimated from each response's tokens and the prices in backtest.llm_prices; without the model's price, only the calls limit it. Once the cap is reached, the run stops with the status "teto do LLM atingido" (LLM cap reached) and the result up to that point.
  • The clock is the simulated one: dates, rate limit and the day's rules follow the candle, not the real clock.
  • The context is reduced and flagged: without higher timeframes, correlated markets, economic calendar and trade memory, which would need data from the future or from the database. Candles, indicators, structure/SMC, session, drawings and the memory of the run's own decisions remain.
  • Each call is recorded: simulated instant, asset, context sha256, decision, confidence, rationale, tokens and cost.
  • The result is not deterministic: another run may give another result, and the model may have seen the period in training.

Limitations: no order book or execution queue, no historical swap, spread per candle (not per tick), the execution resolution drops in long periods, and the broker's gaps shrink the sample.

Persistence
  • PostgreSQL 18:
    • users, with bcrypt passwords;
    • versioned prompts;
    • agents, MT5 accounts and model configuration;
    • Telegram;
    • orders, decisions with attachments, drawings (decision_drawings), sentiment (decision_sentiments) and journal;
    • former names of renamed agents (agent_former_names);
    • the allowed reanalysis of each LLM agent (agent_reanalysis);
    • the positions the core discarded because they were closed outside the bot (position_discards);
    • the result accounting periods of each agent;
    • each agent's position protection (agent_protection) and the protections XTrader AI armed on the positions (position_protections);
    • the agents' news (news_settings and news_rules): the feature on or off, the calendar's MCP server and its token, encrypted, and the blocking window, the same for all agents;
    • the broker stops of the daily loss: each limit's switch (daily_limit_stops, on when there is no row) and the stops requested on the open positions with the last send (daily_stops);
    • the least margin for new entries of each limit, in % of the maximum loss (daily_limit_margins, 10% when there is no row), and the margin locks (daily_margin_guards);
    • the daily lock: the limits of all agents (daily_limit_settings, whose currency column is no longer used: it stores XXX, the ISO code for "no currency", which the CHECK of migration 27 requires with the limit on) and of each agent (agent_daily_limits), each day's locks (daily_guards) and the log of changes, triggers, releases and flattenings (daily_limit_events);
    • the backtests: the batches with the period, the validation and the assumptions (backtest_batches) and the runs with status, progress, the configuration snapshot, the summary and the report (backtest_runs); the candles and the runs' files stay in backtest.dir;
    • the supervisor: the settings (supervisor_settings), the analyses with the snapshot sent (supervisor_runs), the actions (supervisor_actions), the conversations per user (supervisor_messages) and each agent's block and stop (agent_supervision).
  • Secrets (API keys and tokens) encrypted with AES-256-GCM, each bound to its place (table, column and record): copied to another agent or another column, it does not open (see Security).
  • SQL migrations, versioned, applied by cmd/migrator.
  • Reads when an LLM agent starts: the last decisions of each asset and the prompt memory (the last journal decisions of each asset) are read through the agent and asset indexes, one asset at a time, only the rows requested: the read time does not grow with months of stored decisions. The links between decisions and orders are all read, because the dashboard shows the decision of each of the agent's orders, and there is one per order.
  • Paper decisions: they stay in the agent's memory, the last 2000 (the dashboard lists up to 500). In live, they stay in the database; in a backtest, all in memory.
  • Filled order that fails to be stored: an order the broker already filled never becomes an error because of a write failure, for example with the outbox disk full.
    • The bot keeps tracking it in memory: position, legs and profit.
    • The failure is reported on the dashboard and in Telegram, and the write is retried until it succeeds, with another notification when it completes. Failures of new orders during the same outage go out together, at most one notification per minute, even if an order stays refused forever. Orders stored while another one keeps failing are also reported.
    • When stopping, the agent stops trading and then tries to write again before closing the outbox (see "Stopping an agent" in Stopping the controller). Whatever has not been stored yet appears in the log as lost. The position remains at the broker.
    • Non-finite numbers (NaN, infinity) are stored as 0, also in the local storage (buntdb) of paper and backtest.
  • Fill without a price: a fill the broker reports without a price (or the close of a position opened by one) has an unknown profit, instead of an infinite profit or a 100% loss computed with price 0. The order is stored and sent to the dashboard with profit 0, the [PROFIT] notification says the profit is unknown (in MT5, it carries the result the broker recorded, when it arrives), and the bot's results summary does not count it. The position is tracked normally.
  • Stored position the broker does not have: on start, the bot rebuilds the positions from the stored filled orders and, in MT5, checks each one against the bot's position (of its magic number) at the broker, without sending any order.
    • A position the broker does not have, for example closed by hand in the terminal or by stop out, is discarded, with a warning in the log. Before, the next entry on the same side averaged with it, and the profit and results came out wrong (the strategies' decisions did not change, because they read the position from the broker).
    • If there are open orders on the other side that may have closed it while the agent was stopped (the stop loss or the take profit), the position stays until they finish: if one fills, the order closes the position with the result; if all are canceled, the position is discarded if the broker still does not have it. A fill on the asset in the meantime ends the check (the position goes on as before).
    • A position on the other side or of another size at the broker stays as it is, with an error in the log, because there is no way to know what changed. The same goes for a bot position at the broker that the stored orders do not show. When the difference (the extra position at the broker, on the same side) fits in the stored open orders of that side, such as a pending entry (limit or stop) filled while the agent was stopped, the log is only a warning: its fill arrives right after, through the order update, and the position becomes the broker's.
    • With the agent running, the check is made when an order on the other side of the position ends without a fill, like the legs MT5 cancels when the position is closed by hand or by stop out. When no open order that could close it is left and the broker does not have the position, it is discarded, with a warning in the log and without sending an order. If an order on the asset is in progress (for example, a market exit not yet recorded), the check waits for the next update.
    • A position without legs (no stop loss or take profit) closed outside the bot while the agent is running generates no event: it stays in memory until the next restart. A position that already received, before the check, a new entry on the same side is not discarded either: the broker shows another size and the position is kept, with a warning in the log.
    • Each discard is stored (position_discards, through the outbox; in the buntdb of paper and backtest, alongside the orders) with the asset, the side, the size and the asset's last fill before it. On restart, the bot rebuilds the positions from the filled orders and discards the position again right after that fill. So the following trades are computed on their own, as they were, and their stored profit does not change on every restart. Before, the discard only happened after all orders were rebuilt: the next close was computed against the average price of the discarded position combined with the new one, and that wrong profit (in % and in the quote currency) was stored over the right one. Profits stored this way are corrected on the first restart after the discard is stored. The net profit in the account currency, which comes from the broker, does not change.

Architecture

                       ┌──────────────── controller (cmd/controller) ────────────────┐
browser ──── HTTPS ──► │ web dashboard (/api, session + CSRF)  Telegram (allowed IDs)│
                       │ Manager: starts/stops the agents of the DB, tokens per start│
                       │ internal API of the agents (loopback, Bearer per agent)     │──► PostgreSQL
                       └──────▲───────────────────────────────▲──────────────────────┘
                              │ config, runtime, outbox        │ proxy of the API of each agent
                     ┌────────┴────────┐              ┌────────┴────────┐
                     │ llm agent       │  ...         │ trend agent     │ ──► MT5 bridge ──► MT5 terminal
                     └─────────────────┘              └─────────────────┘      (tools/mt5bridge)
  • cmd/controller: the only process that accesses the database.
  • cmd/migrator: applies the migrations and the seeds (gobox/database/migrate), which on a new database set Telegram off and add the prompts and the initial agents (see Initial agents). The configuration lives only in the database and is changed through the dashboard. The controller does not migrate: it checks the schema version. Each seed file starts with a Postgres advisory lock (pg_advisory_xact_lock), so two migrators running at the same time apply the seeds one after the other, without duplicating or failing.
  • Agents: receive the configuration through the internal API (agentapi). The parameters become the same command-line flags, and secrets are never passed as arguments. The block on entries arrives through the same API (in the configuration and in the runtime, with a revision that only grows) and takes effect without restarting the agent.
  • XTrader AI (controller/supervision*.go, the supervisor): runs inside the controller. It builds the snapshot from the database, the Manager, the bridges and each agent's API, calls the model with tools (agents/llm/chat.go, with streaming in chat_stream.go) and executes the actions through the supervisor channel of the agent's API, which only reduces risk, or directly through the bridge when the agent is not running.
  • Position protection (agents/internal/protect): runs in each agent, called by the engine on every candle (the xtrader.CandleHook hook, after the strategy, outside the preload and the backtest), and moves the stop through the order controller's guard (order.Controller.TightenProtection, SetStopGuard), which only tightens the stop of an open position, comparing it with the broker's live level (service.ProtectionReader). The configuration and the armings arrive through the internal API (agentapi.Protection, in the Config and the Runtime), without a restart.
  • Entries blocked in the core (order.Controller): with entries blocked, market orders only reduce the position (CreateOrderMarketReduce in MT5 and in the paper wallet, which never open the remainder), and entries, entry pending orders, orders sized in money and an OCO that does not protect a position are refused with ErrEntriesBlocked. Protecting, moving stops, canceling and closing still work.
  • tools/mt5bridge: an HTTP bridge in Python to the MT5 terminal, which runs on Wine inside the mt5 container. It serves one request at a time and protects the orders:
    • identical reads waiting for the terminal together (the same GET with the same query, e.g. every agent reading the account's /positions every second) are served by a single call to the terminal, made after all of them have arrived: a response is never read before its request. A read that arrives with that call already in progress waits for the next one. Orders (POST /order, POST /check) and the session are never shared, and each request keeps its own deadline. Before this, with 33 agents on one account, each read waited about 0.7 s in the terminal's queue, and closing a position (quote, order and history) took about 3 s;
    • each order carries a 20 s deadline, in two headers: X-Bridge-Deadline (an instant in Unix ms, by the agent's clock) and X-Bridge-Timeout (the remaining ms, which the bridge counts by its own clock from receipt). The bridge uses whichever expires first, counted on the monotonic clock. This way, a bridge on another host with a lagging clock does not send the order later. If the terminal is busy or reconnecting beyond the deadline, the order is refused without going to the terminal (504 with "sent": false), and it is never executed after the agent gave up on it. A bridge clock running ahead shortens the deadline: the agent warns in the log when the difference exceeds 1 s;
    • before each order, the bridge checks that the terminal is still on the --login account and that a real account has --allow-real. If not, it refuses the order (409);
    • a list the terminal could not read (positions, orders, history, candles) is an error (502), never an empty list. The exception is the candles of a range outside the terminal's history (before its start or beyond "Max. bars in chart"), which copy_rates_* refuses as the CopyRates documentation says: if the symbol's last candle is read, the range comes back empty, and the download and the pagination continue as at the end of the history.
  • Orders without a response: each order's comment is the agent's comment followed by # and a tag of its own (e.g. nb:llm#k3f9a2). The magic number is still what identifies the bot's positions. If an order's response is lost, the agent looks for the order in the account by that tag before raising an error. If it finds it, it continues as if the response had arrived; if it does not show up after the deadline (up to about 22 s), the order was not executed.
    • During this wait, only the other orders of the same pair and whoever sent the order wait (the call waits for the result; in a multi-pair bot, its candles wait too). Order tracking, reads, the dashboard and the orders of the other pairs continue.
    • If the account cannot be read after the deadline, the result is unknown and the pair is blocked for orders that open or close a position until a read of the account tells what happened. Stop loss and take profit can still be moved.
    • If the terminal switches accounts (e.g. through VNC), the agent stops sending orders, and applying the positions it reads, until the account comes back. The account is read before and after the lists of each read.
    • Update both images together: with an old bridge, which does not honor the two deadlines, the agent warns in the log and treats an order that was not found as having an unknown result.

Repository layout

agentapi/            contract of the internal API between the controller and the agents
agents/
  llm/               the language model strategy (+ llmagent, its binary) and the tool-calling client of the supervisor
  strategies/        classic strategies
  trendagent/ momentumagent/ breakoutagent/ intradayagent/   binaries of the families
  internal/          shared runner, remote client (outbox, config), protection and the backtest engine
cmd/
  controller/        dashboard, Telegram and supervision of the agents
  migrator/          migrations and seeds
  xtrader/           utilities (candle download, seasonality, metalabel)
config/ configs/     loading of config.yml and the host example
controller/          implementation of the controller (supervision*.go: the AI supervisor)
deploy/docker/       images, compose and install scripts
exchange/ order/     MT5, paper wallet and order control
sql/                 migrations and seeds
store/               PostgreSQL repositories (GORM only for queries)
tools/               MT5 bridge, automator.sh, logs and metrics
ui/                  API of each agent for the dashboard and DTOs (source of the web types)
web/                 dashboard (React 19 + Vite + TypeScript)

Requirements

  • Docker and Docker Compose, for the full stack, which is the recommended path.
  • To develop on the host:
    • Go 1.25+: go.mod requires the go1.25.14 toolchain, which an older Go downloads on its own (GOTOOLCHAIN=auto, the default);
    • PostgreSQL 18;
    • bun, for the dashboard;
    • an MT5 terminal with the bridge (tools/mt5bridge/run.sh), for the live and paper modes.
  • An MT5 account (Exness) and, for the LLM agent, an OpenAI or Anthropic key.

Quick start with Docker

The stack has four services:

Service Role
postgres database
migrator migrations and seeds, on every start
mt5 terminal on Wine, with the bridge and the MCP server
controller dashboard, Telegram and agents
deploy/docker/build.sh                          # images xtrader-controller and xtrader-mt5
# later, to update: make docker-rebuild         # asks which images and whether to recreate the compose
sudo deploy/docker/install.sh                   # installs in /var/containers/xtrader and generates the DB password and the secrets key
sudo nano /var/containers/xtrader/services/controller/.env  # first dashboard user (XTRADER_BOOTSTRAP_*)
cd /var/containers/xtrader && sudo docker compose up -d

The dashboard is at http://127.0.0.1:8082, only on the server's loopback: from outside, reach it through the host's ngrok (or a reverse proxy with HTTPS) or through an SSH tunnel (ssh -N -L 8082:127.0.0.1:8082 <usuário>@<servidor>). After logging in, register the terminal's account in Configurações > Contas MT5 (Settings > MT5 accounts), with the login, server, password, the bridge http://mt5:18812 and the MT5_BRIDGE_TOKEN from the mt5 .env as the token, and activate it; then create the agents in Configurações > Agentes > Novo agente (Settings > Agents > New agent), each with its own account. The complete step-by-step guide, with the economic calendar, ports, backup and migration, is in deploy/docker/README.md.

Running locally (host)

# PostgreSQL 18 in a container
docker run -d --name xtrader-postgres -e POSTGRES_USER=xtrader -e POSTGRES_DB=xtrader \
  -e POSTGRES_PASSWORD="$XTRADER_DB_PASSWORD" -p 127.0.0.1:5432:5432 postgres:18.6-trixie

export XTRADER_DB_PASSWORD='...'                                   # the password of the xtrader user
export XTRADER_SECRETS_KEY="$(head -c 32 /dev/urandom | base64)"   # once: keep it, it encrypts the secrets
export XTRADER_BOOTSTRAP_USERNAME=admin XTRADER_BOOTSTRAP_PASSWORD='...'

cp configs/config.example.yml configs/config.yml
(cd web && bun install --frozen-lockfile && bun run build)   # the dashboard in web/dist
go run ./cmd/migrator -config configs/config.yml up          # schema and seeds (prompts and agents)
go run ./cmd/controller -config configs/config.yml           # or: tools/automator.sh start configs/config.yml

tools/automator.sh runs the migrator and the controller in a session of their own, which does not stop when the terminal is closed, and offers start, stop, status and logs. stop waits for the controller to stop the agents and the bridge for as long as needed, up to AUTOMATOR_STOP_TIMEOUT seconds (300 by default; keep it above shutdown_timeout), and at the end also stops whatever the controller left running.

Configuration

config.yml has only what is needed to start and reach the database. The rest lives in the database and is changed through the dashboard.

In config.yml In the database (Configurações / Settings)
listen, database, secrets_key, migrations, bootstrap (first user), ui, agents (internal API, directory, command of each type, stop time), backtest (concurrency, directory, maximum period and runs, LLM caps and prices), services (host bridge), shutdown_timeout (whole shutdown), log agents (mode, address, MT5 account, model, parameters, secrets, prompt, protection), MT5 accounts, prompts, limits and trading hours, news, XTrader AI, Telegram, users and roles
Variable Use
XTRADER_DB_PASSWORD password of the PostgreSQL xtrader user
XTRADER_SECRETS_KEY 32 bytes in base64 that encrypt the secrets in the database: without it, the secrets must be set again
XTRADER_BOOTSTRAP_USERNAME / XTRADER_BOOTSTRAP_PASSWORD first dashboard user, created while there is none
MT5_BRIDGE_TOKEN token of the host bridge (services in the config)

The ${VAR} references are replaced in the text before the YAML is read, which is why they go in single quotes. This way, any value without ' works.

A ${VAR} with no value would become empty text. That is why the controller and the migrator do not start when a variable of database.dsn or secrets_key is missing (unset or empty), or when an env entry of a services item is empty, such as MT5_BRIDGE_TOKEN (without a token, the host bridge would accept any process on the machine). Any other unset variable produces a warning in the log, except the bootstrap ones, which can be removed after the first login.

The processes launched by the controller do not inherit its environment (and, with it, its secrets). Agents receive PATH, HOME, USER, LOGNAME, TZ, LANG, LC_ALL and TMPDIR, plus agents.env, the internal API address, their own name and, on each start, a new token and key. The services receive the same basic variables plus their own env, never agents.env.

Stopping the controller
  • Times: on SIGINT or SIGTERM, the controller stops the agents, each with agents.stop_timeout (20 s by default) before being killed, and then the services, each with its own stop_timeout (10 s by default). The whole shutdown fits in shutdown_timeout: by default, agents.stop_timeout plus the largest stop_timeout of the services plus 10 s (40 s in the example), and never less than that sum plus 3 s (the controller does not start with a smaller value). Each phase, the agents' and the services', can take up to 1 s beyond its own stop_timeout, waiting for the output (stdout/stderr) of a killed process that another process outside the group still holds, such as the Xvfb that the bridge's run.sh starts in another session; the remaining second covers the rest of the shutdown. Once that time has passed, whatever is still running is killed and the controller exits with an error.
  • Stopping an agent: on the signal, the agent stops trading before closing the outbox.
    • It immediately refuses any new order from the strategy, including the one from the candle in progress.
    • It waits for the broker calls that have already started to finish and be written to the outbox. The model query in progress (LLM agent) is ended without an order and without a record: the stop is not a model failure and does not enter the decision history, the journal or the counts; only the log says the query got no answer (and a requested reanalysis receives "the agent stopped before the model answered").
    • After that, nothing else reaches the broker, neither cancellations nor protections. Only then does it send the pending records to the controller (up to 10 s; the rest goes on the next start) and close the outbox.
    • A slow broker call holds the stop up to agents.stop_timeout. If the agent is killed earlier, what was already in the outbox stays on disk and is sent on the next start.
  • Whoever stops the controller waits longer than that: tools/automator.sh stop (up to AUTOMATOR_STOP_TIMEOUT), the compose stop_grace_period (45 s, above the container's 30 s shutdown_timeout) or the TimeoutStopSec of a systemd unit. An installation in /var/containers/xtrader made before this change only gets stop_grace_period after reinstalling (see "Parar tudo" (Stop everything) in deploy/docker/README.md); until then, Docker waits only 10 s.
  • Controller killed (kill -9, out of memory, a crash): on Linux, the agents and the services receive SIGTERM and stop as in a normal shutdown, including the program that a go run runs. An agent launched by the controller ignores SIGPIPE: its log went to the dead controller, so the lines of that shutdown are lost, but the shutdown runs to the end (it stops trading, writes the order in progress and closes the outbox; what does not reach the controller stays in the outbox for the next start). A controller server that fails (dashboard or internal API) also stops everything in order.
  • Leftover processes: each start of an agent or a service has a pidfile in data/pids under agents.dir. On startup, before launching anything, the controller stops whatever a previous controller left running, as in a normal shutdown. It checks each process's environment to confirm it is really the one that was launched: a PID reused by another program is left untouched. Without Linux (without /proc), these processes are only reported in the log.
  • One controller per agents.dir: a second controller with the same directory does not start, because it would take the first one's processes for leftovers.

Usage

Web dashboard
  • Dashboard (/): choose the agent and the pair in the top bar, where the bot is also started and stopped.
    • Only the strategies open positions: there is no manual order from the dashboard or from Telegram (the order ticket and /buy//sell were removed).
    • Pending orders can be dragged on the chart and canceled in the order list, with the agent's Painel de trading (Trade panel) switch on. Starting and stopping the bot does not depend on it.
    • The reanalysis of an LLM agent (Reanalisar agora, Reanalyze now) depends only on its Permitir reanálise (Allow reanalysis) switch, whether the trade panel is on or not.
    • The chart's timeframe selector changes only the view (see Chart timeframe); the strategy and the LLM stay on the agent's execution timeframe.
  • Configurações (Settings, /settings): the sections Agentes (Agents), Contas MT5 (MT5 accounts), Limites (Limits), Notícias (News), Prompts, XTrader AI, Telegram, Usuários e papéis (Users and roles), Layout and Importar e exportar (Import and export), in the top navigation, which also open by link (/settings#prompts). Each user sees only the sections their role allows.
  • Lists: search and pages. The lists load from the server only the page shown, 10 items at a time (5 batches in Backtesting › Execuções (Runs)), with the pager below them: Contas MT5, Prompts, Telegram › Usuários autorizados (Authorized users), Usuários do painel (Dashboard users), Papéis (Roles), Limites › Limites por agente (Limits per agent), the XTrader AI analyses, actions and protections (in Configurações and in the chat's Análises (Analyses) tab) and, in Backtesting, the runs and the comparison of the results.
    • Search: Contas MT5 (name, login, server, bridge, type, currency, company and agents), Prompts (name, description and the agents that use them), Usuários autorizados (Telegram ID and name), Usuários do painel (user and role) and Papéis (name, description and the areas of the permissions; Administrador (Administrator) matches all of them) have a search at the top of the list, like the one in Agentes: it ignores case and accents, each word must appear in some field, Esc or × clear it, and the note below says how many items were found (or "Nenhum … encontrado para “…”" (No … found for “…”)). The search goes to the server and considers every record, not only those on the page; when searching, the list goes back to the first page.
    • Filters and sorting: the comparison of the results of a batch sorts by any column and filters (minimum number of trades, LLM agents) on the server, before paging; changing the filter or the order goes back to the first page. The other lists keep the order they had before (by name, by ID or newest first).
    • Actions: create, edit, delete, activate, test and the other list actions stay the same; after each one, the current page is read again (the last page, if the current one became empty).
MT5 accounts

The MetaTrader 5 accounts live in the database, managed in Configurações > Contas MT5 (Settings > MT5 accounts).

  • Registration: identification, login, server and password, the bridge of the terminal that serves the account and its token, Permitir conta real (Allow real account) and Somente leitura (Read only). The password and the token are encrypted (AES-GCM, with XTRADER_SECRETS_KEY, which lives outside the database) and bound to the account: they are never displayed, returned by the API or logged. A secret field left blank keeps its value; removing it is explicit.
  • One terminal, one account at a time: the active account of each terminal is the one it logs into. The controller hands the account to the bridge (POST /session), which keeps it without the password. The terminal is identified by the bridge's host and port and by the instance the bridge reports (an identifier written in data/xtrader-bridge/instance): several terminals on the same host are independent, two URLs of the same terminal count as one, and accounts on different terminals are active and trading at the same time, without interrupting one another.
  • Coordinated switch: on the Ativa no terminal (Active on the terminal) toggle of each account, the dashboard first shows what the switch does (GET /api/settings/mt5-accounts/{id}/switch) and asks for confirmation. When activating another account on the same terminal (POST .../activate) or deactivating the current one (POST .../deactivate), the controller stops that terminal's agents and waits for them to stop. If the agents have open positions or pending orders, the switch requires close_positions (the question: "Existem posições abertas ou ordens pendentes na conta …" (There are open positions or pending orders on account …)); it then closes the positions and cancels the orders (recorded as a close_positions action in the XTrader AI history), checks the account and only then logs the terminal into the new account. With move_agents (the option "Levar os agentes da conta … para esta conta" (Move the agents of account … to this account), checked by default in the confirmation), the agents of the account that left move to the new one, after the login, and are started on it again; on a deactivation no agent changes account. If no account is active on the terminal (for example, a previous switch failed and the previous account could not come back), the agents that move along are those of that terminal's inactive accounts; the confirmation says which accounts they come from (from in the preview). Agents of another terminal never change account. If something remains open, the switch is not made, the current account's agents are started again and what is still open is returned (409); if the terminal does not log into the new account, the previous one becomes the active one again (502). Positions opened by hand (without an agent's magic number) are not touched. Afterwards, the agents of the active account are started; those of an inactive account stay stopped, with the reason on the card. Changing the login, the server or the bridge of the active account is still refused while the terminal is in use; changing only the password, the token, the name or the options is allowed at any time.
  • Agents: each agent trades the account associated with it (in the agent's form), receiving the bridge and the token from the account. Changing an agent's account requires the agent to be stopped and without positions or orders on the current account. An agent of an inactive account is not launched, with the reason on the card.
  • Connection test: checks the bridge, the token and the account the terminal is on; if it is this one, the type (real, demo or contest), the currency and the company confirmed by the bridge. It never switches the terminal's account to test.
  • Reconciliation: on startup, before launching the agents, and every 30 s, the controller checks each terminal and, with no agents running on it, logs it into the active account (or updates the options). Without the password, when the terminal asks for it, the account shows "o terminal pede a senha" (the terminal asks for the password).
  • Import: on startup, each bridge with agents still without an account becomes an account (login, server, type and currency read from the bridge itself; the agents' token; allow real account if the bridge already serves a real account), active, with the agents associated. It never duplicates (same login and server) or overwrites an existing account.
  • Log: creation, changes (with secrets only as set or not), activation, deactivation, deletion, import, agent association, tests and sessions sent are kept in mt5_account_events.
  • API: GET/POST /api/settings/mt5-accounts, PATCH/DELETE /api/settings/mt5-accounts/{id}, POST .../{id}/activate, POST .../{id}/test and GET .../{id}/events; the agent gains mt5_account_id in /api/settings/agents.
Agents and parameters

Creating an agent: use Configurações > Agentes > Novo agente (Settings > Agents > New agent). The form asks for:

  • type and mode;
  • the agent's API address, only on loopback (localhost, 127.0.0.0/8 or [::1], e.g. localhost:5580), because only the controller on the same machine accesses it;
  • MT5 account (bridge, magic number, comment);
  • model, for the LLM agent;
  • secrets;
  • parameters.

Magic number and comment: each agent only trades the positions of its own magic number on the account. Without a magic number, it is a hash of the comment; without a comment, nb: plus the strategy is used (nb:llm for the LLM agent; nb:trendconfluence, nb:adxema, nb:atrbreakout or nb:orb when the strategy parameter is not set).

  • Two agents active in live on the same bridge, with the same magic number and a pair in common, would close and move each other's positions. That is why the dashboard refuses the second one (409) when creating, activating or editing. The bridge is compared by host and port (localhost and 127.0.0.1 count as the same).
  • This also applies to agents that run separately (Iniciado pelo controller (Started by the controller) off): they trade the same way, and the dashboard compares them by their saved settings, since the controller does not see them running. Keep the settings of a separate agent equal to the flags it runs with.
  • Disabled agents or agents in paper can repeat the magic number: they do not send orders.
  • The controller also does not start an agent that conflicts with another one running, for example with data saved before this rule. The card shows Não iniciado (Not started) and the reason. This check only sees the agents the controller itself runs.
  • To separate two agents, give one of them its own comment (or magic number). Changing the magic number of an agent with open positions makes it stop recognizing them.

Agent search: the field above the groups, in Configurações › Agentes, lists the agents of every group that match what was typed: by name, by type (e.g. rompimento (breakout), tendência (trend)), by strategy, by assets (e.g. ustecm) or by the model of an LLM agent, ignoring case and accents; with several words, the agent must have all of them. While there is a search, the agents found appear in place of the chosen group, with how many there are; × or Esc clear the search, and clicking a group goes back to it.

Parametrizador global (global parameter editor): the Parametrizador global button, next to Novo agente (New agent), changes parameters on all agents by key (the flag name without the dash, e.g. lot), without touching the other parameters or each agent's settings. Each row has a key and a value; Adicionar parâmetro (Add parameter) creates another row (up to 20) and the trash can removes it. All the parameters go into each agent together: for example, pair and the lot of the new assets in the same operation, without the agent ending up with one and not the other.

  • Key and value: checked as in an agent's parameters: lowercase letters, digits and - in the key, never the key of a dedicated field (e.g. mode, mt5-magic); the value on one line, up to 1024 bytes, without repeating chave= (key=). A key appears only once; a row left blank is ignored. A refused key or value changes nothing (400). The screen suggests the keys the agents have, says on how many agents each key is and with which values, and shows before applying how many agents change (each agent counted once).
  • Somente para agentes de LLM (Only for LLM agents) and Somente para os agentes ativos (Only for the active agents): filters of the agents changed. Agents outside the filter do not change or restart; the result only counts how many were left out. With both, only the LLM agents that are on are affected. Without a filter, all agents are affected. An LLM parameter (llm-, calendar-, news-) applied without the LLM filter is still refused on agents of other types, which do not know these flags and would not start with them: they appear as ignored, with the reason.
  • Adicionar para agentes sem o parâmetro (Add to agents without the parameter): unchecked, only the agents in the filter that already have the key change, on or off (without the active filter); checked, the key is also added to the others.
  • Remover chaves (Remove keys): in the selector at the top, next to Definir valores (Set values). It removes the parameters from the agents in the filter by key, and the agent then uses the strategy's default for them (for example, removing the 30m timeframe from an agent designed for 5m).
    • Each row has the key and, optionally, a value. With a value, the key is removed only from the agents that have exactly that value; without a value, it is removed with any value.
    • Adicionar para agentes sem o parâmetro disappears in this mode. The preview says from how many agents the key is removed, how many have another value and how many do not have the key.
    • The editing rules still apply: the key of a dedicated field is refused, and an agent whose validation refuses the removal stays as it was, with the reason.
    • As with any parameter change, an agent that is on only applies the removal when it restarts: check Reiniciar os agentes ativos (Restart the active agents) or use Reiniciar (Restart) afterwards.
  • Reiniciar os agentes ativos: checked, after saving the parameter, it restarts the agents of the filter that are on and that the controller starts (up to 8 at a time), whether they changed or not; those that are off stay off, and an agent started separately is not restarted (it appears with the reason). Unchecked, the agents that are on and changed get Reinício pendente (Restart pending), as in an edit.
  • How it is saved: one agent at a time, with its row locked, all the parameters in a single write, by the same rules as an individual edit (e.g. a pair change that would make two active agents trade the same magic number and pair is refused on that agent). If a parameter is refused on an agent, none changes on it; a refused agent does not stop the others. An agent that already has all the values is not rewritten.
  • Result: each agent in the filter appears as changed, added, removed (with the value it had), already had the value, ignored or failed (with the reason), with what was done with each parameter (e.g. lot: alterado (antes 0.01) (changed, before 0.01), pair: adicionado (added); with a single parameter, the previous value beside it), and, with the restart requested, as restarted, not restarted (with the reason) or off. Failures come first; the agents outside the filter are only counted.
  • API: POST /api/settings/agents/params with params (a list of key and value; or key and value for a single one), add_missing, restart_active, llm_only, enabled_only and remove (removes the keys, with an empty value for any value; status removed); the response carries the parameters and each agent's result, with params per parameter (excluded for the agents outside the filter).

Which changes take effect immediately: on a running agent, Ligado (On), Painel de trading (Trade panel), Controle via Telegram (Control via Telegram), Permitir reanálise (Allow reanalysis), the prompt and News (the switch, the server, the token and the window, on all agents). The others stay as "reinício pendente" (restart pending), applied only by the Reiniciar button (or by turning the agent off and on again). If the process crashes in the meantime, the automatic relaunch uses the settings the agent was started with: a pending change (from paper to live, of account, of magic number etc.) never takes effect on its own, and the dashboard stays on the address the process listens on. Secrets are the exception, because they are not trading configuration: the relaunch uses the current ones (a bridge token or a key that was revoked and replaced does not leave the agent crash-looping). Each secret only goes to the same endpoint it was started with: the bridge token to the same bridge, the model key to the same provider and base URL, the calendar token to the same calendar. If the endpoint also changed, the relaunch keeps the old endpoint and secret until Reiniciar.

Permitir reanálise (LLM agents): allows asking the model for a new analysis between closes, through the dashboard's Reanalisar agora (Reanalyze now) and Telegram's /reanalyze, with a note for the model. It is independent of Painel de trading: turning the trade panel off blocks only moving and canceling orders.

  • When off, the button appears as DESATIVADO (DISABLED) and the agent itself refuses the request with 403, whether it comes from the dashboard, from Telegram or from a direct API call. On an agent without an LLM, the response is 404.
  • Through Telegram, Controle via Telegram also applies besides it: with the control off, /reanalyze is refused like the other commands.
  • It only exists on LLM agents: the card and the form only show the switch on them, and the controller refuses to turn it on for another type (400). On a new agent, it comes off.
  • It takes effect immediately, with the agent running (paper or live), without a restart.
  • Outside the controller, the LLM agent only accepts reanalysis with the -reanalysis flag.

When the agent exits on its own:

  • With Reiniciar se cair (Restart if it crashes) on, the card shows Reiniciando (Restarting) during the wait and, in the note, the last exit and how many times the controller has restarted it since the last start.
  • With Reiniciar se cair off (at the start of the process), the agent stays Parado (Stopped) and the note says why. It only comes back with Reiniciar, when it is turned off and on again or when the startup settings change after the exit; changing the trade panel, the Telegram control, the reanalysis or the prompt does not start it. A change saved while it was still running is a pending restart and does not start it either (the controller reads the settings as soon as it sees the exit; a change saved in those milliseconds counts as pending).
  • This Parado state lives only in the controller's memory: when the controller restarts, it starts every agent that is on again, including the one that had exited on its own.
  • Restarting or turning off an agent does not lock the dashboard while it stops: the other changes are applied immediately, and the agent that is stopping is adjusted right after. When shutting down, the controller no longer accepts restarts: a restart in progress does not launch the agent again.

Parameters: these are the agent's flags that have no dedicated field. In the form, the name goes without the dash on one side and the value on the other. Each binary lists its flags with -h, for example go run ./agents/llm/llmagent -h. In lists, the items are separated by ; (the comma is still accepted). In sizes (lot, mt5-contract-size), the decimal separator is a dot: a value that may have a decimal comma, such as lot = 1,5 or lot = 0,05, is refused and the agent does not start, because 1,5 with two pairs would become lots of 1 and 5; write 1.5 for one size or 1;5 for one per pair. The comma as a separator is only accepted between sizes with a decimal dot, as in the old format lot = 0.03,0.01. In the LLM agent, lot and llm-correlated have a single format, each pair by name and separated by ;: lot = BTCUSDm=0.01;XAUUSDm=0.02 (every pair of pair) and llm-correlated = BTCUSDm=DXYm+XAUUSDm;XAUUSDm=DXYm+USTECm. One lot for all pairs, the lots in the order of pair, one list of markets for all pairs and the comma are refused, and the agent does not start (the reason, with the example, goes to the controller's log).

Name Value Effect
pair BTCUSDm;XAUUSDm pairs traded by the agent
timeframe 30m timeframe of the candles
lot BTCUSDm=0.01;XAUUSDm=0.02 fixed lot of each pair by name (on strategy agents, also 0.01 for all)
leverage 400 safety cap: refuses a position larger than balance × leverage
max-risk-pct 2 strategy agents: refuses an entry that loses more than 2% of the free margin at the stop (0: no limit)
regime trend or range strategy agents: only enters in a trend, or only in a range (see Entry filter)
equity-curve 20 strategy agents: pauses entries while the theoretical curve is below its 20-trade average
meta-model data/meta/matrend.json strategy agents: only enters with the model's probability above the threshold
intermarket-symbol DXYm strategy agents: allows buying or selling by the reference against its EMA
llm-consult-interval 5m queries the model every 5 min (minimum 10s); required on the LLM agent in live and paper
llm-timeout 2m maximum time of a request to the model
llm-correlated BTCUSDm=DXYm+XAUUSDm;XAUUSDm=DXYm+USTECm correlated markets of each pair by name, joined by +
llm-candles 60 recent candles sent to the model
llm-setup free or trend_pullback decision mode of the model
llm-pending-expiry N (candles, to be set) cancels an unexecuted pending order after N candles (without it, only the model and the rules cancel)
outbox-quarantine true starts even with an unreadable outbox, moved to .corrupt-<hora> (see Records)

About llm-consult-interval:

  • It is the model's only schedule in live and paper, and it is required: without it, the LLM agent does not start. Do not confuse it with llm-timeout, which is the maximum time of a response.
  • The schedule follows the clock: with 5m, the queries fall at :00, :05, :10 and so on, each on the asset's first tick within that slot, with the candle in progress (scheduled in the model's context).
  • A candle close never queries the model. A schedule slot that coincides with a close (e.g. :15 on a 15m timeframe) is queried on the first tick of the next candle, already with the closed candle in the context; a candle still delivered in progress after its close time (a delayed close at the broker) is not queried.
  • The agent's start and a reanalysis take up the slot in which they query: the model is not queried again in it.
  • With an interval larger than the timeframe, the candles in between get no query. The memory and the position's candles (candles_held) count those candles.
  • Each query is a billed request.
Resetting the results

In Configurações → Agentes (Settings → Agents), the Resultados (Results) button on the agent's card shows the results by period and allows resetting them.

  • What is reset: Operações (Trades), Taxa de acerto (Win rate), Lucro líquido (Net profit) and Fator de lucro (Profit factor) of all the agent's assets. After the reset, the dashboard cards and Telegram's /profit count only the trades closed from then on, by close time: the updated_at of the executed exit order, which is the execution time reported by the broker (in MT5, the deal's). Once executed, that time does not change: the database and the agent keep the one from the first write of the execution, even if a later copy of the same order arrives with another time, so a trade never changes period after it closes.
  • Depósito (Deposit): the starting balance of the new period, in the currency of the agent's account (for example BRL), fixed in the form; in the paper wallet, the simulation's currency, and the currency is typed only when the agent is offline. It is a single balance for the agent: the results of all assets add up in it, with no split between assets. It is rounded to the cent as typed (2500.555 becomes 2500.56) and stored in exact cents (NUMERIC(16,2)).
  • What does not change:
    • the orders stay in the history;
    • open positions and pending orders stay at the broker, and a position open at the time of the reset counts in the new period when it closes;
    • the daily limits and the LLM memory still consider all trades.
  • Previous periods: they are kept in the database (agent_periods) and appear in the same dialog, each with deposit, result per asset and final balance. The results come from the agent's orders, so they only appear while it is running.
Prompts
  • Where they live: in the database, with version history. The seed brings the 3 prompts of the strategies that only a language model trades and those created in the dashboard (see Initial agents); the prompts of the coded strategies are in agents/llm/testdata/strategy_prompts.sql.
  • Header: the # Indicators: and # Take profit: lines define the indicators sent and the take profit handling; # Pending orders:, # Drawings: and # Context: turn on the pending orders, the drawings and the SMC context (see SMC/ICT, pending orders and drawings).
    • The header is the lines at the top of the prompt that start with #, and it is not sent to the model. It ends at the first line of other text. After a blank line, it only continues if the next block of lines with # has a key the agent reads (# Indicators:, # Take profit:, # Pending orders:, # Drawings:, # Context:, # Daily gain limit:, # Daily loss limit:) or a line that looks like a daily limit in currency (see Daily limits). Another block after a blank line, such as a ## Regras (Rules) title, already starts the strategy text.
    • A line with # in the strategy text goes to the model like the others.
    • The key is the text before the colon, case-insensitive and with spaces tolerated (# take profit : none works). If a key repeats, the first line wins, except for the daily limits (see below).
  • Times and structure: the times of vwap (the anchor) and of range (start, end and end of trading) follow the clock of the given time zone, including on the days daylight saving time changes (before, on those days, they were off by 1 h). The structure's atr_percentile ignores the ATRs still in warm-up (the 0 that talib writes on the first candles), which used to count as the calmest.
  • Switching: through the agent's card or through Telegram (/useprompt), with the agent running, from the next analysis on. Through Telegram, only with the agent's Controle via Telegram (Control via Telegram) on (see Telegram).
  • Deletion: a prompt used by an agent is not deleted. Deleting a prompt at the same time as it is assigned to an agent (or to a new agent) does not leave the agent with a deleted prompt: the operation that arrives later waits for the other and fails (the prompt is in use, or no longer exists).
  • Prompt invalid for the agent: it is refused, the previous one stays, and the reason appears on the card.
Daily limits

A prompt can set daily limits on the result of each asset, in the header, in the account currency:

# Daily gain limit: 250 BRL
# Daily loss limit: 150 BRL
  • Result of the day: the sum of the results of the asset's positions closed on the trading day, as the broker records them, with swap, commission and fee. A position counts on the day it closes.
  • Trading day: starts at midnight in the agent's time zone, the TZ of the .env (America/Belem in the stack), and the model's context carries the name of that time zone. Without TZ, the system time zone (/etc/localtime) is used. An empty or invalid TZ becomes UTC, with a warning in the log.
  • Value: a number with a decimal dot or comma, without a thousands separator, and the currency code: 1000 BRL, 1000.00 BRL, 1000,00 BRL or 1,50 BRL. A dot or a comma followed by exactly 3 digits, as in 1.000 or 1.500, is ambiguous (thousands or decimal separator) and the prompt is refused, with a request for an unambiguous value.
  • Uninterpreted line: the prompt is refused when a header line looks like a daily limit but the agent would not read it. A line looks like a limit when it talks about a day (daily, diário) and a limit and carries a value. This includes a key different from the two above (for example # Daily loss limits: 150 BRL or # Limite diário: 150 BRL) and the same key twice. This way, a misspelled limit does not stay off silently.
    • Only the header is read and can refuse the prompt. A title in the strategy text, such as ## Limite diário: 3 operações (Daily limit: 3 trades), goes to the model and never refuses the prompt.
    • A currency limit line in the text, such as # Daily loss limit: 150 BRL after the first line of the strategy, also goes to the model and is not applied: a warning goes to the log when the prompt is applied.
    • Currency limit (what keeps a block after a blank line in the header, and the warning about the text): the line that talks about a day and a limit and whose value starts, or whose line ends, with a number and the code of an ISO 4217 currency (e.g. # Limite diário: 150 BRL por dia, # Daily loss limit 150 BRL; USC, of cent accounts, also counts). A number of something else (## Limite diário de perda: 2 ATR) or a currency that is not the value (## Daily limit: 2 trades, max 1 EUR pair, # Daily loss limit for 2 USD pairs) does not count: the title goes to the model.
  • Pairing: each exit counts toward the position it closed. In MT5, the position comes from the ticket, for the orders of the current run and of the history read (60 days). When the history does not say which position an order closed, the exit closes the positions on the other side in order of arrival; a stop or target closes only those opened before it. This applies to orders older than the history or, from a previous run, to the market order that opened a position, and also to a market order of the current run while the exit of one of the positions it closed is not yet in the history. An exit whose entry is not in the agent's orders is left out of the result of the day and the LLM memory, with a warning in the log, without disturbing the following positions.
  • When a limit is reached:
    • new entries on the asset are blocked until the next day;
    • the model is not even queried without a position, including in reanalyses;
    • an entry returned by the model is refused;
    • the other assets stay free.
  • Open position: it keeps being managed normally. The limit does not force an exit or touch the stop or the target, and its result counts when it closes.
  • Close without a recorded result: while the broker has not recorded the result of a close of the day, entries wait, usually for seconds. The agent rereads the broker's history until the result appears: on every check during the first minute, then at growing intervals of up to 5 min, for up to 24 h, with a warning in the log after the first minute.
    • This also applies to a position closed at the broker by the stop, the target or by hand, whose exit is not yet in the history. Its stop and target stay pending in the agent until the history shows the exit; only then is the stop (or the target) taken as executed, with the result, and the other as canceled. After 24 h without the exit, both are canceled and the result is unknown.
    • It also applies after an agent restart in that interval: a bot position that is no longer on the account and whose exit is missing from the history read at startup is awaited the same way, as closed at the agent's start (the close time, before that, is unknown).
    • After 10 min without the result, the agent logs an error and sends a notification to the dashboard and to Telegram, once per close. The block reason then says how long the result has been awaited.
    • Entries keep waiting, at most until the next day, because without that result the result of the day is unknown. When it arrives, another notification says that entries are being checked against the limits again.
  • Manual trades: those opened by hand in MT5, on an agent's magic number, count in the result but are not blocked.
  • Currency: the limits must be in the account currency; otherwise, the prompt is refused.
    • The prompt the agent starts with is checked as soon as the account is read. If it is refused, the reason appears on the card and the agent stops, as with another invalid prompt.
    • If the account currency was not yet known when the prompt was applied, the refusal appears on the card when the currency is read, and entries stay blocked until another prompt is applied.
  • Where it applies: only in live on MT5, where the broker records the results. In backtest and paper, the limits are not applied, and a warning goes to the log.
News

In Configurações > Notícias (Settings > News) is the economic calendar from the MetaTrader 5 MCP server, for every agent, LLM or not:

  • Recurso de notícias (News feature): turns the calendar queries and the news block of all agents on and off. When it is off, no agent queries or blocks: the model of the LLM agents is told that the news was not read (not that there are no releases).
  • Servidor e janela da notícia (News server and window): the address of the MCP server (by default http://mt5:22347/mcp, the compose terminal) and the window, in minutes before and after a release, with the minimum importance (high; medium and high; or all). The defaults are the ones the LLM agent already used: 15 minutes before and after, high importance. Both at 0: no block.
  • Within the window of a release for a currency of an agent's assets (for example USD for XAUUSD and BTCUSD):
    • the agent opens no position: its entries are held, regardless of the XTrader AI block and the daily lock, and on all of its assets, because entry control is per agent;
    • when the window starts, the asset's pending entry orders (limit and stop outside a group) are canceled and its position is flattened at market, once per window;
    • when the window ends, entries resume; the guard queries the calendar every 15 s.
    • In an LLM agent, the calendar also goes into the model's context and entries are removed from the allowed actions during the window, as before, now with the global window.
    • A calendar that cannot be read blocks nothing, and the log warns every 15 min. In backtests the guard does not run: results around releases may differ from live. Only the strategies that trade the releases (newsbreakout) receive, in the controller's backtest, the scheduled times of the period, read from this same calendar (time, code, name and importance, never the released values). With news off or the calendar unreadable, the backtest runs without them, with a warning.
  • Dashboard news card: the calendar releases of the major currencies (USD, EUR, GBP, JPY, CHF, CAD, AUD, NZD and CNY), whatever the agents' assets are, read from the same server with the same token.
    • Period: Hoje (Today), Amanhã (Tomorrow), Hoje e amanhã (Today and tomorrow, the default), Próximas 24 h (Next 24 h), Esta semana (This week), Próxima semana (Next week) or Personalizado (Custom: from one day to another, up to 31 days), by the browser's clock.
    • Impact filter: Baixo (Low), Médio (Medium) and Alto (High), all checked at first; at least one stays checked. Releases without an impact (holidays, for example) are listed with the low-impact ones.
    • The period and the filter are saved in the browser.
    • Each release: the time (or "Dia todo" (All day)), the currency, the impact in three bars, the name and the actual (once published), forecast and previous values, in the calendar's unit. Past releases are dimmed, the next one is highlighted and the list scrolls to it. Releases whose impact blocks entries show bloqueia entradas (blocks entries), and entradas bloqueadas agora (entries blocked now) inside the window; the footer states the window.
    • The card reads the calendar every minute. With news off, without the server or the token, or with the server down, it states the reason, with a shortcut to this tab for those who can see it.
    • In the default layout, it sits beside the chart, with the height of the chart's column, whatever the number of releases the filter leaves. In a layout saved before the card existed, it also goes beside the chart, and it can be moved or hidden like the other cards.
  • Token do servidor MCP (MCP server token; in MetaTrader 5: Ferramentas > Opções > Servidor MCP, that is Tools > Options > MCP Server): a single one, shared by the agents. It is stored encrypted in the database (news_settings), bound to where it is stored, and is never shown, returned by the API or written to the log: the tab only shows whether it is set, with Trocar (Change) and Remover (Remove). Turning the feature on or off without filling in the token keeps the saved one. When it is on without a token (or without a server), no queries are made, nothing is blocked and the model is told that the credential is missing.
  • Applying changes: changes take effect immediately for every running agent, through the runtime they follow: the calendar is turned on or off, and the server, the token and the window are swapped (the MCP client opens a new session). An agent that starts receives the current news settings right away. No restart is needed.
  • Testar conexão (Test connection): on the server and window card, queries the saved server once with the saved token (even with news turned off, to check the credential) and shows Respondeu (Responded), Sem servidor (No server), Token ausente (Token missing), Token recusado (Token refused; HTTP 401/403) or Indisponível (Unavailable), right below the server field.
  • Earlier settings: before, each LLM agent had its own token, its own server address (calendar_url) and its own window (news-block-before, news-block-after, news-block-importance). The migrator moves the token and the address to the global configuration: with a single value, that value is reused (the token turns the feature on); with none, the defaults remain. With different values (or a token that cannot be opened), none is chosen: the tab warns about the conflict, naming the agents, until the value is saved there, and the old values are kept as they were. The agents' windows are removed: the global one applies. Once handled, the old columns (agent_llm_settings.calendar_token and calendar_url) are removed by the migrator, on the next run in case of a conflict.
Telegram

The bot only answers the IDs authorized in Configurações > Telegram (Settings > Telegram). The operation commands apply to the chosen agent and require that agent's Controle via Telegram (Telegram control) to be on.

Command What it does
/agents, /agent <nome> lists the agents and picks the one the commands act on
/status, /balance, /profit bot state, balance and a summary of the latest trades
/start, /stop starts and stops the bot
/reanalyze <par> [nota] asks the model for a new analysis now (LLM agent with Permitir reanálise (Allow reanalysis) on)
/prompts, /prompt <nome> lists and shows the prompts
/editprompt <nome>, /confirm, /cancel edits a prompt, with the text in the next message or in a .txt; saves only with /confirm
/useprompt <agente> <nome> switches the prompt of an LLM agent
/help help

The commands that change the strategy also respect Controle via Telegram: /useprompt requires the agent's control; /editprompt requires the control of every active agent that uses the prompt and, if any of them has it off, refuses the edit and lists which ones (disabled agents do not count). /prompts and /prompt only read and do not require the control.

Editing through Telegram works like this:

  • After /editprompt <nome>, the bot waits 10 minutes for the new text (in the next message or in a .txt). A text that starts with /, such as a mistyped command (/stauts), is never taken as content: the bot warns and keeps waiting, and /cancel gives up.
  • Once the text is received (or if it is already in the lines after the command), the bot shows a summary (lines, bytes and the beginning) and only saves the new version with /confirm, also within 10 minutes. After the deadline, the edit expires without saving anything, and the bot says so on the next message.
  • If the prompt is edited elsewhere (on the dashboard, for example) after /editprompt, the confirmation is refused and nothing is saved; the message states the current version. The agents' Telegram control is checked again at /confirm.
  • If the database fails at /confirm (while reading the prompt or the agents, or while saving), nothing is saved and the content stays pending: a new /confirm tries again, within the same deadline. A definitive refusal (prompt does not exist, invalid content, edited elsewhere or control off) discards the edit.
XTrader AI

In Configurações > XTrader AI (Settings > XTrader AI):

  1. Modelo (Model): provider (OpenAI or Anthropic), model, Chave da API (API key; write-only), optional base URL, reasoning, max tokens and the timeout of each answer. The key is stored encrypted in the database, like the LLM agents' key.
  2. Intervalo (Interval) between analyses (from 5 min to 24 h) and the instruções (instructions): the operational, risk and performance criteria, in free text.
  3. Autonomia (Autonomy): what the supervisor does on its own (Bloquear novas entradas (Block new entries), Parar o agente quando zerado (Stop the agent when flat), Cancelar pendentes de entrada (Cancel pending entry orders)) and how many actions per analysis. When an item is off, that action becomes a proposal.
  4. XTrader AI ativo (XTrader AI active): turns on the periodic analyses; requires the provider, the model and the key. Analisar agora (Analyze now) runs an analysis right away, even when it is off (with the model and the key set).

The same page shows the Histórico (History) of the analyses (summary and findings) and the Registro (Log) of the actions, with origin, status and reason. The origin is the one recorded by the backend (origin in GET /api/supervisor/actions): XTrader AI, Usuário (nome) (User (name)) or an automatic rule, such as Limite diário (automático) (Daily limit (automatic)) and Horário de operação (automático) (Trading hours (automatic)). These rules flatten positions on their own and never appear as XTrader AI actions. In the agent bar, Agente (Agent) shows whether the agent is stopped and Entradas (Entries) whether entries are blocked, each with who did it (e.g. Parado pelo XTrader AI (Stopped by XTrader AI), Bloqueadas por admin (Blocked by admin)).

The floating button in the corner of the screen opens the chat, with the Conversa (Chat) and Análises (Analyses) tabs:

  • Questions ("Which agents are losing today?") get an analytical answer, with the time of the data, written progressively on the screen and formatted in Markdown (for example, a table per agent). Closing the chat panel midway loses nothing: the answer is saved on the server and appears when it is opened again.
  • Action requests ("Block the entries of orb", "Close all positions") become a proposal card: the scope spelled out, the affected positions (agent, pair, side, volume, ticket, SL/TP and P/L in the account currency) and pending orders, with the positions of stopped agents marked, what the action does and what it does not do and, separately, whether the pending orders are canceled and whether entries become blocked. "Close all" only covers the positions of the application's agents. Closing positions and stopping now require a second confirmation click.
  • Result: after Confirmar (Confirm), the card shows the status (completed, partial, failed or unknown result) and the result of each item, checked against the account. An unknown result is never resent: check the account before asking again.

On the agent cards (in Configurações > Agentes (Settings > Agents)), Bloquear entradas (Block entries) and Liberar entradas (Release entries) do the same as the supervisor, recorded as user actions. An agent stopped by the supervisor shows a badge with the reason and only comes back when a user turns it on again.

[!NOTE] The supervisor uses migrations 000020 to 000024 and the seed 0005_supervisor.sql: run the migrator before starting the new controller (in Docker, the compose already does this). Without the seed, the supervisor stays off.

Position protection

In Configurações > Agentes (Settings > Agents), the card's Proteção (Protection) button opens the agent's breakeven and trailing stop: it turns each feature on, sets the trigger, the margin, the distance and the step (in × ATR(14)) and authorizes XTrader AI to arm it or not. Salvar (Save) applies the change right away, without a restart. The button is highlighted when protection is on or authorized.

The protections armed by XTrader AI are listed in Configurações › XTrader AI › Proteções armadas (Settings › XTrader AI › Armed protections), with the position, the protection, the status (armed and waiting for the trigger, confirmed by the broker, refused by the broker, position closed), the previous stop → the requested one (confirmed or not) and the reason; each analysis lists the protections it armed.

[!NOTE] Protection uses migrations 000025 (agent_protection) and 000026 (position_protections). The migrator applies them on its own when the new image starts, without deleting anything.

Backtests and historical data
# candles through the MT5 bridge
go run ./cmd/xtrader download --exchange mt5 --mt5-bridge http://127.0.0.1:18812 \
  --pair XAUUSDm --timeframe 1h --days 90 --output xau-1h.csv

# backtest of a strategy over the CSV
go run ./agents/trendagent -mode backtest -strategy matrend \
  -pair XAUUSDm -timeframe 1h -csv xau-1h.csv -lot 0.01

# with -api, the result stays open for the dashboard when it ends
go run ./agents/trendagent -mode backtest -strategy matrend -pair XAUUSDm -timeframe 1h \
  -csv xau-1h.csv -api 127.0.0.1:5570

The LLM agent also runs backtests, but each candle becomes a paid request to the model.

From the dashboard, the Backtesting tab does the same for several agents at once, with each agent's current configuration, candles read from the bridge, costs, out-of-sample validation and a comparison of the results. The binaries accept -backtest-config <arquivo.json> (the agentapi.BacktestConfig the controller writes: period, balance, costs, symbols, protection, limits, LLM caps and the report file).

Initial agents

On a new database, migrator up creates the agents of the seed sql/seeds/0004_agents.sql: the ones the database had on 2026-10-14, an LLM agent for the support_resistance prompt and a non-LLM agent for each strategy in the code (two for pairs). There are 54, all off and without secrets, on XAUUSDm and BTCUSDm with a lot of 0.01 on each (pair = XAUUSDm;BTCUSDm, lot = XAUUSDm=0.01;BTCUSDm=0.01), except the two pairs agents, each on the two legs of its spread. All are in live mode, with Telegram control and without the trade panel:

  • llm-trend: the LLM strategy with the trend_following prompt (OpenAI gpt-6-astra, reasoning high) on 15m, consulted every 15 min, with the 1h and 4h trends as a filter (llm-higher-trend-filter), llm-min-stop-atr = 1, llm-max-spread-atr = 0.2, leverage 400, the high-importance calendar and reanalysis allowed. Default LLM agent comment (nb:llm). API at localhost:5580;
  • matrend: matrend on 5m (agents/trendagent), a stop of 1 and a take profit of 2 in price, max-distance = 0.5, leverage 400, the strategy's default comment (nb:matrend). API at localhost:5570;
  • llm-smc-liquidity: the LLM strategy with the smc_ict prompt (limit pending orders, drawings on the chart and SMC context; gpt-6-astra, reasoning high) on 5m, consulted every 30 min, 1h bias, 2000 candles of context, a 3 min timeout for the model, leverage 400 and reanalysis allowed. Its own comment (nb:llm-smc), and therefore its own magic number, separate from llm-trend on the same account. API at localhost:5581;
  • fibonacci: the fibonacci strategy (agents/trendagent, no LLM) on 15m, with the classic setup spelled out in the parameters (an impulse of at least 3 ATR between 5-candle pivots, entry on the close that rejects the 50% to 61.8% zone, stop 0.25 ATR beyond 78.6%, target at the extreme of the impulse) and leverage 2000. It keeps the comment nb:fibonacci-xau (the old name), and with it the magic number of its positions. API at localhost:5572;
  • fimathe: the fimathe strategy (agents/breakoutagent, no LLM), analysis on 1h and entries on 15m, weekly mapping, a stop surfing the subcycle, at most 3% of the free balance per trade, leverage 20, its own comment (nb:fimathe). API at localhost:5573. With the fixed lot, the 3% rule refuses (in the log) an entry whose stop goes beyond that risk, given the account's free margin;
  • llm-support-resistance: the LLM strategy with the support_resistance prompt (pure chart analysis, price action at supports and resistances, indicators only for volatility and volume), like llm-trend: gpt-6-astra, reasoning high, 15m, consulted every 15 min, with the flags from the prompt header (llm-setup = free, llm-candles = 60, llm-min-rr = 1.5), the high-importance calendar, leverage 400 and reanalysis allowed. Its own comment (nb:llm-support-resistance), separate from llm-trend (nb:llm). API at localhost:5582;
  • the strategies in the code, one non-LLM agent for each, named after the strategy: on each strategy's default timeframe, leverage 2000, the strategy's default comment (e.g. nb:emacross, and therefore its own magic number) and APIs from localhost:5600 to localhost:5645, in this order:
    • trend (agents/trendagent): trendconfluence, emapullback, emacross, ema200, ribbon, supertrend, emasupertrend, psarema, atrtrailing, ichimoku, ichimokuadx, mtftrend, mtfema (matrend and fibonacci are the ones above);
    • momentum (agents/momentumagent): adxema, macdtrend, emamacd, emarsiadx, rsitrend, stochpullback, papullback;
    • breakout (agents/breakoutagent): atrbreakout, donchian, channel, adxdonchian, donchianatr, bbbreakout, keltner, volumebreakout, highlow, momentumbreakout (fimathe is the one above);
    • intraday (agents/intradayagent): orb, asialondon, vwap, sweep, zscore;
    • the prompt rules, coded, from localhost:5635 to localhost:5639: meanreversion, scalp1m and scalp1mbtc (intraday), trendpullback (trend) and squeezebreakout (breakout);
    • the strategies added later, from localhost:5640 to localhost:5645: consensus (trend), rsi2 (momentum), newsbreakout, seasonality, volumeprofile and cmegap (intraday). newsbreakout only takes entries with news on (the releases come from the calendar of the Notícias (News) tab);
  • pairsgold: the pairs strategy (agents/intradayagent, no LLM) on its default timeframe (1h), gold (leg A, XAUUSDm) against silver (leg B, XAGUSDm), pair = XAUUSDm;XAGUSDm, lot = XAUUSDm=0.02;XAGUSDm=0.03: the lots balance the values of the two legs as closely as the 0.01 lot step allows, with the contract sizes read from the Exness bridge (XAUUSDm 100 oz per lot, 0.02 lot = 2 oz, about US$ 7,800; XAGUSDm 5000 oz per lot, 0.03 lot = 150 oz, about US$ 7,400: a 6% difference, against 26% with 0.01 and 0.02). Leverage 2000, its own comment (nb:pairs-gold). API at localhost:5646;
  • pairscrypto: the same strategy on bitcoin (leg A, BTCUSDm) against ether (leg B, ETHUSDm), pair = BTCUSDm;ETHUSDm, lot = BTCUSDm=0.01;ETHUSDm=0.34: BTCUSDm 1 coin per lot, 0.01 lot about US$ 780; ETHUSDm 1 coin per lot, minimum volume 0.1, 0.34 lot about US$ 770. Leverage 2000, its own comment (nb:pairs-crypto). API at localhost:5647. On the two pairs agents, the break-even and trailing of Position protection must stay off: they move each leg on its own and break the hedge.

The prompts come from sql/seeds/0002_prompts.sql (the 3 for the strategies that only a language model trades: smc_ict, support_resistance and trend_following) and from sql/seeds/0003_prompts_dashboard.sql (the ones created on the dashboard: trend_following_v0, a copy of trend_following), each at version 1. The prompts of the code strategies, and those of the coded prompts (breakout, default, mean_reversion, scalp_1m, scalp_1m_btc), are not put in the database, because those strategies run in the non-LLM agents; an LLM agent without a prompt runs the built-in default (agents/llm/prompts/default.txt). They are kept in agents/llm/testdata/strategy_prompts.sql for the LLM agent's tests, and any of them can still be created on the dashboard. Each agent finds its prompt by name, never by an ID.

Each agent is inserted only once, when no agent has ever had its name, not even a deleted or renamed one. The seeds run on every migrator up, but never overwrite an edit made on the dashboard nor recreate a deleted agent. The secrets (the LLM key and the bridge and calendar tokens) never go into the seed: set them in Configurações > Agentes (Settings > Agents) and only then turn the agent on. While an agent is off, the controller never starts it. To change the initial configuration of a new database, edit the seed; on an existing database, use the dashboard.

Importing and exporting the configuration

In Configurações › Importar e exportar (Settings › Import and export), the configuration is exported to a JSON file (xtrader-config-AAAA-MM-DD.json) and imported back from it, on this installation or another one (for example, when changing machines), as in Nelogica's Profit.

  • What goes in the file: chosen item by item, in a tree by section:
    • prompts: name, description and content;
    • MT5 accounts: login, server, bridge, Permitir conta real (Allow real account) and Somente leitura (Read-only);
    • agents: kind, mode, API address, enabled, the switches, the parameters, the account (bridge, magic number, comment), the LLM, the prompt and the MT5 account by name, the protection and the daily limit (with the stops at the broker);
    • roles, except Administrador (Administrator), which is fixed;
    • limits: global daily limit (with the switch for the stops at the broker and the least margin for new entries), trading hours, exposure per asset and agents per asset;
    • news, XTrader AI and Telegram (the bot and the authorized users);
    • this browser's preferences: dashboard layout, theme, chart type, hide values and the periods of the closed P/L and of Desempenho (Performance). They live in the browser and only pass through the screen, never through the controller.
  • What is left out:
    • the dashboard users, because the password is a hash;
    • the active account of each terminal, which is switched in Contas MT5 (MT5 accounts);
    • the run state: bot stopped, blocks and locks of the day;
    • the history: orders, decisions, backtests and events.
  • Items refer to each other by name, not by ID: an agent points to its prompt and MT5 account by name, and the windows and rules cite agents by name. That is why the file works on another installation.
  • Secrets (LLM and XTrader AI keys, the password and token of the MT5 accounts, and the bridge, Telegram and news tokens):
    • are only included with Incluir os segredos (Include the secrets), encrypted with a password of at least 8 characters (Argon2id and AES-256-GCM). Without the password, no one can open them, not even XTrader;
    • on import, without the right password, the secrets stay as they are and the rest is imported;
    • an area's secrets are only exported and imported for those who can manage that area.
  • Importing: choose the file. Nothing changes before confirmation.
    • The preview checks each item as its screen would and says whether it is Novo (New), Alterado (Changed; with the fields that change), Igual (Same) or Inválido (Invalid; with the reason).
    • It also warns about what the import does beyond the fields: an agent that comes in on and starts trading, an agent that will be turned off, a running agent that needs a restart, a daily limit that would trigger or release the lock now, trading hours that change the windows, and a new account, which comes in inactive.
    • New and changed items come checked. Same items are hidden (Mostrar os iguais (Show the same ones)) and invalid items cannot be checked.
    • Importar N itens (Import N items) applies the checked items together, in one transaction: if one is refused, nothing is applied, and the preview shows which one. An item that is not in the file is never deleted.
    • Agents end up on or off as in the file: those that are on go back to trading.
    • Afterwards, the same effects as saving from the screen apply: agents launched or stopped, the runtime sent to the agents, the daily lock and the trading hours re-evaluated, XTrader AI and the Telegram bot reloaded.
    • The screens' rules also apply: an agent's kind does not change; an agent's MT5 account only changes while the agent is stopped and has no positions; an active MT5 account does not change its login, server or bridge through the file.
  • Permissions: exporting a section requires viewing its area; importing requires managing it (roles, through the users area). The tab shows for anyone who can view some area or the dashboard, because of the browser preferences.
Rebuilding the database from scratch

The migrations in sql/migrations create the whole schema, one table per file, in dependency order, without ALTER. The seeds in sql/seeds insert the settings: Telegram off, the prompts and the agents. On an empty database, migrator up leaves everything ready, missing only the sensitive data. The migrations do not continue the ones from before 2026-10-14: an old database (version 22) is refused by migrator up and must be recreated. The orders, decisions, journal, accounting periods and discards of the old database are not carried over.

Before that, close the positions opened by the agents. Without its orders in the database, an agent's position that is still open at the broker stays as it is, with an error in the log, and the core does not count it in the profit or the results when it closes.

Build the image with these migrations only when it is time to recreate the database: with it, the migrator fails on the old database, and the controller, which waits for it, does not start. The old database is at version 22 of the previous numbering, which is now a supervisor migration: the migrator tries to apply 000023, which fails (the supervisor_actions table does not exist there), and the database is marked dirty (dirty) at version 23, without any new table. To go back to the previous image without recreating the database, clear the mark first: UPDATE schema_migrations SET version = 22, dirty = false;.

deploy/docker/build.sh controller                                                      # in the repository: the image with the new migrations
cd /var/containers/xtrader
docker compose exec -T postgres pg_dump -U xtrader -Fc xtrader > xtrader-$(date +%F).dump  # backup of the old database
docker compose stop controller                                                         # the agents stop
docker compose exec postgres dropdb -U xtrader --force xtrader
docker compose exec postgres createdb -U xtrader -O xtrader xtrader
docker compose up -d                                                                   # the migrator creates the schema and the seeds
docker compose logs migrator                                                           # "schema at version 24 at least"

Then, on the dashboard:

  1. User: if the database has no user, the controller creates the first one with XTRADER_BOOTSTRAP_USERNAME and XTRADER_BOOTSTRAP_PASSWORD from services/controller/.env (at least 8 characters). Recreate the other users in Configurações > Usuários (Settings > Users) and delete the bootstrap password from the .env.
  2. Agents, in Configurações > Agentes (Settings > Agents): the bridge token (MT5_BRIDGE_TOKEN from services/mt5/.env) on the agents you will turn on; the OpenAI key on the LLM agents (llm-trend, llm-smc-liquidity and llm-support-resistance); the calendar MCP token, a single one for all, in Configurações > Notícias (Settings > News). Then turn on the agents you want: each agent that is on is a controller process trading the account.
  3. Telegram, in Configurações > Telegram (Settings > Telegram): the bot token and the authorized users (the old database had none), and then turn it on.

Development

Command What it does
make test go test -race -cover -timeout 30m ./... (the backtests take minutes under -race)
make test-short go test -race -short -timeout 10m ./..., without the long backtests (from testdata)
make bridge-test tests of tools/mt5bridge (python3 -m unittest), with a simulated MetaTrader5
make entrypoint-test tests of the switches (MT5_READ_ONLY etc.) of the mt5 image entrypoint, without Docker
make lint golangci-lint run --fix
make generate / make generate-check generates and checks web/src/api/types.ts from ui/dto.go (tygo)
make ui-install, make ui-dev, make ui-check, make ui-build dependencies, development server, lint + typecheck + tests, and build of the dashboard
deploy/docker/build.sh [controller|mt5] images of the stack
make docker-rebuild (deploy/docker/rebuild.sh [--dry-run]) asks which images to rebuild and whether to recreate the installed compose (up -d --force-recreate)

Database tests: without XTRADER_TEST_DATABASE_URL, the database tests are skipped. With it, each test creates its own database, with the real migrations and seeds, and drops it at the end. The user must be allowed to create databases:

XTRADER_TEST_DATABASE_URL='postgres://postgres:<password>@127.0.0.1:55432/postgres?sslmode=disable' go test -race ./...

API

  • Dashboard (/api): cookie session. Methods that change something require the X-CSRF-Token header with the value of the csrf_token cookie.
    • An error responds {"error": "…"} with the message in Portuguese, shown as is on the dashboard (e.g. Sessão expirada: entre de novo. (Session expired: sign in again.), O agente gold não responde em localhost:5560. (Agent gold does not respond at localhost:5560.)). The agents' API, passed through by the proxy, does the same. Database validations appear by their detail, without the technical prefix (e.g. Desligue o agente gold antes. (Turn off agent gold first.) instead of store: invalid: …), and an order refused while entries are blocked appears as Entradas bloqueadas: (Entries blocked: ) (Telegram recognizes the refusal by this beginning). Only details coming from libraries, the broker or the LLM stay in English (e.g. Falha no LLM: … (LLM failure: …)). A request that does not even reach the server (network down) appears on the dashboard as Sem conexão com o XTrader. Verifique a rede e tente novamente. (No connection to XTrader. Check the network and try again.), instead of the browser's message.
    • /api/auth/login, /api/auth/logout and /api/auth/session;
    • GET /api/agents: the dashboard's agents, each with its type, address, whether it responds, period, supervision and the pairs it trades (pairs, from the agent's settings; none for the default pair);
    • /api/agents/{agente}/…: proxy of each agent's API (snapshot, SSE events, controls, decisions). The proxy does not pass the browser's cookies, Authorization, Proxy-Authorization, X-CSRF-Token, Origin, Referer, Sec-Fetch-*, Forwarded or X-Forwarded-* on to the agent. From the agent's response, only the content headers pass (type, length, Content-Disposition, cache), never Set-Cookie, and only the types the API serves: JSON, text/event-stream, CSV, text, the PNG, JPEG, GIF and WebP images of attachments, and downloads (Content-Disposition: attachment). Any other type, such as HTML or SVG, becomes 502;
    • /api/settings/agents[/{nome}[/restart]], /api/prompts[/{id}], /api/settings/telegram[/users[/{id}]] and /api/users[/{id}];
    • GET /api/positions/open: the agents' open positions on the MT5 accounts, read from the bridges (a read stays valid for 2 s for all tabs), with totals (one per currency of the accounts read, in their order, 0 with no position), balances and accounts (the balances of the accounts read, each account once by login, per currency, and how many there are), complete, positions (agent, pair, side, volume in lots, prices, profit with swap and the account currency, ticket, whether the agent is running), pending_orders (the agents' pending orders on the accounts read, each one once by ticket, manual ones left out) and missing (the accounts not read, with the agents and the reason: unreachable, refused or failed);
    • GET /api/performance?from=…&to=…: the agents' live trades closed from from until before to (Unix seconds, up to 400 days), read from the deals of the MT5 accounts from 30 days before from until now (the read of each interval stays valid for 30 s): trades (position, account, agent, asset, side, lots, opened_at when known, closed_at, entry, exit, gross, costs, net and currency, in closing order), accounts (account, currency, agents, balance and start_balance, the balance at the start of the period), complete and missing, as in /api/positions/open. 400 for an invalid interval;
    • GET /api/performance/excursions?from=…&to=…: the price path of each trade of /api/performance in the same interval, read from the candles of the account's bridge: excursions (account, position, timeframe, high, low, mfe, mae, or error with no path), complete and missing. Each trade read stays stored while the controller runs. 400 for an invalid interval;
    • GET /api/positions/closed?from=…&to=…: the profit of the agents' positions closed from from until before to (Unix seconds, up to 400 days), read from the deals of the MT5 accounts (the read of each interval stays valid for 10 s; deals are read from 30 days before from, to find the entry of each position), with from, to, totals (one per currency of the accounts read, 0 with no close), agents (agent, amount, account currency, how many positions it closed, whether it is running), series (per currency of the totals, the points with at, in Unix seconds, and amount, the running total after the exits of that second, in chronological order, the last one equal to the total; no points when there is no exit), complete and missing, as in /api/positions/open. 400 for an invalid interval;
    • GET /api/agents/{agente}/{par}/candles?timeframe=4h&limit=1000: the pair's candles in the requested timeframe (1m, 5m, 15m, 30m, 4h, 1d or D, or the execution one; without timeframe, the execution one), the last limit candles (1000 by default, up to 5000), the last one still forming, with execution_timeframe and the source (strategy, broker or resampled). 400 for a timeframe outside the list, 404 for an unknown pair, 409 for a timeframe unavailable in the agent's mode (below the execution one in a backtest), 502 when the read at the broker fails. The snapshot carries timeframe (the execution one) and timeframes (the selector's, with execution and available);
    • XTrader AI (supervisor routes): GET/PATCH /api/settings/supervisor (the key is write-only: api_key_set says whether it is set; "" clears it), GET /api/supervisor/overview (the snapshot the model receives), POST /api/supervisor/run (202; 409 with another analysis in progress), GET /api/supervisor/runs[/{id}] (with the snapshot in the detail), GET /api/supervisor/actions, GET/POST /api/supervisor/messages (the conversation of the session's user), POST /api/supervisor/messages/stream (the same question, with the answer as SSE events: message for each saved message, the question and each proposal; stage with the step, reading, thinking or tool; text with the chunks of the model's text; error; and last done, with the messages as the POST above returns them; an empty message is refused with 400 in JSON before the stream), POST /api/supervisor/actions/{id}/confirm and /reject (409 for an action already decided, 410 for an expired proposal), POST /api/supervisor/agents/{nome}/entries with {"blocked": true, "reason": "…"} and POST /api/supervisor/agents/{nome}/close with an optional {"reason": "…"} (closes all of the agent's open positions, responding with the action and the verified result; 409 with no open position or with a close in progress), POST /api/supervisor/close-all with an optional {"reason": "…"} (flattens the positions and cancels the pending entry orders of all agents, responding with the action and the verified result; 409 with a close in progress), GET /api/supervisor/protections (the protections armed on positions, with the reason, the evidence and the previous, requested and confirmed stops; the analyses carry protection_ids).
    • News: GET/PUT /api/settings/news ({"enabled": true, "token": "…", "url": "http://mt5:22347/mcp", "block_before": 15, "block_after": 15, "block_importance": "high"}, with the fields present applied: a missing token is kept, "" removes it; 400 outside the rules: the window from 0 to 1440 minutes, the importance low/medium/high, the http(s) address without credentials; the response carries enabled, url, token_set (never the token), the window, conflict and url_conflict with the agents on different earlier settings, who changed them and when, and all agents with type and state) and POST /api/settings/news/test (the news server: url, agents, status ok/missing_server/missing_token/unauthorized/unavailable and detail, without the token). The dashboard card uses GET /api/news/calendar?from=…&to=…&currencies=USD,EUR (Unix seconds, up to 31 days, up to 20 currencies; dashboard:view): the releases (at, timed, currency, name, importance, unit, actual, forecast, previous and blocks), the block window (window), the status and the detail as in the test, without the token; 400 for an invalid period or currency. Each read serves all tabs for 1 minute. Changes reach all agents through the runtime (news), and so does the configuration at startup.
    • Daily lock: GET /api/daily-guard (the day, the time zone, the result counted for all agents, the result of each account currency in results, and that of the agents with their own limit, the limits, the state off/free/blocked/incomplete/margin (margin: entries blocked by the least margin, nothing flattened), the lock with its reason and flattening, the agents in paper and, in stops, the stops at the broker requested now: agent, asset, side, tickets, source limit, level, margin and share, and the last submission), GET/PUT /api/settings/trading-hours (the trading hours: {"settings": {"enabled": true, "windows": [{"start": "08:00", "end": "10:00", "agents": ["highlow", "matrend"], "flatten": true, "cancel_pending": true}, {"start": "12:00", "end": "14:00", "flatten": false, "cancel_pending": true}]}, "reason": "…"}, applied immediately; without windows, start/end/flatten/cancel_pending count as the only window, and the response still carries the first window in these fields; status carries windows, window (the open one), open, blocked, next_at and last_end (with the window that ended); agents are the names of the agents that may open a position in the window (none means all) and pairs the assets (none means all); 400 for invalid times, a window that crosses midnight, windows that overlap or touch, more than 24, enabled with no window, an agent that does not exist or is repeated, or an invalid or repeated asset; /api/daily-guard carries the same hours), GET/PUT /api/settings/daily-limits (the limit of all agents: {"settings": {"enabled": true, "max_loss": 150, "max_gain": 300, "broker_stops": true}, "reason": "…", "confirm": false}, in each account's currency; currency is refused with 400; broker_stops turns the stops at the broker on or off, and min_margin_pct (from 0 to less than 100) is the least margin for new entries as a % of the maximum loss, both kept as they are when absent) and PUT /api/settings/agents/{nome}/daily-limit (an agent's own limit, in the account currency). A change that would trip or release the lock now returns 409 with the preview (effect trip/release, the result and the message) until it is sent with "confirm": true; 400 outside the rules. /api/agents carries daily_blocked/daily_reason in supervision, and /api/settings/agents the daily_limit of each agent. /api/agents and /api/settings/agents carry supervision (block and stop) on each agent, and /api/settings/agents the protection (breakeven and trailing, unit atr), changed by PATCH /api/settings/agents/{nome} with {"protection": {…}} (400 outside the rules);
    • /api/settings/agents/{nome}/periods: GET lists the agent's accounting periods (the current one first); POST with {"deposit": 1000, "currency": "BRL"} resets the results (201 with the new period);
    • Agents per asset: GET/PUT /api/settings/asset-agents ({"settings": {"rules": [{"pairs": ["XAUUSDm"], "agents": ["orb", "trend"]}]}}; read with limits:view or backtests:manage, change with limits:manage; 400 for an invalid asset or one in two rules, a rule with no asset or no agent, or an agent that does not exist or is repeated). The change reaches the agents immediately, in the runtime entries (entries_pairs/pairs_reason, or entries_blocked when no asset is allowed).
    • Backtests: GET /api/backtests (the last 30 batches with their runs and summaries, the agents with their compatibility and the limits), POST /api/backtests (creates a batch, ui.BacktestRequest, with asset_agents: true to respect the agents per asset: 201; 400 outside the rules), DELETE /api/backtests/{id} (409 with runs queued or running), GET /api/backtests/runs/{id} (the run with the copied configuration and the report) and POST /api/backtests/runs/{id}/cancel (204; 409 if it already finished);
    • Paged lists (ui.PageInfo, with github.com/raykavin/gobox/pagination): ?page= (starting at 1), ?per_page= (default 20, at most 100) and, in the ones that search, ?q= (up to 100 characters; each word in some field, ignoring case and accents, with % and _ taken as text). The response keeps the list's key (prompts, users, …) and carries total (the items of the search), page (the one answered: the last one, for a page beyond it), per_page, total_pages, has_next and has_prev. Without page, the response is the same as before: the whole list, or the latest ones in XTrader AI (50 analyses, 100 actions and protections) and in backtests (30 batches), with the same page fields. 400 for an invalid parameter. These accept page, per_page and q: GET /api/settings/mt5-accounts, /api/prompts, /api/settings/telegram/users (the bot's authorized users; /api/settings/telegram still carries all of them), /api/users and /api/roles (the areas catalog comes on every page). These accept page and per_page: GET /api/supervisor/runs (with the action_ids and protection_ids of each analysis on the page), /api/supervisor/actions, /api/supervisor/protections, /api/settings/daily-limits/agents (the agents with their own limit or lock now, in the order of /api/daily-guard, with zone) and /api/backtests (with running, the queued or running runs of all batches, and choices, the id, name and period of all batches). GET /api/backtests/{id}/comparison?page=&per_page=&sort=ratio&order=desc&min_trades=0&llm=true returns the batch comparison: batch (without the runs), rows (one agent per row, with the fit, the validation and degraded), hidden (the rows the filters hide), differences (the conditions that change between the agents) and active (the batch's runs queued or running); sort is agent, net, return, drawdown, ratio, factor, winrate, trades, months or validation (order is asc by default for agent, desc for the others; the ones with no value last), min_trades hides the agents that made fewer trades (runs without a summary stay) and llm=false hides the LLM agents; 400 for an invalid order or filter, 404 for a batch that does not exist;
    • Configuration file (see Importing and exporting the configuration):
      • GET /api/config/catalog: the sections and items the user can export, and which of them have secrets;
      • POST /api/config/export with {"selection": {"agents": ["orb"]}, "include_secrets": true, "password": "…"}: responds with the file (ui.ConfigFile); 400 for a short password;
      • POST /api/config/import/preview with {"file": {…}, "password": "…"}: the state of each item, without applying anything, and secrets (none, locked or unlocked);
      • POST /api/config/import, with selection: applies the selected items together, and applied says whether they were applied;
      • 400 for a file of another format or of a newer version; the import body goes up to 8 MB;
      • viewing and exporting require the view permission of some area or dashboard:view; importing requires the manage permission of some area, and each item is checked against the permission of its area.
    • the types are in ui/dto.go, generated into web/src/api/types.ts.
  • Agents' internal API (agentapi): loopback only, with Authorization: Bearer <token do start> (the token issued at that start), and each token reaches only its own agent. Routes: config, runtime (long-poll), prompt, order-ids, orders, decisions, decision-links, journal/memory, outbox and outbox/check (responds like outbox, without writing anything).
  • Each agent's API (ui, on its api_address): responds only to the controller. It requires a loopback host in Host, refuses browser requests with 403 (with Origin, or Sec-Fetch-Site cross-site/same-site) and, on an agent launched by the controller, the requests that do not carry X-Xtrader-Agent-Key with the key of that start. POST, PUT, PATCH and DELETE require Content-Type: application/json, even without a body (otherwise 415).
    • supervisor channel: GET /api/supervision (block and applied revision, positions and pending entry orders), POST /api/supervision/entries, POST /api/supervision/close (closes the requested pairs with "reduce only" orders, with the block applied first; result per pair: closed, failed or unknown), POST /api/supervision/cancel (only the pending entry orders), POST /api/supervision/protect (arms the breakeven or the trailing on a position: applied, armed, failed, unknown or refused, with the previous, requested and confirmed stops) and POST /api/supervision/daily-stops (the daily loss stops of the agent's positions, all of them, replacing the previous ones, each applied immediately and answered as in protect). The GET also carries protections, the protection state of each position. The dashboard snapshot and the candle events carry the pair's protection. Only the controller calls them, on the supervisor channel; the dashboard proxy always uses the web channel, and the routes respond 404 to any other channel.

Security

To report a vulnerability, see SECURITY.md, never in a public issue.

  • Login: passwords in bcrypt, session with an HttpOnly cookie (and Secure behind an HTTPS proxy) and CSRF protection. After login, it only goes back to a page of the dashboard itself (a next with a control character, a space, \ or another site goes to /).

  • Login attempt limit: it is counted before the password is checked, because bcrypt costs about 250 ms of CPU on the controller, which also runs the agents:

    • per client address (strict): one login at a time; after a failure, the next one only 1 s later; from the 5th failure in a row, the wait doubles with each failure (2 s, 4 s, 8 s… up to 5 min). Failures are forgotten 1 h after the last one;
    • per user (looser, adding up all addresses, so that an attacker cannot lock out the legitimate user): 10 attempts in a row and then 1 every 30 s. A correct login resets this limit;
    • at most 2 passwords checked at the same time.

    A refused login gets 429 with Retry-After, without the password being checked, whether the user exists or not (the time for a nonexistent user is the same, with a fake bcrypt). An IPv6 address counts by its /64. The counters live in memory (at most 4096 addresses and 4096 users; when full, a new one is refused until the old ones expire) and reset when the controller restarts. A distributed attack (many addresses) against a single user can delay that user's login while it lasts: use strong passwords.

  • Reverse proxy: X-Forwarded-For and X-Forwarded-Proto only count when the connection comes from a trusted proxy, ui.trusted_proxies in config.yml (default: the loopback, where the host's ngrok runs). The client address, used in the logs and in the login limit, is the last one in X-Forwarded-For before the trusted proxies: the earlier ones are supplied by the client itself. In Docker, the host's ngrok reaches the controller through the gateway of the compose network (e.g. 172.18.0.1), so the container's config trusts Docker's private range, 172.16.0.0/12; with the dashboard port published only on the host's loopback, no other client arrives through that range.

  • Sessions: last 7 days, live in the controller's memory (restarting it logs everyone out) and are checked against the database every minute: a user who is deactivated, deleted, has a different password (including one changed through SQL or by the migrator) or has no role ends the session. With the database down, the session continues for up to 5 min since the last check, so that a PostgreSQL restart does not log anyone out; after that, it is refused until the database is back, when it continues if nothing changed.

  • Roles and permissions (Configurações > Usuários e papéis (Settings > Users and roles)): each user has a role, and the role says what they see and do, per area.

    • Areas: Painel (Dashboard), view; Operação (Operation), operate; Chat do XTrader AI (XTrader AI chat), use; Desempenho (Performance), view; and view and manage in Backtesting, Agentes (Agents), Contas MT5 (MT5 accounts), Limites (Limits), Notícias (News), Prompts, XTrader AI, Telegram and Usuários e papéis (Users and roles). The catalog lives in ui/access.go and is served at GET /api/roles.
    • Implied: manage includes view; operate and using the chat include viewing the dashboard.
    • Operação covers starting and stopping the bot, moving and canceling orders, the reanalysis, the × and Zerar tudo (Flatten all), blocking and releasing entries, and confirming or rejecting the proposals of XTrader AI.
    • Backend: each API route declares the permissions it requires (any one of them is enough). Without any of them, the response is 403 ("Você não tem permissão para esta ação." (You do not have permission for this action.)), including on a direct call to the API. Some lists also serve another area: the prompts and the MT5 accounts for those who manage agents, the agents for those who view the limits, the trading hours for those who manage backtests. A test walks through every route and fails if a new one does not declare a permission.
    • Dashboard: shows only the allowed pages, tabs and actions. Without manage, the forms are read-only. A page without permission leads to the first allowed one; a role with no area shows "Sem acesso" (No access), with the Sair (Sign out) button.
    • User without a role: cannot sign in. The login responds 403 ("Seu usuário não tem um papel atribuído: peça acesso a um administrador." (Your user has no role assigned: ask an administrator for access.)), with no session. No permission is given by default.
    • Administrador (Administrator): a fixed role, with all permissions, including the ones created later. It cannot be edited or deleted. The first user (bootstrap) gets this role. On upgrade, the migrator grants it once to all existing users, who keep the access they had.
    • Lock: there is always at least one active user with a role that manages users and roles. Deactivating or deleting that user, changing their role or removing the permission from the role is refused (409). A role with users cannot be deleted.
    • When it applies: a change made through the dashboard applies on the next request of whoever was affected. A change made directly in the database applies at the next session check (up to 1 min). Removing a user's role ends their sessions.
    • Warning: whoever manages users and roles can give themselves any role. In practice, they are an administrator.
    • The Telegram bot has its own list of authorized IDs and does not use the dashboard roles.
  • Secrets: encrypted in the database (AES-256-GCM), write-only on the dashboard and never shown in responses, logs or on Telegram. The bot token is masked in the logs.

    • Each secret is encrypted together with its place (tabela:coluna:id (table:column:id), e.g. agent_llm_settings:api_key:3), with a version prefix. Someone who can write to the database but does not have the key cannot swap secrets between rows or columns: copied to another place (the model's key as the token of a bridge pointed at another server, for example), the secret does not open, and the agent does not start until it is set again.
    • Secrets saved by earlier versions, without the place, still work and become bound to it when they are saved again (the Telegram token, on every save of the bot settings). Until then, they do not have this protection: to bind all of them at once, set them again on the dashboard.
    • Going back to an earlier version after this requires setting the secrets again: it would read the prefix as part of the secret, and the requests using it fail.
    • There is no rotation of XTRADER_SECRETS_KEY: changing it requires setting all secrets again.
  • Agents: receive a minimal environment and a new token on every start, revoked when they exit.

  • Agents' API: has no login, so it stays on the loopback only. The dashboard refuses (400) an api_address outside localhost, 127.0.0.0/8 and [::1]. An agent saved before this rule with another host (e.g. 0.0.0.0:5580) is not launched, does not enter the dashboard and is not probed, and its card shows "Não iniciado" (Not started) with the reason; the others continue normally. Fix the address in the agent's settings. Before upgrading, check with SELECT name, api_address FROM agents;.

    • Per-start key: on every start, the controller hands the agent a random key (XTRADER_AGENT_API_KEY, separate from the internal API token) and sends it in X-Xtrader-Agent-Key from the proxy, the probe and Telegram. The agent refuses (403) whoever does not carry it, so another process on the machine cannot operate the bot. An agent run on its own (e.g. a backtest with -api) has no key, and the dashboard accesses it without one.
    • Browser: a page from another site opened in a browser on the machine reaches localhost, but the API refuses requests with Origin, with a Sec-Fetch-Site from another site or with another Host (DNS rebinding), and only accepts changes in JSON, which a page from another site cannot send without a preflight. The dashboard proxy checks the session and the CSRF and only then removes these headers.
  • Dashboard headers: every response carries a Content-Security-Policy that allows only the dashboard's own files (default-src 'self'; the inline configuration script of index.html allowed by its SHA-256 hash; frame-ancestors 'none'; object-src 'none'; base-uri 'none'), plus X-Frame-Options: DENY, X-Content-Type-Options: nosniff and Referrer-Policy: same-origin. The directories of the dashboard bundle are not listed (404). If the bundle does not load, the error page shows a generic message, and the reason goes only to the log (ui: dashboard bundle unavailable).

  • Slow connections: the dashboard, the internal API and each agent's API allow 10 s for the headers (at most 32 KiB) and 30 s for the whole request, body included, and close an idle keep-alive connection after 2 min. The response has no deadline, because the events (SSE) and the long-poll of the internal API last longer than that.

  • Logs: a message from someone who is not a user of the Telegram bot is refused and logged only by the sender's ID, at most one line per minute (with the count of refused messages in the interval), never the content. An HTTP error from the calendar MCP server keeps only the start of the body (1 KiB), without the token or anything that looks like a key.

  • XTrader AI: the model never receives keys, tokens, the bridge URL, the account login or the magic number (the accounts go by nickname). A read that fails enters the snapshot only as the reason (unreachable, refused, failed, "its API doesn't answer"); the full error goes only to the log. It acts only through tools whose arguments are validated in the backend: none of them opens a position, increases a position, loosens a stop, releases entries or turns an agent back on. The supervisor channel of the agent API only reduces risk and cannot be reached from the dashboard. Closing positions, stopping now and releasing entries require a signed-in user, with the usual session and CSRF. In the chat, the tools that act immediately (execute_action and protect_position) are offered only to those who can operate, and set_daily_limits only to those who manage the limits. A call without permission is refused anyway; those who cannot operate can only propose, and the proposal waits for the confirmation of someone who can. A bridge in read-only mode or on a real account without Permitir conta real (Allow real account) refuses the direct closes.

  • Real account: requires Permitir conta real on the agent and on the MT5 account (Configurações > Contas MT5 (Settings > MT5 accounts)), which the bridge applies together with Somente leitura (Read-only).

  • Ports published in Docker: only on the host's loopback, 127.0.0.1:8082 (dashboard, where the host's ngrok tunnels to), 127.0.0.1:5900 (VNC, which only starts with a password) and 127.0.0.1:5432 (PostgreSQL). Docker publishes the ports outside the host firewall (ufw), so a port on 0.0.0.0 would be open to the network even when "closed" in the firewall. From another machine, use an SSH tunnel, e.g. ssh -N -L 5900:127.0.0.1:5900 <usuário>@<servidor> for VNC and ssh -N -L 5433:127.0.0.1:5432 <usuário>@<servidor> for psql -h 127.0.0.1 -p 5433 (details in deploy/docker/README.md).

  • Dependencies: go.mod pins the toolchain (toolchain go1.25.14), with the security fixes of the standard library, and the image builds with Go 1.26.8. To check for known vulnerabilities: go run golang.org/x/vuln/cmd/govulncheck@latest ./....

Risk disclaimer

XTrader is software for studying and automating trades. Using it, on a demo or a real account, is your decision and your responsibility.

  • Not investment advice: nothing in this repository (code, strategies, prompts, seeds, parameters, screenshots or documentation) is a recommendation to buy or sell any asset, nor a managed trading or signal service.
  • No proven edge: no strategy, prompt or agent shipped here has been shown to be profitable. The seeds are starting points to test, not configurations to trade. Results of backtests, paper and demo accounts don't guarantee future results: on a real account, spread, commissions, swap, slippage, gaps, requotes and latency can change them.
  • Language models: the decisions of an LLM agent and the actions of XTrader AI can be wrong, inconsistent or based on misread data, and every call costs money with the provider.
  • Protections are not guarantees: the daily limits, the stops at the broker, the flattening, the trading hours, the exposure limits and XTrader AI reduce the risk, but don't ensure a maximum loss. A gap or slippage can close a position beyond its stop, and a failure of the controller, the bridge, the MT5 terminal, the broker or the network can leave positions open without the application's protection.
  • Leverage: CFDs, forex, indices, metals and crypto traded with leverage can lose money quickly. Never trade money you cannot afford to lose.
  • Your responsibility: before using it, check your broker's terms (automated trading, use of the MT5 terminal) and the regulation of your country; keep your credentials safe and follow what the application does on a real account.
  • No warranty: as the MIT license states, the software is provided "as is", without warranty of any kind, and the authors and copyright holders are not liable for any loss arising from its use.

License

Distributed under the MIT license: see LICENSE. The software is provided "as is", without warranty of any kind, and the risk of the trades made with it lies with whoever uses it.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	SideTypeBuy                    = model.SideTypeBuy
	SideTypeSell                   = model.SideTypeSell
	OrderTypeLimit                 = model.OrderTypeLimit
	OrderTypeMarket                = model.OrderTypeMarket
	OrderTypeLimitMaker            = model.OrderTypeLimitMaker
	OrderTypeStopLoss              = model.OrderTypeStopLoss
	OrderTypeStopLossLimit         = model.OrderTypeStopLossLimit
	OrderTypeTakeProfit            = model.OrderTypeTakeProfit
	OrderTypeTakeProfitLimit       = model.OrderTypeTakeProfitLimit
	OrderStatusTypeNew             = model.OrderStatusTypeNew
	OrderStatusTypePartiallyFilled = model.OrderStatusTypePartiallyFilled
	OrderStatusTypeFilled          = model.OrderStatusTypeFilled
	OrderStatusTypeCanceled        = model.OrderStatusTypeCanceled
	OrderStatusTypePendingCancel   = model.OrderStatusTypePendingCancel
	OrderStatusTypeRejected        = model.OrderStatusTypeRejected
	OrderStatusTypeExpired         = model.OrderStatusTypeExpired
)
View Source
var ErrBacktestCanceled = errors.New("backtest canceled")

ErrBacktestCanceled is the error of a backtest whose context ended before its last candle.

Functions

This section is empty.

Types

type CandleHook

type CandleHook interface {
	OnCandle(model.Candle)
}

CandleHook is told every candle the bot processes live, and of a backtest, the ones in progress and the closed ones, once the strategy ran on it and, on a closed one, the orders were settled (see processCandle): never the candles of the preload. A panic of it is recovered and logged. It runs on the goroutine of the candles, so it must not wait long: eg: the protection of the positions moving a stop loss.

type CandleSubscriber

type CandleSubscriber interface {
	OnCandle(model.Candle)
}

type Dataframe

type Dataframe = model.Dataframe

type Option

type Option func(*XTrader)

func WithBacktest

func WithBacktest(wallet *exchange.PaperWallet) Option

WithBacktest sets the bot to run in backtest mode, it is required for backtesting environments Backtest mode optimize the input read for CSV and deal with race conditions

func WithBacktestClock

func WithBacktestClock(clock func(time.Time)) Option

WithBacktestClock tells clock the time of each candle of a backtest before it is processed: the end of the data known then (its UpdatedAt, else its open time), the simulated now, eg: of a feed answering until then only.

func WithBacktestProgress

func WithBacktestProgress(progress func(done, total int)) Option

WithBacktestProgress tells progress, after each candle of a backtest, how many it processed of all of them, in place of the progress bar.

func WithCandleHook

func WithCandleHook(hook CandleHook) Option

WithCandleHook sets the hook of the candles, see CandleHook.

func WithCandleSubscription

func WithCandleSubscription(subscriber CandleSubscriber) Option

WithCandleSubscription subscribes a given struct to the candle feed

func WithLogLevel

func WithLogLevel(level log.Level) Option

WithLogLevel sets the log level. eg: log.DebugLevel, log.InfoLevel, log.WarnLevel, log.ErrorLevel, log.FatalLevel

func WithNotifier

func WithNotifier(notifier service.Notifier) Option

WithNotifier registers a notifier to the bot, currently only email and telegram are supported. The notifier is wired to the order controller by NewBot, once it exists.

func WithOrderSubscription

func WithOrderSubscription(subscriber OrderSubscriber) Option

func WithPaperWallet

func WithPaperWallet(wallet *exchange.PaperWallet) Option

WithPaperWallet sets the paper wallet for the bot (used for backtesting and live simulation)

func WithStorage

func WithStorage(storage storage.Storage) Option

WithStorage sets the storage for the bot, by default it uses a local file called xtrader.db

type OrderStatusType

type OrderStatusType = model.OrderStatusType

type OrderSubscriber

type OrderSubscriber interface {
	OnOrder(model.Order)
}

type OrderType

type OrderType = model.OrderType

type Series

type Series = model.Series[float64]

type Settings

type Settings = model.Settings

type SideType

type SideType = model.SideType

type XTrader

type XTrader struct {
	// contains filtered or unexported fields
}

func NewBot

func NewBot(
	ctx context.Context,
	settings model.Settings,
	exch service.Exchange,
	str strategy.Strategy,
	options ...Option,
) (*XTrader, error)

func (*XTrader) Controller

func (n *XTrader) Controller() *order.Controller

func (*XTrader) Run

func (n *XTrader) Run(ctx context.Context) error

Run will initialize the strategy controller, order controller, preload data and start the bot.

Live, it runs until ctx is done, then stops trading before it returns: no order begins any more (order.ErrBotStopped), the strategy ends the candle in progress, its orders refused, and the order controller is closed (see order.Controller.Close), once the calls begun to the exchange are recorded in the storage, which nothing writes to after Run returns.

func (XTrader) SaveReturns

func (n XTrader) SaveReturns(outputDir string) error

func (*XTrader) SetCandleHook

func (n *XTrader) SetCandleHook(hook CandleHook)

SetCandleHook sets the hook of the candles, see CandleHook: before Run.

func (*XTrader) SubscribeCandle

func (n *XTrader) SubscribeCandle(subscriptions ...CandleSubscriber)

func (*XTrader) SubscribeOrder

func (n *XTrader) SubscribeOrder(subscriptions ...OrderSubscriber)

func (*XTrader) Summary

func (n *XTrader) Summary()

Summary function displays all trades, accuracy and some bot metrics in stdout To access the raw data, you may access `bot.Controller().Results`

Directories

Path Synopsis
Package agentapi is the internal API of the controller for the agents it launches: the settings each agent runs with, what it applies while it runs (the channels of its control panel, the prompt of an LLM agent), and the records it keeps through the controller, which alone reaches the database: its orders and the positions its order controller discarded, and the decisions and journal of an LLM agent.
Package agentapi is the internal API of the controller for the agents it launches: the settings each agent runs with, what it applies while it runs (the channels of its control panel, the prompt of an LLM agent), and the records it keeps through the controller, which alone reaches the database: its orders and the positions its order controller discarded, and the decisions and journal of an LLM agent.
agents
backtesting command
breakoutagent command
Command breakoutagent runs the breakout strategies, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet): atrbreakout (the breakouts of the recent range on an expansion of the volatility), fimathe (the first entry of the trend of the reference channel of each week of the Fimathe technique, its levels drawn on the chart), squeezebreakout (the release of a compression with the volume: the rules of the prompt breakout of the LLM agent, its stop loss moved by the R multiple of the position), and the signal strategies donchian, channel, adxdonchian, donchianatr, bbbreakout, keltner, volumebreakout, highlow and momentumbreakout, see strategies.NewSignal.
Command breakoutagent runs the breakout strategies, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet): atrbreakout (the breakouts of the recent range on an expansion of the volatility), fimathe (the first entry of the trend of the reference channel of each week of the Fimathe technique, its levels drawn on the chart), squeezebreakout (the release of a compression with the volume: the rules of the prompt breakout of the LLM agent, its stop loss moved by the R multiple of the position), and the signal strategies donchian, channel, adxdonchian, donchianatr, bbbreakout, keltner, volumebreakout, highlow and momentumbreakout, see strategies.NewSignal.
internal/backtest
Package backtest runs a strategy of an agent over the candles of a period, as the controller asks for it (see Config), on a paper wallet and a feed of files only: never a broker.
Package backtest runs a strategy of an agent over the candles of a period, as the controller asks for it (see Config), on a paper wallet and a feed of files only: never a broker.
internal/entryfilter
Package entryfilter filters the entries of the strategy of a family agent, whatever the strategy: a decorator of strategy.Strategy (see Wrap) handing the strategy a broker whose entries it asks first (see broker.go), so it behaves the same in a backtest, in paper and live.
Package entryfilter filters the entries of the strategy of a family agent, whatever the strategy: a decorator of strategy.Strategy (see Wrap) handing the strategy a broker whose entries it asks first (see broker.go), so it behaves the same in a backtest, in paper and live.
internal/flaglist
Package flaglist reads the flags of a list the agents share.
Package flaglist reads the flags of a list the agents share.
internal/newsguard
Package newsguard keeps an agent out of the market around the releases of the economic calendar, the news of the dashboard (the tab Notícias), for every agent, LLM or not: as the window of a release of a currency of a pair starts, the entries of the agent are held, the pending entries of the pair canceled and its position closed at the market; as no window holds any of its pairs any more, the entries are released.
Package newsguard keeps an agent out of the market around the releases of the economic calendar, the news of the dashboard (the tab Notícias), for every agent, LLM or not: as the window of a release of a currency of a pair starts, the entries of the agent are held, the pending entries of the pair canceled and its position closed at the market; as no window holds any of its pairs any more, the entries are released.
internal/protect
Package protect protects the open positions of an agent: its breakeven and its trailing stop (see ui.ProtectionSettings), applied on every price the bot processes (see xtrader.CandleHook), and the ones the XTrader AI arms on a position, its trigger kept.
Package protect protects the open positions of an agent: its breakeven and its trailing stop (see ui.ProtectionSettings), applied on every price the bot processes (see xtrader.CandleHook), and the ones the XTrader AI arms on a position, its trigger kept.
internal/remote
Package remote runs an agent launched by the controller (cmd/controller) with the settings and the records of the controller, which alone reaches the database, through its internal API (see agentapi): the flags of its settings, its secrets, the switches of its control panel and the prompt of an LLM agent as they change while it runs, and the storage of its orders, of its decisions and of its journal.
Package remote runs an agent launched by the controller (cmd/controller) with the settings and the records of the controller, which alone reaches the database, through its internal API (see agentapi): the flags of its settings, its secrets, the switches of its control panel and the prompt of an LLM agent as they change while it runs, and the storage of its orders, of its decisions and of its journal.
internal/ta
Package ta holds the series of the technical analysis shared by the entry filters (agents/internal/entryfilter) and the features of the meta-labeling (agents/metalabel), following the conventions of Pine Script, as the helpers of the strategies do (agents/strategies/pine.go, unexported there): a missing value is NaN, the counterpart of Pine's na, comparisons involving NaN are false, and the recursive averages (EMA, RMA and everything built on them: ATR, RSI, DMI) are seeded with the SMA of their first length values, so they are NaN until then, like the built-ins.
Package ta holds the series of the technical analysis shared by the entry filters (agents/internal/entryfilter) and the features of the meta-labeling (agents/metalabel), following the conventions of Pine Script, as the helpers of the strategies do (agents/strategies/pine.go, unexported there): a missing value is NaN, the counterpart of Pine's na, comparisons involving NaN are false, and the recursive averages (EMA, RMA and everything built on them: ATR, RSI, DMI) are seeded with the SMA of their first length values, so they are NaN until then, like the built-ins.
intradayagent command
Command intradayagent runs the intraday strategies of the sessions, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet), in ATR from the entry close, on their own timeframe, 5m, unless -timeframe says otherwise: orb (the opening range breakout), asialondon (the Asia range broken in London), vwap (the reclaim and the reject of the VWAP of the session, -setup reject trading the continuation of its trend), sweep (the sweeps of the liquidity of the swings) and zscore (the reversion of the Z-Score of the close); and the rules of prompts of the LLM agent, their stop loss and take profit set by each, moved by the R multiple of the position: meanreversion (the rejections of the Bollinger Bands of a range back to its mean, 15m), scalp1m (the micro pullbacks of the micro trend, 1m) and scalp1mbtc (the strong bursts of momentum, for a spread wide next to the moves, 1m); and newsbreakout (the breakout of the range after the scheduled economic releases, the rules of orb on it, the releases given by the runner, 5m), seasonality (the intraday bias of fixed windows of the day, measured walk-forward, 15m), volumeprofile (the 80% rule of the value area of the volume profile of the previous session, 30m), cmegap (the weekend gap of the CME faded back to its Friday close, 1h) and pairs (the spread of the two pairs of the agent, leg A and leg B in the order of -pair, traded back to its mean on its Z-Score, 1h: the log of the ratio of their prices, its legs of equal value, or with -pairs-hedge ols the residual of the regression of their logs, leg B worth β times leg A; no stop loss nor take profit at the broker).
Command intradayagent runs the intraday strategies of the sessions, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet), in ATR from the entry close, on their own timeframe, 5m, unless -timeframe says otherwise: orb (the opening range breakout), asialondon (the Asia range broken in London), vwap (the reclaim and the reject of the VWAP of the session, -setup reject trading the continuation of its trend), sweep (the sweeps of the liquidity of the swings) and zscore (the reversion of the Z-Score of the close); and the rules of prompts of the LLM agent, their stop loss and take profit set by each, moved by the R multiple of the position: meanreversion (the rejections of the Bollinger Bands of a range back to its mean, 15m), scalp1m (the micro pullbacks of the micro trend, 1m) and scalp1mbtc (the strong bursts of momentum, for a spread wide next to the moves, 1m); and newsbreakout (the breakout of the range after the scheduled economic releases, the rules of orb on it, the releases given by the runner, 5m), seasonality (the intraday bias of fixed windows of the day, measured walk-forward, 15m), volumeprofile (the 80% rule of the value area of the volume profile of the previous session, 30m), cmegap (the weekend gap of the CME faded back to its Friday close, 1h) and pairs (the spread of the two pairs of the agent, leg A and leg B in the order of -pair, traded back to its mean on its Z-Score, 1h: the log of the ratio of their prices, its legs of equal value, or with -pairs-hedge ols the residual of the regression of their logs, leg B worth β times leg A; no stop loss nor take profit at the broker).
llm
Package llm trades with a language model as its analyst.
Package llm trades with a language model as its analyst.
llm/llmagent command
metalabel
Package metalabel is the meta-labeling of the entries of a strategy (Marcos López de Prado, "Advances in Financial Machine Learning", 2018, §3.6): the strategy (the primary model) decides the side of an entry, and a second model, trained on the outcomes of its past entries, tells the probability that an entry reaches its target before its stop, from features of the market at the entry.
Package metalabel is the meta-labeling of the entries of a strategy (Marcos López de Prado, "Advances in Financial Machine Learning", 2018, §3.6): the strategy (the primary model) decides the side of an entry, and a second model, trained on the outcomes of its past entries, tells the probability that an entry reaches its target before its stop, from features of the market at the entry.
momentumagent command
Command momentumagent runs the momentum strategies, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet), the opposite signal closing it: adxema, macdtrend, emamacd, emarsiadx, rsitrend, stochpullback and papullback, see strategies.NewSignal; and rsi2 (the RSI 2 of Connors and Alvarez: the RSI 2 under 10 with the close above the SMA 200 a buy, over 90 under it a sell, closed on the close beyond the SMA 5, on the daily candles of the book, its stop loss and take profit a safety), see strategies.NewRSI2.
Command momentumagent runs the momentum strategies, each entry placed with its stop loss and take profit at the broker (mt5 or the paper wallet), the opposite signal closing it: adxema, macdtrend, emamacd, emarsiadx, rsitrend, stochpullback and papullback, see strategies.NewSignal; and rsi2 (the RSI 2 of Connors and Alvarez: the RSI 2 under 10 with the close above the SMA 200 a buy, over 90 under it a sell, closed on the close beyond the SMA 5, on the daily candles of the book, its stop loss and take profit a safety), see strategies.NewRSI2.
trendagent command
Command trendagent runs the trend following strategies: trendconfluence (RK Trend Confluence), matrend (MA Trend: the break of the SMA 200 with the EMA 9/21 on its side), emapullback (the pullbacks to the fast EMA in a trend of two EMAs), fibonacci (the pullbacks of the impulses to their Fibonacci retracements), trendpullback (the end of the pullbacks of the trend of the EMA 9/21 over the SMA 200, confirmed by the momentum: the rules of the setup trend_pullback of the prompt default of the LLM agent, its stop loss moved by the R multiple of the position), and the signal strategies emacross, ema200, ribbon, supertrend, emasupertrend, psarema, atrtrailing, ichimoku, ichimokuadx, mtftrend and mtfema, see strategies.NewSignal, and consensus (a quorum of the rules of the signal strategies firing the same side within a few candles, none of them the other side), see strategies.NewConsensus.
Command trendagent runs the trend following strategies: trendconfluence (RK Trend Confluence), matrend (MA Trend: the break of the SMA 200 with the EMA 9/21 on its side), emapullback (the pullbacks to the fast EMA in a trend of two EMAs), fibonacci (the pullbacks of the impulses to their Fibonacci retracements), trendpullback (the end of the pullbacks of the trend of the EMA 9/21 over the SMA 200, confirmed by the momentum: the rules of the setup trend_pullback of the prompt default of the LLM agent, its stop loss moved by the R multiple of the position), and the signal strategies emacross, ema200, ribbon, supertrend, emasupertrend, psarema, atrtrailing, ichimoku, ichimokuadx, mtftrend and mtfema, see strategies.NewSignal, and consensus (a quorum of the rules of the signal strategies firing the same side within a few candles, none of them the other side), see strategies.NewConsensus.
cmd
controller command
Command controller runs xtrader: the agents of its database, launched and stopped as they are enabled, served on the web dashboard and on Telegram, with the settings of the controller on the dashboard.
Command controller runs xtrader: the agents of its database, launched and stopped as they are enabled, served on the web dashboard and on Telegram, with the settings of the controller on the dashboard.
migrator command
Command migrator prepares the PostgreSQL of xtrader, the database of configs/config.yml, the one of the controller:
Command migrator prepares the PostgreSQL of xtrader, the database of configs/config.yml, the one of the controller:
xtrader command
Package config is config.yml, the configuration of the controller (cmd/controller) and of the migrations (cmd/migrator): what they need to start and to reach PostgreSQL.
Package config is config.yml, the configuration of the controller (cmd/controller) and of the migrations (cmd/migrator): what they need to start and to reach PostgreSQL.
Package controller runs the bots of xtrader as agents: each bot serves the API of its chart (see ui.Chart) and the controller serves them to the users, on the web dashboard and on Telegram, reaching the agents through their API.
Package controller runs the bots of xtrader as agents: each bot serves the API of its chart (see ui.Chart) and the controller serves them to the users, on the web dashboard and on Telegram, reaching the agents through their API.
internal
pgtest
Package pgtest gives the tests a PostgreSQL database of their own, on the server of XTRADER_TEST_DATABASE_URL, eg: a container of postgres:18.6: the tests are skipped without it.
Package pgtest gives the tests a PostgreSQL database of their own, on the server of XTRADER_TEST_DATABASE_URL, eg: a container of postgres:18.6: the tests are skipped without it.
recovery
Package recovery recovers the panics of the code a bot runs on its candles, eg: a strategy and its indicators, so that a panic fails that call only, rather than the whole agent: reported, never swallowed (see Reporter).
Package recovery recovers the panics of the code a bot runs on its candles, eg: a strategy and its indicators, so that a panic fails that call only, rather than the whole agent: reported, never swallowed (see Reporter).
seedtest
Package seedtest reads the agents the seeds of the database create (sql/seeds/0004_agents.sql), for the tests of the agents: the strategy each agent of a kind trades.
Package seedtest reads the agents the seeds of the database create (sql/seeds/0004_agents.sql), for the tests of the agents: the strategy each agent of a kind trades.
Package store keeps the settings and the data of xtrader in PostgreSQL: the users of the dashboard, the prompts, the agents with their accounts and language models, Telegram, and the orders, decisions and journal of each agent.
Package store keeps the settings and the data of xtrader in PostgreSQL: the users of the dashboard, the prompts, the agents with their accounts and language models, Telegram, and the orders, decisions and journal of each agent.
log
ui
Package ui is the side of the web dashboard that runs in the bots: the Chart collects the state of a bot (candles, indicators, orders, equity) and serves it on an HTTP API, with its control panel.
Package ui is the side of the web dashboard that runs in the bots: the Chart collects the state of a bot (candles, indicators, orders, equity) and serves it on an HTTP API, with its control panel.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL