Skip to content

Exceptions

Every exception the library raises derives from CTraderError, so a single
except CTraderError catches anything that came from the client rather than
from your own code.

from ctrader_api_client import CTraderError

Hierarchy

CTraderError
├── CTraderConnectionError
│   ├── CTraderConnectionFailedError    could not reach the server
│   ├── CTraderConnectionClosedError    the link went away mid-flight
│   └── CTraderConnectionTimeoutError   a request outlived its timeout
├── AuthenticationError
│   ├── ApplicationAuthError            the server rejected client_id/secret
│   ├── AccountAuthError                the server rejected the account
│   ├── TokenExpiredError               the server refused the access or refresh token
│   ├── TokenRefreshError               a refresh exhausted its retries
│   └── AccountNotFoundError            no account matches that trader login
├── APIError                            an error response to a request
└── ProtocolError
    ├── FramingError                    a frame that cannot be on the wire
    ├── DeserializationError            a payload that will not parse
    ├── UnknownPayloadTypeError         a payload type this version cannot map
    └── UnknownEnumValueError           an enum value this version cannot map

What each call raises

Entering the client

from ctrader_api_client import ApplicationAuthError, CTraderConnectionFailedError

try:
    async with CTraderClient(config) as client:
        ...
except CTraderConnectionFailedError as e:
    print(f"Could not reach {e.host}:{e.port}: {e.cause}")
except ApplicationAuthError as e:
    print(f"Application rejected: {e.error_code} - {e.description}")

Bringing the client up connects the transport and authenticates the
application, so those are the two failures async with raises. A client that
cannot do both does not open.

Exceptions leave the block as themselves. Write except CTraderError, not
except*. If several background tasks fail at once the block raises an
ExceptionGroup, because that is genuinely what happened; a single failure is
never wrapped in one.

Authenticating an account

from ctrader_api_client import AccountAuthError, TokenExpiredError

try:
    await client.auth.authenticate_trader(credentials)
except TokenExpiredError:
    credentials = await my_oauth_flow.reauthorize(account_id)
    await client.auth.authenticate_trader(credentials)
except AccountAuthError as e:
    print(f"Account {e.ctid_trader_account_id} rejected: {e.error_code}")

TokenExpiredError means the server refused a token: the access token at
authentication, or the refresh token when the client refreshed an expired access
token first. Neither can be retried back to life. It needs a new OAuth
authorization. An access token that has merely expired does not raise, because
the client refreshes it before it authenticates the account.

Requests

Any call on client.trading, client.symbols, client.accounts or
client.market_data can raise:

  • APIError — the server answered with an error.
  • CTraderConnectionTimeoutError — no answer inside the timeout.
  • CTraderConnectionClosedError — the link died while the request was in
    flight.
from ctrader_api_client import APIError, CTraderConnectionTimeoutError

try:
    await client.trading.place_order(account_id, request)
except APIError as e:
    if e.is_rate_limited():
        await anyio.sleep(e.retry_after or 1)
    elif e.is_maintenance():
        ...  # the server is down until e.maintenance_end_timestamp
    else:
        raise
except CTraderConnectionTimeoutError as e:
    print(f"{e.operation} gave up after {e.timeout_seconds}s")

APIError carries the server's own error_code and description, plus three
questions worth asking before deciding whether to retry:

  • is_rate_limited() — back off; retry_after says how long if the server said.
  • is_maintenance() — the server is down for maintenance, not broken.
  • is_token_failure() — the token is the problem rather than the application,
    the account or the request, so a retry cannot help.

Failures reported as events

Not every failure can be raised, because not everything happens inside a call
you made. Three arrive as events instead:

Event Meaning
TokenRefreshFailedEvent A refresh exhausted its retries. Carries a TokenRefreshError. The credentials are kept and retried on the next check interval, so a repeat means the refresh token is dead.
SubscriptionRestoreFailedEvent Standing subscriptions could not be re-applied to a re-established session. The account is missing market data until the next reconnection.
ReconnectedEvent Carries failed_accounts alongside restored_accounts, for accounts that could not be re-authenticated on the new link.
from ctrader_api_client import TokenRefreshFailedEvent


@client.on(TokenRefreshFailedEvent, account_id=account_id)
async def on_refresh_failed(event: TokenRefreshFailedEvent):
    logger.error("Refresh failed for %d: %s", event.account_id, event.error.cause)

Exceptions raised inside your own event handlers are logged and do not stop the
other handlers for that event.

Reference

CTraderError

Bases: Exception

Base exception for all cTrader API errors.

Connection

CTraderConnectionError

Bases: CTraderError

Base exception for connection-related errors.

CTraderConnectionFailedError

Bases: CTraderConnectionError

Failed to establish connection to the server.

CTraderConnectionClosedError

Bases: CTraderConnectionError

Connection was closed unexpectedly.

CTraderConnectionTimeoutError

Bases: CTraderConnectionError

Connection operation timed out.

CTraderReconnectAbandonedError

Bases: CTraderConnectionError

The client tried to restore a dropped link and gave up.

Raised out of the async with client: block. The client does not stay
alive in a disconnected state, because a client that has stopped
reconnecting cannot recover on its own. The error tells a process
supervisor that a new client is needed.

Reconnection has no limit by default, so a server that stays unreachable
produces retries rather than this error. The error means that
reconnect_attempts was set to a finite number, and every attempt was
spent.

Not raised when reconnect_attempts=0 disables reconnection. Then a lost
link is the documented outcome, not a failure.

Attributes:

Name Type Description
reason

What the client attempted when it gave up.

cause

The final failure, also set as __cause__.

This is the one connection exception that reaches you without your having called
anything: it is raised out of the async with client: block itself. Reconnection
has no limit by default, so seeing it means that reconnect_attempts was set to
a finite number and every attempt was spent.

while True:
    try:
        async with client:
            await asyncio.Event().wait()
    except CTraderReconnectAbandonedError:
        logger.exception("Client abandoned its connection; starting a new one")
        await asyncio.sleep(30)

Catching it is only worthwhile if you intend to build a fresh client, since the
one that raised it is finished. Letting it propagate and having a process
supervisor restart you is an equally good answer. That is why it is raised
rather than logged: a client that has stopped reconnecting has no link, and
nothing short of a new async with client: block brings one back.

Authentication

AuthenticationError

Bases: CTraderError

Base exception for authentication-related errors.

ApplicationAuthError

Bases: AuthenticationError

Application authentication failed.

AccountAuthError

Bases: AuthenticationError

Account authentication failed.

is_already_authorized()

Whether the account was rejected for holding a live session already.

The server refuses to authorize an account twice on one channel. A
caller that was trying to reach exactly that state has already reached
it, so this is a rejection worth reading as success.

TokenExpiredError

Bases: AuthenticationError

The server refused the access token, or the refresh token that was to replace it.

TokenRefreshError

Bases: AuthenticationError

Failed to refresh access token.

AccountNotFoundError

Bases: AuthenticationError

No account found matching the given criteria.

API

APIError

Bases: CTraderError

Error response from the cTrader API.

is_rate_limited()

Check if this error indicates rate limiting.

is_maintenance()

Check if this error indicates server maintenance.

is_token_failure()

Whether the token is the problem, rather than the app, account or request.

A token failure cannot be retried back to life; it needs a new token.

Protocol

ProtocolError

Bases: CTraderError

Base exception for protocol-level errors.

FramingError

Bases: ProtocolError

Error in wire protocol framing.

DeserializationError

Bases: ProtocolError

Failed to deserialize a protobuf message.

UnknownPayloadTypeError

Bases: ProtocolError

Received a message with an unknown payload type.

UnknownEnumValueError

Bases: ProtocolError

The server sent an enum value that this client does not know.

A record with such a value is not converted. A guess would report a
wrong order type or status as a real one.

Attributes:

Name Type Description
enum

The client enum that has no member for the value.

value

The value on the wire.

The client never guesses at an enum value that it does not know. A record
with such a value raises this error from the call that fetched it, and a
server-pushed event with such a value is dropped with a warning. An unset
optional field takes the default that the proto declares, so this error
means that the server sent a value this version has no member for.

  • Events - Failures reported as events
  • Client - Client lifecycle and authentication