BinaryOptionsToolsV1 icon indicating copy to clipboard operation
BinaryOptionsToolsV1 copied to clipboard

Test 4

Open Rick-29 opened this issue 2 years ago • 0 comments

Example issue body

use evalexpr::{build_operator_tree, eval_empty_with_context_mut, HashMapContext, Node};
use once_cell::sync::Lazy;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use std::collections::HashMap;
use std::fmt;
use std::ops::Div;

use pyo3::prelude::*;

static ACTION_MAP: Lazy<HashMap<&'static str, i16>> = Lazy::new(|| {
    HashMap::from([
        ("STRONG_BUY", 2),
        ("BUY", 1),
        ("HOLD", 0),
        ("NEUTRAL", 0),
        ("SELL", -1),
        ("STRONG_SELL", -2),
    ])
});

static ACTIONS: Lazy<String> = Lazy::new(|| {
    ACTION_MAP.iter().fold(String::new(), |acc, (key, value)| {
        acc + key + "=" + &value.to_string() + ";"
    })
});

#[derive(Default)]
pub enum Action {
    StrongBuy,
    Buy,
    #[default]
    Hold,
    Sell,
    StrongSell,
}

#[pyclass]
#[derive(Debug)]
pub enum Strategy { // TODO: Implement custom Deserialize and Serialize implementations to serialize and deserialize the strategy struct
    Simple(Strat),
    Cluster(Vec<Strat>),
}

#[pyclass]
#[derive(Debug, Clone)]
pub struct Strat {
    name: String,
    indicators: HashMap<String, Value>,
    buy: Option<Node>,
    sell: Option<Node>,
    raw: String,
}

impl Strat {
    pub fn from_json(json: String) -> anyhow::Result<Self> {
        let value: Value = serde_json::from_str(&json)?;
        Self::from_value(value)
    }

    pub fn from_value(value: Value) -> anyhow::Result<Self> {
        let name = value
            .get("name")
            .and_then(|v| v.as_str())
            .unwrap_or_default()
            .to_string();
        let indicators = value
            .get("indicators")
            .and_then(Value::as_object)
            .ok_or_else(|| anyhow::anyhow!("Missing 'indicators' field"))?;
        let buy = value.get("buy").and_then(|v| v.as_str());

        let sell = value.get("sell").and_then(|v| v.as_str());

        let indicators = indicators
            .iter()
            .map(|(k, v)| (k.clone(), v.clone()))
            .collect::<HashMap<String, Value>>();
        let buy = match buy {
            Some(buy) => Some(build_operator_tree(buy)?),
            None => None,
        };
        let sell = match sell {
            Some(sell) => Some(build_operator_tree(sell)?),
            None => None,
        };

        let raw = serde_json::to_string_pretty(&value)?;

        Ok(Self {
            name,
            indicators,
            buy,
            sell,
            raw,
        })
    }

    fn buy(&self, context: &HashMapContext) -> anyhow::Result<bool> {
        match &self.buy {
            Some(buy) => buy
                .eval_boolean_with_context(context)
                .map_err(anyhow::Error::from),
            None => Ok(false),
        }
    }

    fn sell(&self, context: &HashMapContext) -> anyhow::Result<bool> {
        match &self.sell {
            Some(sell) => sell
                .eval_boolean_with_context(context)
                .map_err(anyhow::Error::from),
            None => Ok(false),
        }
    }

    pub fn evaluate(&self, context: &HashMapContext) -> anyhow::Result<Action> {
        if self.buy(context)? {
            Ok(Action::Buy)
        } else if self.sell(context)? {
            Ok(Action::Sell)
        } else {
            Ok(Action::Hold)
        }
    }
}

impl Action {
    pub fn to_float(&self) -> f32 {
        match self {
            Action::StrongBuy => 2.0,
            Action::Buy => 1.0,
            Action::Hold => 0.0,
            Action::Sell => -1.0,
            Action::StrongSell => -2.0,
        }
    }
}

impl fmt::Display for Action {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Action::StrongBuy => write!(f, "STRONG_BUY"),
            Action::Buy => write!(f, "BUY"),
            Action::Hold => write!(f, "HOLD"),
            Action::Sell => write!(f, "SELL"),
            Action::StrongSell => write!(f, "STRONG_SELL"),
        }
    }
}

impl Strategy {
    pub fn from_json(value: String) -> anyhow::Result<Self> {
        let value: Value = serde_json::from_str(&value)?;
        if value.as_array().is_some() {
            let arr: &Vec<Value> = value.as_array().expect("Unreachable");
            let strategies = arr
                .iter()
                .cloned()
                .filter_map(|val| Strat::from_value(val).ok())
                .collect::<Vec<Strat>>();
            if strategies.is_empty() {
                return Err(anyhow::Error::msg(
                    "Couldn't parse any value into a Strategy",
                ));
            }
            Ok(Self::Cluster(strategies))
        } else {
            let strategy = Strat::from_value(value)?;
            Ok(Self::Simple(strategy))
        }
    }

    pub fn get_context(
        &self,
        values: &HashMap<String, impl ToString>,
    ) -> anyhow::Result<HashMapContext> {
        let mut context = HashMapContext::new();
        let values =
            values.iter().map(
                |(key, value)| match ACTION_MAP.get(&value.to_string().as_ref()) {
                    Some(num) => (key.clone(), num.to_string()),
                    None => (key.clone(), value.to_string()),
                },
            );
        let mut result = values.fold(String::new(), |a, (key, value)| {
            a + key.as_str() + "=" + value.as_str() + ";"
        });
        result.push_str(&ACTIONS);
        let _ = eval_empty_with_context_mut(&result, &mut context);
        Ok(context)
    }

    pub fn eval(&self, context: HashMap<String, impl ToString>) -> anyhow::Result<String> {
        let context = self.get_context(&context)?;
        match &self {
            Strategy::Simple(strategy) => {
                let pred = strategy.evaluate(&context)?;
                Ok(pred.to_string())
            }
            Strategy::Cluster(strategies) => {
                let res = strategies
                    .iter()
                    .filter_map(|st| st.evaluate(&context).ok())
                    .map(|act| act.to_float())
                    .collect::<Vec<f32>>();
                if res.is_empty() {
                    return Err(anyhow::Error::msg(
                        "Strategy error, no strategy evaluated successfully",
                    ));
                }
                let length = res.len();
                let result = res.into_iter().sum::<f32>().div(length as f32);
                if result > 1.0 {
                    Ok(Action::StrongBuy.to_string())
                } else if result > 0.5 {
                    Ok(Action::Buy.to_string())
                } else if result < -1.0 {
                    Ok(Action::StrongSell.to_string())
                } else if result < -0.5 {
                    Ok(Action::Sell.to_string())
                } else {
                    Ok(Action::default().to_string())
                }
            }
        }
    }

    pub fn get_indicators(&self) -> HashMap<String, Value> {
        match self {
            Strategy::Simple(strategy) => strategy.indicators.clone(),
            Strategy::Cluster(strategies) => {
                let mut indicators = HashMap::new();
                strategies
                    .iter()
                    .cloned()
                    .for_each(|st| indicators.extend(st.indicators));
                indicators
            }
        }
    }

    pub fn get_strategy(&self) -> anyhow::Result<String> {
        match self {
            Self::Simple(strategy) => Ok(strategy.raw.clone()),
            Self::Cluster(strategies) => {
                let raw_strategies = strategies
                    .iter()
                    .map(|st| st.raw.as_str())
                    .collect::<Vec<&str>>();
                serde_json::to_string(&raw_strategies).map_err(anyhow::Error::from)
            }
        }
    }

    pub fn name(&self) -> String {
        match self {
            Self::Cluster(strats) => strats
                .iter()
                .fold(String::new(), |mut names, s| {
                    names.push_str(&format!(" {}", s.name));
                    names
                })
                .trim()
                .to_owned(), // Convert to owned String
            Self::Simple(strat) => strat.name.clone(), // Assuming Strat::name is Clone
        }
    }
}

// #[pymethods]
// impl Strategy {
//     #[new]
//     fn new(json: String) -> PyResult<Self> {
//         let strategy: Strategy = serde_json::from_str(&json).map_err(|e| anyhow::anyhow!("{}", e).into())?;


//     }
// }

Rick-29 avatar Nov 18 '24 00:11 Rick-29