MT4 & MT5 API for Prop Firms
FxSocket gives proprietary trading firms a single API to manage their entire MetaTrader infrastructure. Provision MT4 and MT5 terminals on demand, monitor trader performance in real time, and enforce firm-wide risk policies — all programmatically. Whether you're running a challenge-based evaluation model or managing a roster of funded traders, FxSocket replaces fragile VPS setups and manual oversight with a clean, developer-friendly integration that scales from ten accounts to ten thousand.
What Prop Firms Get
- Multi-account management at scale. Connect hundreds of funded accounts under one integration. Add or remove accounts through the API as traders pass or fail evaluations.
- Real-time monitoring. Stream P&L, equity, drawdown, and position data across all accounts via WebSocket. Build internal dashboards or plug into existing tools.
- Automated risk enforcement. Set drawdown limits, lot size caps, symbol restrictions, and trading hour windows per account. FxSocket enforces them at the API level.
- No MetaTrader infrastructure to manage. We host the terminals. No VPS provisioning, no Windows servers, no terminal crashes to debug at 3am.
- Works with any broker. Funded accounts can be on any broker that supports MT4 or MT5. Switch brokers without changing your integration.
- Sub-30ms execution.Every order routes through low-latency infrastructure co-located near major broker servers. Your traders get the same speed they'd expect from a dedicated terminal — without needing one.
- 99.99% uptime SLA. Pro plans come with an enterprise-grade uptime guarantee so your firm never misses a market session due to infrastructure issues.
Common Prop Firm Workflows
Evaluation and Onboarding
When a trader passes an evaluation, provision their funded account through the API. Connect their broker credentials, apply risk rules, and start monitoring — all automated. The entire flow from "challenge passed" to "live funded account" can happen in seconds with zero manual intervention, freeing your operations team to focus on growing the business instead of onboarding logistics.
Live Monitoring
Stream real-time equity and drawdown for every funded account. Trigger alerts or auto-close positions when a trader approaches their maximum drawdown. No manual monitoring required. FxSocket WebSocket connections deliver account updates with sub-second latency, so your risk engine always has a current picture of every trader's state.
Performance Reporting
Pull trade history, P&L breakdowns, and account metrics through the API. Generate payout reports, leaderboards, or compliance logs automatically. Aggregate data across your entire trader base to identify top performers, flag suspicious patterns, or calculate profit-split payouts without touching a spreadsheet.
Example: Monitor Drawdown Across Accounts
The following Python example connects to the FxSocket WebSocket stream, monitors drawdown across all funded accounts, and automatically closes every open position when a trader breaches the maximum drawdown threshold. It includes reconnection logic and proper error handling for production use.
import websocket
import json
import requests
import time
API_KEY = "your_api_key"
BASE_URL = "https://api.fxsocket.com/v1"
MAX_DRAWDOWN = 0.05 # 5%
def close_all_positions(account_id):
"""Close every open position on the breached account."""
positions = requests.get(
f"{BASE_URL}/accounts/{account_id}/positions",
headers={"Authorization": f"Bearer {API_KEY}"}
).json()
for pos in positions.get("data", []):
requests.post(
f"{BASE_URL}/accounts/{account_id}/positions/{pos['id']}/close",
headers={"Authorization": f"Bearer {API_KEY}"}
)
print(f"Closed {len(positions.get('data', []))} positions on {account_id}")
def on_message(ws, message):
data = json.loads(message)
if data["type"] == "account_update":
account = data["data"]
drawdown = 1 - (account["equity"] / account["balance"])
if drawdown >= MAX_DRAWDOWN:
print(f"ALERT: {account['id']} hit {drawdown:.1%} DD")
close_all_positions(account["id"])
def on_error(ws, error):
print(f"WebSocket error: {error}")
def on_close(ws, status_code, msg):
print(f"Connection closed ({status_code}). Reconnecting in 5s...")
time.sleep(5)
connect()
def connect():
ws = websocket.WebSocketApp(
"wss://ws.fxsocket.com/v1/stream?accounts=all",
on_message=on_message,
on_error=on_error,
on_close=on_close,
header={"Authorization": f"Bearer {API_KEY}"}
)
ws.run_forever()
connect()Example: Automated Account Provisioning
When a trader passes your evaluation challenge, the following snippet provisions their funded account, applies your firm's risk rules, and starts real-time monitoring — all in a single onboarding function.
import requests
API_KEY = "your_api_key"
BASE_URL = "https://api.fxsocket.com/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def onboard_funded_trader(trader):
"""Provision a new funded account after evaluation pass."""
# 1. Add the broker account to FxSocket
account = requests.post(
f"{BASE_URL}/accounts",
headers=HEADERS,
json={
"broker": trader["broker"],
"login": trader["mt_login"],
"password": trader["mt_password"],
"server": trader["mt_server"],
"platform": trader["platform"], # "mt4" or "mt5"
}
).json()
account_id = account["data"]["id"]
# 2. Apply risk rules for this trader's plan
requests.put(
f"{BASE_URL}/accounts/{account_id}/risk-rules",
headers=HEADERS,
json={
"max_daily_loss_pct": 0.05,
"max_total_drawdown_pct": 0.10,
"max_lot_size": 10.0,
"allowed_symbols": ["EURUSD", "GBPUSD", "USDJPY", "XAUUSD"],
"trading_hours": {"start": "08:00", "end": "22:00", "tz": "UTC"},
"auto_close_on_breach": True,
}
).json()
# 3. Subscribe to real-time updates for this account
requests.post(
f"{BASE_URL}/accounts/{account_id}/subscribe",
headers=HEADERS,
json={"events": ["account_update", "position_open", "position_close"]}
).json()
print(f"Onboarded trader {trader['name']} -> account {account_id}")
return account_id
# Example: onboard a trader who just passed Phase 2
onboard_funded_trader({
"name": "Jane Doe",
"broker": "ICMarkets",
"mt_login": "50012345",
"mt_password": "securepass",
"mt_server": "ICMarketsSC-Live07",
"platform": "mt5",
})SDK Comparison: Account Monitoring
FxSocket provides official SDKs for Python, JavaScript/Node.js, Go, and Rust. Here's what drawdown monitoring looks like in each of the most popular options.
Python
from fxsocket import Client
client = Client(api_key="your_api_key")
for update in client.stream_accounts():
dd = 1 - (update.equity / update.balance)
if dd >= 0.05:
client.close_all_positions(update.account_id)
print(f"Breached: {update.account_id} at {dd:.1%}")Node.js
import { FxSocket } from "fxsocket";
const client = new FxSocket({ apiKey: "your_api_key" });
client.streamAccounts((update) => {
const dd = 1 - update.equity / update.balance;
if (dd >= 0.05) {
client.closeAllPositions(update.accountId);
console.log(`Breached: ${update.accountId} at ${(dd * 100).toFixed(1)}%`);
}
});Go
package main
import (
"fmt"
"github.com/fxsocket/fxsocket-go"
)
func main() {
client := fxsocket.NewClient("your_api_key")
client.StreamAccounts(func(update fxsocket.AccountUpdate) {
dd := 1 - (update.Equity / update.Balance)
if dd >= 0.05 {
client.CloseAllPositions(update.AccountID)
fmt.Printf("Breached: %s at %.1f%%\n", update.AccountID, dd*100)
}
})
}Risk Management Patterns
Most prop firms operate under a strict set of risk rules that mirror industry standards set by firms like FTMO, MyForexFunds, and similar challenge-based models. FxSocket lets you implement every one of these rules programmatically — no MQL scripts, no terminal plugins, no manual checks.
Daily Loss Limits
A common rule is that a trader cannot lose more than 5% of their starting balance in a single day. With FxSocket, you track the account's equity at the start of each trading day and compare it against the live equity stream. When the daily loss threshold is hit, the API automatically closes all open positions and can optionally lock the account until the next trading day. This runs server-side — there's nothing the trader can do to bypass it.
Maximum Drawdown Rules
Total drawdown (sometimes called "trailing drawdown" or "maximum loss") is typically set between 8% and 12% of the initial account balance. FxSocket tracks high-water marks and current equity in real time. When the account's equity falls below the threshold relative to its peak, the system triggers an immediate close-all and flags the account for review. You can configure whether the drawdown is calculated from the initial balance (static) or from the equity high-water mark (trailing).
Position Size Limits
Enforce maximum lot sizes per trade or per account. A $100k funded account might be capped at 10 lots per position and 30 lots total exposure. FxSocket validates every order against these limits before it reaches the broker — rejected orders return a clear error code so the trader knows exactly why the order was declined.
Symbol Restrictions
Some prop firm plans restrict traders to major forex pairs, or exclude exotic instruments and crypto CFDs. You define an allowlist or blocklist of symbols per account. Any order targeting a restricted symbol is rejected at the API layer with zero latency impact on permitted trades.
Trading Hour Enforcement
Prevent traders from holding positions over weekends, during high-impact news events, or outside defined session hours. Set a trading window (e.g., 08:00–22:00 UTC on weekdays) and FxSocket will reject new orders outside that window. You can also configure auto-close behavior — for example, liquidate all open positions 5 minutes before the Friday close to avoid gap risk.
Combining Rules
Every rule above can be layered per account. A Phase 1 evaluation account might have a 5% daily loss limit, 10% max drawdown, 5-lot cap, and majors-only restriction. A funded account that's proven itself over three months might have looser limits — 8% daily, 12% max drawdown, 20-lot cap, and access to all symbols. You manage all of this through a single API call per account, and changes take effect immediately.
Scaling Architecture
Running a prop firm with 100+ funded accounts introduces engineering challenges that go beyond a single WebSocket connection. Here's how FxSocket is designed to handle that scale.
Connection Pooling
A single WebSocket connection to ws.fxsocket.comcan stream updates for all accounts tied to your API key. You don't need one connection per account. For firms managing thousands of accounts, you can open multiple connections with account-group filters to distribute load across your backend workers.
Event Batching
Account updates arrive as individual events, but your risk engine and dashboard don't need to process every tick independently. Buffer incoming events into small batches (e.g., 100ms windows) and process them together. This reduces database write pressure and keeps your dashboard responsive even during volatile sessions when hundreds of accounts are updating simultaneously.
Dashboard Data Aggregation
For internal dashboards, maintain an in-memory snapshot of every account's current state (equity, drawdown, open positions, P&L). Update it from the WebSocket stream and serve dashboard queries from the snapshot rather than hitting the API on every page load. This pattern supports sub-second dashboard refresh rates for firms with 1,000+ accounts.
Alerting Pipelines
Route risk alerts through a dedicated pipeline — Slack webhooks, email, SMS, or PagerDuty — separate from your main data processing. A trader hitting 80% of their drawdown limit should notify your risk desk immediately, while routine account updates flow through your standard ingestion path. Keeping these pipelines separate ensures critical alerts are never delayed by dashboard traffic.
Compliance and Reporting
Prop firms handle real money and real payouts. FxSocket provides the data layer you need to keep your reporting accurate and auditable.
Automated Payout Calculations
Pull closed-trade history for any account over any date range via the REST API. Calculate net profit, subtract any fees or commissions, apply your profit-split ratio, and generate payout amounts automatically. No more reconciling spreadsheets against MT4/MT5 statement exports — the API gives you the canonical trade record.
Trade Journals and Audit Trails
Every order, modification, and closure is logged with timestamps, execution prices, and the source of the action (trader vs. risk engine vs. manual override). Store this data in your own database to build complete trade journals for each trader, or to produce audit trails if a payout dispute arises.
Performance Leaderboards
Aggregate account metrics across your trader base — win rate, average R:R, Sharpe ratio, maximum drawdown, total return — and rank them automatically. Publish leaderboards on your marketing site to attract new traders, or use them internally to identify candidates for higher capital allocations.
Regulatory Record-Keeping
If your firm operates in a regulated jurisdiction, FxSocket's API-first approach makes it straightforward to export the data your compliance team needs: complete order histories, risk rule change logs, and account lifecycle events (provisioning, suspension, termination). All data is available via the REST API with pagination and date-range filters.
Dedicated Infrastructure
Our Pro plans include dedicated cloud servers, custom region selection, and a dedicated account manager. Built for firms that need guaranteed uptime and performance at scale. Pro infrastructure is isolated from other FxSocket customers — your accounts run on hardware that's reserved exclusively for your firm, which means consistent sub-30ms execution even during peak market hours. Choose a region close to your broker's trade servers (London, New York, Tokyo, Singapore) to minimize round-trip latency.
Common Errors and Troubleshooting
Account Disconnections
If a broker account loses connectivity (e.g., invalid credentials, account disabled by broker), FxSocket sends a connection_lost event on the WebSocket stream and marks the account as disconnected in the REST API. Your system should listen for this event and alert your operations team. Once the issue is resolved (credential update, broker re-enablement), the account reconnects automatically and resumes streaming.
Broker Maintenance Windows
Most brokers perform weekly maintenance between Friday close and Sunday open. During these windows, account data may be stale or unavailable. FxSocket caches the last known state and includes a last_updatedtimestamp on every account object so your dashboard can display "data as of…" instead of misleading live figures. Plan any automated processes (payout calculations, report generation) to run outside maintenance windows.
Credential Rotation
When a trader's broker password changes — whether voluntarily or due to a broker policy — update the credentials via the REST API. The terminal reconnects within seconds. To minimize disruption, implement a health-check loop that detects auth_failed errors and prompts the trader (or your ops team) to supply new credentials before the next trading session.
Rate Limits and Retries
The FxSocket REST API enforces rate limits to protect infrastructure stability. If you receive a 429 status code, back off and retry with exponential delay. The official SDKs handle this automatically — they retry up to three times with increasing wait times before surfacing the error to your application code.
Why Prop Firms Choose FxSocket
- One API instead of hundreds of MT4/MT5 installations
- Programmatic account provisioning and teardown
- Real-time risk monitoring across all traders
- Broker-agnostic — no vendor lock-in
- Dedicated infrastructure for enterprise workloads
- Official SDKs for Python, Node.js, Go, and Rust
- Sub-30ms execution with 99.99% uptime SLA
- Pricing starts at €11/account/month — scales with you
Frequently Asked Questions
How many accounts can I manage through FxSocket?
There is no hard cap on the number of accounts. Starter plans support any number of accounts at €11/account/month. Pro plans include dedicated infrastructure optimized for firms managing hundreds or thousands of accounts simultaneously. The WebSocket stream and REST API are designed to handle high-volume workloads without degradation.
What happens during broker maintenance?
When a broker goes offline for scheduled maintenance (typically Friday evening through Sunday evening), FxSocket caches the last known account state and marks it with a timestamp. Your dashboard and risk engine continue to function with cached data. As soon as the broker comes back online, live streaming resumes automatically — no manual reconnection is needed on your end.
Can I set different risk rules per account?
Yes. Every account has its own independent risk configuration. You can assign different daily loss limits, max drawdown thresholds, lot size caps, symbol restrictions, and trading hours to each account. This is essential for firms that run multiple plan tiers (e.g., a $10k evaluation with tight limits vs. a $200k funded account with relaxed constraints). Update any account's rules at any time via a single API call — changes take effect immediately.
Do you support white-labeling?
FxSocket is a backend API — there is no trader-facing UI to white-label. Your traders interact with your platform, your dashboard, and your brand. FxSocket powers the infrastructure behind the scenes. This means you have complete control over the user experience, and your traders never see or interact with FxSocket directly.
How do I migrate from my current MT4/MT5 setup?
Most firms migrate incrementally. Start by connecting a handful of accounts to FxSocket alongside your existing infrastructure. Once you've validated that monitoring, risk rules, and reporting work as expected, migrate the rest of your accounts in batches. The API is broker-agnostic, so you can connect accounts from multiple brokers in a single integration. Our team is available to help plan and execute the migration — book a call to get started.