Algo Trading API for MT4 & MT5
FxSocket gives algo traders a clean REST API and real-time WebSocket streams to automate strategies on MetaTrader 4 and MetaTrader 5. Write your logic in Python, Node.js, Go, Rust, or any language that speaks HTTP. No MQL. No VPS. No terminal running on your desktop.
Whether you're running a single mean-reversion strategy or orchestrating a portfolio of bots across multiple broker accounts, FxSocket provides the infrastructure layer so you can focus entirely on alpha generation. Our API handles order routing, position management, account monitoring, and real-time market data — all through standard HTTP and WebSocket protocols that integrate with any tech stack.
Why Algo Traders Choose FxSocket
- Any language, any framework. Stop fighting MQL syntax. Use the tools you already know — pandas, NumPy, backtrader, or your own custom stack.
- Sub-30ms execution. Our cloud terminals are co-located near major broker infrastructure. Orders go from your code to the broker in milliseconds.
- Real-time data via WebSocket. Stream live bid/ask prices, tick data, and order updates directly to your bot. No polling required.
- 24/7 uptime. Your strategy runs on our cloud infrastructure, not your laptop. No disconnections, no missed trades, no babysitting.
- Historical data for backtesting. Pull OHLCV candles and tick history through the same API. Backtest locally, deploy live — same code.
- Official SDKs. First-class client libraries for Python, Node.js, Go, and Rust — with typed responses, automatic retries, and built-in authentication handling.
- Affordable at scale. Starting at just €11/account/month on the Starter plan, with Pro plans available for higher-volume traders who need priority support and advanced features.
How It Works
Connect your broker account to FxSocket. We spin up a cloud-hosted MetaTrader terminal and expose it through our API. Your bot sends HTTP requests to place orders, check positions, and pull market data. WebSocket streams push real-time prices and order updates to your application.
The entire lifecycle looks like this: you sign up at app.fxsocket.com, enter your MT4 or MT5 broker credentials, and receive an API key within seconds. From that point, every operation you would normally perform inside MetaTrader — opening trades, modifying stop-losses, querying account balance, pulling chart data — is available as a straightforward API call to api.fxsocket.com. For real-time streaming, connect to ws.fxsocket.com and subscribe to the symbols and events you care about.
Example: Place a Trade from Python
The simplest way to get started is a basic order placement. Here is a minimal example followed by a production-ready version with proper error handling:
import requests
API_KEY = "your_api_key"
BASE = "https://api.fxsocket.com/v1"
# Open a buy position on EURUSD
response = requests.post(
f"{BASE}/orders",
headers={"Authorization": f"Bearer {API_KEY}"},
json={
"symbol": "EURUSD",
"type": "BUY",
"volume": 0.1,
"sl": 1.0720,
"tp": 1.0950
}
)
print(response.json())Production-Ready Version with Error Handling
In production, you need to handle network errors, authentication failures, and broker rejections gracefully. Here is an expanded version:
import requests
import time
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("fxsocket_bot")
API_KEY = "your_api_key"
BASE = "https://api.fxsocket.com/v1"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def place_order(symbol, order_type, volume, sl=None, tp=None, retries=3):
"""Place an order with automatic retry on transient failures."""
payload = {
"symbol": symbol,
"type": order_type,
"volume": volume,
}
if sl is not None:
payload["sl"] = sl
if tp is not None:
payload["tp"] = tp
for attempt in range(1, retries + 1):
try:
response = requests.post(
f"{BASE}/orders",
headers=HEADERS,
json=payload,
timeout=10
)
if response.status_code == 200:
order = response.json()
logger.info(f"Order placed: {order['id']}")
return order
elif response.status_code == 401:
logger.error("Authentication failed. Check your API key.")
raise SystemExit("Invalid API key")
elif response.status_code == 422:
error = response.json()
logger.error(f"Validation error: {error}")
return None # Do not retry on validation errors
elif response.status_code >= 500:
logger.warning(
f"Server error (attempt {attempt}/{retries})"
)
except requests.exceptions.Timeout:
logger.warning(f"Timeout (attempt {attempt}/{retries})")
except requests.exceptions.ConnectionError:
logger.warning(f"Connection error (attempt {attempt}/{retries})")
if attempt < retries:
time.sleep(2 ** attempt) # Exponential backoff
logger.error("All retries exhausted. Order not placed.")
return None
# Usage
order = place_order("EURUSD", "BUY", 0.1, sl=1.0720, tp=1.0950)
if order:
print(f"Order ID: {order['id']}, Price: {order['price']}")
Example: WebSocket Price Streaming
For strategies that react to real-time price movements, the WebSocket connection at ws.fxsocket.com delivers tick data with minimal latency. The following example shows how to stream prices with automatic reconnection logic:
import asyncio
import json
import websockets
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger("fxsocket_ws")
API_KEY = "your_api_key"
WS_URL = "wss://ws.fxsocket.com/v1/stream"
SYMBOLS = ["EURUSD", "GBPUSD", "USDJPY"]
async def on_tick(symbol, bid, ask, timestamp):
"""Process incoming tick data — replace with your strategy logic."""
spread = ask - bid
logger.info(f"{symbol} | Bid: {bid} | Ask: {ask} | Spread: {spread:.5f}")
async def stream_prices():
"""Connect to FxSocket WebSocket with automatic reconnection."""
reconnect_delay = 1
while True:
try:
async with websockets.connect(
WS_URL,
additional_headers={"Authorization": f"Bearer {API_KEY}"},
ping_interval=20,
ping_timeout=10,
) as ws:
logger.info("Connected to FxSocket WebSocket")
reconnect_delay = 1 # Reset on successful connection
# Subscribe to symbols
await ws.send(json.dumps({
"action": "subscribe",
"symbols": SYMBOLS
}))
async for message in ws:
data = json.loads(message)
if data.get("type") == "tick":
await on_tick(
data["symbol"],
data["bid"],
data["ask"],
data["timestamp"],
)
elif data.get("type") == "order_update":
logger.info(f"Order update: {data}")
except websockets.ConnectionClosedError as e:
logger.warning(f"Connection closed: {e}. Reconnecting...")
except Exception as e:
logger.error(f"WebSocket error: {e}")
await asyncio.sleep(reconnect_delay)
reconnect_delay = min(reconnect_delay * 2, 60)
asyncio.run(stream_prices())SDK Comparison: Python, Node.js, and Go
FxSocket provides official SDKs for Python, Node.js, Go, and Rust. Each SDK wraps the REST API and WebSocket protocol with idiomatic patterns for that language. Here is how placing the same trade looks across three SDKs:
Python SDK
from fxsocket import FxSocketClient
client = FxSocketClient(api_key="your_api_key")
order = client.orders.create(
symbol="EURUSD",
type="BUY",
volume=0.1,
sl=1.0720,
tp=1.0950,
)
print(f"Filled at {order.price}")Node.js SDK
import { FxSocketClient } from "@fxsocket/sdk";
const client = new FxSocketClient({ apiKey: "your_api_key" });
const order = await client.orders.create({
symbol: "EURUSD",
type: "BUY",
volume: 0.1,
sl: 1.0720,
tp: 1.0950,
});
console.log(`Filled at ${order.price}`);Go SDK
package main
import (
"fmt"
"github.com/fxsocket/fxsocket-go"
)
func main() {
client := fxsocket.NewClient("your_api_key")
order, err := client.Orders.Create(&fxsocket.OrderRequest{
Symbol: "EURUSD",
Type: "BUY",
Volume: 0.1,
SL: fxsocket.Float64(1.0720),
TP: fxsocket.Float64(1.0950),
})
if err != nil {
panic(err)
}
fmt.Printf("Filled at %f\n", order.Price)
}All SDKs include automatic retry logic, typed response objects, and WebSocket helpers. Install them via pip install fxsocket, npm install @fxsocket/sdk, or go get github.com/fxsocket/fxsocket-go.
From Backtest to Live in Minutes
Most algo traders spend weeks wiring up MetaTrader connectivity. With FxSocket, you skip that entirely. The same API that serves historical data for backtesting also executes live trades. Switch from demo to live by changing one parameter.
A typical workflow looks like this: start by pulling historical candle data through the REST API, run your backtest locally using pandas or backtrader, iterate on your strategy until the metrics look right, then deploy the same code against a live account. Because the API interface is identical for historical data and live trading, there is no translation layer to build and no MQL conversion step. Your Python or Node.js code is your production trading system.
Built for Serious Automation
- Connect multiple accounts under one API key
- Granular permissions — read-only, trade, or full access
- IP whitelisting for production bots
- No rate limits on WebSocket connections
- Works with any MT4 or MT5 broker
- 99.99% uptime SLA on all plans
- Encrypted credentials — your broker login is never stored in plain text
Broker-Specific Tips
FxSocket works with any MT4 or MT5 broker, but brokers differ in how they configure symbols, execution modes, and trading constraints. Here are some practical tips to keep in mind when building your algo:
Symbol Naming Differences
Not all brokers use the same symbol names. The standard "EURUSD" might appear as "EURUSDm", "EURUSD.r", "EURUSD.ecn", or "EURUSDb" depending on the broker and account type. Micro accounts often append an "m" suffix, while ECN accounts may add ".ecn" or similar. Always use the GET /v1/symbols endpoint to fetch the exact symbol list for your connected account rather than hardcoding symbol names.
Execution Modes
Brokers offer different execution modes: instant execution and market execution. With instant execution, the broker may reject your order with a requote if the price moves between your request and their fill. With market execution, orders are always filled but at the current market price, which may differ from the price you saw. FxSocket surfaces the execution mode per symbol so your bot can adapt — for example, by omitting a price parameter on market execution symbols or by widening your slippage tolerance on instant execution brokers.
Lot Size Constraints
Each broker defines minimum volume, maximum volume, and volume step for every symbol. A typical standard account has a minimum of 0.01 lots with a step of 0.01, but some brokers use 0.1 as the minimum or support micro lots at 0.001. If you send a volume that does not align with the broker's step size, the order will be rejected. Query the symbol details endpoint to retrieve these constraints programmatically and round your lot sizes accordingly.
Spread Considerations
Spreads vary dramatically between brokers and account types. An ECN account might show 0.1-pip spreads on EURUSD during London session but widen to 3+ pips during the Asian rollover. If your strategy is sensitive to spread, subscribe to the WebSocket tick stream and calculate the live spread before placing each order. You can also set a maximum spread threshold in your bot logic to skip trades when conditions are unfavorable.
Common Errors and Troubleshooting
Here are the most frequent issues algo traders encounter when integrating with FxSocket, along with solutions:
401 Unauthorized
This means your API key is missing, expired, or incorrect. Double-check that you are sending the key in the Authorization header as Bearer your_api_key. If you recently rotated your key in the dashboard, make sure your bot is using the new one. API keys are scoped to your account — they do not expire automatically, but you can revoke them at any time.
422 Validation Error
The API returns 422 when the request body is syntactically valid JSON but contains invalid trading parameters. Common causes include:
- Invalid symbol: The symbol name does not match what the broker uses. Call GET /v1/symbols to get the correct names.
- Volume out of range: The lot size is below the minimum, above the maximum, or not aligned to the step size.
- Invalid stop-loss or take-profit: SL/TP levels are too close to the current price. Most brokers enforce a minimum stop distance (usually a few pips).
- Market closed: You are trying to trade a symbol outside its trading hours. Use the symbol details endpoint to check session times.
WebSocket Disconnects
WebSocket connections can drop due to network interruptions, server maintenance, or idle timeouts. Always implement reconnection logic with exponential backoff (as shown in the streaming example above). Send periodic pings to keep the connection alive and detect dead connections early. After reconnecting, re-send your subscription messages — the server does not remember your previous subscriptions.
Order Stuck in "PENDING" State
If an order remains in PENDING status for more than a few seconds, it usually means the broker is experiencing delays. This is more common during high-volatility events like NFP releases or central bank announcements. Your bot should monitor order status via the WebSocket order_update event and implement a timeout — if the order is not filled within your threshold, cancel it and re-evaluate.
Frequently Asked Questions
Can I run multiple strategies on the same account?
Yes. FxSocket does not restrict how you organize your trading logic. You can run multiple bots that each target different symbols or timeframes, all operating against the same connected account. Use the comment or magic number field when placing orders to tag which strategy opened each position. This makes it easy to track performance per strategy and ensures one bot does not accidentally close another bot's positions.
What about rate limits?
REST API requests are rate-limited to prevent abuse, but the limits are generous enough for virtually all algo trading use cases. WebSocket connections have no rate limits on incoming data — you receive every tick as it happens. If you need to place a very high volume of orders in a short window (e.g., during news events), batch your requests or use the WebSocket order placement channel for lower latency. Check the API documentation for current rate limit thresholds, which are returned in the response headers of every request.
How do I handle overnight swaps?
Overnight swap charges (or credits) are applied by your broker, not by FxSocket. Swaps are typically applied at the daily rollover time (usually around 00:00 server time) and appear as adjustments on your open positions. You can query the current swap rates for any symbol through the GET /v1/symbolsendpoint. If your strategy is swap-sensitive, factor these costs into your backtesting by including the swap rates in your P&L calculations. Wednesday usually carries a triple swap to account for the weekend.
Can I use FxSocket with a demo account?
Absolutely. FxSocket works identically with both demo and live accounts. In fact, we recommend starting with a demo account to test your integration, validate your strategy logic, and confirm that symbol names and lot sizes are correct before going live. The API interface is the same — your code does not need to change when switching from demo to production.
How do I monitor my bot's performance?
The FxSocket dashboard at app.fxsocket.com provides real-time visibility into your connected accounts, including open positions, order history, account balance, and equity curves. For programmatic monitoring, use the GET /v1/account endpoint to pull balance, equity, margin, and free margin. Many traders also pipe their order data into a separate analytics platform or database for custom reporting and drawdown tracking.