Skip to main content

Crate dxfeed_graal

Crate dxfeed_graal 

Source
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.

§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 an InstrumentProfile, such as its price_increments and additional_underlyings, as typed values, and the Cfi code of its cfi with 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 with live and arranged into option chains with option.
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 as connect, dump or help.
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.
AnyOfFuture
The future of an AnyOf: any_of.await gives the index and the result of the first promise done, as AnyOf::get_result does, without blocking a thread.
AuthToken
An authorization token: a scheme and a value, as the HTTP Authorization header carries them (AuthToken).
ConnectionError
A connection error of a MessageConnector: a failed connect or a dropped connection; see MessageConnector::get_last_error and DXEndpoint::get_last_connection_error.
DXEndpoint
A connection to a data source or a local hub (DXEndpoint).
DXEndpointBuilder
Builds a DXEndpoint; see DXEndpoint::new_builder.
DXFeed
The feed of a DXEndpoint: creates subscriptions to events and returns the last events of the LastingEvent types (DXFeed).
DXFeedSubscription
A subscription of a DXFeed to events for some symbols (DXFeedSubscription).
DXFeedTimeSeriesSubscription
A subscription to the time-series events of type E from a time on (DXFeedTimeSeriesSubscription), created with DXFeed::create_time_series_subscription or, for several event types and Event, DXFeed::create_time_series_subscription_with_types.
DXPublisher
The publisher of a DXEndpoint: publishes events to its subscribers (DXPublisher).
ErrorInfo
An error without a caller, reported to ErrorManager (ErrorInfo). A value: copies do not change when ErrorManager gets new errors.
EventStream
The events of a subscription as owned events, taken with next in async code or, with the cargo feature stream, through the futures_core::Stream trait (StreamExt of futures or tokio-stream).
Executor
An executor of Java that runs the tasks of an endpoint, listener calls included (java.util.concurrent.Executor).
JavaException
A copy of a Java exception thrown by the SDK.
ListenerId
Identifies a listener added by DXFeedSubscription::add_event_listener, an add_change_listener method or DXEndpoint::add_state_listener.
ManualExecutor
An executor that runs the tasks of an endpoint, listener calls included, only inside process_all_pending, on the calling thread.
MessageConnector
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); see DXEndpoint::get_connectors.
MessageConnectorStatistics
The statistics of a MessageConnector at one moment; see MessageConnector::get_statistics.
ObservableSubscription
The subscription of a DXPublisher to the events of one type, whose change listeners learn the symbols that the subscribers of the publisher ask for (ObservableSubscription); created with DXPublisher::get_subscription.
Promise
The result of a feed request that becomes known later (Promise): an event of DXFeed::get_last_event_promise, or a Vec of events of DXFeed::get_time_series_promise and DXFeed::get_indexed_events_promise. Promise::new creates one that the application completes, and Promise::failed one that has failed.
PromiseFuture
The future of a Promise: promise.await gives its result as Promise::get_result does, without blocking a thread.
StreamOptions
How an EventStream gets the events of its subscription and buffers those that wait to be taken.
SubscriptionController
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.
TaggedEventStream
The events of the subscriptions attached to a SharedEventQueue, each with the tag of its subscription, as owned events for async code: taken with next or, with the cargo feature stream, through the futures_core::Stream trait.
TimeFormat
Parses and formats times as the Java TimeFormat of the SDK does; times are milliseconds since the Unix epoch.
TimePeriod
A period of time in milliseconds, as Java’s TimePeriod.
TimePeriodInfo
The bounds of the aggregation periods that a server applies or that were applied to delivered events, in milliseconds, as Java’s TimePeriodInfo.
TimeZone
A time zone of Java, as java.util.TimeZone; offsets are in milliseconds and times in milliseconds since the Unix epoch.

Enums§

ConnectionErrorCategory
The category of a ConnectionError.
Error
An error of an SDK call.
ErrorManager
Receives the errors that have no caller (ErrorManager).
JavaExceptionClass
A class of the Java exceptions that Promise::complete_exceptionally and Promise::failed create: the fixed set that the SDK creates without reflection.
MessageConnectorKind
The kind of a MessageConnector; see MessageConnector::get_kind.
MessageConnectorState
The state of a MessageConnector (MessageConnectorState); see MessageConnector::get_state.
Promises
The combinations of promises (Promises).
Role
The role of an endpoint (DXEndpoint.Role).
State
The state of an endpoint (DXEndpoint.State); see DXEndpoint::get_state.
Symbol
A symbol that a subscription adds or removes, or that a feed request takes.

Traits§

Observable
The members of Java’s ObservableSubscription interface, which DXFeedSubscription, DXFeedTimeSeriesSubscription and ObservableSubscription have: code generic over this trait works with all of them.
ObservableSubscriptionChangeListener
A listener of the symbols of a subscription (ObservableSubscriptionChangeListener).
PromiseResult
What a Promise completes with: a LastingEvent, a Vec of an IndexedEvent type, or () for Promises::all_of.

Type Aliases§

Result
The result of a fallible call.