cTrader API Client
A Python client for the cTrader Open API. Provides a high-level async interface for trading operations, market data subscriptions, and account management.
Documentation:
Note that this library is in early development. The API may change, and some features may be incomplete. Contributions and feedback are welcome!
Requirements
- Python 3.12+
- An activated cTrader Open API application with client ID and secret
- OAuth tokens for account authentication (see below)
Installation
Using uv (recommended):
uv add ctrader-api-client
Using pip:
pip install ctrader-api-client
Quick Start
import asyncio
from ctrader_api_client import CTraderClient, ClientConfig
from ctrader_api_client.events import ReadyEvent, SpotEvent
config = ClientConfig(
client_id="your_client_id",
client_secret="your_client_secret",
)
client = CTraderClient(config)
@client.on(SpotEvent, symbol_id=270) # US500.cash
async def on_price(event: SpotEvent):
print(f"Price update: {event.bid}/{event.ask}")
@client.on(ReadyEvent)
async def on_ready(event: ReadyEvent):
"""Called when account is authenticated and ready."""
await client.market_data.subscribe_spots(event.account_id, [270])
async def main():
async with client:
await client.auth.authenticate_app()
await client.auth.authenticate_by_trader_login(
trader_login=12345678,
access_token="your_access_token",
refresh_token="your_refresh_token",
expires_at=1778617423,
)
# Keep running to receive events
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())
OAuth Token Generation
This library requires OAuth tokens from cTrader. For simple use cases, you can use ctrader-oauth-fetcher to generate tokens:
uvx ctrader-oauth-fetcher --client-id [ID] --client-secret [SECRET]
This opens a browser for authorization and returns your access token, refresh token, and expiry time.
For production applications, implement the OAuth flow according to the cTrader Open API documentation.
Features
Authentication
# Authenticate the application
await client.auth.authenticate_app()
# Authenticate a trading account
creds = await client.auth.authenticate_by_trader_login(
trader_login=12345678,
access_token="...",
refresh_token="...",
expires_at=1778617423,
)
# Tokens are automatically refreshed before expiry. A refresh that fails is
# retried on the next check rather than dropping the session, and surfaces as a
# TokenRefreshFailedEvent so a persistently dead refresh token is observable.
Market Data
# Subscribe to spot prices
await client.market_data.subscribe_spots(account_id, [symbol_id])
# Subscribe to candles
await client.market_data.subscribe_trendbars(account_id, symbol_id, TrendbarPeriod.M1)
# Get historical data
bars = await client.market_data.get_trendbars(
account_id, symbol_id, TrendbarPeriod.H1, from_ts, to_ts
)
Trading
from ctrader_api_client.models import NewOrderRequest, ClosePositionRequest
from ctrader_api_client.enums import OrderType, OrderSide
# Place a market order
request = NewOrderRequest(
symbol_id=symbol_id,
order_type=OrderType.MARKET,
side=OrderSide.BUY,
volume=100000, # 1 lot in cents
)
result = await client.trading.place_order(account_id, request)
# Get open positions
positions = await client.trading.get_open_positions(account_id)
# Close a position
close_position = ClosePositionRequest(
position_id=position_id,
volume=100000, # Close full volume
)
await client.trading.close_position(account_id, close_position)
Event Handling
from ctrader_api_client.events import (
SpotEvent,
ExecutionEvent,
ReadyEvent,
ReconnectedEvent,
TokenRefreshFailedEvent,
)
# Price updates
@client.on(SpotEvent, symbol_id=270)
async def on_spot(event: SpotEvent):
print(f"{event.bid}/{event.ask}")
# Order executions
@client.on(ExecutionEvent, account_id=account_id)
async def on_execution(event: ExecutionEvent):
print(f"Order {event.order_id}: {event.execution_type}")
# Account ready (fires on initial auth, after reconnection, and after account-disconnect recovery)
@client.on(ReadyEvent)
async def on_ready(event: ReadyEvent):
# Set up subscriptions here
await client.market_data.subscribe_spots(event.account_id, symbols)
# Connection restored
@client.on(ReconnectedEvent)
async def on_reconnected(event: ReconnectedEvent):
print(f"Reconnected, restored accounts: {event.restored_accounts}")
# Token refresh failed (retried automatically; a repeating event means the
# refresh token is no longer usable and the account must be re-authorized)
@client.on(TokenRefreshFailedEvent, account_id=account_id)
async def on_refresh_failed(event: TokenRefreshFailedEvent):
print(f"Token refresh failed for {event.account_id}: {event.error}")
Symbols
# List all symbols
symbols = await client.symbols.list_all(account_id)
# Search by name
results = await client.symbols.search(account_id, "EUR")
# Get specific symbol
symbol = await client.symbols.get_by_id(account_id, symbol_id)
Account Information
# Get account details
account = await client.accounts.get_trader(account_id)
print(f"Balance: {account.balance}")
Automatic Reconnection
The client automatically handles connection drops:
- Reconnects with exponential backoff
- Re-authenticates the app and all accounts
- Emits
ReadyEventfor each restored account (for resubscribing to market data) - Emits
ReconnectedEventwith summary of restored/failed accounts
It also handles server-side account disconnects (e.g. a broker dropping the
account session over the weekend while the connection stays up): the account is
re-authenticated on the existing connection with backoff until it succeeds, then
a ReadyEvent is emitted so subscriptions can be restored. Account
authorization is observable via client.is_account_authorized(account_id),
which is distinct from the transport-level client.is_connected.
Use ReadyEvent to set up subscriptions that persist across reconnections.
Configuration
from ctrader_api_client import ClientConfig
from ctrader_api_client.auth import ReauthPolicy, RefreshPolicy
config = ClientConfig(
client_id="your_client_id",
client_secret="your_client_secret",
# Connection settings
host="live.ctraderapi.com", # or "demo.ctraderapi.com"
port=5035,
use_ssl=True,
# Timeouts
heartbeat_interval=10.0,
heartbeat_timeout=30.0, # Or 0 to disable server heartbeat checks
request_timeout=30.0,
# Reconnection
reconnect_attempts=5,
reconnect_min_wait=1.0,
reconnect_max_wait=60.0,
# Token refresh: when to refresh access tokens and how hard to retry
refresh_policy=RefreshPolicy(
buffer_seconds=300.0, # refresh this long before expiry
check_interval=60.0, # how often to check for expiring tokens
retry_attempts=3,
retry_min_wait=1.0,
retry_max_wait=30.0,
),
# Session recovery: backoff for re-establishing sessions the server dropped
reauth_policy=ReauthPolicy(
min_wait=1.0,
max_wait=60.0,
),
)
Metadata
Release files for ctrader-api-client 0.6.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| ctrader_api_client-0.6.0.tar.gz | 194.8 kB | Without provenance | Details for ctrader_api_client-0.6.0.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| ctrader_api_client-0.6.0-py3-none-any.whl | Python 3 | none | any | Details for ctrader_api_client-0.6.0-py3-none-any.whl |
Total release size: 283.1 kB
Release files / ctrader_api_client-0.6.0.tar.gz
| Download URL | ctrader_api_client-0.6.0.tar.gz |
|---|---|
| Size | 194.8 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
04bb0142a0996fe4af7007cf0bc4ed694418a5f0d412e1af0411982f2e73478f
|
|
BLAKE2b-256 checksum How to use checksums |
44e08b670e99fe62b68d45480b7f41757fa185b75b80f4f63a95c4d4a9329956
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Arch Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Release files / ctrader_api_client-0.6.0-py3-none-any.whl
| Download URL | ctrader_api_client-0.6.0-py3-none-any.whl |
|---|---|
| Size | 88.3 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
967fa8ece49dd0f5f57e327925433762533cb4cb702aa5539b3c2ed096e2811f
|
|
BLAKE2b-256 checksum How to use checksums |
37329769e7149faf2f148331b51e019bb67bfef9f1571b6e5a330963240c78f3
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.11.26 {"installer":{"name":"uv","version":"0.11.26","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Arch Linux","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":null}
|
Security for ctrader-api-client 0.6.0
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.