openxapi-binance 0.2.0

Rust client for Binance API
Documentation
/*
 * Binance Options API
 *
 * OpenAPI specification for Binance exchange - Options API
 *
 * The version of the OpenAPI document: 0.2.0
 * 
 * Generated by: https://openapi-generator.tech
 */


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

/// struct for passing parameters to the method [`create_block_order_create_v1`]
#[derive(Clone, Debug, Default)]
pub struct CreateBlockOrderCreateV1Params {
    pub legs: Vec<String>,
    pub liquidity: String,
    pub price: String,
    pub quantity: String,
    pub side: String,
    pub symbol: String,
    pub timestamp: i32,
    pub recv_window: Option<i32>
}

/// struct for passing parameters to the method [`delete_block_order_create_v1`]
#[derive(Clone, Debug, Default)]
pub struct DeleteBlockOrderCreateV1Params {
    pub block_order_matching_key: String,
    pub timestamp: i32,
    /// The value cannot be greater than 60000
    pub recv_window: Option<i32>
}


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

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


/// Send in a new block trade order.
pub async fn create_block_order_create_v1(configuration: &configuration::Configuration, params: CreateBlockOrderCreateV1Params) -> Result<models::OptionsCreateBlockOrderCreateV1Resp, Error<CreateBlockOrderCreateV1Error>> {

    let uri_str = format!("{}/eapi/v1/block/order/create", 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 mut multipart_form_params = std::collections::HashMap::new();
    multipart_form_params.insert("legs", params.legs.into_iter().map(|p| serde_json::to_string(&p).unwrap_or_default()).collect::<Vec<String>>().join(",").to_string());
    multipart_form_params.insert("liquidity", params.liquidity.to_string());
    multipart_form_params.insert("price", params.price.to_string());
    multipart_form_params.insert("quantity", params.quantity.to_string());
    if let Some(param_value) = params.recv_window {
        multipart_form_params.insert("recvWindow", param_value.to_string());
    }
    multipart_form_params.insert("side", params.side.to_string());
    multipart_form_params.insert("symbol", params.symbol.to_string());
    multipart_form_params.insert("timestamp", params.timestamp.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 `models::OptionsCreateBlockOrderCreateV1Resp`"))),
            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::OptionsCreateBlockOrderCreateV1Resp`")))),
        }
    } else {
        let content = resp.text().await?;
        let entity: Option<CreateBlockOrderCreateV1Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}

/// Cancel a block trade order.
pub async fn delete_block_order_create_v1(configuration: &configuration::Configuration, params: DeleteBlockOrderCreateV1Params) -> Result<serde_json::Value, Error<DeleteBlockOrderCreateV1Error>> {

    let uri_str = format!("{}/eapi/v1/block/order/create", 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(("blockOrderMatchingKey".to_string(), params.block_order_matching_key.to_string()));
    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 `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<DeleteBlockOrderCreateV1Error> = serde_json::from_str(&content).ok();
        Err(Error::ResponseError(ResponseContent { status, content, entity }))
    }
}