<?php

/**
 * FutureAlgoApi
 * PHP version 8.1.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */

/**
 * Binance Algo REST API.
 *
 * OpenAPI Specification for the Binance Algo REST API
 *
 * The version of the OpenAPI document: 1.0.0
 * Generated by: https://openapi-generator.tech
 * Generator version: 7.12.0
 */

/**
 * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech).
 * https://openapi-generator.tech
 * Do not edit the class manually.
 */

namespace Binance\Client\Algo\Api;

use Binance\Client\Algo\Model\CancelAlgoOrderFutureAlgoResponse;
use Binance\Client\Algo\Model\QueryCurrentAlgoOpenOrdersFutureAlgoResponse;
use Binance\Client\Algo\Model\QueryHistoricalAlgoOrdersFutureAlgoResponse;
use Binance\Client\Algo\Model\QuerySubOrdersFutureAlgoResponse;
use Binance\Client\Algo\Model\TimeWeightedAveragePriceFutureAlgoRequest;
use Binance\Client\Algo\Model\TimeWeightedAveragePriceFutureAlgoResponse;
use Binance\Client\Algo\Model\VolumeParticipationFutureAlgoRequest;
use Binance\Client\Algo\Model\VolumeParticipationFutureAlgoResponse;
use Binance\Common\ApiException;
use Binance\Common\Auth\SignerFactory;
use Binance\Common\Auth\SignerInterface;
use Binance\Common\CommonUtils;
use Binance\Common\Configuration\ClientConfiguration;
use Binance\Common\Dtos\ApiResponse;
use Binance\Common\HeaderSelector;
use Binance\Common\HttpClient;
use Binance\Common\ObjectSerializer;
use GuzzleHttp\ClientInterface;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\MultipartStream;
use GuzzleHttp\Psr7\Request;
use GuzzleHttp\Utils;
use Psr\Http\Message\RequestInterface;
use Psr\Http\Message\ResponseInterface;

/**
 * FutureAlgoApi Class Doc Comment.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */
class FutureAlgoApi
{
    /** @var string[] */
    public const contentTypes = [
        'cancelAlgoOrderFutureAlgo' => ['application/x-www-form-urlencoded'],
        'queryCurrentAlgoOpenOrdersFutureAlgo' => ['application/x-www-form-urlencoded'],
        'queryHistoricalAlgoOrdersFutureAlgo' => ['application/x-www-form-urlencoded'],
        'querySubOrdersFutureAlgo' => ['application/x-www-form-urlencoded'],
        'timeWeightedAveragePriceFutureAlgo' => ['application/x-www-form-urlencoded'],
        'volumeParticipationFutureAlgo' => ['application/x-www-form-urlencoded'],
    ];
    private const HAS_TIME_UNIT = false;

    /**
     * @var ClientInterface
     */
    protected $client;

    /**
     * @var HeaderSelector
     */
    protected $headerSelector;

    /**
     * Summary of clientConfig.
     *
     * @var ClientConfiguration
     */
    protected $clientConfig;

    /**
     * Summary of signer.
     *
     * @var SignerInterface
     */
    protected $signer;

    /**
     * userAgent for HTTP requests.
     *
     * @var string
     */
    private $userAgent;

    public function __construct(
        ?ClientConfiguration $clientConfig = new ClientConfiguration(),
        ?ClientInterface $client = null,
        ?HeaderSelector $selector = null,
    ) {
        $this->clientConfig = $clientConfig;
        $this->client = $client ?: new HttpClient($clientConfig);
        $this->headerSelector = $selector ?: new HeaderSelector();
        if (!empty($clientConfig->getSignatureConfiguration())) {
            $this->signer = SignerFactory::getSigner($clientConfig->getSignatureConfiguration());
        }
        $this->userAgent = CommonUtils::getUserAgent('algo');
    }

    /**
     * Operation cancelAlgoOrderFutureAlgo.
     *
     * Cancel Algo Order(TRADE)
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $recvWindow recvWindow (optional)
     *
     * @return ApiResponse<CancelAlgoOrderFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function cancelAlgoOrderFutureAlgo($algoId, $recvWindow = null): ApiResponse
    {
        return $this->cancelAlgoOrderFutureAlgoWithHttpInfo($algoId, $recvWindow);
    }

    /**
     * Operation cancelAlgoOrderFutureAlgoWithHttpInfo.
     *
     * Cancel Algo Order(TRADE)
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $recvWindow (optional)
     *
     * @return ApiResponse<CancelAlgoOrderFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function cancelAlgoOrderFutureAlgoWithHttpInfo($algoId, $recvWindow = null): ApiResponse
    {
        $request = $this->cancelAlgoOrderFutureAlgoRequest($algoId, $recvWindow);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\CancelAlgoOrderFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\CancelAlgoOrderFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\CancelAlgoOrderFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'cancelAlgoOrderFutureAlgo'.
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $recvWindow (optional)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function cancelAlgoOrderFutureAlgoRequest($algoId, $recvWindow = null)
    {
        $contentType = self::contentTypes['cancelAlgoOrderFutureAlgo'][0];

        // verify the required parameter 'algoId' is set
        if (null === $algoId || (is_array($algoId) && 0 === count($algoId))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $algoId when calling cancelAlgoOrderFutureAlgo'
            );
        }

        $resourcePath = '/sapi/v1/algo/futures/order';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $algoId,
            'algoId', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $recvWindow,
            'recvWindow', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'DELETE',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation queryCurrentAlgoOpenOrdersFutureAlgo.
     *
     * Query Current Algo Open Orders(USER_DATA)
     *
     * @param null|int $recvWindow recvWindow (optional)
     *
     * @return ApiResponse<QueryCurrentAlgoOpenOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function queryCurrentAlgoOpenOrdersFutureAlgo($recvWindow = null): ApiResponse
    {
        return $this->queryCurrentAlgoOpenOrdersFutureAlgoWithHttpInfo($recvWindow);
    }

    /**
     * Operation queryCurrentAlgoOpenOrdersFutureAlgoWithHttpInfo.
     *
     * Query Current Algo Open Orders(USER_DATA)
     *
     * @param null|int $recvWindow (optional)
     *
     * @return ApiResponse<QueryCurrentAlgoOpenOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function queryCurrentAlgoOpenOrdersFutureAlgoWithHttpInfo($recvWindow = null): ApiResponse
    {
        $request = $this->queryCurrentAlgoOpenOrdersFutureAlgoRequest($recvWindow);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\QueryCurrentAlgoOpenOrdersFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\QueryCurrentAlgoOpenOrdersFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\QueryCurrentAlgoOpenOrdersFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'queryCurrentAlgoOpenOrdersFutureAlgo'.
     *
     * @param null|int $recvWindow (optional)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function queryCurrentAlgoOpenOrdersFutureAlgoRequest($recvWindow = null)
    {
        $contentType = self::contentTypes['queryCurrentAlgoOpenOrdersFutureAlgo'][0];

        $resourcePath = '/sapi/v1/algo/futures/openOrders';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $recvWindow,
            'recvWindow', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'GET',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation queryHistoricalAlgoOrdersFutureAlgo.
     *
     * Query Historical Algo Orders(USER_DATA)
     *
     * @param null|string $symbol     Trading symbol eg. BTCUSDT (optional)
     * @param null|string $side       BUY or SELL (optional)
     * @param null|int    $startTime  in milliseconds  eg.1641522717552 (optional)
     * @param null|int    $endTime    in milliseconds  eg.1641522526562 (optional)
     * @param null|int    $page       Default is 1 (optional)
     * @param null|int    $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int    $recvWindow recvWindow (optional)
     *
     * @return ApiResponse<QueryHistoricalAlgoOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function queryHistoricalAlgoOrdersFutureAlgo($symbol = null, $side = null, $startTime = null, $endTime = null, $page = null, $pageSize = null, $recvWindow = null): ApiResponse
    {
        return $this->queryHistoricalAlgoOrdersFutureAlgoWithHttpInfo($symbol, $side, $startTime, $endTime, $page, $pageSize, $recvWindow);
    }

    /**
     * Operation queryHistoricalAlgoOrdersFutureAlgoWithHttpInfo.
     *
     * Query Historical Algo Orders(USER_DATA)
     *
     * @param null|string $symbol     Trading symbol eg. BTCUSDT (optional)
     * @param null|string $side       BUY or SELL (optional)
     * @param null|int    $startTime  in milliseconds  eg.1641522717552 (optional)
     * @param null|int    $endTime    in milliseconds  eg.1641522526562 (optional)
     * @param null|int    $page       Default is 1 (optional)
     * @param null|int    $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int    $recvWindow (optional)
     *
     * @return ApiResponse<QueryHistoricalAlgoOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function queryHistoricalAlgoOrdersFutureAlgoWithHttpInfo($symbol = null, $side = null, $startTime = null, $endTime = null, $page = null, $pageSize = null, $recvWindow = null): ApiResponse
    {
        $request = $this->queryHistoricalAlgoOrdersFutureAlgoRequest($symbol, $side, $startTime, $endTime, $page, $pageSize, $recvWindow);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\QueryHistoricalAlgoOrdersFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\QueryHistoricalAlgoOrdersFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\QueryHistoricalAlgoOrdersFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'queryHistoricalAlgoOrdersFutureAlgo'.
     *
     * @param null|string $symbol     Trading symbol eg. BTCUSDT (optional)
     * @param null|string $side       BUY or SELL (optional)
     * @param null|int    $startTime  in milliseconds  eg.1641522717552 (optional)
     * @param null|int    $endTime    in milliseconds  eg.1641522526562 (optional)
     * @param null|int    $page       Default is 1 (optional)
     * @param null|int    $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int    $recvWindow (optional)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function queryHistoricalAlgoOrdersFutureAlgoRequest($symbol = null, $side = null, $startTime = null, $endTime = null, $page = null, $pageSize = null, $recvWindow = null)
    {
        $contentType = self::contentTypes['queryHistoricalAlgoOrdersFutureAlgo'][0];

        $resourcePath = '/sapi/v1/algo/futures/historicalOrders';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $symbol,
            'symbol', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $side,
            'side', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $startTime,
            'startTime', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $endTime,
            'endTime', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page,
            'page', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $pageSize,
            'pageSize', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $recvWindow,
            'recvWindow', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'GET',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation querySubOrdersFutureAlgo.
     *
     * Query Sub Orders(USER_DATA)
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $page       Default is 1 (optional)
     * @param null|int $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int $recvWindow recvWindow (optional)
     *
     * @return ApiResponse<QuerySubOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function querySubOrdersFutureAlgo($algoId, $page = null, $pageSize = null, $recvWindow = null): ApiResponse
    {
        return $this->querySubOrdersFutureAlgoWithHttpInfo($algoId, $page, $pageSize, $recvWindow);
    }

    /**
     * Operation querySubOrdersFutureAlgoWithHttpInfo.
     *
     * Query Sub Orders(USER_DATA)
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $page       Default is 1 (optional)
     * @param null|int $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int $recvWindow (optional)
     *
     * @return ApiResponse<QuerySubOrdersFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function querySubOrdersFutureAlgoWithHttpInfo($algoId, $page = null, $pageSize = null, $recvWindow = null): ApiResponse
    {
        $request = $this->querySubOrdersFutureAlgoRequest($algoId, $page, $pageSize, $recvWindow);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\QuerySubOrdersFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\QuerySubOrdersFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\QuerySubOrdersFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'querySubOrdersFutureAlgo'.
     *
     * @param int      $algoId     eg. 14511 (required)
     * @param null|int $page       Default is 1 (optional)
     * @param null|int $pageSize   MIN 1, MAX 100; Default 100 (optional)
     * @param null|int $recvWindow (optional)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function querySubOrdersFutureAlgoRequest($algoId, $page = null, $pageSize = null, $recvWindow = null)
    {
        $contentType = self::contentTypes['querySubOrdersFutureAlgo'][0];

        // verify the required parameter 'algoId' is set
        if (null === $algoId || (is_array($algoId) && 0 === count($algoId))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $algoId when calling querySubOrdersFutureAlgo'
            );
        }

        $resourcePath = '/sapi/v1/algo/futures/subOrders';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $algoId,
            'algoId', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $page,
            'page', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $pageSize,
            'pageSize', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $recvWindow,
            'recvWindow', // param base name
            'integer', // openApiType
            'form', // style
            true, // explode
            false // required
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'GET',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation timeWeightedAveragePriceFutureAlgo.
     *
     * Time-Weighted Average Price(Twap) New Order(TRADE)
     *
     * @param TimeWeightedAveragePriceFutureAlgoRequest $timeWeightedAveragePriceFutureAlgoRequest timeWeightedAveragePriceFutureAlgoRequest (required)
     *
     * @return ApiResponse<TimeWeightedAveragePriceFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function timeWeightedAveragePriceFutureAlgo($timeWeightedAveragePriceFutureAlgoRequest): ApiResponse
    {
        return $this->timeWeightedAveragePriceFutureAlgoWithHttpInfo($timeWeightedAveragePriceFutureAlgoRequest);
    }

    /**
     * Operation timeWeightedAveragePriceFutureAlgoWithHttpInfo.
     *
     * Time-Weighted Average Price(Twap) New Order(TRADE)
     *
     * @param TimeWeightedAveragePriceFutureAlgoRequest $timeWeightedAveragePriceFutureAlgoRequest (required)
     *
     * @return ApiResponse<TimeWeightedAveragePriceFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function timeWeightedAveragePriceFutureAlgoWithHttpInfo($timeWeightedAveragePriceFutureAlgoRequest): ApiResponse
    {
        $request = $this->timeWeightedAveragePriceFutureAlgoRequest($timeWeightedAveragePriceFutureAlgoRequest);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\TimeWeightedAveragePriceFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\TimeWeightedAveragePriceFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\TimeWeightedAveragePriceFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'timeWeightedAveragePriceFutureAlgo'.
     *
     * @param TimeWeightedAveragePriceFutureAlgoRequest $timeWeightedAveragePriceFutureAlgoRequest (required)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function timeWeightedAveragePriceFutureAlgoRequest($timeWeightedAveragePriceFutureAlgoRequest)
    {
        $contentType = self::contentTypes['timeWeightedAveragePriceFutureAlgo'][0];

        // verify the required parameter 'timeWeightedAveragePriceFutureAlgoRequest' is set
        if (null === $timeWeightedAveragePriceFutureAlgoRequest || (is_array($timeWeightedAveragePriceFutureAlgoRequest) && 0 === count($timeWeightedAveragePriceFutureAlgoRequest))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $timeWeightedAveragePriceFutureAlgoRequest when calling timeWeightedAveragePriceFutureAlgo'
            );
        }

        $resourcePath = '/sapi/v1/algo/futures/newOrderTwap';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        $getters = $timeWeightedAveragePriceFutureAlgoRequest::getters();
        $formParams = [];
        foreach ($getters as $property => $getter) {
            $value = $timeWeightedAveragePriceFutureAlgoRequest->{$getter}();
            if (!empty($value)) {
                $formParams[$property] = $timeWeightedAveragePriceFutureAlgoRequest->{$getter}();
            }
        }

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        } elseif (isset($timeWeightedAveragePriceFutureAlgoRequest)) {
            if (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the body
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($timeWeightedAveragePriceFutureAlgoRequest));
            } else {
                $httpBody = $timeWeightedAveragePriceFutureAlgoRequest;
            }
        }

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'POST',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Operation volumeParticipationFutureAlgo.
     *
     * Volume Participation(VP) New Order (TRADE)
     *
     * @param VolumeParticipationFutureAlgoRequest $volumeParticipationFutureAlgoRequest volumeParticipationFutureAlgoRequest (required)
     *
     * @return ApiResponse<VolumeParticipationFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function volumeParticipationFutureAlgo($volumeParticipationFutureAlgoRequest): ApiResponse
    {
        return $this->volumeParticipationFutureAlgoWithHttpInfo($volumeParticipationFutureAlgoRequest);
    }

    /**
     * Operation volumeParticipationFutureAlgoWithHttpInfo.
     *
     * Volume Participation(VP) New Order (TRADE)
     *
     * @param VolumeParticipationFutureAlgoRequest $volumeParticipationFutureAlgoRequest (required)
     *
     * @return ApiResponse<VolumeParticipationFutureAlgoResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function volumeParticipationFutureAlgoWithHttpInfo($volumeParticipationFutureAlgoRequest): ApiResponse
    {
        $request = $this->volumeParticipationFutureAlgoRequest($volumeParticipationFutureAlgoRequest);

        try {
            try {
                $response = $this->client->send($request, []);
            } catch (RequestException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    $e->getResponse() ? $e->getResponse()->getHeaders() : null,
                    $e->getResponse() ? (string) $e->getResponse()->getBody() : null
                );
            } catch (ConnectException $e) {
                throw new ApiException(
                    "[{$e->getCode()}] {$e->getMessage()}",
                    (int) $e->getCode(),
                    null,
                    null
                );
            }

            $statusCode = $response->getStatusCode();

            switch ($statusCode) {
                case 200:
                    return $this->handleResponseWithDataType(
                        '\Binance\Client\Algo\Model\VolumeParticipationFutureAlgoResponse',
                        $request,
                        $response,
                    );
            }

            if ($statusCode < 200 || $statusCode > 299) {
                throw new ApiException(
                    sprintf(
                        '[%d] Error connecting to the API (%s)',
                        $statusCode,
                        (string) $request->getUri()
                    ),
                    $statusCode,
                    $response->getHeaders(),
                    (string) $response->getBody()
                );
            }

            return $this->handleResponseWithDataType(
                '\Binance\Client\Algo\Model\VolumeParticipationFutureAlgoResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\Algo\Model\VolumeParticipationFutureAlgoResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'volumeParticipationFutureAlgo'.
     *
     * @param VolumeParticipationFutureAlgoRequest $volumeParticipationFutureAlgoRequest (required)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function volumeParticipationFutureAlgoRequest($volumeParticipationFutureAlgoRequest)
    {
        $contentType = self::contentTypes['volumeParticipationFutureAlgo'][0];

        // verify the required parameter 'volumeParticipationFutureAlgoRequest' is set
        if (null === $volumeParticipationFutureAlgoRequest || (is_array($volumeParticipationFutureAlgoRequest) && 0 === count($volumeParticipationFutureAlgoRequest))) {
            throw new \InvalidArgumentException(
                'Missing the required parameter $volumeParticipationFutureAlgoRequest when calling volumeParticipationFutureAlgo'
            );
        }

        $resourcePath = '/sapi/v1/algo/futures/newOrderVp';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        $getters = $volumeParticipationFutureAlgoRequest::getters();
        $formParams = [];
        foreach ($getters as $property => $getter) {
            $value = $volumeParticipationFutureAlgoRequest->{$getter}();
            if (!empty($value)) {
                $formParams[$property] = $volumeParticipationFutureAlgoRequest->{$getter}();
            }
        }

        $headers = $this->headerSelector->selectHeaders(
            ['application/json'],
            $contentType,
            $multipart
        );

        // for model (json/xml)
        if (count($formParams) > 0) {
            if ($multipart) {
                $multipartContents = [];
                foreach ($formParams as $formParamName => $formParamValue) {
                    $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue];
                    foreach ($formParamValueItems as $formParamValueItem) {
                        $multipartContents[] = [
                            'name' => $formParamName,
                            'contents' => $formParamValueItem,
                        ];
                    }
                }
                // for HTTP post (form)
                $httpBody = new MultipartStream($multipartContents);
            } elseif (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the form parameters
                $httpBody = Utils::jsonEncode($formParams);
            } else {
                // for HTTP post (form)
                $httpBody = ObjectSerializer::buildQuery($formParams);
            }
        } elseif (isset($volumeParticipationFutureAlgoRequest)) {
            if (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the body
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($volumeParticipationFutureAlgoRequest));
            } else {
                $httpBody = $volumeParticipationFutureAlgoRequest;
            }
        }

        $defaultHeaders = [];
        $defaultHeaders['User-Agent'] = $this->userAgent;

        if (self::HAS_TIME_UNIT && !empty($this->clientConfig->getTimeUnit())) {
            $defaultHeaders['X-MBX-TIME-UNIT'] = $this->clientConfig->getTimeUnit();
        }

        $headers = array_merge(
            $defaultHeaders,
            $headerParams,
            $headers
        );

        $operationHost = $this->clientConfig->getUrl();

        $queryParams['timestamp'] = $this->getTimestamp();
        $query = ObjectSerializer::buildQuery($queryParams);
        $queryParams['signature'] = $this->signer->sign($query.$httpBody);
        $headers['X-MBX-APIKEY'] = $this->clientConfig->getSignatureConfiguration()->getApiKey();
        $query = ObjectSerializer::buildQuery($queryParams);

        return new Request(
            'POST',
            $operationHost.$resourcePath.($query ? "?{$query}" : ''),
            $headers,
            $httpBody
        );
    }

    /**
     * Summary of getTimestamp.
     */
    public function getTimestamp(): string
    {
        return date_create()->format('Uv');
    }

    private function handleResponseWithDataType(
        string $dataType,
        RequestInterface $request,
        ResponseInterface $response
    ): ApiResponse {
        if ('\SplFileObject' === $dataType) {
            $content = $response->getBody(); // stream goes to serializer
        } else {
            $content = (string) $response->getBody();
            if ('string' !== $dataType) {
                try {
                    $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR);
                } catch (\JsonException $exception) {
                    throw new ApiException(
                        sprintf(
                            'Error JSON decoding server response (%s)',
                            $request->getUri()
                        ),
                        $response->getStatusCode(),
                        $response->getHeaders(),
                        $content
                    );
                }
            }
        }

        $rateLimits = CommonUtils::getRateLimits($response->getStatusCode(), $response->getHeaders());

        return new ApiResponse(
            $response->getStatusCode(),
            $response->getHeaders(),
            ObjectSerializer::deserialize($content, $dataType, []),
            $rateLimits
        );
    }

    private function responseWithinRangeCode(
        string $rangeCode,
        int $statusCode
    ): bool {
        $left = (int) ($rangeCode[0].'00');
        $right = (int) ($rangeCode[0].'99');

        return $statusCode >= $left && $statusCode <= $right;
    }
}
