Establishing a Connection¶
You can connect to a cTrader Open API proxy using either the TCP protocol or the WebSocket protocol. This guide covers both of these options.
Using TCP¶
SSL Usage
The TCP client connection must use SSL, otherwise you will not be able to connect or interact with the API.
You can establish a connection as follows using the official cTrader Open API SDKs.
1 2 |
|
The OpenClient.Connect()
method calls the OpenClient.ConnectTcp()
method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
|
The Python Open API client automatically attempts to establish a connection when it is initialized.
1 |
|
Via WebSocket¶
When connecting via the WebSocket protocol the host and port are the same as when connecting via the TCP protocol.
Here is how the official cTrader Open API SDKs establish a connection via WebSocket.
1 2 |
|
The OpenClient.Connect()
method calls the OpenClient.ConnectWebSocket()
method
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
|
The Python SDK does not support the WebSocket standard.
For an example of a .NET Blazor web app that uses the WebSocket standard to establish and maintain a connection, click here.
Best Practices¶
Here are some guidelines that you should keep in mind when connecting to the cTrader Open API.
- At most, you should create two connections - one for demo accounts and one for live accounts. Each connection can support an unlimited number of accounts of a certain type.
- After a connection is established, you should pass the app authorization flow. If you send any messages before your application is authorized, you will receive an error.
- To keep a connection alive, keep sending a heartbeat event (
ProtoHeartbeatEvent
) every 10 seconds. - Use a message queue for sending/receiving data to avoid concurrent send/receive events.