Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

#101 Optional server time #106

Merged
merged 3 commits into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion examples/contract_details.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ fn main() -> anyhow::Result<()> {
let client = Client::connect("127.0.0.1:4002", 100)?;

println!("server_version: {}", client.server_version());
println!("connection_time: {}", client.connection_time());
println!("connection_time: {:?}", client.connection_time());
println!("managed_accounts: {}", client.managed_accounts());
println!("next_order_id: {}", client.next_order_id());

Expand Down
2 changes: 1 addition & 1 deletion examples/stream_bars.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ fn main() -> anyhow::Result<()> {
let client = Client::connect("127.0.0.1:4002", 100).unwrap();

println!("server_version: {}", client.server_version());
println!("server_time: {}", client.connection_time());
println!("server_time: {:?}", client.connection_time());
println!("managed_accounts: {}", client.managed_accounts());
println!("next_order_id: {}", client.next_order_id());

Expand Down
45 changes: 30 additions & 15 deletions src/client.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,8 +35,8 @@ pub struct Client {
pub(crate) server_version: i32,
/// IB Server time
// pub server_time: OffsetDateTime,
pub(crate) connection_time: OffsetDateTime,
pub(crate) time_zone: &'static Tz,
pub(crate) connection_time: Option<OffsetDateTime>,
pub(crate) time_zone: Option<&'static Tz>,

managed_accounts: String,
client_id: i32, // ID of client.
Expand All @@ -62,7 +62,7 @@ impl Client {
/// let client = Client::connect("127.0.0.1:4002", 100).expect("connection failed");
///
/// println!("server_version: {}", client.server_version());
/// println!("connection_time: {}", client.connection_time());
/// println!("connection_time: {:?}", client.connection_time());
/// println!("managed_accounts: {}", client.managed_accounts());
/// println!("next_order_id: {}", client.next_order_id());
/// ```
Expand All @@ -74,8 +74,8 @@ impl Client {
fn do_connect(client_id: i32, message_bus: RefCell<Box<dyn MessageBus>>) -> Result<Client, Error> {
let mut client = Client {
server_version: 0,
connection_time: OffsetDateTime::now_utc(),
time_zone: time_tz::timezones::db::UTC,
connection_time: None,
time_zone: None,
managed_accounts: String::from(""),
message_bus,
client_id,
Expand Down Expand Up @@ -200,8 +200,8 @@ impl Client {
}

/// The time of the server when the client connected
pub fn connection_time(&self) -> &OffsetDateTime {
&self.connection_time
pub fn connection_time(&self) -> Option<OffsetDateTime> {
self.connection_time.clone()
}

/// Returns the managed accounts.
Expand Down Expand Up @@ -889,8 +889,8 @@ impl Client {
pub(crate) fn stubbed(message_bus: RefCell<Box<dyn MessageBus>>, server_version: i32) -> Client {
Client {
server_version: server_version,
connection_time: OffsetDateTime::now_utc(),
time_zone: time_tz::timezones::db::UTC,
connection_time: None,
time_zone: None,
managed_accounts: String::from(""),
message_bus,
client_id: 100,
Expand Down Expand Up @@ -964,17 +964,32 @@ impl Debug for Client {
}

// Parses following format: 20230405 22:20:39 PST
fn parse_connection_time(connection_time: &str) -> (OffsetDateTime, &'static Tz) {
fn parse_connection_time(connection_time: &str) -> (Option<OffsetDateTime>, Option<&'static Tz>) {
let parts: Vec<&str> = connection_time.split(' ').collect();

let zones = timezones::find_by_name(parts[2]);
if zones.is_empty() {
error!("time zone not found for {}", parts[2]);
return (None, None);
}

let format = format_description!("[year][month][day] [hour]:[minute]:[second]");
let date = time::PrimitiveDateTime::parse(format!("{} {}", parts[0], parts[1]).as_str(), format).unwrap();
let timezone = zones[0];
match date.assume_timezone(timezone) {
OffsetResult::Some(date) => (date, timezone),
_ => (OffsetDateTime::now_utc(), time_tz::timezones::db::UTC),

let format = format_description!("[year][month][day] [hour]:[minute]:[second]");
let date_str = format!("{} {}", parts[0], parts[1]);
let date = time::PrimitiveDateTime::parse(date_str.as_str(), format);
match date {
Ok(connected_at) => match connected_at.assume_timezone(timezone) {
OffsetResult::Some(date) => (Some(date), Some(timezone)),
_ => {
error!("error setting timezone");
(None, Some(timezone))
}
},
Err(err) => {
error!("could not parse connection time from {date_str}: {err}");
return (None, Some(timezone));
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/client/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,6 @@ fn test_parse_connection_time() {

let la = timezones::db::america::LOS_ANGELES;
if let OffsetResult::Some(other) = datetime!(2023-04-05 22:20:39).assume_timezone(la) {
assert_eq!(connection_time, other);
assert_eq!(connection_time, Some(other));
}
}
11 changes: 9 additions & 2 deletions src/market_data/historical.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
use std::collections::VecDeque;
use std::fmt::Debug;

use log::error;
use log::{error, warn};
use time::{Date, OffsetDateTime};
use time_tz::Tz;

use crate::client::transport::ResponseIterator;
use crate::contracts::Contract;
Expand Down Expand Up @@ -360,8 +361,14 @@ pub(crate) fn historical_data(
let mut messages = client.send_request(request_id, request)?;

if let Some(mut message) = messages.next() {
let time_zone = if let Some(tz) = client.time_zone {
tz
} else {
warn!("server timezone unknown. assuming UTC, but that may be incorrect!");
time_tz::timezones::db::UTC
};
match message.message_type() {
IncomingMessages::HistoricalData => decoders::decode_historical_data(client.server_version, client.time_zone, &mut message),
IncomingMessages::HistoricalData => decoders::decode_historical_data(client.server_version, time_zone, &mut message),
IncomingMessages::Error => Err(Error::Simple(message.peek_string(4))),
_ => Err(Error::Simple(format!("unexpected message: {:?}", message.message_type()))),
}
Expand Down
Loading