MT5 TradeManager

DRY RUN

Source

You open the position.It looks after the stop.

TradeManager runs on the same Windows machine as your MetaTrader 5 terminal and looks after the positions you opened yourself: it fills in the stop loss you forgot, trails it as price moves, and builds pending ladders under your manual orders. You drive it from Telegram.

Self-hosted Python, FastAPI and SQLite, one instance per account. Windows only, because the MetaTrader 5 Python API is.

EXECUTION INTERLOCK

execute_actions()

HELD
open a position Not a setting. There is no key for it because there is no code behind it: the only actions the service can emit are MODIFY_SLTP and PLACE_PENDING. no switch
mt5 binding verified Login 51884402 on MetaQuotes-Demo, from this terminal path. PASS

OUTPUT HELD

Actions are computed and written to the execution log as DRY_RUN. Nothing is sent to MetaTrader 5.

Flip the switches. They govern the console and the log below, the way they govern the real service. A fifth switch, execution.allow_live_place_pending, gates pending orders separately — one permission per kind of action.

One call shows the whole instance

GET /dashboard/summary returns the account and its binding, every open position and pending order, the config in force, the safety flags, the worker's counters and the recent execution log. Below is that response, drawn out and running. Every figure in it is synthetic.

ACCOUNT

GET /mt5/direct/status

BINDING OK

POSITIONS

GET /mt5/direct/snapshot

4 OPEN
Open positions on the synthetic demo account
TICKET SYMBOL TYPE VOL OPEN PRICE SL TP P/L

A stop loss shown as none is what Initial SL/TP looks for. The snapshot adapter normalises MT5's 0.0 to missing, so "no stop" and "stop at zero" cannot be confused.

PENDING ORDERS

magic 880002

4
Pending orders, manual and generated
TICKET SYMBOL TYPE VOL PRICE MAGIC COMMENT PLACED BY

SAFETY FLAGS

derive_safety_flags()

HELD

AUTOMATION WORKER

GET /automation/status

RUNNING

Every 2 seconds the worker takes a snapshot, asks each enabled feature what it would do, and hands the result to the execution gate.

CONFIG IN FORCE

GET /config/all


              

Stored as key/value rows in SQLite. The ladder ships off and stays off here: it is the one feature that creates orders rather than adjusting them.

EXECUTION LOG

GET /mt5/direct/executions/recent

DRY_RUN

Waiting for the first cycle.

Every computed action is written here before anything else happens, with its source feature, the request, the result and the status — SUCCESS, FAILED, SKIPPED or DRY_RUN. A skipped action is a recorded decision, not a silence.

Three jobs, and the arithmetic behind each

Each feature is a pure function: a snapshot and a config go in, a list of actions comes out, and nothing touches MT5. The widgets below run that same arithmetic, ported from app/features/. Move the dials and watch the decision change — including when it decides to do nothing.

INITIAL SL/TP

app/features/initial_sltp.py

IDLE

You opened a position and never set a stop. This fills one in at a fixed pip distance from your open price, and a target on the other side. With only_if_missing on it will never overwrite a level you set yourself.

The computed level is checked against the current price before it becomes an action. A stop that would land on the wrong side of price is dropped with a warning rather than sent — try dragging sl_pips low enough to see it.

TRAILING SL

app/features/trailing_sl.py

IDLE

Once a position is far enough in profit, the stop follows price at a fixed distance. The interesting half is the restraint: the stop only moves when the improvement beats step_pips, so a position that wobbles does not generate a stream of requests to your broker.

The stop never moves backwards. The executor rejects a worse SL even if a feature asks for one — two independent checks, in the feature and at the choke point.

PENDING LADDER

app/features/pending_ladder.py

IDLE

You place one pending order by hand. This builds a ladder of children away from it, stepping the price and growing the volume each level. It is the highest-risk feature in the system — the only one that creates orders rather than adjusting them — so it ships off, and the automation loop has a separate switch for it.

Each child carries magic 880002 and a comment naming its parent and level, so the next cycle can tell its own orders from yours and never ladders a ladder.

Every action has a rehearsal

Each feature comes as a pair of endpoints. The preview computes and returns; the apply computes and hands the result to the gate. Step 14 of the pre-flight checklist is the whole discipline: call the preview, read it, then apply.

REHEARSAL

GET /mt5/direct/trailing-preview

READ ONLY
# nothing is sent, nothing is logged as executed
GET /mt5/direct/trailing-preview?symbol=XAUUSD.r

{
  "actions": [
    {
      "type": "MODIFY_SLTP",
      "source_feature": "trailing_sl",
      "ticket": 10846998,
      "symbol": "XAUUSD.r",
      "sl": 4073.55,
      "tp": null,
      "reason": "Trailing SL update"
    }
  ],
  "warnings": [],
  "count": 1
}

A preview also surfaces binding problems early, so you learn about a mismatch before you have flipped anything live.

THE GATE

POST /mt5/direct/apply-trailing

HELD
POST /mt5/direct/apply-trailing?symbol=XAUUSD.r

# execution.enabled = false
{
  "results": [
    {
      "action_id": "a00041",
      "status": "SKIPPED",
      "dry_run": true,
      "ticket": 10846998,
      "message": "Execution disabled"
    }
  ]
}

# the same call, four switches later
      "status": "SUCCESS",
      "mt5_result": { "retcode": 10009 }

The outcome is a row in execution_log either way. Refusals are recorded with the reason they were refused.

The control panel is a chat

The bot is a separate process that speaks to TradeManager only over HTTP — it never imports MetaTrader5 and holds no trading logic of its own. Tap through it; these are the real menus.

TradeManager BOT

One bot controls exactly one instance. The token lives in that instance's own .env alongside a single TRADE_MANAGER_URL, so the bot for account A has no address it could use to reach account B.

Anyone whose chat id is not in TELEGRAM_ALLOWED_CHAT_IDS is refused. An empty list authorises nobody, which is the right way round for a default.

StatusAccount, positions, worker state, and buttons to start, stop or run one cycle.
SettingsBuilt from /config/schema, so the menu cannot drift from the running service. Values are validated before they are saved.
FeaturesToggles for each feature and, separately, for whether the automation loop runs it.
InstrumentsPer-symbol pip size, digits and volume limits, and which symbols automation may touch.
SafetyStop All, which returns every switch to its safe default in one tap, and the live-mode switches behind a confirmation.
LogsRecent execution entries and recent ladder plans.

Two accounts, nothing shared

Multiple accounts run as separate vertical stacks. Not the port, not the database, not the bot token, not the terminal. The binding check exists so an instance can prove which account it is talking to before it acts.

What happens when the terminal is the wrong one

Instance A is pinned to one terminal64.exe and expects login 51884402 on MetaQuotes-Demo. If it finds itself connected to anything else, verify_mt5_binding() returns an error and every live-modifying action is refused at the choke point:

"status": "SKIPPED",
"message": "MT5 binding verification failed. Live execution blocked.
            (Expected MT5 login 51884402, but connected account is 7310442)"

Leaving mt5.terminal_path empty is allowed, and the service falls back to whichever terminal happens to be running — fine for one instance, and flagged as a warning in both the status and the dashboard. The pre-flight script treats it as a hard failure, because with two terminals open "whichever is running" is a coin toss.

The pre-flight checklist

Worked through for every instance, every time, before any live switch moves. Steps 7 to 10 are automated by check_instance_ready.ps1, which prints PASS or FAIL and is deliberately stricter than the runtime guard.

  1. Start MT5 with this instance's script, so the right terminal opens in portable mode.
  2. Log in to the correct account in that terminal.
  3. Enable Algo Trading. The toolbar button must be green.
  4. Check Tools → Options → Expert Advisors → Allow algorithmic trading.
  5. Start this instance's TradeManager on its own port.
  6. Run set_instance_config.ps1 with this terminal path and expected login.
  7. Call GET /mt5/direct/status.SCRIPTED
  8. Confirm binding.ok = true.SCRIPTED
  9. Confirm the reported terminal path is this instance's.SCRIPTED
  10. Confirm the connected login and server are the expected ones.SCRIPTED
  11. Confirm terminal_info.trade_allowed = true, so Algo Trading really is on.
  12. Confirm account_info.trade_expert = true if your broker needs it.
  13. Open a small test position on demo and confirm the snapshot sees it.
  14. Call the preview endpoint and read it, before the matching apply.
  15. Only now set execution.enabled = true, and dry_run = false when you are truly ready.

What it does not do

A private tool with a narrow job. Most of these are deliberate; two are someone else's decision.

If you meet 10026, nothing in the codebase can fix it: the request reached the broker and was refused. Test on a demo account of the same broker and server type first, and get the answer in writing before planning around live API execution. Prop-firm and challenge accounts are the usual place this bites.

Built to be boring on purpose

A FastAPI service, three pure feature modules, one executor, a background worker and a Telegram bot that only speaks HTTP. Trading logic has no I/O; the parts that touch MetaTrader 5 hold no arithmetic. That split is why each piece can be read on its own, and why the gate is a single function with four conditions rather than a check scattered across the codebase.

The decision behind it: every computed action is written to execution_log before anything is attempted, with the full request and result as JSON — including the ones that were refused. If the system did something you did not expect, the row explaining why already exists.

Read the source Installation

About this demo

Every price, ticket, account number and log line on this page is synthetic, generated from one seed so the interlock, the console, the three mechanisms and the Telegram panel all describe the same instance.

The arithmetic is not synthetic. The three feature widgets and the console's worker run the same formulas as app/features/trailing_sl.py, initial_sltp.py and pending_ladder.py, and the gate follows execute_actions() condition for condition.

What you need to run it

A Windows machine or VPS, Python 3.10 or newer, one MetaTrader 5 terminal per account, a broker account whose server permits Python API trading, and a Telegram bot token with your own chat id. Start on demo.

Why a Telegram bot and not a web UI

The service binds to 127.0.0.1 and stays there. A chat app you already have on your phone gives you remote control without opening a port, serving a login page or managing a certificate for one user. The allowlist is a line in a .env file.