Skip to main content

Module open_api

Module open_api 

Source
Expand description

Client for the cTrader Open API, which exchanges Protobuf messages over TLS.

client::OpenApiClient is the entry point: it opens one connection, authorises the application and its trading accounts on it, and carries every request. The other modules hold the requests of one group each and the values they return.

use ctrader_connector::common::config::ConfigurationOpenApi;
use ctrader_connector::open_api::client::OpenApiClient;
use ctrader_connector::open_api::symbols::SymbolsParams;

let client = OpenApiClient::connect(ConfigurationOpenApi::from_env()?).await?;
client.authorise_application().await?;
let account = client.accounts().await?[0].id;
client.authorise_account(account).await?;
let listed = client.symbols(SymbolsParams::new(account)).await?;
println!("{} symbols", listed.symbols.len());
client.shutdown().await;

§Configuration

ConfigurationOpenApi is built with demo, live or read from the environment with from_env.

VariableBuilder optionRequiredDefault
BROKER_CLIENT_IDclient_idyesnone
BROKER_CLIENT_SECRETclient_secretyesnone
BROKER_ACCESS_TOKENaccess_tokenyesnone
BROKER_REFRESH_TOKENrefresh_tokennonone; a refresh then fails
BROKER_ENVIRONMENTdemo() or live()nodemo
BROKER_DEMO_HOSThostnodemo.ctraderapi.com; read for demo only
BROKER_TOKEN_URLtoken_urlnohttps://connect.spotware.com/apps/token
nonehostnolive.ctraderapi.com for live
noneportno5035
nonetimeoutno10 s for one response
noneretriesno3 after a limit error
nonebackoffno1 s before the first retry
nonereconnect_delayno5 s before the first attempt

An empty variable counts as absent. Secrets are held in types that do not print their value.

OpenApiClient::connect_with also takes ConnectionOptions for what the configuration does not cover:

OptionDefault
heartbeat_interval10 s
inbound_timeout75 s
reconnect_attemptsunlimited
request_limit50 per second
historical_limit5 per second
command_capacity64 requests waiting for the connection
event_capacity1024 events held for a reader

§Connection lifecycle

One task owns the socket; see connection for the whole account.

  • Heartbeat: the task sends one whenever nothing was written for the heartbeat interval.
  • Inbound silence: a server that sends nothing, not even its own heartbeat, for the inbound timeout counts as lost, as does a write that does not complete in time.
  • Reconnect: after a loss the requests in flight fail, Event::Disconnected is reported and the task connects again, waiting twice as long before every further attempt, up to a minute or the configured delay when that is longer.
  • Replay: once connected it authorises the application and the accounts again, restores the subscriptions and reports Event::Reconnected. Requests made while the connection is down fail at once.
  • Never sent again: orders. A request that trades is written at most once; it is neither retried after a limit error nor replayed after a reconnection.
  • OpenApiClient::shutdown ends the task; later requests fail with ConnectorError::Closed.

§Error handling

Every call returns ConnectorError.

VariantMeaningReaction
Config, ValueRejected before anything was sent.Correct the input.
ServerThe server refused; the error carries its code and text.Decide by the code.
TransportThe connection failed or is down.Wait for Event::Reconnected, then repeat a request that reads.
TimeoutNo answer in time to a request that may be repeated.Repeat it.
OutcomeUnknownA request that trades was written and no answer came: the server may have acted on it.Look the order up with reconcile or by its label before placing it again.
SessionEndedThe server ended the authorisation of the account or the application.Authorise again, see client; then subscribe again.
LaggedA reader fell behind and events were dropped.Go on reading; refresh the state from the server.
IncompleteThe server announced more history than it sent.Treat the range the error names as missing: it cannot be asked for in smaller parts.
TokenA token refresh failed.Obtain a new pair.
ClosedThe client was shut down.Connect anew.

§Streams

The typed streams are each read with next. A subscription returns the first three of them; the streams of executions and of margin events send no request and read what the server reports for an authorised account: QuoteStream, DepthStream, TrendbarStream, ExecutionStream and MarginStream. OpenApiClient::events gives every event of the connection untyped. Streams are bounded: a stream read too slowly loses its oldest events and reports the loss once with Lagged, after which it goes on. Subscriptions are restored after a reconnection, and a stream reports SessionEnded when the authorisation of its account ends.

§Rate limits

The server accepts 50 requests per second on a connection and 5 per second for historical data. The task holds requests back so that neither limit is exceeded. When the server still answers that a limit was exceeded, the task pauses and sends the request again, up to the configured number of retries, with a pause that doubles up to thirty seconds, or up to the configured backoff when that is longer. Long ranges of bars and ticks take several requests, each counted.

§Logging

With the logging feature the connection task emits tracing events at debug level: connected, connection lost, reconnected, reconnection failed, replayed request failed, authorisation ended and limit exceeded. They carry no secret. Without the feature nothing is emitted and tracing is not compiled in. The application installs the subscriber.

§Testing

  • Mock servers: the tests named open_api_*_mock and open_api_mock run against scripted servers on the loopback interface, reached through Plain and connect_with. open_api_clock_mock runs over a stream held in memory, on a paused clock. They need no credentials.
  • Live tests: open_api_live refuses any environment but the demo one; the host is the one the configuration names. It reads the variables of the table above and BROKER_ENV_FILE, the absolute path of a file that holds the token pair as export BROKER_ACCESS_TOKEN= and export BROKER_REFRESH_TOKEN= lines.
  • Token rotation: a refresh makes the old pair useless at once. The live test of the refresh writes the new pair back to that file; a run that cannot write it loses the pair, and a session opened with the old access token ends with SessionEnded.
  • Live tests trade the smallest volume, label what they create and remove it afterwards.

§Protocol facts

  • Prices travel as integers in 1/100000 of a unit and volumes in 0.01 of a unit; the library takes and returns decimals in units, see crate::common::decimals.
  • Ticks: on the wire toTimestamp is exclusive. ticks takes a range with both ends included and asks for one millisecond more.
  • Bars: on the wire toTimestamp is inclusive; trendbars returns the bars that overlap the range, oldest first, without the bar still forming.
  • A stop-limit order is a stop price and a slippage in points, not two prices.
  • An order at market takes its stop loss and take profit as distances from the fill price; absolute prices are refused before anything is sent.
  • A request that trades is answered by the first execution event for it, for an order at market its acceptance; the fill follows on the executions stream.

Modules§

account
Details of a trading account: its balance, deposit currency, leverage and kind.
client
Client that authorises an application and its trading accounts over one connection.
connection
Connection task and the handle callers talk to it through.
depth
Stream of market depth and the order book rebuilt from it.
errors
Conversions from the error messages of the Open API to the shared error types.
executions
Stream of the execution events of an account.
history
Deals, orders and changes of the balance of an account inside a range of time.
margin
Margin of positions and margin calls of an account.
messages
payload
Typed pairing of messages with their payload types and of requests with their responses.
quotes
Stream of spot quotes of subscribed symbols.
symbols
Reference data of a trading account: its assets, its symbols and the details of a symbol.
ticks
Tick history: every price change of one side of a symbol within a range of time.
token
Token pairs and their refresh over the token endpoint.
trading
Orders, positions and deals of a trading account, and the requests that change them.
transport
Length-prefixed framing, and the connectors shared with the other protocols.
trendbars
Trendbars (candles) of a symbol: their history and the bar that is forming now.