#![allow(dead_code)]
use std::fmt;
use std::future::Future;
use std::sync::{Mutex, PoisonError};
use std::time::Duration;
use ctrader_connector::common::decimals::Price;
use ctrader_connector::common::errors::ConnectorError;
use ctrader_connector::common::time::Timestamp;
use rust_decimal::Decimal;
#[cfg(feature = "fix")]
pub mod fix;
pub mod guard;
#[cfg(feature = "open-api")]
pub mod open_api;
pub const ENV_SYMBOL: &str = "BROKER_EXAMPLE_SYMBOL";
pub const DEFAULT_SYMBOL: &str = "BTCUSD";
pub const STEP: Duration = Duration::from_secs(30);
pub const QUOTES: Duration = Duration::from_secs(90);
static KNOWN: Mutex<Vec<String>> = Mutex::new(Vec::new());
pub fn veil(identifier: impl fmt::Display) {
let identifier = identifier.to_string();
if !identifier.is_empty() {
KNOWN
.lock()
.unwrap_or_else(PoisonError::into_inner)
.push(identifier);
}
}
fn veiled(text: &str) -> String {
KNOWN
.lock()
.unwrap_or_else(PoisonError::into_inner)
.iter()
.fold(text.to_owned(), |text, known| {
text.replace(known, "<account>")
})
}
pub struct Failure(String);
impl Failure {
pub fn new(message: impl Into<String>) -> Self {
Self(message.into())
}
}
impl fmt::Debug for Failure {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&veiled(&self.0))
}
}
impl From<guard::Refusal> for Failure {
fn from(refusal: guard::Refusal) -> Self {
Self(refusal.to_string())
}
}
impl<E: Into<ConnectorError>> From<E> for Failure {
fn from(error: E) -> Self {
let error = error.into();
Self(format!("{}: {error}", kind(&error)))
}
}
const fn kind(error: &ConnectorError) -> &'static str {
match error {
ConnectorError::Config(_) => "Config",
ConnectorError::Server(_) => "Server",
ConnectorError::Value(_) => "Value",
ConnectorError::Transport(_) => "Transport",
ConnectorError::Token(_) => "Token",
ConnectorError::Fix(_) => "Fix",
ConnectorError::Timeout(_) => "Timeout",
ConnectorError::OutcomeUnknown(_) => "OutcomeUnknown",
ConnectorError::SessionEnded(_) => "SessionEnded",
ConnectorError::Closed => "Closed",
ConnectorError::Lagged { .. } => "Lagged",
ConnectorError::Incomplete { .. } => "Incomplete",
ConnectorError::UnexpectedResponse { .. } => "UnexpectedResponse",
_ => "Other",
}
}
pub async fn within<T>(
limit: Duration,
what: &str,
work: impl Future<Output = T>,
) -> Result<T, Failure> {
tokio::time::timeout(limit, work)
.await
.map_err(|_| Failure::new(format!("{what} did not arrive within {limit:?}")))
}
pub fn setting(name: &str, default: &str) -> String {
std::env::var(name)
.ok()
.filter(|value| !value.trim().is_empty())
.unwrap_or_else(|| default.to_owned())
}
pub fn flag(argument: &str, variable: &str) -> bool {
std::env::args().any(|given| given == argument)
|| matches!(setting(variable, "").as_str(), "1" | "true" | "yes")
}
pub fn symbol_name() -> String {
setting(ENV_SYMBOL, DEFAULT_SYMBOL)
}
pub fn run_label(group: &str) -> String {
format!("example-{group}-{}", Timestamp::now())
}
pub fn scaled(price: Price, percent: i64, digits: u32) -> Result<Price, Failure> {
let scaled = price
.value()
.checked_mul(Decimal::new(percent, 2))
.ok_or_else(|| Failure::new("the scaled price is out of range"))?
.round_dp(digits);
Ok(Price::new(scaled)?)
}
pub fn seconds_from_now(seconds: i64) -> Result<Timestamp, Failure> {
let second = Timestamp::now().as_millis() / 1_000 + seconds;
Ok(Timestamp::from_millis(second * 1_000)?)
}