openxapi-binance 0.1.2

Rust client for Binance API
Documentation
/*
 * Binance Spot API
 *
 * OpenAPI specification for Binance exchange - Spot 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::spot::{apis::ResponseContent, models};
use super::{Error, configuration, ContentType};

/// struct for passing parameters to the method [`spot_get_exchange_info_v3`]
#[derive(Clone, Debug, Default)]
pub struct SpotGetExchangeInfoV3Params {
    /// Example: curl -X GET &#34;<a href=\"https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?symbol=BNBBTC</a>&#34;
    pub symbol: Option<String>,
    /// Examples: curl -X GET &#34;<a href=\"https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BNBBTC%22,%22BTCUSDT%22%5D\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BNBBTC%22,%22BTCUSDT%22%5D</a>&#34; <br/> or <br/> curl -g -X  GET &#39;<a href=\"https://api.binance.com/api/v3/exchangeInfo?symbols=%5B%22BTCUSDT%22,%22BNBBTC\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?symbols=[&#34;BTCUSDT&#34;,&#34;BNBBTC</a>&#34;]&#39;
    pub symbols: Option<Vec<String>>,
    /// Examples: curl -X GET &#34;<a href=\"https://api.binance.com/api/v3/exchangeInfo?permissions=SPOT\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?permissions=SPOT</a>&#34; <br/> or <br/> curl -X GET &#34;<a href=\"https://api.binance.com/api/v3/exchangeInfo?permissions=%5B%22MARGIN%22%2C%22LEVERAGED%22%5D\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?permissions=%5B%22MARGIN%22%2C%22LEVERAGED%22%5D</a>&#34; <br/> or <br/> curl -g -X GET &#39;<a href=\"https://api.binance.com/api/v3/exchangeInfo?permissions=%5B%22MARGIN%22,%22LEVERAGED\" target=\"_blank\" rel=\"noopener noreferrer\">https://api.binance.com/api/v3/exchangeInfo?permissions=[&#34;MARGIN&#34;,&#34;LEVERAGED</a>&#34;]&#39;
    pub permissions: Option<String>,
    /// Controls whether the content of the `permissionSets` field is populated or not. Defaults to `true`
    pub show_permission_sets: Option<bool>,
    /// Filters symbols that have this `tradingStatus`. Valid values: `TRADING`, `HALT`, `BREAK` <br/> Cannot be used in combination with `symbols` or `symbol`.
    pub symbol_status: Option<String>
}


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

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

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


/// Current exchange trading rules and symbol information
pub async fn spot_get_exchange_info_v3(configuration: &configuration::Configuration, params: SpotGetExchangeInfoV3Params) -> Result<models::SpotGetExchangeInfoV3Resp, Error<SpotGetExchangeInfoV3Error>> {

    let uri_str = format!("{}/api/v3/exchangeInfo", 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.symbol {
        query_params.push(("symbol".to_string(), param_value.to_string()));
    }
    if let Some(ref param_value) = params.symbols {
        match "multi" {
            "multi" => {
                for p in param_value {
                    query_params.push(("symbols".to_string(), p.to_string()));
                }
            },
            _ => {
                let joined = param_value.iter()
                    .map(|p| p.to_string())
                    .collect::<Vec<String>>()
                    .join(",");
                query_params.push(("symbols".to_string(), joined));
            }
        };
    }
    if let Some(ref param_value) = params.permissions {
        query_params.push(("permissions".to_string(), param_value.to_string()));
    }
    if let Some(ref param_value) = params.show_permission_sets {
        query_params.push(("showPermissionSets".to_string(), param_value.to_string()));
    }
    if let Some(ref param_value) = params.symbol_status {
        query_params.push(("symbolStatus".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 `models::SpotGetExchangeInfoV3Resp`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SpotGetExchangeInfoV3Resp`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SpotGetExchangeInfoV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Test connectivity to the Rest API.
pub async fn spot_get_ping_v3(configuration: &configuration::Configuration) -> Result<serde_json::Value, Error<SpotGetPingV3Error>> {

    let uri_str = format!("{}/api/v3/ping", 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 `serde_json::Value`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `serde_json::Value`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SpotGetPingV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Test connectivity to the Rest API and get the current server time.
pub async fn spot_get_time_v3(configuration: &configuration::Configuration) -> Result<models::SpotGetTimeV3Resp, Error<SpotGetTimeV3Error>> {

    let uri_str = format!("{}/api/v3/time", 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 `models::SpotGetTimeV3Resp`"))),
            ContentType::Unsupported(unknown_type) => return Err(Error::from(serde_json::Error::custom(format!("Received `{unknown_type}` content type response that cannot be converted to `models::SpotGetTimeV3Resp`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SpotGetTimeV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}