use crate::presentation::order::Status;
use pretty_simple_display::{DebugPretty, DisplaySimple};
use regex::Regex;
use serde::{Deserialize, Deserializer, Serialize};
use tracing::warn;
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize, PartialEq)]
pub struct ParsedOptionInfo {
pub asset_name: String,
pub strike: Option<String>,
pub option_type: Option<String>,
}
#[derive(DebugPretty, DisplaySimple, Clone, Serialize, Deserialize)]
pub struct ParsedMarketData {
pub epic: String,
pub instrument_name: String,
pub expiry: String,
pub asset_name: String,
pub strike: Option<String>,
pub option_type: Option<String>,
}
impl ParsedMarketData {
pub fn is_call(&self) -> bool {
self.instrument_name.contains("CALL")
}
pub fn is_put(&self) -> bool {
self.instrument_name.contains("PUT")
}
}
pub fn normalize_text(text: &str) -> String {
if text.contains("Japón") {
return text.replace("Japón", "Japan");
}
let mut result = String::with_capacity(text.len());
for c in text.chars() {
match c {
'á' | 'à' | 'ä' | 'â' | 'ã' => result.push('a'),
'é' | 'è' | 'ë' | 'ê' => result.push('e'),
'í' | 'ì' | 'ï' | 'î' => result.push('i'),
'ó' | 'ò' | 'ö' | 'ô' | 'õ' => result.push('o'),
'ú' | 'ù' | 'ü' | 'û' => result.push('u'),
'ñ' => result.push('n'),
'ç' => result.push('c'),
'Á' | 'À' | 'Ä' | 'Â' | 'Ã' => result.push('A'),
'É' | 'È' | 'Ë' | 'Ê' => result.push('E'),
'Í' | 'Ì' | 'Ï' | 'Î' => result.push('I'),
'Ó' | 'Ò' | 'Ö' | 'Ô' | 'Õ' => result.push('O'),
'Ú' | 'Ù' | 'Ü' | 'Û' => result.push('U'),
'Ñ' => result.push('N'),
'Ç' => result.push('C'),
_ => result.push(c),
}
}
result
}
pub fn parse_instrument_name(instrument_name: &str) -> ParsedOptionInfo {
lazy_static::lazy_static! {
static ref OPTION_PATTERN: Regex = Regex::new(r"^(.*?)\s+(\d+(?:\.\d+)?)\s+(CALL|PUT)(?:\s+\(.*?\))?$").expect("valid option regex");
static ref DECIMAL_OPTION_PATTERN: Regex = Regex::new(r"^(.*?)\s+(\d+\.\d+)\s+(CALL|PUT)(?:\s+\(.*?\))?$").expect("valid decimal option regex");
static ref SPECIAL_OPTION_PATTERN: Regex = Regex::new(r"^(.*?)\s+\(([^)]+)\)(\d+)\s+(CALL|PUT)(?:\s+\(.*?\))?$").expect("valid special option regex");
static ref INCOMPLETE_PAREN_PATTERN: Regex = Regex::new(r"^(.*?)\s+(\d+(?:\.\d+)?)\s+(CALL|PUT)\s+\([^)]*$").expect("valid incomplete paren regex");
static ref GENERIC_PATTERN: Regex = Regex::new(r"^(.*?)(?:\s+\(.*?\))?$").expect("valid generic regex");
static ref DAILY_WEEKLY_PATTERN: Regex = Regex::new(r"^(Daily|Weekly)\s+(.*?)$").expect("valid daily/weekly regex");
static ref END_OF_MONTH_PATTERN: Regex = Regex::new(r"^(End of Month)\s+(.*?)$").expect("valid end-of-month regex");
static ref QUARTERLY_PATTERN: Regex = Regex::new(r"^(Quarterly)\s+(.*?)$").expect("valid quarterly regex");
static ref MONTHLY_PATTERN: Regex = Regex::new(r"^(Monthly)\s+(.*?)$").expect("valid monthly regex");
static ref SUFFIX_PATTERN: Regex = Regex::new(r"^(.*?)\s+\(.*?\)$").expect("valid suffix regex");
}
fn clean_asset_name(asset_name: &str) -> String {
let normalized_name = normalize_text(asset_name);
let asset_name = if let Some(captures) = DAILY_WEEKLY_PATTERN.captures(&normalized_name) {
captures.get(2).map_or("", |m| m.as_str()).trim()
} else if let Some(captures) = END_OF_MONTH_PATTERN.captures(&normalized_name) {
captures.get(2).map_or("", |m| m.as_str()).trim()
} else if let Some(captures) = QUARTERLY_PATTERN.captures(&normalized_name) {
captures.get(2).map_or("", |m| m.as_str()).trim()
} else if let Some(captures) = MONTHLY_PATTERN.captures(&normalized_name) {
captures.get(2).map_or("", |m| m.as_str()).trim()
} else {
&normalized_name
};
let asset_name = if let Some(captures) = SUFFIX_PATTERN.captures(asset_name) {
captures.get(1).map_or("", |m| m.as_str()).trim()
} else {
asset_name
};
asset_name.to_string()
}
if let Some(captures) = OPTION_PATTERN.captures(instrument_name) {
let asset_name = captures.get(1).map_or("", |m| m.as_str()).trim();
ParsedOptionInfo {
asset_name: clean_asset_name(asset_name),
strike: captures.get(2).map(|m| m.as_str().to_string()),
option_type: captures.get(3).map(|m| m.as_str().to_string()),
}
} else if let Some(captures) = SPECIAL_OPTION_PATTERN.captures(instrument_name) {
let base_name = captures.get(1).map_or("", |m| m.as_str()).trim();
ParsedOptionInfo {
asset_name: clean_asset_name(base_name),
strike: captures.get(3).map(|m| m.as_str().to_string()),
option_type: captures.get(4).map(|m| m.as_str().to_string()),
}
} else if let Some(captures) = INCOMPLETE_PAREN_PATTERN.captures(instrument_name) {
let asset_name = captures.get(1).map_or("", |m| m.as_str()).trim();
ParsedOptionInfo {
asset_name: clean_asset_name(asset_name),
strike: captures.get(2).map(|m| m.as_str().to_string()),
option_type: captures.get(3).map(|m| m.as_str().to_string()),
}
} else if let Some(captures) = DECIMAL_OPTION_PATTERN.captures(instrument_name) {
let asset_name = captures.get(1).map_or("", |m| m.as_str()).trim();
ParsedOptionInfo {
asset_name: clean_asset_name(asset_name),
strike: captures.get(2).map(|m| m.as_str().to_string()),
option_type: captures.get(3).map(|m| m.as_str().to_string()),
}
} else if let Some(captures) = GENERIC_PATTERN.captures(instrument_name) {
let asset_name = captures.get(1).map_or("", |m| m.as_str()).trim();
ParsedOptionInfo {
asset_name: clean_asset_name(asset_name),
strike: None,
option_type: None,
}
} else {
warn!("Could not parse instrument name: {}", instrument_name);
ParsedOptionInfo {
asset_name: instrument_name.to_string(),
strike: None,
option_type: None,
}
}
}
pub fn deserialize_null_as_empty_vec<'de, D, T>(deserializer: D) -> Result<Vec<T>, D::Error>
where
D: serde::Deserializer<'de>,
T: serde::Deserialize<'de>,
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or_default())
}
pub fn deserialize_nullable_status<'de, D>(deserializer: D) -> Result<Status, D::Error>
where
D: Deserializer<'de>,
{
let opt = Option::deserialize(deserializer)?;
Ok(opt.unwrap_or(Status::Open))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_parse_instrument_name_standard_option() {
let info = parse_instrument_name("US Tech 100 19200 CALL ($1)");
assert_eq!(info.asset_name, "US Tech 100");
assert_eq!(info.strike, Some("19200".to_string()));
assert_eq!(info.option_type, Some("CALL".to_string()));
}
#[test]
fn test_parse_instrument_name_decimal_strike() {
let info = parse_instrument_name("Volatility Index 10.5 PUT ($1)");
assert_eq!(info.asset_name, "Volatility Index");
assert_eq!(info.strike, Some("10.5".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_no_option() {
let info = parse_instrument_name("Germany 40");
assert_eq!(info.asset_name, "Germany 40");
assert_eq!(info.strike, None);
assert_eq!(info.option_type, None);
}
#[test]
fn test_parse_instrument_name_with_parenthesis() {
let info = parse_instrument_name("US 500 (Mini)");
assert_eq!(info.asset_name, "US 500");
assert_eq!(info.strike, None);
assert_eq!(info.option_type, None);
}
#[test]
fn test_parse_instrument_name_special_format() {
let info = parse_instrument_name("Weekly Germany 40 (Wed)27500 PUT");
assert_eq!(info.asset_name, "Germany 40");
assert_eq!(info.strike, Some("27500".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_daily_prefix() {
let info = parse_instrument_name("Daily Germany 40 24225 CALL");
assert_eq!(info.asset_name, "Germany 40");
assert_eq!(info.strike, Some("24225".to_string()));
assert_eq!(info.option_type, Some("CALL".to_string()));
}
#[test]
fn test_parse_instrument_name_weekly_prefix() {
let info = parse_instrument_name("Weekly US Tech 100 19200 CALL");
assert_eq!(info.asset_name, "US Tech 100");
assert_eq!(info.strike, Some("19200".to_string()));
assert_eq!(info.option_type, Some("CALL".to_string()));
}
#[test]
fn test_parse_instrument_name_end_of_month_prefix() {
let info = parse_instrument_name("End of Month EU Stocks 50 4575 PUT");
assert_eq!(info.asset_name, "EU Stocks 50");
assert_eq!(info.strike, Some("4575".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_end_of_month_suffix() {
let info = parse_instrument_name("US 500 (End of Month) 3200 PUT");
assert_eq!(info.asset_name, "US 500");
assert_eq!(info.strike, Some("3200".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_quarterly_prefix() {
let info = parse_instrument_name("Quarterly GBPUSD 10000 PUT ($1)");
assert_eq!(info.asset_name, "GBPUSD");
assert_eq!(info.strike, Some("10000".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_weekly_with_day() {
let info = parse_instrument_name("Weekly Germany 40 (Mon) 18500 PUT");
assert_eq!(info.asset_name, "Germany 40");
assert_eq!(info.strike, Some("18500".to_string()));
assert_eq!(info.option_type, Some("PUT".to_string()));
}
#[test]
fn test_parse_instrument_name_incomplete_parenthesis() {
let info = parse_instrument_name("Weekly USDJPY 12950 CALL (Y100");
assert_eq!(info.asset_name, "USDJPY");
assert_eq!(info.strike, Some("12950".to_string()));
assert_eq!(info.option_type, Some("CALL".to_string()));
}
#[test]
fn test_parse_instrument_name_with_accents() {
let info = parse_instrument_name("Japón 225 18500 CALL");
assert_eq!(info.asset_name, "Japan 225");
assert_eq!(info.strike, Some("18500".to_string()));
assert_eq!(info.option_type, Some("CALL".to_string()));
}
}