How to Build a Custom MT5 Prop Firm Backend Using the Manager API

MetaTrader 5 Development

15 May, 2026

mt5-manager-api-prop-firm-backend
Ajaysingh Narayansingh Rajpurohit

Ajaysingh Narayansingh Rajpurohit

Sr Developer, Softices

Most prop trading firms hit a wall around 200–300 active challenges. Not because their traders aren't performing but because the infrastructure holding everything together starts breaking at scale. Manual account resets, spreadsheet-tracked drawdowns, and copy-pasted challenge rules were never meant to run a real business.

MetaTrader 5 is an exceptional trading platform. It is not a prop firm operating system. That distinction matters, because building your firm on the assumption that MT5 handles both is exactly where the operational debt starts piling up.

This article explains how to build a custom backend on top of MT5 using the Manager API, what the architecture looks like, how each layer works, and what you need to get it right.

Why MT5 Alone Cannot Run a Prop Firm

MT5 handles order execution, position management, and market data with institutional precision including tools like Expert Advisors for automated trade execution. What it does not handle is the business logic that wraps around those trades.

A functioning prop firm needs:

  • Automated account creation tied to a purchase or onboarding flow
  • Multi-phase challenge evaluation (Phase 1 → Phase 2 → Funded)
  • Profit targets, daily loss limits, and maximum drawdown enforcement
  • Automatic account transitions when rules are met or broken
  • Trade restrictions, position resets, and equity snapshots
  • Profit splits and payout calculations
  • Real-time risk monitoring across hundreds or thousands of accounts

None of this is built into MT5 as a complete system. The trading layer is there. The operational layer is not. That layer has to be built, and the MT5 Manager API is the interface that connects your backend to the platform.

Why the Manager API is the Right Interface

MT5 offers several integration points, each serving a different purpose:

API

Primary Use

Gateway API Market data distribution
Trade Server API Order execution and routing
Manager API Server-side account and group management


For prop firm infrastructure, the Manager API is the correct tool. It operates at the administration layer of the MT5 server, giving your backend the ability to act on accounts and trading data rather than just observe them.

With the Manager API, your backend can:

  • Create and configure trading accounts programmatically
  • Assign accounts to server-side groups (e.g., Challenge Phase 1, Funded, Failed)
  • Modify leverage, settings, and account parameters
  • Monitor live positions and account equity
  • Close trades and manage positions server-side
  • Pull full trade history for evaluation and payout logic

Think of it as the control plane for your MT5 server. Your backend sends instructions; MT5 executes them.

What You Need Before Writing Any Code

Before writing any backend code, make sure these are in place before development starts.

1. Manager-Level Server Access

Standard trading accounts will not work. You need manager-level credentials from a licensed broker or MT5 server provider. Without this, none of the Manager API calls are available to you.

2. Backend Technology

The Manager API ships with official SDKs for C++ and C#. Most teams choose C# because it integrates more cleanly with REST APIs, background job systems, and modern backend frameworks.

3. Database Architecture

Plan for multiple stores from the start:

  • PostgreSQL → users, challenge records, phase transitions, payout history, audit logs
  • Redis → real-time state: live drawdown, open positions, active account status
  • InfluxDB (optional) → time-series equity curves and risk metrics for dashboards

4. Security Setup

This system has direct control over trading accounts. Security is not optional:

  • Encrypt all credentials and API keys at rest
  • Restrict MT5 server access to whitelisted IPs
  • Implement role-based access controls for admin tooling
  • Log every state-changing operation for audit purposes

How the Manager API Works in Practice

Once your service establishes a connection to the MT5 server, you have access to operations like:

  • UserRecordNew (userRecord) create a new trading account
  • UserRecordUpdate (userId, updatedRecord) update account settings or move phases (e.g., from Challenge to Funded)
  • TradeRequestSend (closeRequest) close or manage trades
  • PositionGetTicket (accountId) fetch all open positions for an account
  • HistoryOrderSelect (accountId, fromDate, toDate) pull historical trade records for payout calculation

One thing to understand clearly: the Manager API does not push real-time updates. Your backend must poll the MT5 server at regular intervals, typically every 10 to 30 seconds depending on your risk tolerance and process the results in your own system.

This polling architecture shapes everything about how you build the backend.

Stop Managing MT5 Challenges Manually

We build the backend infrastructure that automates your challenge system, risk engine, and payouts end to end.

Core Backend Architecture

A production prop firm backend has four main layers:

Layer 1: MT5 Connector Service

A lightweight, dedicated service responsible for: 

maintaining a stable connection to the Manager API

polling account and trade data on schedule

pushing results into Redis

This service should be isolated from business logic. Its only job is data collection and connection management.

public class MT5ConnectorService
{
  private readonly IMT5ManagerAPI _manager;
  private readonly IRedisCache _cache;

  public async Task PollAccountData(int accountId)
  {
    var positions = await _manager.PositionGetTicket(accountId);
    var equity = CalculateEquity(positions);
     
    await _cache.SetAsync($"account:{accountId}:equity", equity);
    await _cache.SetAsync($"account:{accountId}:positions", positions);
  }
}

Layer 2: Backend Processing Service

This is the main logic layer.

  • Challenge rule evaluation
  • Drawdown calculations
  • Phase transition decisions
  • Risk checks before and after trades
  • Payout calculations

It reads from Redis for real-time state and writes final records to PostgreSQL.

Layer 3: Database Layer

  • PostgreSQL stores everything that needs to persist: user records, challenge configurations, phase history, payout records, and audit logs.
  • Redis holds the fast-access state your processing service needs every few seconds: current equity, open position counts, drawdown figures, account status flags.
  • InfluxDB (if used) stores timestamped equity snapshots, useful for rendering equity curves in trader dashboards and for risk analysis.

Layer 4: Dashboard Layer

Two separate interfaces serve different users:

Trader dashboard:

  • Current challenge phase and status
  • Progress toward profit target
  • Daily and maximum drawdown remaining
  • Trade history and performance metrics
  • Rules and restrictions in effect

Admin dashboard:

  • All active accounts and their risk exposure
  • Accounts approaching drawdown limits
  • Phase transition queue
  • Payout approval workflow
  • Server-level controls

Building the Challenge System

The challenge system is the core product logic of your firm. Every other component supports it.

Step 1: Account Creation

When a trader purchases a challenge, your backend:

  • Calls UserRecordNew to create an MT5 account with the correct parameters
  • Assigns the account to the appropriate server group (e.g., challenge_phase1_100k)
  • Stores the challenge configuration in PostgreSQL: profit target, loss limits, start date, time limit
  • Records the initial balance as a reference point for all future drawdown calculations
public async Task<ChallengeAccount> CreateChallenge(int userId, ChallengeConfig config)
{
  var mt5Account = await _manager.UserRecordNew(new UserRecord
  {
    Group = config.GroupName,
    Leverage = config.Leverage,
    Balance = config.AccountSize
  });

  var challenge = new ChallengeAccount
  {
    UserId = userId,
    MT5Login = mt5Account.Login,
    StartingBalance = config.AccountSize,
    ProfitTarget = config.AccountSize * config.ProfitTargetPct,
    MaxDrawdownLimit = config.AccountSize * config.MaxDrawdownPct,
    DailyLossLimit = config.AccountSize * config.DailyLossPct,
    Phase = 1,
    Status = ChallengeStatus.Active
  };

  await _db.ChallengeAccounts.AddAsync(challenge);
  return challenge;
}

Step 2: Continuous Rule Evaluation

A background job runs on a schedule, every 15 to 30 seconds for most firms and evaluates every active account against its rules.

public async Task EvaluateAccount(ChallengeAccount challenge)
{
  var currentEquity = await _cache.GetAsync<decimal>($"account:{challenge.MT5Login}:equity");
  var dailyLow = await _cache.GetAsync<decimal>($"account:{challenge.MT5Login}:daily_low");

  var drawdown = challenge.StartingBalance - currentEquity;
  var dailyLoss = challenge.DailyOpeningBalance - dailyLow;
  var profit = currentEquity - challenge.StartingBalance;

  // Check failure conditions first
  if (drawdown >= challenge.MaxDrawdownLimit || dailyLoss >= challenge.DailyLossLimit)
  {
    await FailAccount(challenge);
    return;
  }

  // Check success conditions
  if (profit >= challenge.ProfitTarget && challenge.Phase < challenge.TotalPhases)
  {
    await AdvancePhase(challenge);
  }
  else if (profit >= challenge.ProfitTarget && challenge.Phase == challenge.TotalPhases)
  {
    await TransitionToFunded(challenge);
  }
}

Step 3: Phase Transitions and Failures

When an account passes a phase:

  • Call UserRecordUpdate to move the account to the next group on the MT5 server
  • Reset daily tracking figures in Redis
  • Update the challenge record in PostgreSQL
  • Notify the trader

When an account fails:

  • Close all open positions using TradeRequestSend
  • Move the account to the failed group
  • Mark the challenge as failed in PostgreSQL
  • Log the failure reason for audit and analysis

Risk Management in Real Time

Risk management is where the backend earns its keep. Two layers handle this: pre-trade validation and live monitoring.

Pre-Trade Checks

Before a trade is allowed to execute, your system validates:

  • Is the account's remaining daily loss limit sufficient to absorb the trade's potential downside?
  • Does the position size comply with any restrictions on the account?
  • Is the account in a state that allows new trades (not in reset, not in review)?

Live Position Monitoring

After trades are open, the connector service tracks:

  • Open floating P&L across all positions
  • Current equity relative to the drawdown limit
  • Time-weighted exposure for accounts with restrictions

If equity breaches a threshold, the backend calls TradeRequestSend to close all open positions immediately and flags the account for review.

public async Task CheckLiveRisk(int mt5Login)
{
  var equity = await _cache.GetAsync<decimal>($"account:{mt5Login}:equity");
  var challenge = await _db.GetActiveChallengeByLogin(mt5Login);

  if (equity <= challenge.StartingBalance - challenge.MaxDrawdownLimit)
  {
    await _manager.CloseAllPositions(mt5Login);
    await FailAccount(challenge, FailureReason.MaxDrawdownBreached);
  }
}

Redis is the right tool here because you need sub-second reads on current equity state, not round-trips to PostgreSQL.

Payout and Profit Split System

Once a trader is in a funded account, profit splits are calculated from their closed trade history.

  • Fetch closed trades using HistoryOrderSelect
  • Calculate total profit
  • Apply profit split (e.g. 80/20)
  • Store results in database
  • Trigger payout workflow
public async Task<PayoutRecord> CalculatePayout(int mt5Login, DateTime periodStart, DateTime periodEnd)
{
  var trades = await _manager.HistoryOrderSelect(mt5Login, periodStart, periodEnd);
   
  var grossProfit = trades
    .Where(t => t.State == OrderState.Filled)
    .Sum(t => t.Profit);

  var traderShare = grossProfit * TRADER_PROFIT_SPLIT; // e.g., 0.80
  var firmShare = grossProfit * (1 - TRADER_PROFIT_SPLIT);

  return new PayoutRecord
  {
    MT5Login = mt5Login,
    GrossProfit = grossProfit,
    TraderAmount = traderShare,
    FirmAmount = firmShare,
    Period = (periodStart, periodEnd),
    Status = PayoutStatus.PendingApproval
  };
}

Whether payouts are triggered automatically or require manual approval is a business decision. Either way, every record should be fully traceable back to the specific trades that generated it.

Full Data Flow Through the System

Here is how data moves through the system end to end:

Trader places trade in MT5 terminal
    ↓
MT5 Connector polls Manager API (every 15–30s)
    ↓
Raw data pushed to Redis (equity, positions, drawdown state)
    ↓
Processing service reads Redis → evaluates challenge rules
    ↓
State changes written to PostgreSQL (phase transitions, failures)
    ↓
Metrics written to InfluxDB (equity curve snapshots)
    ↓
Dashboard reads PostgreSQL + InfluxDB → displays to trader/admin

This cycle runs continuously. The separation between Redis (real-time) and PostgreSQL (persistent) is intentional. It keeps the rule evaluation fast without hammering your primary database.

Common Problems and How to Handle Them

1. MT5 Connection Drops

The Manager API connection will drop occasionally. 

  • Solution: Build a heartbeat check into your connector service and implement automatic reconnect with exponential backoff. Never assume the connection is alive.

2. Performance Degradation at Scale

Polling per account stops working above a few hundred accounts. 

  • Solution: Switch to group-level queries that batch account data retrieval, then process results in parallel.

3. Incorrect Drawdown Calculations

Always calculate drawdown from the starting balance stored in your database at account creation. Do not rely on MT5's internal balance adjustments. They can differ due to swaps, credits, and corrections.

4. Missing or Misconfigured Server Groups

All MT5 server groups (challenge phases, funded, failed, reset) must exist on the server before launch. Create and test them in a staging environment first. Trying to assign an account to a non-existent group will throw an error that silently breaks your onboarding flow.

Deployment Considerations

A few things matter significantly when you go live:

  • Latency to the MT5 server: Host your connector service in the same data center or region as your MT5 server. Network latency directly affects how fresh your data is.
  • Polling frequency: Start conservative (30 seconds) and increase only when you have load data to justify it. Aggressive polling under high account volume can strain the Manager API connection.
  • Caching: Cache account configurations and group mappings in Redis. You do not need to re-fetch static data on every poll cycle.
  • Staged rollout: Launch with a small number of active accounts. Monitor API response times and error rates before scaling.

What You Can Add Once the Core is Running

The base system gives you full operational control. Extensions that firms commonly add next:

  • TradingView webhook integration → connect external signals to automated execution
  • Telegram bot or Discord bot → admin controls and trader notifications in real time
  • Grafana dashboards → risk monitoring across all active accounts at a glance
  • CRM integration → sync account status, phase progress, and payout history with your user management system
  • Leaderboards and performance analytics → visible to traders, useful for retention and marketing

Where MT5 Ends and Your Backend Begins

A prop firm backend is not a trading system. It is a rules and operations layer that sits on top of MT5 and manages how traders move through challenges, risk limits, and payouts.

The Manager API gives you access to the MT5 server's control layer. Everything around it including the challenge logic, the risk engine, the payout system, the dashboards has to be designed and built separately.

Done well, this architecture gives you complete control over your trading program: consistent rule enforcement, automated operations, and a system that scales without adding headcount.

If you'd prefer not to build this from scratch, Softices builds custom MT5 backends and Manager API integrations for prop firms, brokers, and fintech platforms.


Django

Previous

Django

Next

Agentic AI vs Traditional AI: Differences & Use Cases for Businesses

agentic-ai-vs-traditional-ai

Frequently Asked Questions (FAQs)

The MT5 Manager API is a server-side interface that gives licensed operators programmatic control over MT5 accounts, groups, and trades. It can create accounts, move them between groups, close positions, and pull trade history, all without manual action inside the terminal.

Not reliably at scale. MT5 handles trade execution but has no native system for multi-phase challenges, drawdown enforcement, or automated account transitions. That logic has to be built in a separate backend connected to MT5 via the Manager API.

The Manager API supports C++ and C# SDKs. Most teams choose C# because it integrates more cleanly with REST APIs, background job systems, and modern backend frameworks.

The backend polls the Manager API every 10–30 seconds to fetch open positions and current equity. That data is stored in Redis for fast reads. A processing service compares current equity against the starting balance and triggers account failure or position closure if limits are breached.

Most systems use three: PostgreSQL for persistent records like users, challenges, and payouts; Redis for real-time state like live drawdown and open positions; and optionally InfluxDB for time-series equity data used in performance dashboards.

The backend pulls closed trade history using HistoryOrderSelect, calculates total profit for the period, applies the agreed split percentage, and stores the result as a payout record. Payouts can be triggered automatically or routed through a manual approval workflow

Cost varies based on complexity like number of challenge phases, risk engine requirements, dashboard scope, and integrations. A basic system with challenge automation and a trader dashboard typically starts in the range of $15,000–$40,000. Firms with multi-phase evaluation, real-time risk monitoring, and CRM integrations should expect higher investment.