/*
 * Binance Algo REST API
 *
 * OpenAPI Specification for the Binance Algo REST API
 *
 * The version of the OpenAPI document: 1.0.0
 *
 *
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

#![allow(unused_imports)]
use async_trait::async_trait;
use derive_builder::Builder;
use reqwest;
use rust_decimal::prelude::*;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::BTreeMap;

use crate::algo::rest_api::models;
use crate::common::{
    config::ConfigurationRestApi,
    models::{ParamBuildError, RestApiResponse},
    utils::send_request,
};

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait SpotAlgoApi: Send + Sync {
    async fn cancel_algo_order_spot_algo(
        &self,
        params: CancelAlgoOrderSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::CancelAlgoOrderSpotAlgoResponse>>;
    async fn query_current_algo_open_orders_spot_algo(
        &self,
        params: QueryCurrentAlgoOpenOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse>>;
    async fn query_historical_algo_orders_spot_algo(
        &self,
        params: QueryHistoricalAlgoOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryHistoricalAlgoOrdersSpotAlgoResponse>>;
    async fn query_sub_orders_spot_algo(
        &self,
        params: QuerySubOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QuerySubOrdersSpotAlgoResponse>>;
    async fn time_weighted_average_price_spot_algo(
        &self,
        params: TimeWeightedAveragePriceSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::TimeWeightedAveragePriceSpotAlgoResponse>>;
}

#[derive(Debug, Clone)]
pub struct SpotAlgoApiClient {
    configuration: ConfigurationRestApi,
}

impl SpotAlgoApiClient {
    pub fn new(configuration: ConfigurationRestApi) -> Self {
        Self { configuration }
    }
}

/// Request parameters for the [`cancel_algo_order_spot_algo`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`cancel_algo_order_spot_algo`](#method.cancel_algo_order_spot_algo).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct CancelAlgoOrderSpotAlgoParams {
    /// eg. 14511
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub algo_id: i64,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl CancelAlgoOrderSpotAlgoParams {
    /// Create a builder for [`cancel_algo_order_spot_algo`].
    ///
    /// Required parameters:
    ///
    /// * `algo_id` — eg. 14511
    ///
    #[must_use]
    pub fn builder(algo_id: i64) -> CancelAlgoOrderSpotAlgoParamsBuilder {
        CancelAlgoOrderSpotAlgoParamsBuilder::default().algo_id(algo_id)
    }
}
/// Request parameters for the [`query_current_algo_open_orders_spot_algo`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_current_algo_open_orders_spot_algo`](#method.query_current_algo_open_orders_spot_algo).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryCurrentAlgoOpenOrdersSpotAlgoParams {
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryCurrentAlgoOpenOrdersSpotAlgoParams {
    /// Create a builder for [`query_current_algo_open_orders_spot_algo`].
    ///
    #[must_use]
    pub fn builder() -> QueryCurrentAlgoOpenOrdersSpotAlgoParamsBuilder {
        QueryCurrentAlgoOpenOrdersSpotAlgoParamsBuilder::default()
    }
}
/// Request parameters for the [`query_historical_algo_orders_spot_algo`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_historical_algo_orders_spot_algo`](#method.query_historical_algo_orders_spot_algo).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryHistoricalAlgoOrdersSpotAlgoParams {
    /// Trading symbol eg. BTCUSDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub symbol: Option<String>,
    /// BUY or SELL
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub side: Option<String>,
    /// in milliseconds  eg.1641522717552
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    /// in milliseconds  eg.1641522526562
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Default is 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    /// MIN 1, MAX 100; Default 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page_size: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryHistoricalAlgoOrdersSpotAlgoParams {
    /// Create a builder for [`query_historical_algo_orders_spot_algo`].
    ///
    #[must_use]
    pub fn builder() -> QueryHistoricalAlgoOrdersSpotAlgoParamsBuilder {
        QueryHistoricalAlgoOrdersSpotAlgoParamsBuilder::default()
    }
}
/// Request parameters for the [`query_sub_orders_spot_algo`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_sub_orders_spot_algo`](#method.query_sub_orders_spot_algo).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QuerySubOrdersSpotAlgoParams {
    /// eg. 14511
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub algo_id: i64,
    /// Default is 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    /// MIN 1, MAX 100; Default 100
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page_size: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QuerySubOrdersSpotAlgoParams {
    /// Create a builder for [`query_sub_orders_spot_algo`].
    ///
    /// Required parameters:
    ///
    /// * `algo_id` — eg. 14511
    ///
    #[must_use]
    pub fn builder(algo_id: i64) -> QuerySubOrdersSpotAlgoParamsBuilder {
        QuerySubOrdersSpotAlgoParamsBuilder::default().algo_id(algo_id)
    }
}
/// Request parameters for the [`time_weighted_average_price_spot_algo`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`time_weighted_average_price_spot_algo`](#method.time_weighted_average_price_spot_algo).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct TimeWeightedAveragePriceSpotAlgoParams {
    /// Trading symbol eg. BTCUSDT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub symbol: String,
    /// Trading side ( BUY or SELL )
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub side: String,
    /// Quantity of base asset; Maximum notional per order is 200k, 2mm or 10mm, depending on symbol. Please reduce your size if you order is above the maximum notional per order.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub quantity: rust_decimal::Decimal,
    /// Duration for TWAP orders in seconds. [300, 86400]
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub duration: i64,
    /// A unique id among Algo orders (length should be 32 characters)， If it is not sent, we will give default value
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub client_algo_id: Option<String>,
    /// Limit price of the order; If it is not sent, will place order by market price by default
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit_price: Option<rust_decimal::Decimal>,
}

impl TimeWeightedAveragePriceSpotAlgoParams {
    /// Create a builder for [`time_weighted_average_price_spot_algo`].
    ///
    /// Required parameters:
    ///
    /// * `symbol` — Trading symbol eg. BTCUSDT
    /// * `side` — Trading side ( BUY or SELL )
    /// * `quantity` — Quantity of base asset; Maximum notional per order is 200k, 2mm or 10mm, depending on symbol. Please reduce your size if you order is above the maximum notional per order.
    /// * `duration` — Duration for TWAP orders in seconds. [300, 86400]
    ///
    #[must_use]
    pub fn builder(
        symbol: String,
        side: String,
        quantity: rust_decimal::Decimal,
        duration: i64,
    ) -> TimeWeightedAveragePriceSpotAlgoParamsBuilder {
        TimeWeightedAveragePriceSpotAlgoParamsBuilder::default()
            .symbol(symbol)
            .side(side)
            .quantity(quantity)
            .duration(duration)
    }
}

#[async_trait]
impl SpotAlgoApi for SpotAlgoApiClient {
    async fn cancel_algo_order_spot_algo(
        &self,
        params: CancelAlgoOrderSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::CancelAlgoOrderSpotAlgoResponse>> {
        let CancelAlgoOrderSpotAlgoParams {
            algo_id,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("algoId".to_string(), json!(algo_id));

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::CancelAlgoOrderSpotAlgoResponse>(
            &self.configuration,
            "/sapi/v1/algo/spot/order",
            reqwest::Method::DELETE,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_current_algo_open_orders_spot_algo(
        &self,
        params: QueryCurrentAlgoOpenOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse>> {
        let QueryCurrentAlgoOpenOrdersSpotAlgoParams { recv_window } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse>(
            &self.configuration,
            "/sapi/v1/algo/spot/openOrders",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_historical_algo_orders_spot_algo(
        &self,
        params: QueryHistoricalAlgoOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryHistoricalAlgoOrdersSpotAlgoResponse>> {
        let QueryHistoricalAlgoOrdersSpotAlgoParams {
            symbol,
            side,
            start_time,
            end_time,
            page,
            page_size,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        if let Some(rw) = symbol {
            query_params.insert("symbol".to_string(), json!(rw));
        }

        if let Some(rw) = side {
            query_params.insert("side".to_string(), json!(rw));
        }

        if let Some(rw) = start_time {
            query_params.insert("startTime".to_string(), json!(rw));
        }

        if let Some(rw) = end_time {
            query_params.insert("endTime".to_string(), json!(rw));
        }

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = page_size {
            query_params.insert("pageSize".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::QueryHistoricalAlgoOrdersSpotAlgoResponse>(
            &self.configuration,
            "/sapi/v1/algo/spot/historicalOrders",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_sub_orders_spot_algo(
        &self,
        params: QuerySubOrdersSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::QuerySubOrdersSpotAlgoResponse>> {
        let QuerySubOrdersSpotAlgoParams {
            algo_id,
            page,
            page_size,
            recv_window,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("algoId".to_string(), json!(algo_id));

        if let Some(rw) = page {
            query_params.insert("page".to_string(), json!(rw));
        }

        if let Some(rw) = page_size {
            query_params.insert("pageSize".to_string(), json!(rw));
        }

        if let Some(rw) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<models::QuerySubOrdersSpotAlgoResponse>(
            &self.configuration,
            "/sapi/v1/algo/spot/subOrders",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn time_weighted_average_price_spot_algo(
        &self,
        params: TimeWeightedAveragePriceSpotAlgoParams,
    ) -> anyhow::Result<RestApiResponse<models::TimeWeightedAveragePriceSpotAlgoResponse>> {
        let TimeWeightedAveragePriceSpotAlgoParams {
            symbol,
            side,
            quantity,
            duration,
            client_algo_id,
            limit_price,
        } = params;

        let mut query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        query_params.insert("symbol".to_string(), json!(symbol));

        query_params.insert("side".to_string(), json!(side));

        query_params.insert("quantity".to_string(), json!(quantity));

        query_params.insert("duration".to_string(), json!(duration));

        if let Some(rw) = client_algo_id {
            query_params.insert("clientAlgoId".to_string(), json!(rw));
        }

        if let Some(rw) = limit_price {
            query_params.insert("limitPrice".to_string(), json!(rw));
        }

        send_request::<models::TimeWeightedAveragePriceSpotAlgoResponse>(
            &self.configuration,
            "/sapi/v1/algo/spot/newOrderTwap",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "algo"))]
mod tests {
    use super::*;
    use crate::TOKIO_SHARED_RT;
    use crate::{errors::ConnectorError, models::DataFuture, models::RestApiRateLimit};
    use async_trait::async_trait;
    use std::collections::HashMap;

    struct DummyRestApiResponse<T> {
        inner: Box<dyn FnOnce() -> DataFuture<Result<T, ConnectorError>> + Send + Sync>,
        status: u16,
        headers: HashMap<String, String>,
        rate_limits: Option<Vec<RestApiRateLimit>>,
    }

    impl<T> From<DummyRestApiResponse<T>> for RestApiResponse<T> {
        fn from(dummy: DummyRestApiResponse<T>) -> Self {
            Self {
                data_fn: dummy.inner,
                status: dummy.status,
                headers: dummy.headers,
                rate_limits: dummy.rate_limits,
            }
        }
    }

    struct MockSpotAlgoApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl SpotAlgoApi for MockSpotAlgoApiClient {
        async fn cancel_algo_order_spot_algo(
            &self,
            _params: CancelAlgoOrderSpotAlgoParams,
        ) -> anyhow::Result<RestApiResponse<models::CancelAlgoOrderSpotAlgoResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"algoId":14511,"success":true,"code":0,"msg":"OK"}"#)
                    .unwrap();
            let dummy_response: models::CancelAlgoOrderSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CancelAlgoOrderSpotAlgoResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn query_current_algo_open_orders_spot_algo(
            &self,
            _params: QueryCurrentAlgoOpenOrdersSpotAlgoParams,
        ) -> anyhow::Result<RestApiResponse<models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14517,"symbol":"ETHUSDT","side":"SELL","totalQty":"5.000","executedQty":"0.000","executedAmt":"0.00000000","avgPrice":"0.00","clientAlgoId":"d7096549481642f8a0bb69e9e2e31f2e","bookTime":1649756817004,"endTime":0,"algoStatus":"WORKING","algoType":"TWAP","urgency":"LOW"}]}"#).unwrap();
            let dummy_response: models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn query_historical_algo_orders_spot_algo(
            &self,
            _params: QueryHistoricalAlgoOrdersSpotAlgoParams,
        ) -> anyhow::Result<RestApiResponse<models::QueryHistoricalAlgoOrdersSpotAlgoResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14518,"symbol":"BNBUSDT","side":"BUY","totalQty":"100.00","executedQty":"0.00","executedAmt":"0.00000000","avgPrice":"0.000","clientAlgoId":"acacab56b3c44bef9f6a8f8ebd2a8408","bookTime":1649757019503,"endTime":1649757088101,"algoStatus":"CANCELLED","algoType":"VP","urgency":"LOW"}]}"#).unwrap();
            let dummy_response: models::QueryHistoricalAlgoOrdersSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryHistoricalAlgoOrdersSpotAlgoResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn query_sub_orders_spot_algo(
            &self,
            _params: QuerySubOrdersSpotAlgoParams,
        ) -> anyhow::Result<RestApiResponse<models::QuerySubOrdersSpotAlgoResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"executedQty":"1.000","executedAmt":"3229.44000000","subOrders":[{"algoId":13723,"orderId":8389765519993909000,"orderStatus":"FILLED","executedQty":"1.000","executedAmt":"3229.44000000","feeAmt":"-1.61471999","feeAsset":"USDT","bookTime":1649319001964,"avgPrice":"3229.44","side":"SELL","symbol":"ETHUSDT","subId":1,"timeInForce":"IMMEDIATE_OR_CANCEL","origQty":"1.000"}]}"#).unwrap();
            let dummy_response: models::QuerySubOrdersSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QuerySubOrdersSpotAlgoResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }

        async fn time_weighted_average_price_spot_algo(
            &self,
            _params: TimeWeightedAveragePriceSpotAlgoParams,
        ) -> anyhow::Result<RestApiResponse<models::TimeWeightedAveragePriceSpotAlgoResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"clientAlgoId":"65ce1630101a480b85915d7e11fd5078","success":true,"code":0,"msg":"OK"}"#).unwrap();
            let dummy_response: models::TimeWeightedAveragePriceSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::TimeWeightedAveragePriceSpotAlgoResponse");

            let dummy = DummyRestApiResponse {
                inner: Box::new(move || Box::pin(async move { Ok(dummy_response) })),
                status: 200,
                headers: HashMap::new(),
                rate_limits: None,
            };

            Ok(dummy.into())
        }
    }

    #[test]
    fn cancel_algo_order_spot_algo_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = CancelAlgoOrderSpotAlgoParams::builder(1).build().unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"algoId":14511,"success":true,"code":0,"msg":"OK"}"#)
                    .unwrap();
            let expected_response: models::CancelAlgoOrderSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CancelAlgoOrderSpotAlgoResponse");

            let resp = client
                .cancel_algo_order_spot_algo(params)
                .await
                .expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn cancel_algo_order_spot_algo_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = CancelAlgoOrderSpotAlgoParams::builder(1)
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"algoId":14511,"success":true,"code":0,"msg":"OK"}"#)
                    .unwrap();
            let expected_response: models::CancelAlgoOrderSpotAlgoResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::CancelAlgoOrderSpotAlgoResponse");

            let resp = client
                .cancel_algo_order_spot_algo(params)
                .await
                .expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn cancel_algo_order_spot_algo_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: true };

            let params = CancelAlgoOrderSpotAlgoParams::builder(1).build().unwrap();

            match client.cancel_algo_order_spot_algo(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn query_current_algo_open_orders_spot_algo_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QueryCurrentAlgoOpenOrdersSpotAlgoParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14517,"symbol":"ETHUSDT","side":"SELL","totalQty":"5.000","executedQty":"0.000","executedAmt":"0.00000000","avgPrice":"0.00","clientAlgoId":"d7096549481642f8a0bb69e9e2e31f2e","bookTime":1649756817004,"endTime":0,"algoStatus":"WORKING","algoType":"TWAP","urgency":"LOW"}]}"#).unwrap();
            let expected_response : models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse");

            let resp = client.query_current_algo_open_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_current_algo_open_orders_spot_algo_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QueryCurrentAlgoOpenOrdersSpotAlgoParams::builder().recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14517,"symbol":"ETHUSDT","side":"SELL","totalQty":"5.000","executedQty":"0.000","executedAmt":"0.00000000","avgPrice":"0.00","clientAlgoId":"d7096549481642f8a0bb69e9e2e31f2e","bookTime":1649756817004,"endTime":0,"algoStatus":"WORKING","algoType":"TWAP","urgency":"LOW"}]}"#).unwrap();
            let expected_response : models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryCurrentAlgoOpenOrdersSpotAlgoResponse");

            let resp = client.query_current_algo_open_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_current_algo_open_orders_spot_algo_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: true };

            let params = QueryCurrentAlgoOpenOrdersSpotAlgoParams::builder()
                .build()
                .unwrap();

            match client
                .query_current_algo_open_orders_spot_algo(params)
                .await
            {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn query_historical_algo_orders_spot_algo_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QueryHistoricalAlgoOrdersSpotAlgoParams::builder().build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14518,"symbol":"BNBUSDT","side":"BUY","totalQty":"100.00","executedQty":"0.00","executedAmt":"0.00000000","avgPrice":"0.000","clientAlgoId":"acacab56b3c44bef9f6a8f8ebd2a8408","bookTime":1649757019503,"endTime":1649757088101,"algoStatus":"CANCELLED","algoType":"VP","urgency":"LOW"}]}"#).unwrap();
            let expected_response : models::QueryHistoricalAlgoOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryHistoricalAlgoOrdersSpotAlgoResponse");

            let resp = client.query_historical_algo_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_historical_algo_orders_spot_algo_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QueryHistoricalAlgoOrdersSpotAlgoParams::builder().symbol("BTCUSDT".to_string()).side("BUY".to_string()).start_time(1623319461670).end_time(1641782889000).page(1).page_size(100).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"orders":[{"algoId":14518,"symbol":"BNBUSDT","side":"BUY","totalQty":"100.00","executedQty":"0.00","executedAmt":"0.00000000","avgPrice":"0.000","clientAlgoId":"acacab56b3c44bef9f6a8f8ebd2a8408","bookTime":1649757019503,"endTime":1649757088101,"algoStatus":"CANCELLED","algoType":"VP","urgency":"LOW"}]}"#).unwrap();
            let expected_response : models::QueryHistoricalAlgoOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryHistoricalAlgoOrdersSpotAlgoResponse");

            let resp = client.query_historical_algo_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_historical_algo_orders_spot_algo_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: true };

            let params = QueryHistoricalAlgoOrdersSpotAlgoParams::builder()
                .build()
                .unwrap();

            match client.query_historical_algo_orders_spot_algo(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn query_sub_orders_spot_algo_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QuerySubOrdersSpotAlgoParams::builder(1,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"executedQty":"1.000","executedAmt":"3229.44000000","subOrders":[{"algoId":13723,"orderId":8389765519993909000,"orderStatus":"FILLED","executedQty":"1.000","executedAmt":"3229.44000000","feeAmt":"-1.61471999","feeAsset":"USDT","bookTime":1649319001964,"avgPrice":"3229.44","side":"SELL","symbol":"ETHUSDT","subId":1,"timeInForce":"IMMEDIATE_OR_CANCEL","origQty":"1.000"}]}"#).unwrap();
            let expected_response : models::QuerySubOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QuerySubOrdersSpotAlgoResponse");

            let resp = client.query_sub_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_sub_orders_spot_algo_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = QuerySubOrdersSpotAlgoParams::builder(1,).page(1).page_size(100).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":1,"executedQty":"1.000","executedAmt":"3229.44000000","subOrders":[{"algoId":13723,"orderId":8389765519993909000,"orderStatus":"FILLED","executedQty":"1.000","executedAmt":"3229.44000000","feeAmt":"-1.61471999","feeAsset":"USDT","bookTime":1649319001964,"avgPrice":"3229.44","side":"SELL","symbol":"ETHUSDT","subId":1,"timeInForce":"IMMEDIATE_OR_CANCEL","origQty":"1.000"}]}"#).unwrap();
            let expected_response : models::QuerySubOrdersSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QuerySubOrdersSpotAlgoResponse");

            let resp = client.query_sub_orders_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn query_sub_orders_spot_algo_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: true };

            let params = QuerySubOrdersSpotAlgoParams::builder(1).build().unwrap();

            match client.query_sub_orders_spot_algo(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }

    #[test]
    fn time_weighted_average_price_spot_algo_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = TimeWeightedAveragePriceSpotAlgoParams::builder("BTCUSDT".to_string(),"BUY".to_string(),dec!(1.0),5000,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"clientAlgoId":"65ce1630101a480b85915d7e11fd5078","success":true,"code":0,"msg":"OK"}"#).unwrap();
            let expected_response : models::TimeWeightedAveragePriceSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::TimeWeightedAveragePriceSpotAlgoResponse");

            let resp = client.time_weighted_average_price_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn time_weighted_average_price_spot_algo_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: false };

            let params = TimeWeightedAveragePriceSpotAlgoParams::builder("BTCUSDT".to_string(),"BUY".to_string(),dec!(1.0),5000,).client_algo_id("1".to_string()).limit_price(dec!(1.0)).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"clientAlgoId":"65ce1630101a480b85915d7e11fd5078","success":true,"code":0,"msg":"OK"}"#).unwrap();
            let expected_response : models::TimeWeightedAveragePriceSpotAlgoResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::TimeWeightedAveragePriceSpotAlgoResponse");

            let resp = client.time_weighted_average_price_spot_algo(params).await.expect("Expected a response");
            let data_future = resp.data();
            let actual_response = data_future.await.unwrap();
            assert_eq!(actual_response, expected_response);
        });
    }

    #[test]
    fn time_weighted_average_price_spot_algo_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockSpotAlgoApiClient { force_error: true };

            let params = TimeWeightedAveragePriceSpotAlgoParams::builder(
                "BTCUSDT".to_string(),
                "BUY".to_string(),
                dec!(1.0),
                5000,
            )
            .build()
            .unwrap();

            match client.time_weighted_average_price_spot_algo(params).await {
                Ok(_) => panic!("Expected an error"),
                Err(err) => {
                    assert_eq!(err.to_string(), "Connector client error: ResponseError");
                }
            }
        });
    }
}
