/*
 * Binance Derivatives Trading Options REST API
 *
 * OpenAPI Specification for the Binance Derivatives Trading Options 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::common::{
    config::ConfigurationRestApi,
    models::{ParamBuildError, RestApiResponse},
    utils::send_request,
};
use crate::derivatives_trading_options::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait MarketMakerEndpointsApi: Send + Sync {
    async fn auto_cancel_all_open_orders(
        &self,
        params: AutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::AutoCancelAllOpenOrdersResponse>>;
    async fn get_auto_cancel_all_open_orders(
        &self,
        params: GetAutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::GetAutoCancelAllOpenOrdersResponse>>;
    async fn get_market_maker_protection_config(
        &self,
        params: GetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::GetMarketMakerProtectionConfigResponse>>;
    async fn reset_market_maker_protection_config(
        &self,
        params: ResetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::ResetMarketMakerProtectionConfigResponse>>;
    async fn set_auto_cancel_all_open_orders(
        &self,
        params: SetAutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::SetAutoCancelAllOpenOrdersResponse>>;
    async fn set_market_maker_protection_config(
        &self,
        params: SetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::SetMarketMakerProtectionConfigResponse>>;
}

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

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

/// Request parameters for the [`auto_cancel_all_open_orders`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`auto_cancel_all_open_orders`](#method.auto_cancel_all_open_orders).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct AutoCancelAllOpenOrdersParams {
    /// Option Underlying Symbols, e.g BTCUSDT,ETHUSDT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub underlyings: String,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl AutoCancelAllOpenOrdersParams {
    /// Create a builder for [`auto_cancel_all_open_orders`].
    ///
    /// Required parameters:
    ///
    /// * `underlyings` — Option Underlying Symbols, e.g BTCUSDT,ETHUSDT
    ///
    #[must_use]
    pub fn builder(underlyings: String) -> AutoCancelAllOpenOrdersParamsBuilder {
        AutoCancelAllOpenOrdersParamsBuilder::default().underlyings(underlyings)
    }
}
/// Request parameters for the [`get_auto_cancel_all_open_orders`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_auto_cancel_all_open_orders`](#method.get_auto_cancel_all_open_orders).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetAutoCancelAllOpenOrdersParams {
    /// underlying, e.g BTCUSDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub underlying: Option<String>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetAutoCancelAllOpenOrdersParams {
    /// Create a builder for [`get_auto_cancel_all_open_orders`].
    ///
    #[must_use]
    pub fn builder() -> GetAutoCancelAllOpenOrdersParamsBuilder {
        GetAutoCancelAllOpenOrdersParamsBuilder::default()
    }
}
/// Request parameters for the [`get_market_maker_protection_config`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_market_maker_protection_config`](#method.get_market_maker_protection_config).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetMarketMakerProtectionConfigParams {
    /// underlying, e.g BTCUSDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub underlying: Option<String>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetMarketMakerProtectionConfigParams {
    /// Create a builder for [`get_market_maker_protection_config`].
    ///
    #[must_use]
    pub fn builder() -> GetMarketMakerProtectionConfigParamsBuilder {
        GetMarketMakerProtectionConfigParamsBuilder::default()
    }
}
/// Request parameters for the [`reset_market_maker_protection_config`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`reset_market_maker_protection_config`](#method.reset_market_maker_protection_config).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct ResetMarketMakerProtectionConfigParams {
    /// underlying, e.g BTCUSDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub underlying: Option<String>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl ResetMarketMakerProtectionConfigParams {
    /// Create a builder for [`reset_market_maker_protection_config`].
    ///
    #[must_use]
    pub fn builder() -> ResetMarketMakerProtectionConfigParamsBuilder {
        ResetMarketMakerProtectionConfigParamsBuilder::default()
    }
}
/// Request parameters for the [`set_auto_cancel_all_open_orders`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`set_auto_cancel_all_open_orders`](#method.set_auto_cancel_all_open_orders).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SetAutoCancelAllOpenOrdersParams {
    /// Option underlying, e.g BTCUSDT
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub underlying: String,
    /// Countdown time in milliseconds (ex. 1,000 for 1 second). 0 to disable the timer. Negative values (ex. -10000) are not accepted. Minimum acceptable value is 5,000
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub countdown_time: i64,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl SetAutoCancelAllOpenOrdersParams {
    /// Create a builder for [`set_auto_cancel_all_open_orders`].
    ///
    /// Required parameters:
    ///
    /// * `underlying` — Option underlying, e.g BTCUSDT
    /// * `countdown_time` — Countdown time in milliseconds (ex. 1,000 for 1 second). 0 to disable the timer. Negative values (ex. -10000) are not accepted. Minimum acceptable value is 5,000
    ///
    #[must_use]
    pub fn builder(
        underlying: String,
        countdown_time: i64,
    ) -> SetAutoCancelAllOpenOrdersParamsBuilder {
        SetAutoCancelAllOpenOrdersParamsBuilder::default()
            .underlying(underlying)
            .countdown_time(countdown_time)
    }
}
/// Request parameters for the [`set_market_maker_protection_config`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`set_market_maker_protection_config`](#method.set_market_maker_protection_config).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct SetMarketMakerProtectionConfigParams {
    /// underlying, e.g BTCUSDT
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub underlying: Option<String>,
    /// MMP Interval in milliseconds; Range (0,5000]
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub window_time_in_milliseconds: Option<i64>,
    /// MMP frozen time in milliseconds, if set to 0 manual reset is required
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub frozen_time_in_milliseconds: Option<i64>,
    /// quantity limit
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub qty_limit: Option<rust_decimal::Decimal>,
    /// net delta limit
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub delta_limit: Option<rust_decimal::Decimal>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl SetMarketMakerProtectionConfigParams {
    /// Create a builder for [`set_market_maker_protection_config`].
    ///
    #[must_use]
    pub fn builder() -> SetMarketMakerProtectionConfigParamsBuilder {
        SetMarketMakerProtectionConfigParamsBuilder::default()
    }
}

#[async_trait]
impl MarketMakerEndpointsApi for MarketMakerEndpointsApiClient {
    async fn auto_cancel_all_open_orders(
        &self,
        params: AutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::AutoCancelAllOpenOrdersResponse>> {
        let AutoCancelAllOpenOrdersParams {
            underlyings,
            recv_window,
        } = params;

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

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

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

        send_request::<models::AutoCancelAllOpenOrdersResponse>(
            &self.configuration,
            "/eapi/v1/countdownCancelAllHeartBeat",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_auto_cancel_all_open_orders(
        &self,
        params: GetAutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::GetAutoCancelAllOpenOrdersResponse>> {
        let GetAutoCancelAllOpenOrdersParams {
            underlying,
            recv_window,
        } = params;

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

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

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

        send_request::<models::GetAutoCancelAllOpenOrdersResponse>(
            &self.configuration,
            "/eapi/v1/countdownCancelAll",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_market_maker_protection_config(
        &self,
        params: GetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::GetMarketMakerProtectionConfigResponse>> {
        let GetMarketMakerProtectionConfigParams {
            underlying,
            recv_window,
        } = params;

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

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

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

        send_request::<models::GetMarketMakerProtectionConfigResponse>(
            &self.configuration,
            "/eapi/v1/mmp",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn reset_market_maker_protection_config(
        &self,
        params: ResetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::ResetMarketMakerProtectionConfigResponse>> {
        let ResetMarketMakerProtectionConfigParams {
            underlying,
            recv_window,
        } = params;

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

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

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

        send_request::<models::ResetMarketMakerProtectionConfigResponse>(
            &self.configuration,
            "/eapi/v1/mmpReset",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn set_auto_cancel_all_open_orders(
        &self,
        params: SetAutoCancelAllOpenOrdersParams,
    ) -> anyhow::Result<RestApiResponse<models::SetAutoCancelAllOpenOrdersResponse>> {
        let SetAutoCancelAllOpenOrdersParams {
            underlying,
            countdown_time,
            recv_window,
        } = params;

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

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

        query_params.insert("countdownTime".to_string(), json!(countdown_time));

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

        send_request::<models::SetAutoCancelAllOpenOrdersResponse>(
            &self.configuration,
            "/eapi/v1/countdownCancelAll",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn set_market_maker_protection_config(
        &self,
        params: SetMarketMakerProtectionConfigParams,
    ) -> anyhow::Result<RestApiResponse<models::SetMarketMakerProtectionConfigResponse>> {
        let SetMarketMakerProtectionConfigParams {
            underlying,
            window_time_in_milliseconds,
            frozen_time_in_milliseconds,
            qty_limit,
            delta_limit,
            recv_window,
        } = params;

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

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

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

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

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

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

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

        send_request::<models::SetMarketMakerProtectionConfigResponse>(
            &self.configuration,
            "/eapi/v1/mmpSet",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

#[cfg(all(test, feature = "derivatives_trading_options"))]
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 MockMarketMakerEndpointsApiClient {
        force_error: bool,
    }

    #[async_trait]
    impl MarketMakerEndpointsApi for MockMarketMakerEndpointsApiClient {
        async fn auto_cancel_all_open_orders(
            &self,
            _params: AutoCancelAllOpenOrdersParams,
        ) -> anyhow::Result<RestApiResponse<models::AutoCancelAllOpenOrdersResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"underlyings":["BTCUSDT","ETHUSDT"]}"#).unwrap();
            let dummy_response: models::AutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::AutoCancelAllOpenOrdersResponse");

            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 get_auto_cancel_all_open_orders(
            &self,
            _params: GetAutoCancelAllOpenOrdersParams,
        ) -> anyhow::Result<RestApiResponse<models::GetAutoCancelAllOpenOrdersResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":100000}"#).unwrap();
            let dummy_response: models::GetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetAutoCancelAllOpenOrdersResponse");

            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 get_market_maker_protection_config(
            &self,
            _params: GetMarketMakerProtectionConfigParams,
        ) -> anyhow::Result<RestApiResponse<models::GetMarketMakerProtectionConfigResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let dummy_response: models::GetMarketMakerProtectionConfigResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetMarketMakerProtectionConfigResponse");

            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 reset_market_maker_protection_config(
            &self,
            _params: ResetMarketMakerProtectionConfigParams,
        ) -> anyhow::Result<RestApiResponse<models::ResetMarketMakerProtectionConfigResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let dummy_response: models::ResetMarketMakerProtectionConfigResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::ResetMarketMakerProtectionConfigResponse");

            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 set_auto_cancel_all_open_orders(
            &self,
            _params: SetAutoCancelAllOpenOrdersParams,
        ) -> anyhow::Result<RestApiResponse<models::SetAutoCancelAllOpenOrdersResponse>> {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":30000}"#).unwrap();
            let dummy_response: models::SetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SetAutoCancelAllOpenOrdersResponse");

            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 set_market_maker_protection_config(
            &self,
            _params: SetMarketMakerProtectionConfigParams,
        ) -> anyhow::Result<RestApiResponse<models::SetMarketMakerProtectionConfigResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let dummy_response: models::SetMarketMakerProtectionConfigResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SetMarketMakerProtectionConfigResponse");

            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 auto_cancel_all_open_orders_required_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = AutoCancelAllOpenOrdersParams::builder("underlyings_example".to_string())
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"underlyings":["BTCUSDT","ETHUSDT"]}"#).unwrap();
            let expected_response: models::AutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::AutoCancelAllOpenOrdersResponse");

            let resp = client
                .auto_cancel_all_open_orders(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 auto_cancel_all_open_orders_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = AutoCancelAllOpenOrdersParams::builder("underlyings_example".to_string())
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"underlyings":["BTCUSDT","ETHUSDT"]}"#).unwrap();
            let expected_response: models::AutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::AutoCancelAllOpenOrdersResponse");

            let resp = client
                .auto_cancel_all_open_orders(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 auto_cancel_all_open_orders_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

            let params = AutoCancelAllOpenOrdersParams::builder("underlyings_example".to_string())
                .build()
                .unwrap();

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

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

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

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":100000}"#).unwrap();
            let expected_response: models::GetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetAutoCancelAllOpenOrdersResponse");

            let resp = client
                .get_auto_cancel_all_open_orders(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 get_auto_cancel_all_open_orders_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = GetAutoCancelAllOpenOrdersParams::builder()
                .underlying("underlying_example".to_string())
                .recv_window(5000)
                .build()
                .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":100000}"#).unwrap();
            let expected_response: models::GetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetAutoCancelAllOpenOrdersResponse");

            let resp = client
                .get_auto_cancel_all_open_orders(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 get_auto_cancel_all_open_orders_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::GetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarketMakerProtectionConfigResponse");

            let resp = client.get_market_maker_protection_config(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 get_market_maker_protection_config_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = GetMarketMakerProtectionConfigParams::builder().underlying("underlying_example".to_string()).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::GetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarketMakerProtectionConfigResponse");

            let resp = client.get_market_maker_protection_config(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 get_market_maker_protection_config_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::ResetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ResetMarketMakerProtectionConfigResponse");

            let resp = client.reset_market_maker_protection_config(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 reset_market_maker_protection_config_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = ResetMarketMakerProtectionConfigParams::builder().underlying("underlying_example".to_string()).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::ResetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::ResetMarketMakerProtectionConfigResponse");

            let resp = client.reset_market_maker_protection_config(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 reset_market_maker_protection_config_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

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

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

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

            let params =
                SetAutoCancelAllOpenOrdersParams::builder("underlying_example".to_string(), 789)
                    .build()
                    .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":30000}"#).unwrap();
            let expected_response: models::SetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SetAutoCancelAllOpenOrdersResponse");

            let resp = client
                .set_auto_cancel_all_open_orders(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 set_auto_cancel_all_open_orders_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params =
                SetAutoCancelAllOpenOrdersParams::builder("underlying_example".to_string(), 789)
                    .recv_window(5000)
                    .build()
                    .unwrap();

            let resp_json: Value =
                serde_json::from_str(r#"{"underlying":"ETHUSDT","countdownTime":30000}"#).unwrap();
            let expected_response: models::SetAutoCancelAllOpenOrdersResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::SetAutoCancelAllOpenOrdersResponse");

            let resp = client
                .set_auto_cancel_all_open_orders(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 set_auto_cancel_all_open_orders_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

            let params =
                SetAutoCancelAllOpenOrdersParams::builder("underlying_example".to_string(), 789)
                    .build()
                    .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::SetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::SetMarketMakerProtectionConfigResponse");

            let resp = client.set_market_maker_protection_config(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 set_market_maker_protection_config_optional_params_success() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: false };

            let params = SetMarketMakerProtectionConfigParams::builder().underlying("underlying_example".to_string()).window_time_in_milliseconds(789).frozen_time_in_milliseconds(789).qty_limit(dec!(1.0)).delta_limit(dec!(1.0)).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"underlyingId":2,"underlying":"BTCUSDT","windowTimeInMilliseconds":3000,"frozenTimeInMilliseconds":300000,"qtyLimit":"2","deltaLimit":"2.3","lastTriggerTime":0}"#).unwrap();
            let expected_response : models::SetMarketMakerProtectionConfigResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::SetMarketMakerProtectionConfigResponse");

            let resp = client.set_market_maker_protection_config(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 set_market_maker_protection_config_response_error() {
        TOKIO_SHARED_RT.block_on(async {
            let client = MockMarketMakerEndpointsApiClient { force_error: true };

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

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