Client
The main entry point for interacting with the cTrader API.
A client is used inside async with. The block owns the connection and the
background tasks that keep it alive, so leaving it — normally or by exception —
winds them down, and a background task that dies is raised at the end of the
block rather than discovered later.
CTraderClient
CTraderClient
Unified cTrader API client.
Provides access to all API operations through namespaced interfaces
and supports decorator-based event registration.
Example
from ctrader_api_client import CTraderClient, ClientConfig
from ctrader_api_client.auth import AccountCredentials
from ctrader_api_client.events import SpotEvent
config = ClientConfig(
client_id="your_client_id",
client_secret="your_client_secret",
)
client = CTraderClient(config)
@client.on(SpotEvent, symbol_id=270)
async def on_price(event: SpotEvent) -> None:
print(f"PRICE: {event.bid}/{event.ask}")
async with client:
account_id = await client.accounts.resolve_account_id(
access_token="...",
trader_login=17091452,
)
await client.auth.authenticate_trader(
AccountCredentials(
account_id=account_id,
access_token="...",
refresh_token="...",
expires_at=1778617423,
)
)
await client.market_data.subscribe_spots(account_id, [270])
await asyncio.Event().wait() # Run forever
Attributes:
| Name | Type | Description |
|---|---|---|
auth |
AuthManager
|
Account authentication and the sessions it produces. |
accounts |
AccountsAPI
|
Account discovery and information operations. |
symbols |
SymbolsAPI
|
Symbol lookup and search. |
trading |
TradingAPI
|
Order and position operations. |
market_data |
MarketDataAPI
|
Market data subscriptions and historical data. |
protocol |
Protocol
|
Low-level protocol access for advanced usage. |
auth
Authentication operations.
The application is authenticated as the client connects, so what is
left here is authenticating trading accounts and asking after the
sessions they hold.
accounts
Account information operations.
Provides methods to discover the accounts an access token covers and to
retrieve account/trader details.
symbols
Symbol lookup and search.
Provides methods to list, retrieve, and search trading symbols.
trading
Order and position operations.
Provides methods for:
- Placing orders (market, limit, stop)
- Modifying orders
- Canceling orders
- Closing positions
- Querying positions and orders
market_data
Market data subscriptions and historical data.
Provides methods for:
- Subscribing to spot prices
- Subscribing to trendbars (candles)
- Subscribing to depth of market
- Retrieving historical data
is_connected
Whether the client is connected to the server (transport level).
protocol
Direct access to the protocol layer.
For advanced usage when you need to send raw protobuf messages
or handle responses not covered by the high-level API.
__init__(config, *, token_store=None)
Initialize the client with the default object graph.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ClientConfig
|
Client configuration including credentials and settings. |
required |
token_store
|
TokenStore | None
|
Durable storage for credentials. The client writes |
None
|
from_graph(graph)
Build a client around a graph assembled by the caller.
For substituting a collaborator the default assembly does not expose,
such as a deterministic clock.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
graph
|
ClientGraph
|
The collaborators the client should run on. |
required |
Returns:
| Type | Description |
|---|---|
CTraderClient
|
A client driving that graph. |
on(event_type, *, account_id=None, symbol_id=None)
on(
event_type: type[T_BothFilters],
*,
account_id: int | None = ...,
symbol_id: int | None = ...
) -> Callable[
[EventHandler[T_BothFilters]],
EventHandler[T_BothFilters],
]
Decorator to register an event handler.
Handlers are called when events of the specified type arrive.
Optional filters can be used to only receive events for specific
accounts or symbols. The event must have the corresponding account_id or symbol_id attributes
for filtering to work. Else this will raise ValueError at registration time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
type[T]
|
The event class to listen for. |
required |
account_id
|
int | None
|
Only receive events for this account (optional). |
None
|
symbol_id
|
int | None
|
Only receive events for this symbol (optional). |
None
|
Returns:
| Type | Description |
|---|---|
Callable[[EventHandler[T]], EventHandler[T]]
|
Decorator function that registers the handler. |
off(event_type, handler)
Unregister an event handler.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
event_type
|
type[T]
|
The event class. |
required |
handler
|
EventHandler[T]
|
The handler function to remove. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if handler was found and removed, False otherwise. |
Composition
CTraderClient(config) assembles its own collaborators, which is all most
callers need. When you have to substitute one of them, assemble the graph
yourself and hand it over:
from ctrader_api_client import CTraderClient
from ctrader_api_client.composition import build_graph
graph = build_graph(config, clock=my_clock)
client = CTraderClient.from_graph(graph)
build_graph(config, *, token_store=None, clock=None)
Assemble the default object graph from configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ClientConfig
|
Client configuration including credentials and settings. |
required |
token_store
|
TokenStore | None
|
Durable storage for rotated credentials. Without one, |
None
|
clock
|
Clock | None
|
Time source for the heartbeat and token-refresh timers. Defaults |
None
|
Returns:
| Type | Description |
|---|---|
ClientGraph
|
The assembled graph, ready to hand to |
ClientGraph
Every collaborator a client needs, already wired to each other.
Attributes:
| Name | Type | Description |
|---|---|---|
config |
ClientConfig
|
The settings the graph was built from. |
transport |
Transport
|
The TCP/SSL link. |
protocol |
Protocol
|
Framing and request/response correlation over the transport. |
supervisor |
ConnectionSupervisor
|
Owns the link, and the reader and heartbeat that run on it. |
emitter |
EventEmitter
|
The consumer-facing event bus. |
router |
EventRouter
|
Translates protocol messages into events on the bus. |
auth |
AuthManager
|
App and account sessions. |
maintainer |
SessionMaintainer
|
Refreshes the tokens, recovers the sessions that the server |
accounts |
AccountsAPI
|
Account information operations. |
symbols |
SymbolsAPI
|
Symbol lookup and search. |
trading |
TradingAPI
|
Order and position operations. |
market_data |
MarketDataAPI
|
Market data subscriptions and historical data. |
ClientConfig
ClientConfig
Bases: BaseModel
Configuration for CTraderClient.
Attributes:
| Name | Type | Description |
|---|---|---|
host |
str
|
cTrader API server hostname. |
port |
int
|
cTrader API server port. |
use_ssl |
bool
|
Whether to use SSL/TLS encryption. |
client_id |
str
|
OAuth application client ID. |
client_secret |
str
|
OAuth application client secret. |
heartbeat_interval |
float
|
Seconds between heartbeat sends. |
heartbeat_timeout |
float
|
Seconds without server-initiated messages before disconnect. Set to 0 to disable. |
request_timeout |
float
|
Seconds to wait for the response to a request, when |
connect_timeout |
float
|
Seconds allowed for the TCP connection and TLS |
reconnect_attempts |
int | None
|
Max reconnection attempts. None (the default) |
reconnect_min_wait |
float
|
Initial wait between reconnection attempts. |
reconnect_max_wait |
float
|
Maximum wait between reconnection attempts. |
refresh_policy |
RefreshPolicy
|
When to refresh access tokens and how hard to try. |
reauth_policy |
ReauthPolicy
|
Backoff for re-establishing sessions the server dropped. |
Example
Authentication Policies
Token-refresh and session-recovery timing, passed via
ClientConfig(refresh_policy=..., reauth_policy=...).
RefreshPolicy
When to refresh an access token, and how hard to try.
Attributes:
| Name | Type | Description |
|---|---|---|
buffer_seconds |
float
|
Refresh a token this many seconds before it expires. |
check_interval |
float
|
Seconds between checks for tokens that expire soon. |
retry_attempts |
int
|
How many attempts one refresh gets before it is |
retry_min_wait |
float
|
The wait after the first failed attempt. |
retry_max_wait |
float
|
The upper limit of the wait between attempts. |
ReauthPolicy
How hard to try to re-establish a session that the server dropped.
Recovery has no attempt limit. Only the wait between attempts is limited,
and it is kept per account.
Attributes:
| Name | Type | Description |
|---|---|---|
min_wait |
float
|
The wait after the first failed attempt. |
max_wait |
float
|
The upper limit of the wait between attempts. |
Authentication
The client.auth property provides access to authentication operations. The
application is authenticated as the client connects, so what is left here is
authenticating trading accounts and asking after the sessions they hold. An
account whose access token has expired is refreshed before it is authenticated,
so the refresh token in the credentials is what a restart depends on.
AuthManager
Authorizes trading accounts and answers for the sessions they hold.
The application is authenticated by the client as it connects, so a caller
only ever presents account credentials.
An account the manager knows about is always in exactly one of three
situations: credentials are held but there is no server-side session,
the session is live and authorized, or the server dropped the session
and recovery is pending. The credentials outlive the sessions: a dropped
link or a server-side disconnect ends the session, and the tokens stay valid.
is_app_authenticated
Whether the application has been authenticated.
authenticated_accounts
List of account IDs the manager holds credentials for.
authorized_accounts
List of account IDs with a live, authorized server-side session.
authenticate_trader(credentials, timeout=None)
Authenticate a trading account and keep its session alive.
An expired access token is refreshed first. The credentials are kept,
so the tokens are refreshed before they expire and the session is
re-established after a disconnect.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
AccountCredentials
|
The account credentials including tokens. |
required |
timeout
|
float | None
|
Request timeout in seconds. None uses the configured default. |
None
|
Raises:
| Type | Description |
|---|---|
TokenExpiredError
|
If the server rejects the access token, or if |
APIError
|
If the server refuses a refresh for another reason. |
AccountAuthError
|
If the server rejects the account. |
CTraderConnectionTimeoutError
|
If request times out. |
is_account_authorized(account_id)
Whether the account currently has a live, authorized session.
Returns False after a server-side account disconnect, or after the
connection drops, until re-authentication succeeds.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account_id
|
int
|
The cTID trader account ID. |
required |
get_credentials(account_id)
Get credentials for an account.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account_id
|
int
|
The cTID trader account ID. |
required |
Returns:
| Type | Description |
|---|---|
AccountCredentials | None
|
The account credentials, or None if not authenticated. |
all_credentials()
Credentials for every account the manager holds, oldest first.
Returns:
| Type | Description |
|---|---|
list[AccountCredentials]
|
A snapshot list, safe to iterate while accounts are added or removed. |
remove_account(account_id)
Forget an account: its credentials, its session, and its subscriptions.
The manager re-establishes no session for a forgotten account, so
nothing is kept for restoration either.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
account_id
|
int
|
The cTID trader account ID. |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if the account was removed. False if it was not held. |
AccountCredentials
AccountCredentials
Stores authentication credentials for a trading account.
Attributes:
| Name | Type | Description |
|---|---|---|
account_id |
int
|
The cTID trader account ID. |
access_token |
str
|
OAuth access token for API authentication. |
refresh_token |
str
|
OAuth refresh token for obtaining new access tokens. |
expires_at |
float
|
Unix epoch timestamp when the access token expires. |
expires_soon(buffer_seconds=300.0)
Check if the access token expires within the buffer period.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
buffer_seconds
|
float
|
Number of seconds before expiry to consider "soon". |
300.0
|
Returns:
| Type | Description |
|---|---|
bool
|
True if the token expires within buffer_seconds from now. |
is_expired()
Check if the access token has already expired.
Returns:
| Type | Description |
|---|---|
bool
|
True if the token has expired. |
time_until_expiry()
Get seconds remaining until token expires.
Returns:
| Type | Description |
|---|---|
float
|
Seconds until expiry. Negative if already expired. |
with_refreshed_tokens(access_token, refresh_token, expires_in)
Create a new instance with refreshed tokens.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
The new access token. |
required |
refresh_token
|
str
|
The new refresh token. |
required |
expires_in
|
int
|
Seconds until the new access token expires. |
required |
Returns:
| Type | Description |
|---|---|
AccountCredentials
|
A new AccountCredentials instance with updated tokens. |
TokenStore
Passed as CTraderClient(config, token_store=...). cTrader rotates both tokens
on every refresh and invalidates the old pair immediately, so a process that
restarts holding the pair it was originally given can no longer authenticate.
TokenStore
Bases: Protocol
Durable storage that the client writes rotated credentials through.
cTrader rotates the access token and the refresh token on every refresh,
and it invalidates the old pair at once. A process that restarts with the
pair it was first given cannot authenticate. So the client persists each
new pair as the server issues it.
The store is write-only. The caller reads the stored pair at startup and
passes it to authenticate_trader, because only the caller knows which
accounts a process is responsible for.
save(credentials)
Persist the credentials for an account. Replace any earlier pair.
Called during a token refresh, before the new access token is used.
A save that raises aborts the refresh. The client reports that as a
TokenRefreshFailedEvent and tries again at the next check, so a
short storage outage recovers on its own.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
AccountCredentials
|
The new tokens and their expiry. |
required |
The contract is write-only, because writing is the half the client has to do for
you: rotation happens mid-session, at a moment you cannot observe. Reading back at
startup is yours, since only you know which accounts a given process is
responsible for. Nothing stops the same class from doing both:
class PostgresTokenStore(TokenStore):
async def save(self, credentials: AccountCredentials) -> None:
... # required by the protocol, called by the client
async def load(self, account_id: int) -> AccountCredentials | None:
... # not part of the protocol, called by you at startup
store = PostgresTokenStore(pool)
client = CTraderClient(config, token_store=store)
async with client:
stored = await store.load(account_id)
if stored is None:
stored = AccountCredentials(
account_id=account_id,
access_token="your_access_token",
refresh_token="your_refresh_token",
expires_at=1778617423,
)
await client.auth.authenticate_trader(stored)