/*
 * Binance Sub Account REST API
 *
 * OpenAPI Specification for the Binance Sub Account 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::sub_account::rest_api::models;

const HAS_TIME_UNIT: bool = false;

#[async_trait]
pub trait ManagedSubAccountApi: Send + Sync {
    async fn deposit_assets_into_the_managed_sub_account(
        &self,
        params: DepositAssetsIntoTheManagedSubAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositAssetsIntoTheManagedSubAccountResponse>>;
    async fn get_managed_sub_account_deposit_address(
        &self,
        params: GetManagedSubAccountDepositAddressParams,
    ) -> anyhow::Result<RestApiResponse<models::GetManagedSubAccountDepositAddressResponse>>;
    async fn query_managed_sub_account_asset_details(
        &self,
        params: QueryManagedSubAccountAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>>>;
    async fn query_managed_sub_account_futures_asset_details(
        &self,
        params: QueryManagedSubAccountFuturesAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountFuturesAssetDetailsResponse>>;
    async fn query_managed_sub_account_list(
        &self,
        params: QueryManagedSubAccountListParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountListResponse>>;
    async fn query_managed_sub_account_margin_asset_details(
        &self,
        params: QueryManagedSubAccountMarginAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountMarginAssetDetailsResponse>>;
    async fn query_managed_sub_account_snapshot(
        &self,
        params: QueryManagedSubAccountSnapshotParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountSnapshotResponse>>;
    async fn query_managed_sub_account_transfer_log_master_account_investor(
        &self,
        params: QueryManagedSubAccountTransferLogMasterAccountInvestorParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse>,
    >;
    async fn query_managed_sub_account_transfer_log_master_account_trading(
        &self,
        params: QueryManagedSubAccountTransferLogMasterAccountTradingParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse>,
    >;
    async fn query_managed_sub_account_transfer_log_sub_account_trading(
        &self,
        params: QueryManagedSubAccountTransferLogSubAccountTradingParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogSubAccountTradingResponse>,
    >;
    async fn withdrawl_assets_from_the_managed_sub_account(
        &self,
        params: WithdrawlAssetsFromTheManagedSubAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::WithdrawlAssetsFromTheManagedSubAccountResponse>>;
}

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

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

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

impl DepositAssetsIntoTheManagedSubAccountParams {
    /// Create a builder for [`deposit_assets_into_the_managed_sub_account`].
    ///
    /// Required parameters:
    ///
    /// * `to_email` — String
    /// * `asset` — String
    /// * `amount` — `rust_decimal::Decimal`
    ///
    #[must_use]
    pub fn builder(
        to_email: String,
        asset: String,
        amount: rust_decimal::Decimal,
    ) -> DepositAssetsIntoTheManagedSubAccountParamsBuilder {
        DepositAssetsIntoTheManagedSubAccountParamsBuilder::default()
            .to_email(to_email)
            .asset(asset)
            .amount(amount)
    }
}
/// Request parameters for the [`get_managed_sub_account_deposit_address`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`get_managed_sub_account_deposit_address`](#method.get_managed_sub_account_deposit_address).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct GetManagedSubAccountDepositAddressParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    ///
    /// The `coin` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub coin: String,
    /// networks can be found in `GET /sapi/v1/capital/deposit/address`
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub network: Option<String>,
    ///
    /// The `amount` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub amount: Option<rust_decimal::Decimal>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl GetManagedSubAccountDepositAddressParams {
    /// Create a builder for [`get_managed_sub_account_deposit_address`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    /// * `coin` — String
    ///
    #[must_use]
    pub fn builder(email: String, coin: String) -> GetManagedSubAccountDepositAddressParamsBuilder {
        GetManagedSubAccountDepositAddressParamsBuilder::default()
            .email(email)
            .coin(coin)
    }
}
/// Request parameters for the [`query_managed_sub_account_asset_details`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_asset_details`](#method.query_managed_sub_account_asset_details).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountAssetDetailsParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryManagedSubAccountAssetDetailsParams {
    /// Create a builder for [`query_managed_sub_account_asset_details`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    ///
    #[must_use]
    pub fn builder(email: String) -> QueryManagedSubAccountAssetDetailsParamsBuilder {
        QueryManagedSubAccountAssetDetailsParamsBuilder::default().email(email)
    }
}
/// Request parameters for the [`query_managed_sub_account_futures_asset_details`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_futures_asset_details`](#method.query_managed_sub_account_futures_asset_details).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountFuturesAssetDetailsParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    /// No input or input "MARGIN" to get Cross Margin account details. Input "`ISOLATED_MARGIN`" to get Isolated Margin account details.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub account_type: Option<String>,
}

impl QueryManagedSubAccountFuturesAssetDetailsParams {
    /// Create a builder for [`query_managed_sub_account_futures_asset_details`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    ///
    #[must_use]
    pub fn builder(email: String) -> QueryManagedSubAccountFuturesAssetDetailsParamsBuilder {
        QueryManagedSubAccountFuturesAssetDetailsParamsBuilder::default().email(email)
    }
}
/// Request parameters for the [`query_managed_sub_account_list`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_list`](#method.query_managed_sub_account_list).
#[derive(Clone, Debug, Builder, Default)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountListParams {
    /// Managed sub-account email
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub email: Option<String>,
    /// Default value: 1
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub page: Option<i64>,
    /// Default value: 1, Max value: 200
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryManagedSubAccountListParams {
    /// Create a builder for [`query_managed_sub_account_list`].
    ///
    #[must_use]
    pub fn builder() -> QueryManagedSubAccountListParamsBuilder {
        QueryManagedSubAccountListParamsBuilder::default()
    }
}
/// Request parameters for the [`query_managed_sub_account_margin_asset_details`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_margin_asset_details`](#method.query_managed_sub_account_margin_asset_details).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountMarginAssetDetailsParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    /// No input or input "MARGIN" to get Cross Margin account details. Input "`ISOLATED_MARGIN`" to get Isolated Margin account details.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub account_type: Option<String>,
}

impl QueryManagedSubAccountMarginAssetDetailsParams {
    /// Create a builder for [`query_managed_sub_account_margin_asset_details`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    ///
    #[must_use]
    pub fn builder(email: String) -> QueryManagedSubAccountMarginAssetDetailsParamsBuilder {
        QueryManagedSubAccountMarginAssetDetailsParamsBuilder::default().email(email)
    }
}
/// Request parameters for the [`query_managed_sub_account_snapshot`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_snapshot`](#method.query_managed_sub_account_snapshot).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountSnapshotParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    /// "SPOT", "MARGIN"（cross）, "FUTURES"（UM）
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub r#type: String,
    ///
    /// The `start_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub start_time: Option<i64>,
    ///
    /// The `end_time` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub end_time: Option<i64>,
    /// Default value: 1, Max value: 200
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub limit: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryManagedSubAccountSnapshotParams {
    /// Create a builder for [`query_managed_sub_account_snapshot`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    /// * `r#type` — \"SPOT\", \"MARGIN\"（cross）, \"FUTURES\"（UM）
    ///
    #[must_use]
    pub fn builder(email: String, r#type: String) -> QueryManagedSubAccountSnapshotParamsBuilder {
        QueryManagedSubAccountSnapshotParamsBuilder::default()
            .email(email)
            .r#type(r#type)
    }
}
/// Request parameters for the [`query_managed_sub_account_transfer_log_master_account_investor`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_transfer_log_master_account_investor`](#method.query_managed_sub_account_transfer_log_master_account_investor).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountTransferLogMasterAccountInvestorParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    /// Start Time
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub start_time: i64,
    /// End Time (The start time and end time interval cannot exceed half a year)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub end_time: i64,
    /// Page
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub page: i64,
    /// Limit (Max: 500)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub limit: i64,
    /// Transfer Direction (FROM/TO)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfers: Option<String>,
    /// Transfer function account type (`SPOT/MARGIN/ISOLATED_MARGIN/USDT_FUTURE/COIN_FUTURE`)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfer_function_account_type: Option<String>,
}

impl QueryManagedSubAccountTransferLogMasterAccountInvestorParams {
    /// Create a builder for [`query_managed_sub_account_transfer_log_master_account_investor`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    /// * `start_time` — Start Time
    /// * `end_time` — End Time (The start time and end time interval cannot exceed half a year)
    /// * `page` — Page
    /// * `limit` — Limit (Max: 500)
    ///
    #[must_use]
    pub fn builder(
        email: String,
        start_time: i64,
        end_time: i64,
        page: i64,
        limit: i64,
    ) -> QueryManagedSubAccountTransferLogMasterAccountInvestorParamsBuilder {
        QueryManagedSubAccountTransferLogMasterAccountInvestorParamsBuilder::default()
            .email(email)
            .start_time(start_time)
            .end_time(end_time)
            .page(page)
            .limit(limit)
    }
}
/// Request parameters for the [`query_managed_sub_account_transfer_log_master_account_trading`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_transfer_log_master_account_trading`](#method.query_managed_sub_account_transfer_log_master_account_trading).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountTransferLogMasterAccountTradingParams {
    /// [Sub-account email](#email-address)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub email: String,
    /// Start Time
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub start_time: i64,
    /// End Time (The start time and end time interval cannot exceed half a year)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub end_time: i64,
    /// Page
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub page: i64,
    /// Limit (Max: 500)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub limit: i64,
    /// Transfer Direction (FROM/TO)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfers: Option<String>,
    /// Transfer function account type (`SPOT/MARGIN/ISOLATED_MARGIN/USDT_FUTURE/COIN_FUTURE`)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfer_function_account_type: Option<String>,
}

impl QueryManagedSubAccountTransferLogMasterAccountTradingParams {
    /// Create a builder for [`query_managed_sub_account_transfer_log_master_account_trading`].
    ///
    /// Required parameters:
    ///
    /// * `email` — [Sub-account email](#email-address)
    /// * `start_time` — Start Time
    /// * `end_time` — End Time (The start time and end time interval cannot exceed half a year)
    /// * `page` — Page
    /// * `limit` — Limit (Max: 500)
    ///
    #[must_use]
    pub fn builder(
        email: String,
        start_time: i64,
        end_time: i64,
        page: i64,
        limit: i64,
    ) -> QueryManagedSubAccountTransferLogMasterAccountTradingParamsBuilder {
        QueryManagedSubAccountTransferLogMasterAccountTradingParamsBuilder::default()
            .email(email)
            .start_time(start_time)
            .end_time(end_time)
            .page(page)
            .limit(limit)
    }
}
/// Request parameters for the [`query_managed_sub_account_transfer_log_sub_account_trading`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`query_managed_sub_account_transfer_log_sub_account_trading`](#method.query_managed_sub_account_transfer_log_sub_account_trading).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct QueryManagedSubAccountTransferLogSubAccountTradingParams {
    /// Start Time
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub start_time: i64,
    /// End Time (The start time and end time interval cannot exceed half a year)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub end_time: i64,
    /// Page
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub page: i64,
    /// Limit (Max: 500)
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub limit: i64,
    /// Transfer Direction (FROM/TO)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfers: Option<String>,
    /// Transfer function account type (`SPOT/MARGIN/ISOLATED_MARGIN/USDT_FUTURE/COIN_FUTURE`)
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfer_function_account_type: Option<String>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl QueryManagedSubAccountTransferLogSubAccountTradingParams {
    /// Create a builder for [`query_managed_sub_account_transfer_log_sub_account_trading`].
    ///
    /// Required parameters:
    ///
    /// * `start_time` — Start Time
    /// * `end_time` — End Time (The start time and end time interval cannot exceed half a year)
    /// * `page` — Page
    /// * `limit` — Limit (Max: 500)
    ///
    #[must_use]
    pub fn builder(
        start_time: i64,
        end_time: i64,
        page: i64,
        limit: i64,
    ) -> QueryManagedSubAccountTransferLogSubAccountTradingParamsBuilder {
        QueryManagedSubAccountTransferLogSubAccountTradingParamsBuilder::default()
            .start_time(start_time)
            .end_time(end_time)
            .page(page)
            .limit(limit)
    }
}
/// Request parameters for the [`withdrawl_assets_from_the_managed_sub_account`] operation.
///
/// This struct holds all of the inputs you can pass when calling
/// [`withdrawl_assets_from_the_managed_sub_account`](#method.withdrawl_assets_from_the_managed_sub_account).
#[derive(Clone, Debug, Builder)]
#[builder(pattern = "owned", build_fn(error = "ParamBuildError"))]
pub struct WithdrawlAssetsFromTheManagedSubAccountParams {
    ///
    /// The `from_email` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub from_email: String,
    ///
    /// The `asset` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub asset: String,
    ///
    /// The `amount` parameter.
    ///
    /// This field is **required.
    #[builder(setter(into))]
    pub amount: rust_decimal::Decimal,
    /// Withdrawals is automatically occur on the transfer date(UTC0). If a date is not selected, the withdrawal occurs right now
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub transfer_date: Option<i64>,
    ///
    /// The `recv_window` parameter.
    ///
    /// This field is **optional.
    #[builder(setter(into), default)]
    pub recv_window: Option<i64>,
}

impl WithdrawlAssetsFromTheManagedSubAccountParams {
    /// Create a builder for [`withdrawl_assets_from_the_managed_sub_account`].
    ///
    /// Required parameters:
    ///
    /// * `from_email` — String
    /// * `asset` — String
    /// * `amount` — `rust_decimal::Decimal`
    ///
    #[must_use]
    pub fn builder(
        from_email: String,
        asset: String,
        amount: rust_decimal::Decimal,
    ) -> WithdrawlAssetsFromTheManagedSubAccountParamsBuilder {
        WithdrawlAssetsFromTheManagedSubAccountParamsBuilder::default()
            .from_email(from_email)
            .asset(asset)
            .amount(amount)
    }
}

#[async_trait]
impl ManagedSubAccountApi for ManagedSubAccountApiClient {
    async fn deposit_assets_into_the_managed_sub_account(
        &self,
        params: DepositAssetsIntoTheManagedSubAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::DepositAssetsIntoTheManagedSubAccountResponse>>
    {
        let DepositAssetsIntoTheManagedSubAccountParams {
            to_email,
            asset,
            amount,
            recv_window,
        } = params;

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

        query_params.insert("toEmail".to_string(), json!(to_email));

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

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

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

        send_request::<models::DepositAssetsIntoTheManagedSubAccountResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/deposit",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn get_managed_sub_account_deposit_address(
        &self,
        params: GetManagedSubAccountDepositAddressParams,
    ) -> anyhow::Result<RestApiResponse<models::GetManagedSubAccountDepositAddressResponse>> {
        let GetManagedSubAccountDepositAddressParams {
            email,
            coin,
            network,
            amount,
            recv_window,
        } = params;

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

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

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

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

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

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

        send_request::<models::GetManagedSubAccountDepositAddressResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/deposit/address",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_asset_details(
        &self,
        params: QueryManagedSubAccountAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>>>
    {
        let QueryManagedSubAccountAssetDetailsParams { email, recv_window } = params;

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

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

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

        send_request::<Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/asset",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_futures_asset_details(
        &self,
        params: QueryManagedSubAccountFuturesAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountFuturesAssetDetailsResponse>>
    {
        let QueryManagedSubAccountFuturesAssetDetailsParams {
            email,
            account_type,
        } = params;

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

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

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

        send_request::<models::QueryManagedSubAccountFuturesAssetDetailsResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/fetch-future-asset",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_list(
        &self,
        params: QueryManagedSubAccountListParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountListResponse>> {
        let QueryManagedSubAccountListParams {
            email,
            page,
            limit,
            recv_window,
        } = params;

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

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

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

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

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

        send_request::<models::QueryManagedSubAccountListResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/info",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_margin_asset_details(
        &self,
        params: QueryManagedSubAccountMarginAssetDetailsParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountMarginAssetDetailsResponse>>
    {
        let QueryManagedSubAccountMarginAssetDetailsParams {
            email,
            account_type,
        } = params;

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

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

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

        send_request::<models::QueryManagedSubAccountMarginAssetDetailsResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/marginAsset",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_snapshot(
        &self,
        params: QueryManagedSubAccountSnapshotParams,
    ) -> anyhow::Result<RestApiResponse<models::QueryManagedSubAccountSnapshotResponse>> {
        let QueryManagedSubAccountSnapshotParams {
            email,
            r#type,
            start_time,
            end_time,
            limit,
            recv_window,
        } = params;

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

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

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

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

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

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

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

        send_request::<models::QueryManagedSubAccountSnapshotResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/accountSnapshot",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_transfer_log_master_account_investor(
        &self,
        params: QueryManagedSubAccountTransferLogMasterAccountInvestorParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse>,
    > {
        let QueryManagedSubAccountTransferLogMasterAccountInvestorParams {
            email,
            start_time,
            end_time,
            page,
            limit,
            transfers,
            transfer_function_account_type,
        } = params;

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

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

        query_params.insert("startTime".to_string(), json!(start_time));

        query_params.insert("endTime".to_string(), json!(end_time));

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

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

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

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

        send_request::<models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/queryTransLogForInvestor",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_transfer_log_master_account_trading(
        &self,
        params: QueryManagedSubAccountTransferLogMasterAccountTradingParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse>,
    > {
        let QueryManagedSubAccountTransferLogMasterAccountTradingParams {
            email,
            start_time,
            end_time,
            page,
            limit,
            transfers,
            transfer_function_account_type,
        } = params;

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

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

        query_params.insert("startTime".to_string(), json!(start_time));

        query_params.insert("endTime".to_string(), json!(end_time));

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

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

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

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

        send_request::<models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/queryTransLogForTradeParent",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn query_managed_sub_account_transfer_log_sub_account_trading(
        &self,
        params: QueryManagedSubAccountTransferLogSubAccountTradingParams,
    ) -> anyhow::Result<
        RestApiResponse<models::QueryManagedSubAccountTransferLogSubAccountTradingResponse>,
    > {
        let QueryManagedSubAccountTransferLogSubAccountTradingParams {
            start_time,
            end_time,
            page,
            limit,
            transfers,
            transfer_function_account_type,
            recv_window,
        } = params;

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

        query_params.insert("startTime".to_string(), json!(start_time));

        query_params.insert("endTime".to_string(), json!(end_time));

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

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

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

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

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

        send_request::<models::QueryManagedSubAccountTransferLogSubAccountTradingResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/query-trans-log",
            reqwest::Method::GET,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }

    async fn withdrawl_assets_from_the_managed_sub_account(
        &self,
        params: WithdrawlAssetsFromTheManagedSubAccountParams,
    ) -> anyhow::Result<RestApiResponse<models::WithdrawlAssetsFromTheManagedSubAccountResponse>>
    {
        let WithdrawlAssetsFromTheManagedSubAccountParams {
            from_email,
            asset,
            amount,
            transfer_date,
            recv_window,
        } = params;

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

        query_params.insert("fromEmail".to_string(), json!(from_email));

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

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

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

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

        send_request::<models::WithdrawlAssetsFromTheManagedSubAccountResponse>(
            &self.configuration,
            "/sapi/v1/managed-subaccount/withdraw",
            reqwest::Method::POST,
            query_params,
            body_params,
            if HAS_TIME_UNIT {
                self.configuration.time_unit
            } else {
                None
            },
            true,
        )
        .await
    }
}

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

    #[async_trait]
    impl ManagedSubAccountApi for MockManagedSubAccountApiClient {
        async fn deposit_assets_into_the_managed_sub_account(
            &self,
            _params: DepositAssetsIntoTheManagedSubAccountParams,
        ) -> anyhow::Result<RestApiResponse<models::DepositAssetsIntoTheManagedSubAccountResponse>>
        {
            if self.force_error {
                return Err(ConnectorError::ConnectorClientError {
                    msg: "ResponseError".to_string(),
                    code: None,
                }
                .into());
            }

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let dummy_response: models::DepositAssetsIntoTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::DepositAssetsIntoTheManagedSubAccountResponse",
                );

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

            let resp_json: Value = serde_json::from_str(r#"{"coin":"USDT","address":"0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d","tag":"","url":"https://etherscan.io/address/0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d"}"#).unwrap();
            let dummy_response: models::GetManagedSubAccountDepositAddressResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::GetManagedSubAccountDepositAddressResponse");

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

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"INJ","name":"Injective Protocol","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"},{"coin":"FILDOWN","name":"FILDOWN","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"}]"#).unwrap();
            let dummy_response : Vec<models::QueryManagedSubAccountAssetDetailsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>");

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

            let resp_json: Value = serde_json::from_str(r#"{"code":"200","message":"OK","snapshotVos":[{"type":"FUTURES","updateTime":1672893855394,"data":{"assets":[{"asset":"USDT","marginBalance":100,"walletBalance":120}],"position":[{"symbol":"BTCUSDT","entryPrice":17000,"markPrice":17000,"positionAmt":1.0E-4}]}}]}"#).unwrap();
            let dummy_response: models::QueryManagedSubAccountFuturesAssetDetailsResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::QueryManagedSubAccountFuturesAssetDetailsResponse",
                );

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

            let resp_json: Value = serde_json::from_str(r#"{"total":3,"managerSubUserInfoVoList":[{"rootUserId":1000138475670,"managersubUserId":1000137842513,"bindParentUserId":1000138475669,"email":"test_0_virtual@kq3kno9imanagedsub.com","insertTimeStamp":1678435149000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842514,"bindParentUserId":1000138475669,"email":"test_1_virtual@4qd2u7zxmanagedsub.com","insertTimeStamp":1678435152000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842515,"bindParentUserId":1000138475669,"email":"test_2_virtual@akc05o8hmanagedsub.com","insertTimeStamp":1678435153000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false}]}"#).unwrap();
            let dummy_response: models::QueryManagedSubAccountListResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryManagedSubAccountListResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"marginLevel":"999","totalAssetOfBtc":"0","totalLiabilityOfBtc":"0","totalNetAssetOfBtc":"0","userAssets":[{"asset":"MATIC","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"VET","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"BAKE","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"}]}"#).unwrap();
            let dummy_response: models::QueryManagedSubAccountMarginAssetDetailsResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::QueryManagedSubAccountMarginAssetDetailsResponse",
                );

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

            let resp_json: Value = serde_json::from_str(r#"{"code":200,"msg":"","snapshotVos":[{"data":{"balances":[{"asset":"BTC","free":"0.09905021","locked":"0.00000000"},{"asset":"USDT","free":"1.89109409","locked":"0.00000000"}],"totalAssetOfBtc":"0.09942700"},"type":"spot","updateTime":1576281599000},{"data":{"marginLevel":"2748.02909813","totalAssetOfBtc":"0.00274803","totalLiabilityOfBtc":"0.00000100","totalNetAssetOfBtc":"0.00274750","userAssets":[{"asset":"XRP","borrowed":"0.00000000","free":"1.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"1.00000000"}]},"type":"margin","updateTime":1576281599000},{"data":{"assets":[{"asset":"USDT","marginBalance":"118.99782335","walletBalance":"120.23811389"}],"position":[{"entryPrice":"7130.41000000","markPrice":"7257.66239673","positionAmt":"0.01000000","symbol":"BTCUSDT","unRealizedProfit":"1.24029054"}]},"type":"futures","updateTime":1576281599000}]}"#).unwrap();
            let dummy_response: models::QueryManagedSubAccountSnapshotResponse =
                serde_json::from_value(resp_json.clone())
                    .expect("should parse into models::QueryManagedSubAccountSnapshotResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let dummy_response : models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let dummy_response : models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let dummy_response : models::QueryManagedSubAccountTransferLogSubAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogSubAccountTradingResponse");

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

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let dummy_response: models::WithdrawlAssetsFromTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::WithdrawlAssetsFromTheManagedSubAccountResponse",
                );

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

            let params = DepositAssetsIntoTheManagedSubAccountParams::builder(
                "to_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let expected_response: models::DepositAssetsIntoTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::DepositAssetsIntoTheManagedSubAccountResponse",
                );

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

            let params = DepositAssetsIntoTheManagedSubAccountParams::builder(
                "to_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .recv_window(5000)
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let expected_response: models::DepositAssetsIntoTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::DepositAssetsIntoTheManagedSubAccountResponse",
                );

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

            let params = DepositAssetsIntoTheManagedSubAccountParams::builder(
                "to_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

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

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

            let params = GetManagedSubAccountDepositAddressParams::builder("sub-account-email@email.com".to_string(),"coin_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"coin":"USDT","address":"0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d","tag":"","url":"https://etherscan.io/address/0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d"}"#).unwrap();
            let expected_response : models::GetManagedSubAccountDepositAddressResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetManagedSubAccountDepositAddressResponse");

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

            let params = GetManagedSubAccountDepositAddressParams::builder("sub-account-email@email.com".to_string(),"coin_example".to_string(),).network("network_example".to_string()).amount(dec!(1.0)).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"coin":"USDT","address":"0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d","tag":"","url":"https://etherscan.io/address/0x206c22d833bb0bb2102da6b7c7d4c3eb14bcf73d"}"#).unwrap();
            let expected_response : models::GetManagedSubAccountDepositAddressResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::GetManagedSubAccountDepositAddressResponse");

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

            let params = GetManagedSubAccountDepositAddressParams::builder(
                "sub-account-email@email.com".to_string(),
                "coin_example".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"INJ","name":"Injective Protocol","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"},{"coin":"FILDOWN","name":"FILDOWN","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"}]"#).unwrap();
            let expected_response : Vec<models::QueryManagedSubAccountAssetDetailsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>");

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

            let params = QueryManagedSubAccountAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"[{"coin":"INJ","name":"Injective Protocol","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"},{"coin":"FILDOWN","name":"FILDOWN","totalBalance":"0","availableBalance":"0","inOrder":"0","btcValue":"0"}]"#).unwrap();
            let expected_response : Vec<models::QueryManagedSubAccountAssetDetailsResponseInner> = serde_json::from_value(resp_json.clone()).expect("should parse into Vec<models::QueryManagedSubAccountAssetDetailsResponseInner>");

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

            let params = QueryManagedSubAccountAssetDetailsParams::builder(
                "sub-account-email@email.com".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountFuturesAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"200","message":"OK","snapshotVos":[{"type":"FUTURES","updateTime":1672893855394,"data":{"assets":[{"asset":"USDT","marginBalance":100,"walletBalance":120}],"position":[{"symbol":"BTCUSDT","entryPrice":17000,"markPrice":17000,"positionAmt":1.0E-4}]}}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountFuturesAssetDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountFuturesAssetDetailsResponse");

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

            let params = QueryManagedSubAccountFuturesAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).account_type("account_type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":"200","message":"OK","snapshotVos":[{"type":"FUTURES","updateTime":1672893855394,"data":{"assets":[{"asset":"USDT","marginBalance":100,"walletBalance":120}],"position":[{"symbol":"BTCUSDT","entryPrice":17000,"markPrice":17000,"positionAmt":1.0E-4}]}}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountFuturesAssetDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountFuturesAssetDetailsResponse");

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

            let params = QueryManagedSubAccountFuturesAssetDetailsParams::builder(
                "sub-account-email@email.com".to_string(),
            )
            .build()
            .unwrap();

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

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

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

            let resp_json: Value = serde_json::from_str(r#"{"total":3,"managerSubUserInfoVoList":[{"rootUserId":1000138475670,"managersubUserId":1000137842513,"bindParentUserId":1000138475669,"email":"test_0_virtual@kq3kno9imanagedsub.com","insertTimeStamp":1678435149000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842514,"bindParentUserId":1000138475669,"email":"test_1_virtual@4qd2u7zxmanagedsub.com","insertTimeStamp":1678435152000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842515,"bindParentUserId":1000138475669,"email":"test_2_virtual@akc05o8hmanagedsub.com","insertTimeStamp":1678435153000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountListResponse");

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

            let params = QueryManagedSubAccountListParams::builder().email("email_example".to_string()).page(1).limit(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"total":3,"managerSubUserInfoVoList":[{"rootUserId":1000138475670,"managersubUserId":1000137842513,"bindParentUserId":1000138475669,"email":"test_0_virtual@kq3kno9imanagedsub.com","insertTimeStamp":1678435149000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842514,"bindParentUserId":1000138475669,"email":"test_1_virtual@4qd2u7zxmanagedsub.com","insertTimeStamp":1678435152000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false},{"rootUserId":1000138475670,"managersubUserId":1000137842515,"bindParentUserId":1000138475669,"email":"test_2_virtual@akc05o8hmanagedsub.com","insertTimeStamp":1678435153000,"bindParentEmail":"wdyw8xsh8pey@test.com","isSubUserEnabled":true,"isUserActive":true,"isMarginEnabled":false,"isFutureEnabled":false,"isSignedLVTRiskAgreement":false}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountListResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountListResponse");

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

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

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

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

            let params = QueryManagedSubAccountMarginAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"marginLevel":"999","totalAssetOfBtc":"0","totalLiabilityOfBtc":"0","totalNetAssetOfBtc":"0","userAssets":[{"asset":"MATIC","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"VET","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"BAKE","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountMarginAssetDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountMarginAssetDetailsResponse");

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

            let params = QueryManagedSubAccountMarginAssetDetailsParams::builder("sub-account-email@email.com".to_string(),).account_type("account_type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"marginLevel":"999","totalAssetOfBtc":"0","totalLiabilityOfBtc":"0","totalNetAssetOfBtc":"0","userAssets":[{"asset":"MATIC","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"VET","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"},{"asset":"BAKE","borrowed":"0","free":"0","interest":"0","locked":"0","netAsset":"0"}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountMarginAssetDetailsResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountMarginAssetDetailsResponse");

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

            let params = QueryManagedSubAccountMarginAssetDetailsParams::builder(
                "sub-account-email@email.com".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountSnapshotParams::builder("sub-account-email@email.com".to_string(),"r#type_example".to_string(),).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":200,"msg":"","snapshotVos":[{"data":{"balances":[{"asset":"BTC","free":"0.09905021","locked":"0.00000000"},{"asset":"USDT","free":"1.89109409","locked":"0.00000000"}],"totalAssetOfBtc":"0.09942700"},"type":"spot","updateTime":1576281599000},{"data":{"marginLevel":"2748.02909813","totalAssetOfBtc":"0.00274803","totalLiabilityOfBtc":"0.00000100","totalNetAssetOfBtc":"0.00274750","userAssets":[{"asset":"XRP","borrowed":"0.00000000","free":"1.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"1.00000000"}]},"type":"margin","updateTime":1576281599000},{"data":{"assets":[{"asset":"USDT","marginBalance":"118.99782335","walletBalance":"120.23811389"}],"position":[{"entryPrice":"7130.41000000","markPrice":"7257.66239673","positionAmt":"0.01000000","symbol":"BTCUSDT","unRealizedProfit":"1.24029054"}]},"type":"futures","updateTime":1576281599000}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountSnapshotResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountSnapshotResponse");

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

            let params = QueryManagedSubAccountSnapshotParams::builder("sub-account-email@email.com".to_string(),"r#type_example".to_string(),).start_time(1623319461670).end_time(1641782889000).limit(1).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"code":200,"msg":"","snapshotVos":[{"data":{"balances":[{"asset":"BTC","free":"0.09905021","locked":"0.00000000"},{"asset":"USDT","free":"1.89109409","locked":"0.00000000"}],"totalAssetOfBtc":"0.09942700"},"type":"spot","updateTime":1576281599000},{"data":{"marginLevel":"2748.02909813","totalAssetOfBtc":"0.00274803","totalLiabilityOfBtc":"0.00000100","totalNetAssetOfBtc":"0.00274750","userAssets":[{"asset":"XRP","borrowed":"0.00000000","free":"1.00000000","interest":"0.00000000","locked":"0.00000000","netAsset":"1.00000000"}]},"type":"margin","updateTime":1576281599000},{"data":{"assets":[{"asset":"USDT","marginBalance":"118.99782335","walletBalance":"120.23811389"}],"position":[{"entryPrice":"7130.41000000","markPrice":"7257.66239673","positionAmt":"0.01000000","symbol":"BTCUSDT","unRealizedProfit":"1.24029054"}]},"type":"futures","updateTime":1576281599000}]}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountSnapshotResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountSnapshotResponse");

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

            let params = QueryManagedSubAccountSnapshotParams::builder(
                "sub-account-email@email.com".to_string(),
                "r#type_example".to_string(),
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountTransferLogMasterAccountInvestorParams::builder("sub-account-email@email.com".to_string(),1623319461670,1641782889000,789,789,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse");

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

            let params = QueryManagedSubAccountTransferLogMasterAccountInvestorParams::builder("sub-account-email@email.com".to_string(),1623319461670,1641782889000,789,789,).transfers("transfers_example".to_string()).transfer_function_account_type("transfer_function_account_type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountInvestorResponse");

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

            let params = QueryManagedSubAccountTransferLogMasterAccountInvestorParams::builder(
                "sub-account-email@email.com".to_string(),
                1623319461670,
                1641782889000,
                789,
                789,
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountTransferLogMasterAccountTradingParams::builder("sub-account-email@email.com".to_string(),1623319461670,1641782889000,789,789,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse");

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

            let params = QueryManagedSubAccountTransferLogMasterAccountTradingParams::builder("sub-account-email@email.com".to_string(),1623319461670,1641782889000,789,789,).transfers("transfers_example".to_string()).transfer_function_account_type("transfer_function_account_type_example".to_string()).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogMasterAccountTradingResponse");

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

            let params = QueryManagedSubAccountTransferLogMasterAccountTradingParams::builder(
                "sub-account-email@email.com".to_string(),
                1623319461670,
                1641782889000,
                789,
                789,
            )
            .build()
            .unwrap();

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

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

            let params = QueryManagedSubAccountTransferLogSubAccountTradingParams::builder(1623319461670,1641782889000,789,789,).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogSubAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogSubAccountTradingResponse");

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

            let params = QueryManagedSubAccountTransferLogSubAccountTradingParams::builder(1623319461670,1641782889000,789,789,).transfers("transfers_example".to_string()).transfer_function_account_type("transfer_function_account_type_example".to_string()).recv_window(5000).build().unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"managerSubTransferHistoryVos":[{"fromEmail":"test_0_virtual@kq3kno9imanagedsub.com","fromAccountType":"SPOT","toEmail":"wdywl0lddakh@test.com","toAccountType":"SPOT","asset":"BNB","amount":"0.01","scheduledData":1679416673000,"createTime":1679416673000,"status":"SUCCESS","tranId":91077779},{"fromEmail":"wdywl0lddakh@test.com","fromAccountType":"SPOT","toEmail":"test_0_virtual@kq3kno9imanagedsub.com","toAccountType":"SPOT","asset":"BNB","amount":"1","scheduledData":1679416616000,"createTime":1679416616000,"status":"SUCCESS","tranId":91077676}],"count":2}"#).unwrap();
            let expected_response : models::QueryManagedSubAccountTransferLogSubAccountTradingResponse = serde_json::from_value(resp_json.clone()).expect("should parse into models::QueryManagedSubAccountTransferLogSubAccountTradingResponse");

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

            let params = QueryManagedSubAccountTransferLogSubAccountTradingParams::builder(
                1623319461670,
                1641782889000,
                789,
                789,
            )
            .build()
            .unwrap();

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

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

            let params = WithdrawlAssetsFromTheManagedSubAccountParams::builder(
                "from_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let expected_response: models::WithdrawlAssetsFromTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::WithdrawlAssetsFromTheManagedSubAccountResponse",
                );

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

            let params = WithdrawlAssetsFromTheManagedSubAccountParams::builder(
                "from_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .transfer_date(789)
            .recv_window(5000)
            .build()
            .unwrap();

            let resp_json: Value = serde_json::from_str(r#"{"tranId":66157362489}"#).unwrap();
            let expected_response: models::WithdrawlAssetsFromTheManagedSubAccountResponse =
                serde_json::from_value(resp_json.clone()).expect(
                    "should parse into models::WithdrawlAssetsFromTheManagedSubAccountResponse",
                );

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

            let params = WithdrawlAssetsFromTheManagedSubAccountParams::builder(
                "from_email_example".to_string(),
                "asset_example".to_string(),
                dec!(1.0),
            )
            .build()
            .unwrap();

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