Skip to content

Events

The client uses an event-driven architecture. Register handlers with @client.on() to receive real-time updates.

Registering Handlers

from ctrader_api_client import ExecutionEvent, SpotEvent

@client.on(SpotEvent, symbol_id=270)  # Filter by symbol
async def on_spot(event: SpotEvent):
    print(f"{event.bid}/{event.ask}")


@client.on(ExecutionEvent, account_id=12345)  # Filter by account
async def on_execution(event: ExecutionEvent):
    print(f"Order {event.order.order_id}: {event.execution_type}")

Filtering

Different events support different filters:

Event account_id symbol_id
SpotEvent Yes Yes
ExecutionEvent Yes No
DepthEvent Yes Yes
ReadyEvent Yes No
OrderErrorEvent Yes No
TraderUpdateEvent Yes No
MarginChangeEvent Yes No
SubscriptionRestoreFailedEvent Yes No
ReconnectedEvent No No
ClientDisconnectEvent No No

Using an unsupported filter raises ValueError at registration time.

Market Data Events

SpotEvent

Price tick event.

Emitted when bid/ask prices update for a subscribed symbol.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

symbol_id int

The symbol identifier.

bid Decimal | None

Current bid price

ask Decimal | None

Current ask price

trendbar list[Trendbar]

Live trend bar. Only populated if subscribed to trendbar updates via MarketDataAPI.subscribe_trendbars

timestamp datetime

Server timestamp of the tick.

SpotEvent contains live trendbar data when subscribed:

from ctrader_api_client import TrendbarPeriod

# Subscribe to both spot prices and M1 trendbars
await client.market_data.subscribe_spots(account_id, [270])
await client.market_data.subscribe_trendbars(account_id, 270, TrendbarPeriod.M1)

@client.on(SpotEvent, symbol_id=270)
async def on_spot(event: SpotEvent):
    # Prices are Decimals
    print(f"Bid: {event.bid}, Ask: {event.ask}")

    # Trendbar is included when subscribed
    if event.trendbar:
        bar = event.trendbar
        print(f"Candle: O={bar.open} H={bar.high} L={bar.low} C={bar.close}")

DepthEvent

Market depth (order book) event.

Emitted when the order book updates for a subscribed symbol.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

symbol_id int

The symbol identifier.

new_quotes tuple[DepthQuote, ...]

New or updated quotes.

deleted_quote_ids tuple[int, ...]

IDs of quotes that were removed.

DepthQuote

Single depth of market quote.

Attributes:

Name Type Description
quote_id int

Unique identifier for the quote (used for updates/deletions).

price int

Quote price (raw integer, divide by 10^priceDigits).

size int

Quote size (volume in cents).

is_bid bool

True if this is a bid quote, False if it's an ask quote.

Trading Events

An execution event carries the Order, Position and Deal models that the
trading API returns. Each one is None when the server sent no such message.
A swap or a deposit has no order. An accepted order has no position and no deal
yet.

The order says why a position closed:

from ctrader_api_client import ExecutionEvent, ExecutionType, OrderType

@client.on(ExecutionEvent, account_id=12345)
async def on_execution(event: ExecutionEvent):
    if event.execution_type is not ExecutionType.ORDER_FILLED or event.order is None:
        return
    if not event.order.is_closing_order:
        return  # An entry fill.
    if event.order.is_stop_out:
        print("Closed by a margin stop-out")
    elif event.order.order_type is OrderType.STOP_LOSS_TAKE_PROFIT:
        print("Closed by a stop loss or a take profit")
    else:
        print("Closed by a market order")

ExecutionEvent

Order execution event.

Emitted when an order is accepted, filled, modified, canceled, etc.

The server attaches the order, the position and the deal that the
execution touched. Each one is None when the server sent no such message.
A swap or a deposit has no order. An accepted order has no position and no
deal yet.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

execution_type ExecutionType

Type of execution (fill, cancel, etc.).

order Order | None

The order, or None.

position Position | None

The position, or None.

deal Deal | None

The deal, or None.

is_server_event bool

True if generated by server (e.g., stop-out).

error_code str | None

Error code if execution failed.

OrderErrorEvent

Order error event.

Emitted when an order operation fails.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

order_id int | None

The order identifier (if available).

position_id int | None

The position identifier (if available).

error_code str

The error code from the server.

description str

Human-readable error description.

Account Events

ReadyEvent

Emitted when an account is authenticated and ready for use.

Fired whenever a server-side session is (re)established and subscriptions
must be (re)applied: initial authentication, re-authentication after a
transport reconnection, and recovery after a server-side account
disconnect. It is not fired for token-refresh re-auth, where the session
and its subscriptions remain intact.

Attributes:

Name Type Description
account_id int

The cTID trader account ID that is now ready.

trigger AuthTrigger

Why the session was established. Never TOKEN_REFRESH.

is_reconnect

True if this follows a reconnection or account-disconnect recovery.

Use this to reconcile account state after an interruption. It fires on
initial auth, after a transport reconnection, and after recovery from a
server-side account disconnect — is_reconnect is True for the latter two:

@client.on(ReadyEvent)
async def on_ready(event: ReadyEvent):
    if event.is_reconnect:
        # Market data subscriptions are already restored. Positions opened or
        # orders filled while disconnected produced events you never saw.
        positions = await client.trading.get_open_positions(event.account_id)
        my_book.replace(positions)

Market data subscriptions are re-applied before this event is emitted, so do not
re-subscribe here — the server rejects a duplicate subscription.

event.trigger carries the exact reason as an AuthTrigger, for cases where
is_reconnect is too coarse. The event is emitted for INITIAL, RECONNECT,
and ACCOUNT_REAUTH (all of which lose or re-establish subscriptions), and
suppressed for TOKEN_REFRESH (session intact).

AuthTrigger

Bases: Enum

Reason an account authentication was performed.

Threaded through account authentication so downstream logic can
distinguish cases where the server-side session (and its subscriptions)
is lost from cases where it is preserved.

INITIAL = 'INITIAL'

RECONNECT = 'RECONNECT'

TOKEN_REFRESH = 'TOKEN_REFRESH'

ACCOUNT_REAUTH = 'ACCOUNT_REAUTH'

A trader update carries the Account model that the accounts API returns.
Its balance is a Decimal in account currency units.

TraderUpdateEvent

Trader account update event.

Emitted when account information changes (balance, leverage, etc.).

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

account Account

The entire Account object.

MarginChangeEvent

Position margin change event.

Emitted when the margin allocated to a position changes.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

position_id int

The position identifier.

used_margin int

New margin value (raw, divide by 10^moneyDigits).

money_digits int

Exponent for monetary values.

MarginCallTriggerEvent

Margin call triggered event.

Emitted when account margin level reaches a configured threshold.
Sent at most once every 10 minutes per threshold to avoid spam.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

margin_call_type int

Type of margin call (1, 2, or 3 for different thresholds).

margin_level_threshold Decimal

The threshold that was breached (percentage).

TrailingStopChangedEvent

Trailing stop loss level changed event.

Emitted when a trailing stop loss price is updated due to
favorable price movement.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

position_id int

The position identifier.

order_id int

The stop loss order identifier.

stop_price Decimal

New stop loss price.

timestamp datetime

Server timestamp of the update.

Connection Events

ReconnectedEvent

Emitted after an automatic reconnection.

The client publishes this event when a new link replaces a lost one. On
that link the application is authenticated, and the client has tried to
re-authenticate each account. Each restored account also gets a ReadyEvent,
which is the event to use for subscriptions. Use this event for logic
that depends on the reconnection as a whole, such as logging or alerting.

Attributes:

Name Type Description
restored_accounts tuple[int, ...]

The account IDs that were re-authenticated.

failed_accounts tuple[tuple[int, str], ...]

The accounts that failed, as (account_id, error_message) tuples.

Example:

@client.on(ReconnectedEvent)
async def on_reconnected(event: ReconnectedEvent):
    print(f"Restored accounts: {event.restored_accounts}")
    if event.failed_accounts:
        print(f"Failed accounts: {event.failed_accounts}")

The application is always authenticated on the link that this event reports.
A link where the application cannot authenticate is dropped, and the client
connects again with backoff. No event is published for such a link.

ClientDisconnectEvent

Client disconnect event.

Emitted when the server terminates the client connection.

Attributes:

Name Type Description
reason str

Reason for disconnection.

AccountDisconnectEvent

Account disconnect event.

Emitted when an account's session has been terminated by the server while
the underlying connection stays up, and could not be re-established on the
spot. The client keeps re-authenticating on the existing connection with
backoff until it succeeds, then emits a ReadyEvent; no user action is
required to restore the session.

The server also reports a disconnect whenever the token behind an
authorization is rotated, for a session it has not actually ended. Those
reports are checked against the server and discarded, so they do not appear
here — every event published is a drop that outlived a re-authentication
attempt.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

The client recovers from this automatically — it re-authenticates the account on
the existing connection with backoff and emits a ReadyEvent on success. The
event is informational; subscribe to it only if you want to observe or log the
drop. Check current authorization with client.is_account_authorized(account_id).

A disconnect the server reports is checked before it is published. Rotating an
access token makes the server report one for a session it has not ended, so the
client asks whether the account is still served on this connection: if it is,
nothing is published. The check does not re-authenticate, because that answers
for the token as much as for the session, and the rotation prompting the report
is the very thing that would make such an answer unreliable.

The check also waits for any token refresh on that account to finish first.
Rotating a token means the server drops the old authorization and the client
establishes a new one, and in between the account is genuinely unauthorized — it
refuses everything, including the check. Since the refresh always begins before
the report it provokes, waiting for it to settle is what keeps a moment the
client itself created from reading as a lost session.

A check that cannot be completed — a timeout, a link that has just gone — is not
read as a disconnect either. The account is left as it was, and the next report
is checked afresh. What reaches a handler is therefore always a session the
server confirmed it was no longer serving.

TokenInvalidatedEvent

Token invalidated event.

Emitted when access tokens are revoked or expired.

Attributes:

Name Type Description
account_ids tuple[int, ...]

List of affected account IDs.

reason str

Reason for invalidation.

TokenRefreshFailedEvent

Token refresh failed event.

Emitted when an access token could not be refreshed after all retries.
The old credentials are kept and the client retries on the next refresh
check, so a transient failure recovers on its own. A persistent failure
means the refresh token is no longer usable and the account must be
re-authorized out of band.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

error TokenRefreshError

The refresh failure, including its underlying cause.

The client keeps the existing credentials and retries on the next refresh check,
so a single event usually means a transient outage. If the event keeps repeating,
the refresh token is no longer usable and the account has to be re-authorized out
of band.

SubscriptionRestoreFailedEvent

Subscription restore failed event.

Emitted when standing market data subscriptions could not be re-applied
after a session was re-established. Restoration stops at the first failure,
so subscriptions after it in the sequence are also missing.

The intent is kept, so the next reconnection tries again. Until then the
account receives no data for the affected symbols, and a consumer that
needs it sooner should re-subscribe from a handler.

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

error Exception

The failure that stopped restoration.

Emitted when the client could not re-apply an account's market data
subscriptions to a new session. Restoration stops at the first failure, so
anything after it in the sequence is missing too. The intent is kept and the
next reconnection tries again, but until then the account receives no data for
the affected symbols. Re-subscribe from a handler if you need it sooner.

Symbol Events

SymbolChangedEvent

Symbol configuration changed event.

Emitted when a symbol's configuration is updated (trading hours,
margin requirements, spreads, etc.).

Attributes:

Name Type Description
account_id int

The cTID trader account ID.

symbol_ids tuple[int, ...]

List of symbol IDs that changed.

Unregistering Handlers

@client.on(SpotEvent)
async def my_handler(event: SpotEvent):
    ...

# Later, unregister
client.off(SpotEvent, my_handler)