Python SDK
fundedops is the official Python SDK for the FundedOps API. It ships two clients with the same methods, a synchronous FundedOps and an asynchronous AsyncFundedOps, plus typed pydantic models and a typed exception hierarchy. Pick the one that fits your program.
The SDK supports both MT4 and MT5 accounts. The same clients, methods, and models work identically against either platform, so there are no MT4-specific calls to learn.
Install
Requires Python 3.10 or newer.
pip install fundedopsAccount methods live under the client.accounts namespace. wait_until_connected, stream, search_servers, get_billing and the trading methods are on the client itself.
Synchronous usage
Construct a FundedOps client with your API key. It works as a context manager, or call close() when you are done.
from fundedops import FundedOps
with FundedOps(api_key="fo_live_...") as client:
# List your accounts.
for account in client.accounts.list():
print(account.id, account.state, account.connection_status)
# Read last-known figures.
info = client.accounts.account_information("9b2c…")
print(info.balance, info.equity, info.currency)
# Deploy an account and block until it connects (timeout is mandatory).
client.accounts.deploy("9b2c…")
account = client.wait_until_connected("9b2c…", timeout=180)
print(account.connection_status) # "connected"The full lifecycle and read surface is available on client.accounts:
| Group | Methods |
|---|---|
| Lifecycle | create, get, list, update (name, tags, metadata and password), delete, deploy, undeploy, redeploy |
| Account state | account_information, positions, pending_orders |
| History | history_deals, history_positions, history_orders, balance_operations, balance_history |
| Symbols and prices | symbols, symbol, quote, quotes, candles |
| Calculations and checks | calculate_margin, calculate_profit, check_order |
| Statistics | trade_stats, equity_history |
client.search_servers( finds broker server names, best match first.
client.get_billing() returns your prepaid balance and every billed account with its next charge:
billing = client.get_billing()
print(billing.balance_cents, billing.top_up_needed_cents)
for item in billing.accounts:
print(item.account_id, item.status, item.renews_at, item.undeploy_at)Asynchronous usage
AsyncFundedOps has the same constructor, method names and return types as FundedOps. Use async with (or await client.aclose()), and await each call.
import asyncio
from fundedops import AsyncFundedOps
async def main():
async with AsyncFundedOps(api_key="fo_live_...") as client:
accounts = await client.accounts.list()
info = await client.accounts.account_information(accounts[0].id)
print(info.equity)
await client.accounts.deploy(accounts[0].id)
account = await client.wait_until_connected(accounts[0].id, timeout=180)
print(account.connection_status)
asyncio.run(main())A parity test in the package checks that every FundedOps method exists on AsyncFundedOps with the same signature.
Streaming
client.stream([account_id, ...]) opens a WebSocket, subscribes each account, answers server pings for you, and yields typed events. The synchronous client returns an iterable; the async client returns an async-iterable.
# Synchronous
from fundedops import FundedOps
client = FundedOps(api_key="fo_live_...")
for event in client.stream(["9b2c…"]):
if event.type == "positions_updated":
print("open:", len(event.updated), "closed:", event.removed_ids)
elif event.type == "account_information_updated":
print("equity", event.account_information.equity)# Asynchronous
import asyncio
from fundedops import AsyncFundedOps
async def main():
client = AsyncFundedOps(api_key="fo_live_...")
async for event in client.stream(["9b2c…"]):
if event.type == "deal_added":
print("closed", event.deal.symbol, event.deal.profit)
asyncio.run(main())v1 does not auto-reconnect: a clean server close ends iteration, and an abnormal close raises StreamClosed. To resume, reconnect and resubscribe, and the server sends a fresh snapshot. See WebSockets for the frame vocabulary.
Prices
client.accounts.quote( returns the latest bid and ask. client.accounts.candles( returns up to 1,000 bars, oldest first (limit defaults to 100). Both are on the async client too. A call waits up to about 10 seconds for the account. It raises ServiceUnavailableError with code E_PRICES_UNAVAILABLE when the account cannot read prices right now or did not answer within about 10 seconds; retry shortly.
quote = client.accounts.quote("9b2c…", "EURUSD")
print(quote.bid, quote.ask, quote.time)
bars = client.accounts.candles("9b2c…", "EURUSD", "H1", limit=200)
for bar in bars.candles:
print(bar.time, bar.open, bar.high, bar.low, bar.close, bar.tick_volume)client.accounts.quotes( takes a list of names or one comma-separated string and returns the latest prices of 1 to 50 distinct symbols in one call. Every symbol ends up in quotes or in errors, so one unknown symbol never fails the call. An error's status is the HTTP status quote would answer for that symbol alone (404 or 503), with code when that answer carries one. Only symbols subscribed on a WebSocket stream are answered from the cache. Every other symbol is one request to the account, which answers about 40 a second and shares a queue of 100 waiting requests with Get Quote and the calculations, so polling many unstreamed symbols quickly can return 503 E_PRICES_UNAVAILABLE. Stream the symbols you poll often.
result = client.accounts.quotes("9b2c…", ["EURUSD", "GBPUSD", "XAUUSD"])
for quote in result.quotes:
print(quote.symbol, quote.bid, quote.ask)
for error in result.errors:
print(error.symbol, error.status, error.code)Calculations
Three read-only calls ask the account what a trade would cost, without trading. They work with a Read Only key, and they are on the async client too. The Trading guide has the rules.
| Method | What it does |
|---|---|
client.accounts.calculate_margin( | The margin the order needs. |
client.accounts.calculate_profit( | The profit of a trade between two prices. |
client.accounts.check_order( | Whether the account could place the order now. |
margin = client.accounts.calculate_margin("9b2c…", "EURUSD", "buy", 0.1)
print(margin.margin, margin.currency)
profit = client.accounts.calculate_profit("9b2c…", "EURUSD", "buy", 0.1, 1.08, 1.09)
print(profit.profit)
check = client.accounts.check_order("9b2c…", "buy_limit", "EURUSD", 0.1, price=1.08)
if not check.can_place:
print(check.code, check.message)
else:
print(check.margin, check.free_margin, check.margin_level)A refusal is a normal answer, not an exception: can_place is False with a code such as E_INVALID_VOLUME or E_ACCOUNT_CANNOT_TRADE. The money fields are None when the order cannot be placed for a reason other than free margin.
For live prices, call the subscribe methods on the stream, before the loop or while you iterate. Frames sent before iteration wait and go out once, right after the accounts subscribe. The async stream's methods are awaited. A stream holds up to 50 price subscriptions, quote symbols and candle streams together.
# Synchronous
stream = client.stream(["9b2c…"])
stream.subscribe_quotes("9b2c…", ["EURUSD", "GBPUSD"])
stream.subscribe_candles("9b2c…", "EURUSD", "M5")
for event in stream:
if event.type == "quotes":
for quote in event.quotes:
print(quote.symbol, quote.bid, quote.ask)
elif event.type == "candle" and event.closed:
print("closed", event.symbol, event.timeframe, event.candle.time, event.candle.close)# Asynchronous
stream = client.stream(["9b2c…"])
await stream.subscribe_quotes("9b2c…", ["EURUSD"])
async for event in stream:
if event.type == "quotes":
print(event.quotes[0].bid)unsubscribe_quotes and unsubscribe_candles take the same arguments. Each call is answered with a price_subscriptions event. Closed bars arrive at least once, so de-duplicate them on symbol, timeframe and candle.time. WebSockets has the frames, caps and the coalescing rules.
Trading
The trading methods need a Full Access API key and an account connected with its master password (account.trade_allowed is True). The Trading guide explains the rules behind them.
| Method | What it does |
|---|---|
place_order( | Opens a position at the market price or places a pending order. |
modify_order( | Changes a pending order. |
cancel_order( | Cancels a pending order. |
modify_position( | Changes a position's stop loss or take profit. |
close_position( | Closes a position, or part of it with volume. |
close_positions( | Closes every open position, or those on symbol. |
close_position_by( | Closes a position against an opposite position on the same symbol. trade.result.remaining_ticket is the position left open, or None when both closed in full. None also when, on MT4, the new ticket of the rest could not be identified; message then says so, so list positions. |
get_trade_request( | One trade request. |
list_trade_requests( | The account's trade requests, newest first. |
wait_for_trade_request( | Polls until the status is done, rejected, expired or unknown and returns the trade request. Raises TimeoutError once timeout passes. |
Each trading write returns a TradeRequest: done when the broker carried it out, or queued, sent or unknown when it had not answered within about 10 seconds. Then call wait_for_trade_request. A write that is rejected or expires raises an error; wait_for_trade_request returns such a request with its status instead.
from fundedops import KEEP, FundedOps, TradeRejectedError
client = FundedOps(api_key="fo_live_...") # a Full Access key
try:
trade = client.place_order("9b2c…", "buy", "EURUSD", 0.1, stop_loss=1.079)
except TradeRejectedError as err:
print(err.code, err.broker_code, err.retryable, err.idempotency_key)
else:
if trade.status != "done":
trade = client.wait_for_trade_request("9b2c…", trade.id, timeout=60)
print(trade.status, trade.result.position_ticket if trade.result else None)
# Move the stop loss. take_profit=KEEP (the default) leaves the take profit as it is.
client.modify_position("9b2c…", "1834920571", stop_loss=1.0815, take_profit=KEEP)
# Remove the take profit.
client.modify_position("9b2c…", "1834920571", take_profit=None)- Idempotency keys. Every trading write sends an
Idempotency-Key. Passidempotency_key=to choose it; otherwise the SDK generatesuuid4().hexonce per call. The key it sent is ontrade.idempotency_keyand on.idempotency_keyof any error the call raises, so you can send the same trade again safely with the same key. When the connection fails before any answer arrives (a timeout, a reset), the call raisesTradeOutcomeUnknownErrorwith the key. The SDK never retries on its own. KEEPandNone. Inmodify_orderandmodify_position, a field left atKEEPkeeps its value andNoneremoves it (stop loss, take profit).- Numbers. Prices and volumes are sent exactly. A
floatis rounded to 10 decimal places, so0.1 + 0.2is sent as0.3. ADecimalis sent as given, and one with more than 10 decimal places raisesValueErrorbefore anything is sent. - Times.
expiration_timetakes adatetimeand is sent in UTC ending inZ. A naivedatetimeis read as UTC. - Account fields.
Account.trade_allowedandAccount.margin_mode(hedging,nettingorexchange) say whether the account can trade.client.accounts.update(switches it to another password.account_id, password= "...")
Error handling
Every non-2xx response raises a typed exception derived from FundedOpsError. Each carries status, error, message, request_id, and optional details / metadata.
| Exception | Status | Meaning |
|---|---|---|
ValidationError | 400 | The request failed validation. |
CredentialsBlockedError | 400 | The broker rejected this login recently; retry after blocked_until (rejected_at, blocked_until). |
UnauthorizedError | 401 | Missing or invalid API key. |
PaymentRequiredError | 402 | Insufficient credit balance (required_cents, balance_cents). |
ForbiddenError | 403 | The API key is read-only, or limited to chosen accounts and the endpoint covers your whole developer account. On trading calls code is E_ACCOUNT_CANNOT_TRADE or E_TRADING_NOT_SUPPORTED when the account cannot trade. |
NotFoundError | 404 | The resource does not exist, is not yours, or your API key is limited to other accounts. |
ConflictError | 409 | The request conflicts with current state. |
RateLimitedError | 429 | Rate limit exceeded (retry_after, in seconds), or 50 trade requests are already waiting for the account (metadata["code"] is E_QUEUE_FULL). |
InternalError | 500 | Server-side error, or a non-envelope error body. |
TradeRejectedError | 422 | The broker rejected a trade (code, broker_code, retryable, trade_request_id). |
IdempotencyKeyReusedError | 422 | The idempotency key was already used for a different request. |
ServiceUnavailableError | 503 | The account job could not be queued, or the account is not connected for trading (metadata["code"] is E_ACCOUNT_NOT_CONNECTED); retry shortly. |
TradeExpiredError | 503 | A subclass of ServiceUnavailableError: the trade expired before it was sent, so nothing happened at the broker (code, trade_request_id). Send it again with a new key. |
TradeOutcomeUnknownError | none | A trading write failed on the way (timeout, connection reset, protocol error) before any answer arrived, so the outcome is unknown. Send the same call again with idempotency_key=, or find it with list_trade_requests. The httpx error is its __cause__. |
DeployFailedError | none | Raised by wait_until_connected when the account cannot connect: it reached deploy_failed, or it stopped on an error that is not retryable such as E_INSUFFICIENT_CREDIT (code, retryable, account). |
client.rate_limit holds the request budget from the latest response as RateLimit(, read from the X-RateLimit-* headers (None before the first request).
Catch a specific class, or FundedOpsError to handle everything. RateLimitedError exposes the Retry-After value as retry_after:
import time
from fundedops import FundedOps
from fundedops.errors import RateLimitedError, NotFoundError
client = FundedOps(api_key="fo_live_...")
try:
account = client.accounts.get("9b2c…")
except RateLimitedError as err:
time.sleep(err.retry_after or 1) # seconds until the limit resets
account = client.accounts.get("9b2c…")
except NotFoundError:
account = NoneFor the complete list of endpoints and their request and response shapes, see the API reference.