/*
 * Binance Margin Trading REST API
 *
 * OpenAPI Specification for the Binance Margin Trading 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::margin_trading::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait MarketDataApi: Send + Sync {
    async fn cross_margin_collateral_ratio(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::CrossMarginCollateralRatioResponseInner>>>;
    async fn get_all_cross_margin_pairs(
        &self,
        params: GetAllCrossMarginPairsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllCrossMarginPairsResponseInner>>>;
    async fn get_all_isolated_margin_symbol(
        &self,
        params: GetAllIsolatedMarginSymbolParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllIsolatedMarginSymbolResponseInner>>>;
    async fn get_all_margin_assets(
        &self,
        params: GetAllMarginAssetsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllMarginAssetsResponseInner>>>;
    async fn get_delist_schedule(
        &self,
        params: GetDelistScheduleParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetDelistScheduleResponseInner>>>;
    async fn get_limit_price_pairs(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::GetLimitPricePairsResponse>>;
    async fn get_list_schedule(
        &self,
        params: GetListScheduleParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetListScheduleResponseInner>>>;
    async fn get_margin_asset_risk_based_liquidation_ratio(
        &self,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>>,
    >;
    async fn get_margin_restricted_assets(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::GetMarginRestrictedAssetsResponse>>;
    async fn query_isolated_margin_tier_data(
        &self,
        params: QueryIsolatedMarginTierDataParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::QueryIsolatedMarginTierDataResponseInner>>>;
    async fn query_liability_coin_leverage_bracket_in_cross_margin_pro_mode(
        &self,
    ) -> anyhow::Result<
        RestApiResponse<
            Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>,
        >,
    >;
    async fn query_margin_available_inventory(
        &self,
        params: QueryMarginAvailableInventoryParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryMarginAvailableInventoryResponse>>;
    async fn query_margin_priceindex(
        &self,
        params: QueryMarginPriceindexParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryMarginPriceindexResponse>>;
}

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

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

/// Request parameters for the [`get_all_cross_margin_pairs`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_all_cross_margin_pairs`](#method.get_all_cross_margin_pairs).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetAllCrossMarginPairsParams {
    /// isolated margin pair
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub symbol: Option<String>,
}

impl GetAllCrossMarginPairsParams {
    /// Create a builder for [`get_all_cross_margin_pairs`].
    ///
    #[must_use]
    pub fn builder() -> GetAllCrossMarginPairsParamsBuilder {
        GetAllCrossMarginPairsParamsBuilder::default()
    }
}
/// Request parameters for the [`get_all_isolated_margin_symbol`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_all_isolated_margin_symbol`](#method.get_all_isolated_margin_symbol).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetAllIsolatedMarginSymbolParams {
    /// isolated margin pair
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub symbol: Option<String>,
    /// No more than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetAllIsolatedMarginSymbolParams {
    /// Create a builder for [`get_all_isolated_margin_symbol`].
    ///
    #[must_use]
    pub fn builder() -> GetAllIsolatedMarginSymbolParamsBuilder {
        GetAllIsolatedMarginSymbolParamsBuilder::default()
    }
}
/// Request parameters for the [`get_all_margin_assets`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_all_margin_assets`](#method.get_all_margin_assets).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetAllMarginAssetsParams {
    ///
    /// The `asset` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub asset: Option<String>,
}

impl GetAllMarginAssetsParams {
    /// Create a builder for [`get_all_margin_assets`].
    ///
    #[must_use]
    pub fn builder() -> GetAllMarginAssetsParamsBuilder {
        GetAllMarginAssetsParamsBuilder::default()
    }
}
/// Request parameters for the [`get_delist_schedule`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_delist_schedule`](#method.get_delist_schedule).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetDelistScheduleParams {
    /// No more than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetDelistScheduleParams {
    /// Create a builder for [`get_delist_schedule`].
    ///
    #[must_use]
    pub fn builder() -> GetDelistScheduleParamsBuilder {
        GetDelistScheduleParamsBuilder::default()
    }
}
/// Request parameters for the [`get_list_schedule`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_list_schedule`](#method.get_list_schedule).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetListScheduleParams {
    /// No more than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetListScheduleParams {
    /// Create a builder for [`get_list_schedule`].
    ///
    #[must_use]
    pub fn builder() -> GetListScheduleParamsBuilder {
        GetListScheduleParamsBuilder::default()
    }
}
/// Request parameters for the [`query_isolated_margin_tier_data`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_isolated_margin_tier_data`](#method.query_isolated_margin_tier_data).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryIsolatedMarginTierDataParams {
    ///
    /// The `symbol` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub symbol: String,
    /// All margin tier data will be returned if tier is omitted
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub tier: Option<i64>,
    /// No more than 60000
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryIsolatedMarginTierDataParams {
    /// Create a builder for [`query_isolated_margin_tier_data`].
    ///
    /// Required parameters:
    ///
    /// * `symbol` — String
    ///
    #[must_use]
    pub fn builder(symbol: String) -> QueryIsolatedMarginTierDataParamsBuilder {
        QueryIsolatedMarginTierDataParamsBuilder::default().symbol(symbol)
    }
}
/// Request parameters for the [`query_margin_available_inventory`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_margin_available_inventory`](#method.query_margin_available_inventory).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryMarginAvailableInventoryParams {
    /// `MARGIN`,`ISOLATED`
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub r#type: String,
}

impl QueryMarginAvailableInventoryParams {
    /// Create a builder for [`query_margin_available_inventory`].
    ///
    /// Required parameters:
    ///
    /// * `r#type` — `MARGIN`,`ISOLATED`
    ///
    #[must_use]
    pub fn builder(r#type: String) -> QueryMarginAvailableInventoryParamsBuilder {
        QueryMarginAvailableInventoryParamsBuilder::default().r#type(r#type)
    }
}
/// Request parameters for the [`query_margin_priceindex`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_margin_priceindex`](#method.query_margin_priceindex).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryMarginPriceindexParams {
    ///
    /// The `symbol` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub symbol: String,
}

impl QueryMarginPriceindexParams {
    /// Create a builder for [`query_margin_priceindex`].
    ///
    /// Required parameters:
    ///
    /// * `symbol` — String
    ///
    #[must_use]
    pub fn builder(symbol: String) -> QueryMarginPriceindexParamsBuilder {
        QueryMarginPriceindexParamsBuilder::default().symbol(symbol)
    }
}

#[async_trait]
impl MarketDataApi for MarketDataApiClient {
    async fn cross_margin_collateral_ratio(
        &self,
    ) -> anyhow::Result<RestApiResponse<Vec<models::CrossMarginCollateralRatioResponseInner>>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<Vec<models::CrossMarginCollateralRatioResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/crossMarginCollateralRatio",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_all_cross_margin_pairs(
        &self,
        params: GetAllCrossMarginPairsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllCrossMarginPairsResponseInner>>> {
        let GetAllCrossMarginPairsParams { symbol } = 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));
        }

        send_request::<Vec<models::GetAllCrossMarginPairsResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/allPairs",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_all_isolated_margin_symbol(
        &self,
        params: GetAllIsolatedMarginSymbolParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllIsolatedMarginSymbolResponseInner>>> {
        let GetAllIsolatedMarginSymbolParams {
            symbol,
            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) = recv_window {
            query_params.insert("recvWindow".to_string(), json!(rw));
        }

        send_request::<Vec<models::GetAllIsolatedMarginSymbolResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/isolated/allPairs",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_all_margin_assets(
        &self,
        params: GetAllMarginAssetsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetAllMarginAssetsResponseInner>>> {
        let GetAllMarginAssetsParams { asset } = params;

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

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

        send_request::<Vec<models::GetAllMarginAssetsResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/allAssets",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_delist_schedule(
        &self,
        params: GetDelistScheduleParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetDelistScheduleResponseInner>>> {
        let GetDelistScheduleParams { 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::<Vec<models::GetDelistScheduleResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/delist-schedule",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_limit_price_pairs(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::GetLimitPricePairsResponse>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<models::GetLimitPricePairsResponse>(
            &self.configuration,
            "/sapi/v1/margin/limit-price-pairs",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_list_schedule(
        &self,
        params: GetListScheduleParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::GetListScheduleResponseInner>>> {
        let GetListScheduleParams { 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::<Vec<models::GetListScheduleResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/list-schedule",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_margin_asset_risk_based_liquidation_ratio(
        &self,
    ) -> anyhow::Result<
        RestApiResponse<Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>>,
    > {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/risk-based-liquidation-ratio",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn get_margin_restricted_assets(
        &self,
    ) -> anyhow::Result<RestApiResponse<models::GetMarginRestrictedAssetsResponse>> {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<models::GetMarginRestrictedAssetsResponse>(
            &self.configuration,
            "/sapi/v1/margin/restricted-asset",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn query_isolated_margin_tier_data(
        &self,
        params: QueryIsolatedMarginTierDataParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::QueryIsolatedMarginTierDataResponseInner>>>
    {
        let QueryIsolatedMarginTierDataParams {
            symbol,
            tier,
            recv_window,
        } = params;

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

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

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

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

        send_request::<Vec<models::QueryIsolatedMarginTierDataResponseInner>>(
            &self.configuration,
            "/sapi/v1/margin/isolatedMarginTier",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_liability_coin_leverage_bracket_in_cross_margin_pro_mode(
        &self,
    ) -> anyhow::Result<
        RestApiResponse<
            Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>,
        >,
    > {
        let query_params = BTreeMap::new();
        let body_params = BTreeMap::new();

        send_request::<
            Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>,
        >(
            &self.configuration,
            "/sapi/v1/margin/leverageBracket",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }

    async fn query_margin_available_inventory(
        &self,
        params: QueryMarginAvailableInventoryParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryMarginAvailableInventoryResponse>> {
        let QueryMarginAvailableInventoryParams { r#type } = params;

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

        query_params.insert("type".to_string(), json!(r#type));

        send_request::<models::QueryMarginAvailableInventoryResponse>(
            &self.configuration,
            "/sapi/v1/margin/available-inventory",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_margin_priceindex(
        &self,
        params: QueryMarginPriceindexParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryMarginPriceindexResponse>> {
        let QueryMarginPriceindexParams { symbol } = params;

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

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

        send_request::<models::QueryMarginPriceindexResponse>(
            &self.configuration,
            "/sapi/v1/margin/priceIndex",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            false,
        )
        .await
    }
}

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

    #[async_trait]
    impl MarketDataApi for MockMarketDataApiClient {
        async fn cross_margin_collateral_ratio(
            &self,
        ) -> anyhow::Result<RestApiResponse<Vec<models::CrossMarginCollateralRatioResponseInner>>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"[{"collaterals":[{"minUsdValue":"0","maxUsdValue":"13000000","discountRate":"1"},{"minUsdValue":"13000000","maxUsdValue":"20000000","discountRate":"0.975"},{"minUsdValue":"20000000","discountRate":"0"}],"assetNames":["BNX"]},{"collaterals":[{"minUsdValue":"0","discountRate":"1"}],"assetNames":["BTC","BUSD","ETH","USDT"]}]"#).unwrap();
            let dummy_response: Vec<models::CrossMarginCollateralRatioResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::CrossMarginCollateralRatioResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","id":351637150141315840,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","id":351637923235429100,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC","delistTime":1704973040},{"base":"XRP","id":351638112213990140,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"XRPBTC"},{"base":"ETH","id":351638524530850560,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"ETHBTC"}]"#).unwrap();
            let dummy_response: Vec<models::GetAllCrossMarginPairsResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::GetAllCrossMarginPairsResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC"}]"#).unwrap();
            let dummy_response: Vec<models::GetAllIsolatedMarginSymbolResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::GetAllIsolatedMarginSymbolResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"[{"assetFullName":"USD coin","assetName":"USDC","isBorrowable":true,"isMortgageable":true,"userMinBorrow":"0.00000000","userMinRepay":"0.00000000","delistTime":1704973040}]"#).unwrap();
            let dummy_response: Vec<models::GetAllMarginAssetsResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::GetAllMarginAssetsResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let dummy_response: Vec<models::GetDelistScheduleResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::GetDelistScheduleResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"{"crossMarginSymbols":["BLURUSDC","SANDBTC","QKCBTC","SEIFDUSD","NEOUSDC","ARBFDUSD","ORDIUSDC"]}"#).unwrap();
            let dummy_response: models::GetLimitPricePairsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetLimitPricePairsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"[{"listTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"listTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let dummy_response: Vec<models::GetListScheduleResponseInner> =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into Vec<models::GetListScheduleResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","riskBasedLiquidationRatio":"0.01"},{"asset":"BUSD","riskBasedLiquidationRatio":"0.01"}]"#).unwrap();
            let dummy_response : Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"{"openLongRestrictedAsset":["ADA","CHZ","ETH","LTC","XRP","币安人生"],"maxCollateralExceededAsset":["ACH","BNB","BTC","USDT"]}"#).unwrap();
            let dummy_response: models::GetMarginRestrictedAssetsResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetMarginRestrictedAssetsResponse");

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

            let resp_json: Value = serde_json::from_str(r#"[{"symbol":"BTCUSDT","tier":1,"effectiveMultiple":"10","initialRiskRatio":"1.111","liquidationRiskRatio":"1.05","baseAssetMaxBorrowable":"9","quoteAssetMaxBorrowable":"70000"}]"#).unwrap();
            let dummy_response: Vec<models::QueryIsolatedMarginTierDataResponseInner> =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into Vec<models::QueryIsolatedMarginTierDataResponseInner>",
                );

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

            let resp_json: Value = serde_json::from_str(r#"[{"assetNames":["SHIB","FDUSD","BTC","ETH","USDC"],"rank":1,"brackets":[{"leverage":10,"maxDebt":1000000,"maintenanceMarginRate":0.02,"initialMarginRate":0.1112,"fastNum":0},{"leverage":3,"maxDebt":4000000,"maintenanceMarginRate":0.07,"initialMarginRate":0.5,"fastNum":60000}]}]"#).unwrap();
            let dummy_response : Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"{"assets":{"MATIC":"100000000","STPT":"100000000","TVK":"100000000","SHIB":"97409653"},"updateTime":1699272487}"#).unwrap();
            let dummy_response: models::QueryMarginAvailableInventoryResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryMarginAvailableInventoryResponse");

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

            let resp_json: Value = serde_json::from_str(
                r#"{"calcTime":1562046418000,"price":"0.00333930","symbol":"BNBBTC"}"#,
            )
            .unwrap();
            let dummy_response: models::QueryMarginPriceindexResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryMarginPriceindexResponse");

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


            let resp_json: Value = serde_json::from_str(r#"[{"collaterals":[{"minUsdValue":"0","maxUsdValue":"13000000","discountRate":"1"},{"minUsdValue":"13000000","maxUsdValue":"20000000","discountRate":"0.975"},{"minUsdValue":"20000000","discountRate":"0"}],"assetNames":["BNX"]},{"collaterals":[{"minUsdValue":"0","discountRate":"1"}],"assetNames":["BTC","BUSD","ETH","USDT"]}]"#).unwrap();
            let expected_response : Vec<models::CrossMarginCollateralRatioResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::CrossMarginCollateralRatioResponseInner>");

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


            let resp_json: Value = serde_json::from_str(r#"[{"collaterals":[{"minUsdValue":"0","maxUsdValue":"13000000","discountRate":"1"},{"minUsdValue":"13000000","maxUsdValue":"20000000","discountRate":"0.975"},{"minUsdValue":"20000000","discountRate":"0"}],"assetNames":["BNX"]},{"collaterals":[{"minUsdValue":"0","discountRate":"1"}],"assetNames":["BTC","BUSD","ETH","USDT"]}]"#).unwrap();
            let expected_response : Vec<models::CrossMarginCollateralRatioResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::CrossMarginCollateralRatioResponseInner>");

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","id":351637150141315840,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","id":351637923235429100,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC","delistTime":1704973040},{"base":"XRP","id":351638112213990140,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"XRPBTC"},{"base":"ETH","id":351638524530850560,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"ETHBTC"}]"#).unwrap();
            let expected_response : Vec<models::GetAllCrossMarginPairsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllCrossMarginPairsResponseInner>");

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

            let params = GetAllCrossMarginPairsParams::builder().symbol("symbol_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","id":351637150141315840,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","id":351637923235429100,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC","delistTime":1704973040},{"base":"XRP","id":351638112213990140,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"XRPBTC"},{"base":"ETH","id":351638524530850560,"isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"ETHBTC"}]"#).unwrap();
            let expected_response : Vec<models::GetAllCrossMarginPairsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllCrossMarginPairsResponseInner>");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC"}]"#).unwrap();
            let expected_response : Vec<models::GetAllIsolatedMarginSymbolResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllIsolatedMarginSymbolResponseInner>");

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

            let params = GetAllIsolatedMarginSymbolParams::builder().symbol("symbol_example".to_string()).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"base":"BNB","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"BNBBTC"},{"base":"TRX","isBuyAllowed":true,"isMarginTrade":true,"isSellAllowed":true,"quote":"BTC","symbol":"TRXBTC"}]"#).unwrap();
            let expected_response : Vec<models::GetAllIsolatedMarginSymbolResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllIsolatedMarginSymbolResponseInner>");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"assetFullName":"USD coin","assetName":"USDC","isBorrowable":true,"isMortgageable":true,"userMinBorrow":"0.00000000","userMinRepay":"0.00000000","delistTime":1704973040}]"#).unwrap();
            let expected_response : Vec<models::GetAllMarginAssetsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllMarginAssetsResponseInner>");

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

            let params = GetAllMarginAssetsParams::builder().asset("asset_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"assetFullName":"USD coin","assetName":"USDC","isBorrowable":true,"isMortgageable":true,"userMinBorrow":"0.00000000","userMinRepay":"0.00000000","delistTime":1704973040}]"#).unwrap();
            let expected_response : Vec<models::GetAllMarginAssetsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetAllMarginAssetsResponseInner>");

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

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let expected_response : Vec<models::GetDelistScheduleResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetDelistScheduleResponseInner>");

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"delistTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"delistTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let expected_response : Vec<models::GetDelistScheduleResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetDelistScheduleResponseInner>");

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

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

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

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


            let resp_json: Value = serde_json::from_str(r#"{"crossMarginSymbols":["BLURUSDC","SANDBTC","QKCBTC","SEIFDUSD","NEOUSDC","ARBFDUSD","ORDIUSDC"]}"#).unwrap();
            let expected_response : models::GetLimitPricePairsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetLimitPricePairsResponse");

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


            let resp_json: Value = serde_json::from_str(r#"{"crossMarginSymbols":["BLURUSDC","SANDBTC","QKCBTC","SEIFDUSD","NEOUSDC","ARBFDUSD","ORDIUSDC"]}"#).unwrap();
            let expected_response : models::GetLimitPricePairsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetLimitPricePairsResponse");

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

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

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"listTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"listTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let expected_response : Vec<models::GetListScheduleResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetListScheduleResponseInner>");

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

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

            let resp_json: Value = serde_json::from_str(r#"[{"listTime":1686161202000,"crossMarginAssets":["BTC","USDT"],"isolatedMarginSymbols":["ADAUSDT","BNBUSDT"]},{"listTime":1686222232000,"crossMarginAssets":["ADA"],"isolatedMarginSymbols":[]}]"#).unwrap();
            let expected_response : Vec<models::GetListScheduleResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetListScheduleResponseInner>");

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

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

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

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


            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","riskBasedLiquidationRatio":"0.01"},{"asset":"BUSD","riskBasedLiquidationRatio":"0.01"}]"#).unwrap();
            let expected_response : Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>");

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


            let resp_json: Value = serde_json::from_str(r#"[{"asset":"USDC","riskBasedLiquidationRatio":"0.01"},{"asset":"BUSD","riskBasedLiquidationRatio":"0.01"}]"#).unwrap();
            let expected_response : Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::GetMarginAssetRiskBasedLiquidationRatioResponseInner>");

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

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

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


            let resp_json: Value = serde_json::from_str(r#"{"openLongRestrictedAsset":["ADA","CHZ","ETH","LTC","XRP","币安人生"],"maxCollateralExceededAsset":["ACH","BNB","BTC","USDT"]}"#).unwrap();
            let expected_response : models::GetMarginRestrictedAssetsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarginRestrictedAssetsResponse");

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


            let resp_json: Value = serde_json::from_str(r#"{"openLongRestrictedAsset":["ADA","CHZ","ETH","LTC","XRP","币安人生"],"maxCollateralExceededAsset":["ACH","BNB","BTC","USDT"]}"#).unwrap();
            let expected_response : models::GetMarginRestrictedAssetsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetMarginRestrictedAssetsResponse");

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

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

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

            let params = QueryIsolatedMarginTierDataParams::builder("symbol_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"symbol":"BTCUSDT","tier":1,"effectiveMultiple":"10","initialRiskRatio":"1.111","liquidationRiskRatio":"1.05","baseAssetMaxBorrowable":"9","quoteAssetMaxBorrowable":"70000"}]"#).unwrap();
            let expected_response : Vec<models::QueryIsolatedMarginTierDataResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryIsolatedMarginTierDataResponseInner>");

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

            let params = QueryIsolatedMarginTierDataParams::builder("symbol_example".to_string(),).tier(789).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"symbol":"BTCUSDT","tier":1,"effectiveMultiple":"10","initialRiskRatio":"1.111","liquidationRiskRatio":"1.05","baseAssetMaxBorrowable":"9","quoteAssetMaxBorrowable":"70000"}]"#).unwrap();
            let expected_response : Vec<models::QueryIsolatedMarginTierDataResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryIsolatedMarginTierDataResponseInner>");

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

            let params = QueryIsolatedMarginTierDataParams::builder("symbol_example".to_string())
                .build()
                .unwrap();

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

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


            let resp_json: Value = serde_json::from_str(r#"[{"assetNames":["SHIB","FDUSD","BTC","ETH","USDC"],"rank":1,"brackets":[{"leverage":10,"maxDebt":1000000,"maintenanceMarginRate":0.02,"initialMarginRate":0.1112,"fastNum":0},{"leverage":3,"maxDebt":4000000,"maintenanceMarginRate":0.07,"initialMarginRate":0.5,"fastNum":60000}]}]"#).unwrap();
            let expected_response : Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>");

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


            let resp_json: Value = serde_json::from_str(r#"[{"assetNames":["SHIB","FDUSD","BTC","ETH","USDC"],"rank":1,"brackets":[{"leverage":10,"maxDebt":1000000,"maintenanceMarginRate":0.02,"initialMarginRate":0.1112,"fastNum":0},{"leverage":3,"maxDebt":4000000,"maintenanceMarginRate":0.07,"initialMarginRate":0.5,"fastNum":60000}]}]"#).unwrap();
            let expected_response : Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryLiabilityCoinLeverageBracketInCrossMarginProModeResponseInner>");

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

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

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

            let params = QueryMarginAvailableInventoryParams::builder("r#type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"assets":{"MATIC":"100000000","STPT":"100000000","TVK":"100000000","SHIB":"97409653"},"updateTime":1699272487}"#).unwrap();
            let expected_response : models::QueryMarginAvailableInventoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryMarginAvailableInventoryResponse");

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

            let params = QueryMarginAvailableInventoryParams::builder("r#type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"assets":{"MATIC":"100000000","STPT":"100000000","TVK":"100000000","SHIB":"97409653"},"updateTime":1699272487}"#).unwrap();
            let expected_response : models::QueryMarginAvailableInventoryResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryMarginAvailableInventoryResponse");

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

            let params = QueryMarginAvailableInventoryParams::builder("r#type_example".to_string())
                .build()
                .unwrap();

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

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

            let params = QueryMarginPriceindexParams::builder("symbol_example".to_string())
                .build()
                .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"calcTime":1562046418000,"price":"0.00333930","symbol":"BNBBTC"}"#,
            )
            .unwrap();
            let expected_response: models::QueryMarginPriceindexResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryMarginPriceindexResponse");

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

            let params = QueryMarginPriceindexParams::builder("symbol_example".to_string())
                .build()
                .unwrap();

            let resp_json: Value = serde_json::from_str(
                r#"{"calcTime":1562046418000,"price":"0.00333930","symbol":"BNBBTC"}"#,
            )
            .unwrap();
            let expected_response: models::QueryMarginPriceindexResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryMarginPriceindexResponse");

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

            let params = QueryMarginPriceindexParams::builder("symbol_example".to_string())
                .build()
                .unwrap();

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