Expand description
Safe Rust API for dxFeed market data over the dxFeed Graal Native SDK.
The project is in alpha: the API may change in any release. It covers the dxFeed Java API 3.357 wherever the SDK exports it; the README lists the Java members that wait for their wrappers or for new SDK exports.
The names follow the dxFeed Java API: DXEndpoint, DXFeed, DXFeedSubscription, DXPublisher, with
methods in snake case: addEventListener is add_event_listener and
getFeed is get_feed. The Java names are search aliases in the documentation.
§Example
Print the quotes of a symbol until Enter is pressed:
use dxfeed_graal::DXEndpoint;
use dxfeed_graal::event::Quote;
fn main() -> dxfeed_graal::Result<()> {
let endpoint = DXEndpoint::create()?;
let subscription = endpoint.get_feed().create_subscription::<Quote>()?;
subscription.add_event_listener(|quotes| {
for quote in quotes {
println!("{quote}");
}
})?;
subscription.add_symbols(["AAPL"])?;
endpoint.connect("demo.dxfeed.com:7300")?;
std::io::stdin().read_line(&mut String::new()).ok();
endpoint.close_and_await_termination()
}A quote prints as Java prints it: Quote{AAPL, eventTime=0, time=20241004-093000.000, timeNanoPart=0, ...}.
A subscription to several event types, DXFeed::create_subscription_with_types, gives its listeners an
EventRef to match. All 27 event types of the SDK are mapped; see event.
The last event of a LastingEvent type, such as a quote, comes from the local cache with
DXFeed::get_last_event_if_subscribed and DXFeed::get_last_event, or from the uplink with
DXFeed::get_last_event_promise, whose Promise is waited for with a timeout:
use std::time::Duration;
use dxfeed_graal::DXEndpoint;
use dxfeed_graal::event::Quote;
fn main() -> dxfeed_graal::Result<()> {
let endpoint = DXEndpoint::create()?;
endpoint.connect("demo.dxfeed.com:7300")?;
let quote = endpoint.get_feed().get_last_event_promise::<Quote>("AAPL")?.wait(Duration::from_secs(10))?;
println!("{quote}");
endpoint.close_and_await_termination()
}The default feed of the process, DXFeed::get_instance, connects to the address in the dxfeed.address system
property or in the dxfeed.properties file. System properties come from the code, from the
dxfeed.system.properties file and from the DXFEED_* environment variables (see system):
use dxfeed_graal::event::Quote;
use dxfeed_graal::{DXFeed, system};
fn main() -> dxfeed_graal::Result<()> {
system::set_property("dxfeed.address", "demo.dxfeed.com:7300")?;
let subscription = DXFeed::get_instance()?.create_subscription::<Quote>()?;
subscription.add_event_listener(|quotes| quotes.for_each(|quote| println!("{quote}")))?;
subscription.add_symbols(["AAPL"])?;
std::io::stdin().read_line(&mut String::new()).ok();
Ok(())
}§How-to
The common tasks have short examples on the items that do them; the samples directory of the repository has
complete programs.
- Subscribe, add and change symbols, close; several event types at once:
DXFeedSubscription. - Events from a time on, such as candles or time and sales:
DXFeedTimeSeriesSubscription; a history in one request:DXFeed::get_time_series_promise. - The orders of one source, all the symbols, a time-series symbol:
Symbol. - Candle symbols with a period, a price, an exchange or a session:
CandleSymbol. - Read the fields of events, keep copies, use event flags:
event; the main fields ofQuote,Trade,TimeAndSale,Order,CandleandSeries. - The last event of a symbol and other requests:
Promise, several at once:Promises; in async code: the Async section. - Conflate events or limit their batches:
SubscriptionController. - Order books:
OrderBookModel,MarketDepthModeland their lists,ObservableListModel. - Whole transactions and snapshots:
IndexedTxModel,TimeSeriesTxModel,IndexedEventTxModel; live lists:IndexedEventModel,TimeSeriesEventModel. - Publish events:
DXPublisher; poll events without listeners:event_queue.
§Threads
The SDK runs in a GraalVM isolate that the crate creates on first use and never tears down. A thread is attached to
it on its first call and detached when it exits. All types are Send and Sync.
§Listeners
A listener’s closure runs on a thread of the endpoint’s executor, its own threads by default or an Executor
thread pool, or inside ManualExecutor::process_all_pending. The calls of one listener do not overlap. The events
are valid during the call only; copy what you keep with to_owned(). A panic in a closure is caught and goes to
ErrorManager.
Without listeners, an event queue gives the events of subscriptions to a thread of the application, which polls them; the listeners of its subscriptions, and of the models and the collector on its executor, then run inside the polls.
Add listeners before symbols. Removing a listener or dropping its DXFeedSubscription waits for its running
calls, except inside a callback, and so does dropping the last owner of an endpoint with state listeners. So do not
hold a lock that a closure takes while doing that from another thread.
§Async
Promise and AnyOf implement IntoFuture, so async code awaits them instead of
blocking a thread in wait. The futures work on any executor (tokio, async-std, smol or another);
the crate depends on no runtime and needs no cargo feature for them:
use dxfeed_graal::event::Quote;
use dxfeed_graal::{DXFeed, Result};
async fn last_quote(feed: &DXFeed) -> Result<Quote> {
feed.get_last_event_promise::<Quote>("AAPL")?.await
}A PromiseFuture keeps its promise: cancel makes it ready at once, so a timer of the
runtime that cancels it is the async timeout. Dropping the future does not cancel the request, closing the endpoint
leaves a pending request pending, and system::shutdown makes pending futures ready with Error::ShutDown. A
worker thread of the runtime that polls a future is attached to the isolate, as any thread that calls the SDK is.
A subscription turns into an EventStream of owned events with
into_stream, before its symbols are added:
use dxfeed_graal::DXFeed;
use dxfeed_graal::event::Quote;
async fn print_quotes(feed: &DXFeed) -> dxfeed_graal::Result<()> {
let mut quotes = feed.create_subscription::<Quote>()?.into_stream()?;
quotes.subscription().add_symbols(["AAPL"])?;
while let Some(quote) = quotes.next().await {
println!("{quote}");
}
Ok(())
}Its buffer drops the oldest events when it is full; with StreamOptions::event_queue the events stay in the SDK
until the consumer waits for them, and the SDK keeps the last quote of each symbol meanwhile (StreamOptions).
The stream ends when it or its subscription is closed, when its endpoints are closed and on system::shutdown.
The cargo feature stream implements futures_core::Stream for it.
A SharedEventQueue turns into a TaggedEventStream with
into_stream: it yields the events of all the subscriptions attached
to the queue with their tags, takes them only while the consumer waits, as an event-queue stream does, and runs the
work of the executor of the queue meanwhile. It ends when it or its queue is closed and on system::shutdown.
The models stream whole items into a ModelStream, built in place of their listener:
build_stream of the builders of IndexedTxModel and
TimeSeriesTxModel yields a Transaction per transaction or
snapshot, and build_stream of MarketDepthModel or
OrderBookModel::into_stream yields BookSides, the
whole book after a change. A model stream never splits an item: when its consumer lags, a snapshot drops the
buffered transactions of its source and a book replaces the buffered book, and otherwise the buffer grows. It ends
as an event stream does.
§Errors
Every fallible call returns Result. A Java exception becomes Error::Java with its class, message, stack
trace and causes; invalid arguments, such as strings with NUL bytes, are rejected before any SDK call. A wait that
times out returns Error::Timeout.
§Closing and exit
Close an endpoint with DXEndpoint::close_and_await_termination, which waits for the notifications already
scheduled, or with DXEndpoint::close, which does not; dropping its last handle closes it as well. The process
may also exit with open endpoints and running listeners: from the moment it starts exiting, listeners are no longer
called and destructors no longer call the SDK.
system::shutdown is an advanced function with no counterpart in the other dxFeed APIs: it stops all listeners
and closes all endpoints of the process, the default one included; afterwards nothing new can be created.
§Deployment
The SDK library is linked dynamically and must be found at run time; see the README of the repository.
Re-exports§
pub use event::Event;pub use event::EventKind;pub use event::EventRef;pub use event::EventType;pub use event::Events;pub use event::SubscriptionItem;
Modules§
- event
- Market events: borrowed views passed to listeners and owned values for publishing.
- event_
queue - Event queues: the events of subscriptions pulled on a thread of the application, without listeners.
- feed_
filter - Feed filters: named categories of QD filter expressions that a subscription or an event passes (experimental).
- glossary
- The glossary of instrument attributes (
com.dxfeed.glossary): the text values of anInstrumentProfile, such as itsprice_incrementsandadditional_underlyings, as typed values, and theCficode of itscfiwith the meanings of its letters. - history
- The history service: the time series events of a symbol for a period, such as candles and time and sales, over HTTP.
- ipf
- Instrument profiles (
com.dxfeed.ipf): the reference data of instruments in the Instrument Profile Format, read from files and URLs, written to files and memory, followed live withliveand arranged into option chains withoption. - logging
- The log of the SDK (
InterceptableLogging). - model
- Transactional models of indexed and time-series events (
IndexedTxModel,TimeSeriesTxModel): a model subscribes to the events of a symbol and passes them to its listener in whole transactions and snapshots only. - ondemand
- On-demand historical data replay (
com.dxfeed.ondemand). - orcs
- The Order Reconstruction Service (
com.dxfeed.orcs): the price levels and the quotes of a symbol for a period. - qds
- The QDS tools of the SDK (Java
com.devexperts.qd.tools.Tools): the symbol list parser and the runner of the qds-tools, such asconnect,dumporhelp. - schedule
- Trading schedules (
com.dxfeed.schedule): the trading days of an instrument and their sessions. - system
- Java system properties of the SDK, its version and features, and its shutdown.
Structs§
- AnyOf
- The first of several promises to be done, from
Promises::any_of: it is done when one of them is, and its result is the index and the result of that one. - AnyOf
Future - The future of an
AnyOf:any_of.awaitgives the index and the result of the first promise done, asAnyOf::get_resultdoes, without blocking a thread. - Auth
Token - An authorization token: a scheme and a value, as the HTTP
Authorizationheader carries them (AuthToken). - Connection
Error - A connection error of a
MessageConnector: a failed connect or a dropped connection; seeMessageConnector::get_last_errorandDXEndpoint::get_last_connection_error. - DXEndpoint
- A connection to a data source or a local hub (
DXEndpoint). - DXEndpoint
Builder - Builds a
DXEndpoint; seeDXEndpoint::new_builder. - DXFeed
- The feed of a
DXEndpoint: creates subscriptions to events and returns the last events of theLastingEventtypes (DXFeed). - DXFeed
Subscription - A subscription of a
DXFeedto events for some symbols (DXFeedSubscription). - DXFeed
Time Series Subscription - A subscription to the time-series events of type
Efrom a time on (DXFeedTimeSeriesSubscription), created withDXFeed::create_time_series_subscriptionor, for several event types andEvent,DXFeed::create_time_series_subscription_with_types. - DXPublisher
- The publisher of a
DXEndpoint: publishes events to its subscribers (DXPublisher). - Error
Info - An error without a caller, reported to
ErrorManager(ErrorInfo). A value: copies do not change whenErrorManagergets new errors. - Event
Stream - The events of a subscription as owned events, taken with
nextin async code or, with the cargo featurestream, through thefutures_core::Streamtrait (StreamExtoffuturesortokio-stream). - Executor
- An executor of Java that runs the tasks of an endpoint, listener calls included (
java.util.concurrent.Executor). - Java
Exception - A copy of a Java exception thrown by the SDK.
- Listener
Id - Identifies a listener added by
DXFeedSubscription::add_event_listener, anadd_change_listenermethod orDXEndpoint::add_state_listener. - Manual
Executor - An executor that runs the tasks of an endpoint, listener calls included, only inside
process_all_pending, on the calling thread. - Message
Connector - A message connector of an endpoint (
MessageConnector): one per address of the address string that the endpoint is connected to, such as two for(host1:7300)(host2:7300); seeDXEndpoint::get_connectors. - Message
Connector Statistics - The statistics of a
MessageConnectorat one moment; seeMessageConnector::get_statistics. - Observable
Subscription - The subscription of a
DXPublisherto the events of one type, whose change listeners learn the symbols that the subscribers of the publisher ask for (ObservableSubscription); created withDXPublisher::get_subscription. - Promise
- The result of a feed request that becomes known later (
Promise): an event ofDXFeed::get_last_event_promise, or aVecof events ofDXFeed::get_time_series_promiseandDXFeed::get_indexed_events_promise.Promise::newcreates one that the application completes, andPromise::failedone that has failed. - Promise
Future - The future of a
Promise:promise.awaitgives its result asPromise::get_resultdoes, without blocking a thread. - Stream
Options - How an
EventStreamgets the events of its subscription and buffers those that wait to be taken. - Subscription
Controller - The controller of a subscription (
SubscriptionController): it attaches the subscription to feeds and detaches it, and changes how the events are delivered. Experimental in Java and in the SDK. - Tagged
Event Stream - The events of the subscriptions attached to a
SharedEventQueue, each with the tag of its subscription, as owned events for async code: taken withnextor, with the cargo featurestream, through thefutures_core::Streamtrait. - Time
Format - Parses and formats times as the Java
TimeFormatof the SDK does; times are milliseconds since the Unix epoch. - Time
Period - A period of time in milliseconds, as Java’s
TimePeriod. - Time
Period Info - The bounds of the aggregation periods that a server applies or that were applied to delivered events, in
milliseconds, as Java’s
TimePeriodInfo. - Time
Zone - A time zone of Java, as
java.util.TimeZone; offsets are in milliseconds and times in milliseconds since the Unix epoch.
Enums§
- Connection
Error Category - The category of a
ConnectionError. - Error
- An error of an SDK call.
- Error
Manager - Receives the errors that have no caller (
ErrorManager). - Java
Exception Class - A class of the Java exceptions that
Promise::complete_exceptionallyandPromise::failedcreate: the fixed set that the SDK creates without reflection. - Message
Connector Kind - The kind of a
MessageConnector; seeMessageConnector::get_kind. - Message
Connector State - The state of a
MessageConnector(MessageConnectorState); seeMessageConnector::get_state. - Promises
- The combinations of promises (
Promises). - Role
- The role of an endpoint (
DXEndpoint.Role). - State
- The state of an endpoint (
DXEndpoint.State); seeDXEndpoint::get_state. - Symbol
- A symbol that a subscription adds or removes, or that a feed request takes.
Traits§
- Observable
- The members of Java’s
ObservableSubscriptioninterface, whichDXFeedSubscription,DXFeedTimeSeriesSubscriptionandObservableSubscriptionhave: code generic over this trait works with all of them. - Observable
Subscription Change Listener - A listener of the symbols of a subscription (
ObservableSubscriptionChangeListener). - Promise
Result - What a
Promisecompletes with: aLastingEvent, aVecof anIndexedEventtype, or()forPromises::all_of.
Type Aliases§
- Result
- The result of a fallible call.