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_delete_user_data_stream_v3`]
#[derive(Clone, Debug, Default)]
pub struct SpotDeleteUserDataStreamV3Params {
    pub listen_key: String
}

/// struct for passing parameters to the method [`spot_update_user_data_stream_v3`]
#[derive(Clone, Debug, Default)]
pub struct SpotUpdateUserDataStreamV3Params {
    pub listen_key: String
}


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

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

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


/// Start a new user data stream. The stream will close after 60 minutes unless a keepalive is sent.
pub async fn spot_create_user_data_stream_v3(configuration: &configuration::Configuration) -> Result<models::SpotCreateUserDataStreamV3Resp, Error<SpotCreateUserDataStreamV3Error>> {

    let uri_str = format!("{}/api/v3/userDataStream", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::POST, &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::SpotCreateUserDataStreamV3Resp`"))),
            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::SpotCreateUserDataStreamV3Resp`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<SpotCreateUserDataStreamV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Close out a user data stream.
pub async fn spot_delete_user_data_stream_v3(configuration: &configuration::Configuration, params: SpotDeleteUserDataStreamV3Params) -> Result<serde_json::Value, Error<SpotDeleteUserDataStreamV3Error>> {

    let uri_str = format!("{}/api/v3/userDataStream", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::DELETE, &uri_str);

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

    query_params.push(("listenKey".to_string(), params.listen_key.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 `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<SpotDeleteUserDataStreamV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Keepalive a user data stream to prevent a time out. User data streams will close after 60 minutes. It's recommended to send a ping about every 30 minutes.
pub async fn spot_update_user_data_stream_v3(configuration: &configuration::Configuration, params: SpotUpdateUserDataStreamV3Params) -> Result<serde_json::Value, Error<SpotUpdateUserDataStreamV3Error>> {

    let uri_str = format!("{}/api/v3/userDataStream", configuration.base_path);
    let mut req_builder = configuration.client.request(reqwest::Method::PUT, &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 mut multipart_form_params = std::collections::HashMap::new();
    multipart_form_params.insert("listenKey", params.listen_key.to_string());
    req_builder = req_builder.form(&multipart_form_params);

    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<SpotUpdateUserDataStreamV3Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}