openxapi-binance 0.1.2

Rust client for Binance API
Documentation
/*
 * Binance Portfolio Margin Pro API
 *
 * OpenAPI specification for Binance exchange - Pmarginpro API
 *
 * The version of the OpenAPI document: 0.1.0
 * 
 * Generated by: https://openapi-generator.tech
 */


use reqwest;
use serde::{Deserialize, Serialize, de::Error as _};
use crate::derivatives::pmarginpro::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};

/// struct for passing parameters to the method [`pmarginpro_get_portfolio_asset_index_price_v1`]
#[derive(Clone, Debug, Default)]
pub struct PmarginproGetPortfolioAssetIndexPriceV1Params {
    pub asset: Option<String>
}

/// struct for passing parameters to the method [`pmarginpro_get_portfolio_collateral_rate_v2`]
#[derive(Clone, Debug, Default)]
pub struct PmarginproGetPortfolioCollateralRateV2Params {
    pub timestamp: i64,
    pub recv_window: Option<i64>
}


/// struct for typed errors of method [`pmarginpro_get_portfolio_asset_index_price_v1`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PmarginproGetPortfolioAssetIndexPriceV1Error {
    Status4XX(models::ApiError),
    Status5XX(models::ApiError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`pmarginpro_get_portfolio_collateral_rate_v1`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PmarginproGetPortfolioCollateralRateV1Error {
    Status4XX(models::ApiError),
    Status5XX(models::ApiError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`pmarginpro_get_portfolio_collateral_rate_v2`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PmarginproGetPortfolioCollateralRateV2Error {
    Status4XX(models::ApiError),
    Status5XX(models::ApiError),
    UnknownValue(serde_json::Value),
}

/// struct for typed errors of method [`pmarginpro_get_portfolio_margin_asset_leverage_v1`]
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(untagged)]
pub enum PmarginproGetPortfolioMarginAssetLeverageV1Error {
    Status4XX(models::ApiError),
    Status5XX(models::ApiError),
    UnknownValue(serde_json::Value),
}


/// Query Portfolio Margin Asset Index Price
pub async fn pmarginpro_get_portfolio_asset_index_price_v1(configuration: &configuration::Configuration, params: PmarginproGetPortfolioAssetIndexPriceV1Params) -> Result<Vec<models::PmarginproGetPortfolioAssetIndexPriceV1RespItem>, Error<PmarginproGetPortfolioAssetIndexPriceV1Error>> {

    let uri_str = format!("{}/sapi/v1/portfolio/asset-index-price", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    // Create a mutable vector for query parameters
    let mut query_params: Vec<(String, String)> = Vec::new();

    if let Some(ref param_value) = params.asset {
        query_params.push(("asset".to_string(), param_value.to_string()));
    }

    // Create header parameters collection
    let mut header_params = std::collections::HashMap::new();

    // Handle Binance Auth first if configured
    if let Some(ref binance_auth) = configuration.binance_auth {
        // Add API key to headers
        header_params.insert("X-MBX-APIKEY".to_string(), binance_auth.api_key().to_string());
        
        // Generate request body for signing (if any)
        let body_string: Option<Vec<u8>> = None;
        
        // Sign the request
        let signature = match binance_auth.sign(Some(&query_params), body_string.as_deref()) {
            Ok(sig) => sig,
            Err(e) => return Err(Error::Generic(format!("Failed to sign request: {}", e))),
        };
        
        // Add signature to query params
        query_params.push(("signature".to_string(), signature));
    }

    // Apply all query parameters
    if !query_params.is_empty() {
        req_builder = req_builder.query(&query_params);
    }


    // Add user agent if configured
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    // Apply all header parameters
    for (header_name, header_value) in header_params {
        req_builder = req_builder.header(&header_name, &header_value);
    }


    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioAssetIndexPriceV1RespItem&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioAssetIndexPriceV1RespItem&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PmarginproGetPortfolioAssetIndexPriceV1Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Portfolio Margin Collateral Rate
pub async fn pmarginpro_get_portfolio_collateral_rate_v1(configuration: &configuration::Configuration) -> Result<Vec<models::PmarginproGetPortfolioCollateralRateV1RespItem>, Error<PmarginproGetPortfolioCollateralRateV1Error>> {

    let uri_str = format!("{}/sapi/v1/portfolio/collateralRate", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    // Create a mutable vector for query parameters
    let mut query_params: Vec<(String, String)> = Vec::new();


    // Create header parameters collection
    let mut header_params = std::collections::HashMap::new();

    // Handle Binance Auth first if configured
    if let Some(ref binance_auth) = configuration.binance_auth {
        // Add API key to headers
        header_params.insert("X-MBX-APIKEY".to_string(), binance_auth.api_key().to_string());
        
        // Generate request body for signing (if any)
        let body_string: Option<Vec<u8>> = None;
        
        // Sign the request
        let signature = match binance_auth.sign(Some(&query_params), body_string.as_deref()) {
            Ok(sig) => sig,
            Err(e) => return Err(Error::Generic(format!("Failed to sign request: {}", e))),
        };
        
        // Add signature to query params
        query_params.push(("signature".to_string(), signature));
    }

    // Apply all query parameters
    if !query_params.is_empty() {
        req_builder = req_builder.query(&query_params);
    }


    // Add user agent if configured
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    // Apply all header parameters
    for (header_name, header_value) in header_params {
        req_builder = req_builder.header(&header_name, &header_value);
    }


    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioCollateralRateV1RespItem&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioCollateralRateV1RespItem&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PmarginproGetPortfolioCollateralRateV1Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Portfolio Margin PRO Tiered Collateral Rate
pub async fn pmarginpro_get_portfolio_collateral_rate_v2(configuration: &configuration::Configuration, params: PmarginproGetPortfolioCollateralRateV2Params) -> Result<Vec<models::PmarginproGetPortfolioCollateralRateV2RespItem>, Error<PmarginproGetPortfolioCollateralRateV2Error>> {

    let uri_str = format!("{}/sapi/v2/portfolio/collateralRate", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    // Create a mutable vector for query parameters
    let mut query_params: Vec<(String, String)> = Vec::new();

    if let Some(ref param_value) = params.recv_window {
        query_params.push(("recvWindow".to_string(), param_value.to_string()));
    }
    query_params.push(("timestamp".to_string(), params.timestamp.to_string()));

    // Create header parameters collection
    let mut header_params = std::collections::HashMap::new();

    // Handle Binance Auth first if configured
    if let Some(ref binance_auth) = configuration.binance_auth {
        // Add API key to headers
        header_params.insert("X-MBX-APIKEY".to_string(), binance_auth.api_key().to_string());
        
        // Generate request body for signing (if any)
        let body_string: Option<Vec<u8>> = None;
        
        // Sign the request
        let signature = match binance_auth.sign(Some(&query_params), body_string.as_deref()) {
            Ok(sig) => sig,
            Err(e) => return Err(Error::Generic(format!("Failed to sign request: {}", e))),
        };
        
        // Add signature to query params
        query_params.push(("signature".to_string(), signature));
    }

    // Apply all query parameters
    if !query_params.is_empty() {
        req_builder = req_builder.query(&query_params);
    }


    // Add user agent if configured
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    // Apply all header parameters
    for (header_name, header_value) in header_params {
        req_builder = req_builder.header(&header_name, &header_value);
    }


    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioCollateralRateV2RespItem&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioCollateralRateV2RespItem&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PmarginproGetPortfolioCollateralRateV2Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Get Portfolio Margin Asset Leverage
pub async fn pmarginpro_get_portfolio_margin_asset_leverage_v1(configuration: &configuration::Configuration) -> Result<Vec<models::PmarginproGetPortfolioMarginAssetLeverageV1RespItem>, Error<PmarginproGetPortfolioMarginAssetLeverageV1Error>> {

    let uri_str = format!("{}/sapi/v1/portfolio/margin-asset-leverage", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::GET, &uri_str);

    // Create a mutable vector for query parameters
    let mut query_params: Vec<(String, String)> = Vec::new();


    // Create header parameters collection
    let mut header_params = std::collections::HashMap::new();

    // Handle Binance Auth first if configured
    if let Some(ref binance_auth) = configuration.binance_auth {
        // Add API key to headers
        header_params.insert("X-MBX-APIKEY".to_string(), binance_auth.api_key().to_string());
        
        // Generate request body for signing (if any)
        let body_string: Option<Vec<u8>> = None;
        
        // Sign the request
        let signature = match binance_auth.sign(Some(&query_params), body_string.as_deref()) {
            Ok(sig) => sig,
            Err(e) => return Err(Error::Generic(format!("Failed to sign request: {}", e))),
        };
        
        // Add signature to query params
        query_params.push(("signature".to_string(), signature));
    }

    // Apply all query parameters
    if !query_params.is_empty() {
        req_builder = req_builder.query(&query_params);
    }


    // Add user agent if configured
    if let Some(ref user_agent) = configuration.user_agent {
        req_builder = req_builder.header(reqwest::header::USER_AGENT, user_agent.clone());
    }

    // Apply all header parameters
    for (header_name, header_value) in header_params {
        req_builder = req_builder.header(&header_name, &header_value);
    }


    let req = req_builder.build()?;
    let resp = configuration.client.execute(req).await?;

    let status = resp.status();
    let content_type = resp
        .headers()
        .get("content-type")
        .and_then(|v| v.to_str().ok())
        .unwrap_or("application/octet-stream");
    let content_type = super::ContentType::from(content_type);

    if !status.is_client_error() && !status.is_server_error() {
        let content = resp.text().await?;
        match content_type {
            ContentType::Json => serde_json::from_str(&content).map_err(Error::from),
            ContentType::Text => return Err(Error::from(serde_json::Error::custom("Received `text/plain` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioMarginAssetLeverageV1RespItem&gt;`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `Vec&lt;models::PmarginproGetPortfolioMarginAssetLeverageV1RespItem&gt;`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<PmarginproGetPortfolioMarginAssetLeverageV1Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}