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 fundedops

Account 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:

GroupMethods
Lifecyclecreate, get, list, update (name, tags, metadata and password), delete, deploy, undeploy, redeploy
Account stateaccount_information, positions, pending_orders
Historyhistory_deals, history_positions, history_orders, balance_operations, balance_history
Symbols and pricessymbols, symbol, quote, quotes, candles
Calculations and checkscalculate_margin, calculate_profit, check_order
Statisticstrade_stats, equity_history

client.search_servers("ic markets demo", platform="mt5") 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(account_id, symbol) returns the latest bid and ask. client.accounts.candles(account_id, symbol, timeframe, start_time=None, end_time=None, limit=None) 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(account_id, symbols) 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.

MethodWhat it does
client.accounts.calculate_margin(account_id, symbol, type, volume, price=None)The margin the order needs.
client.accounts.calculate_profit(account_id, symbol, type, volume, open_price, close_price)The profit of a trade between two prices.
client.accounts.check_order(account_id, type, symbol, volume, *, price, stop_limit_price, stop_loss, take_profit)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.

MethodWhat it does
place_order(account_id, type, symbol, volume, *, price, stop_limit_price, stop_loss, take_profit, slippage, comment, magic, expiration_type, expiration_time, filling_mode, expires_in_seconds, idempotency_key)Opens a position at the market price or places a pending order.
modify_order(account_id, ticket, *, price, stop_limit_price, stop_loss, take_profit, expiration_type, expiration_time, expires_in_seconds, idempotency_key)Changes a pending order.
cancel_order(account_id, ticket, *, idempotency_key)Cancels a pending order.
modify_position(account_id, ticket, *, stop_loss, take_profit, expires_in_seconds, idempotency_key)Changes a position's stop loss or take profit.
close_position(account_id, ticket, *, volume, slippage, expires_in_seconds, idempotency_key)Closes a position, or part of it with volume.
close_positions(account_id, *, symbol, slippage, expires_in_seconds, idempotency_key)Closes every open position, or those on symbol.
close_position_by(account_id, ticket, opposite_ticket, *, expires_in_seconds, idempotency_key)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(account_id, trade_request_id)One trade request.
list_trade_requests(account_id, offset=0, limit=None)The account's trade requests, newest first.
wait_for_trade_request(account_id, trade_request_id, timeout=60.0, interval=1.0)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. Pass idempotency_key= to choose it; otherwise the SDK generates uuid4().hex once per call. The key it sent is on trade.idempotency_key and on .idempotency_key of 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 raises TradeOutcomeUnknownError with the key. The SDK never retries on its own.
  • KEEP and None. In modify_order and modify_position, a field left at KEEP keeps its value and None removes it (stop loss, take profit).
  • Numbers. Prices and volumes are sent exactly. A float is rounded to 10 decimal places, so 0.1 + 0.2 is sent as 0.3. A Decimal is sent as given, and one with more than 10 decimal places raises ValueError before anything is sent.
  • Times. expiration_time takes a datetime and is sent in UTC ending in Z. A naive datetime is read as UTC.
  • Account fields. Account.trade_allowed and Account.margin_mode (hedging, netting or exchange) say whether the account can trade. client.accounts.update(account_id, password="...") switches it to another 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.

ExceptionStatusMeaning
ValidationError400The request failed validation.
CredentialsBlockedError400The broker rejected this login recently; retry after blocked_until (rejected_at, blocked_until).
UnauthorizedError401Missing or invalid API key.
PaymentRequiredError402Insufficient credit balance (required_cents, balance_cents).
ForbiddenError403The 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.
NotFoundError404The resource does not exist, is not yours, or your API key is limited to other accounts.
ConflictError409The request conflicts with current state.
RateLimitedError429Rate limit exceeded (retry_after, in seconds), or 50 trade requests are already waiting for the account (metadata["code"] is E_QUEUE_FULL).
InternalError500Server-side error, or a non-envelope error body.
TradeRejectedError422The broker rejected a trade (code, broker_code, retryable, trade_request_id).
IdempotencyKeyReusedError422The idempotency key was already used for a different request.
ServiceUnavailableError503The account job could not be queued, or the account is not connected for trading (metadata["code"] is E_ACCOUNT_NOT_CONNECTED); retry shortly.
TradeExpiredError503A 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.
TradeOutcomeUnknownErrornoneA 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=err.idempotency_key, or find it with list_trade_requests. The httpx error is its __cause__.
DeployFailedErrornoneRaised 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(limit, remaining, reset), 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 = None

For the complete list of endpoints and their request and response shapes, see the API reference.