Client
The main entry point for interacting with the cTrader API.
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.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:
await client.auth.authenticate_app()
creds = await client.auth.authenticate_by_trader_login(
trader_login=17091452,
access_token="...",
refresh_token="...",
expires_at=1778617423,
)
await client.market_data.subscribe_spots(creds.account_id, [270])
await asyncio.Event().wait() # Run forever
Attributes:
| Name | Type | Description |
|---|---|---|
auth |
AuthManager
|
Authentication operations (app auth, account auth, token refresh). |
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. |
protocol |
Protocol
|
Low-level protocol access for advanced usage. |
auth
Authentication operations.
Provides methods for:
- Application authentication
- Account authentication
- Token refresh management
- Account discovery
accounts
Account information operations.
Provides methods 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.
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)
Initialize the client.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
config
|
ClientConfig
|
Client configuration including credentials and settings. |
required |
connect()
Connect to the cTrader server.
Establishes the TCP/SSL connection, starts the protocol reader,
heartbeat monitor, and event router.
Raises:
| Type | Description |
|---|---|
CTraderConnectionFailedError
|
If connection cannot be established. |
close()
Close the connection and clean up resources.
Stops the event router, heartbeat monitor, protocol reader,
and closes the transport.
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. |
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 heartbeat before disconnect. Set to 0 to disable. |
request_timeout |
float
|
Default timeout for API requests in seconds. |
reconnect_attempts |
int
|
Max reconnection attempts (0 to disable). |
reconnect_min_wait |
float
|
Initial wait between reconnection attempts. |
reconnect_max_wait |
float
|
Maximum wait between reconnection attempts. |
Example
Authentication
The client.auth property provides access to authentication operations.
AuthManager
Manages authentication for cTrader API connections.
Handles application authentication, account authentication for multiple
trading accounts, and automatic token refresh before expiry.
Example
auth = AuthManager(
protocol=protocol,
client_id="your_client_id",
client_secret="your_client_secret",
on_tokens_refreshed=save_tokens_to_storage,
)
await auth.authenticate_app()
await auth.authenticate_account(credentials)
await auth.start() # Start refresh monitor
# ... trading operations ...
await auth.stop()
is_app_authenticated
Whether the application has been authenticated.
authenticated_accounts
List of authenticated account IDs.
authenticate_app(timeout=30.0)
Authenticate the application with cTrader.
This must be called before authenticating any accounts.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
float
|
Request timeout in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
ProtoOAApplicationAuthRes
|
The authentication response from the server. |
Raises:
| Type | Description |
|---|---|
APIError
|
If authentication fails. |
CTraderConnectionTimeoutError
|
If request times out. |
authenticate_account(credentials, timeout=30.0, reauth=False, reconnect=False)
Authenticate a trading account.
The account credentials are stored for automatic token refresh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
credentials
|
AccountCredentials
|
The account credentials including tokens. |
required |
timeout
|
float
|
Request timeout in seconds. |
30.0
|
reauth
|
bool
|
Whether this is a re-authentication (token refresh) or initial auth. |
False
|
reconnect
|
bool
|
Whether this authentication is happening during a connection reconnect. This can be used |
False
|
Returns:
| Type | Description |
|---|---|
ProtoOAAccountAuthRes
|
The authentication response from the server. |
Raises:
| Type | Description |
|---|---|
APIError
|
If authentication fails. |
CTraderConnectionTimeoutError
|
If request times out. |
authenticate_by_trader_login(trader_login, access_token, refresh_token, expires_at, timeout=30.0)
Authenticate an account using trader login (discovers cTID automatically).
This is a convenience method that:
1. Resolves the trader login to the cTID trader account ID
2. Creates AccountCredentials with the resolved ID
3. Authenticates the account
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
trader_login
|
int
|
The trader login number (visible in cTrader app). |
required |
access_token
|
str
|
OAuth access token. |
required |
refresh_token
|
str
|
OAuth refresh token. |
required |
expires_at
|
float
|
Unix timestamp when access token expires. |
required |
timeout
|
float
|
Request timeout in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
AccountCredentials
|
AccountCredentials with the resolved account_id, ready for use. |
Raises:
| Type | Description |
|---|---|
AccountNotFoundError
|
If no account matches the trader login. |
APIError
|
If authentication fails. |
CTraderConnectionTimeoutError
|
If request times out. |
get_accounts(access_token, timeout=30.0)
Get all trading accounts associated with an access token.
This retrieves the list of accounts without authenticating them.
Useful for discovering available accounts or letting users select
which account to use.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
OAuth access token. |
required |
timeout
|
float
|
Request timeout in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
list[AccountSummary]
|
List of account summaries (lightweight account info). |
Raises:
| Type | Description |
|---|---|
APIError
|
If the request fails. |
CTraderConnectionTimeoutError
|
If request times out. |
resolve_account_id(access_token, trader_login, timeout=30.0)
Resolve a trader login to its cTID trader account ID.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
access_token
|
str
|
OAuth access token. |
required |
trader_login
|
int
|
The trader login number (visible in cTrader app). |
required |
timeout
|
float
|
Request timeout in seconds. |
30.0
|
Returns:
| Type | Description |
|---|---|
int
|
The cTID trader account ID (used for API calls). |
Raises:
| Type | Description |
|---|---|
AccountNotFoundError
|
If no account matches the trader login. |
APIError
|
If the request fails. |
CTraderConnectionTimeoutError
|
If request times out. |
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. |
remove_account(account_id)
Remove an account from refresh monitoring.
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 wasn't registered. |
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. |