<?php

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

/**
 * Binance Margin Trading REST API.
 *
 * OpenAPI Specification for the Binance Margin Trading 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\MarginTrading\Api;

use Binance\Client\MarginTrading\Model\KeepaliveIsolatedMarginUserDataStreamRequest;
use Binance\Client\MarginTrading\Model\KeepaliveMarginUserDataStreamRequest;
use Binance\Client\MarginTrading\Model\StartIsolatedMarginUserDataStreamRequest;
use Binance\Client\MarginTrading\Model\StartIsolatedMarginUserDataStreamResponse;
use Binance\Client\MarginTrading\Model\StartMarginUserDataStreamResponse;
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;

/**
 * TradeDataStreamApi Class Doc Comment.
 *
 * @category Class
 *
 * @author   OpenAPI Generator team
 *
 * @see     https://openapi-generator.tech
 */
class TradeDataStreamApi
{
    /** @var string[] */
    public const contentTypes = [
        'closeIsolatedMarginUserDataStream' => ['application/x-www-form-urlencoded'],
        'closeMarginUserDataStream' => ['application/x-www-form-urlencoded'],
        'keepaliveIsolatedMarginUserDataStream' => ['application/x-www-form-urlencoded'],
        'keepaliveMarginUserDataStream' => ['application/x-www-form-urlencoded'],
        'startIsolatedMarginUserDataStream' => ['application/x-www-form-urlencoded'],
        'startMarginUserDataStream' => ['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('margin-trading');
    }

    /**
     * Operation closeIsolatedMarginUserDataStream.
     *
     * Close Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param string $symbol    symbol (required)
     * @param string $listenkey listenkey (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function closeIsolatedMarginUserDataStream($symbol, $listenkey)
    {
        $this->closeIsolatedMarginUserDataStreamWithHttpInfo($symbol, $listenkey);
    }

    /**
     * Operation closeIsolatedMarginUserDataStreamWithHttpInfo.
     *
     * Close Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param string $symbol    (required)
     * @param string $listenkey (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function closeIsolatedMarginUserDataStreamWithHttpInfo($symbol, $listenkey)
    {
        $request = $this->closeIsolatedMarginUserDataStreamRequest($symbol, $listenkey);

        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();

            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }

            throw $e;
        }
    }

    /**
     * Create request for operation 'closeIsolatedMarginUserDataStream'.
     *
     * @param string $symbol    (required)
     * @param string $listenkey (required)
     *
     * @return Request
     *
     * @throws \InvalidArgumentException
     */
    public function closeIsolatedMarginUserDataStreamRequest($symbol, $listenkey)
    {
        $contentType = self::contentTypes['closeIsolatedMarginUserDataStream'][0];

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

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

        $resourcePath = '/sapi/v1/userDataStream/isolated';
        $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
            true // required
        ) ?? []);
        // query params
        $queryParams = array_merge($queryParams, ObjectSerializer::toQueryValue(
            $listenkey,
            'listenkey', // param base name
            'string', // openApiType
            'form', // style
            true, // explode
            true // required
        ) ?? []);

        $headers = $this->headerSelector->selectHeaders(
            [],
            $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();

        $query = ObjectSerializer::buildQuery($queryParams);

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

    /**
     * Operation closeMarginUserDataStream.
     *
     * Close Margin User Data Stream (USER_STREAM)
     *
     * @param string $listenkey listenkey (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function closeMarginUserDataStream($listenkey)
    {
        $this->closeMarginUserDataStreamWithHttpInfo($listenkey);
    }

    /**
     * Operation closeMarginUserDataStreamWithHttpInfo.
     *
     * Close Margin User Data Stream (USER_STREAM)
     *
     * @param string $listenkey (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function closeMarginUserDataStreamWithHttpInfo($listenkey)
    {
        $request = $this->closeMarginUserDataStreamRequest($listenkey);

        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();

            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }

            throw $e;
        }
    }

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

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

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

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

        $headers = $this->headerSelector->selectHeaders(
            [],
            $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();

        $query = ObjectSerializer::buildQuery($queryParams);

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

    /**
     * Operation keepaliveIsolatedMarginUserDataStream.
     *
     * Keepalive Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param KeepaliveIsolatedMarginUserDataStreamRequest $keepaliveIsolatedMarginUserDataStreamRequest keepaliveIsolatedMarginUserDataStreamRequest (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function keepaliveIsolatedMarginUserDataStream($keepaliveIsolatedMarginUserDataStreamRequest)
    {
        $this->keepaliveIsolatedMarginUserDataStreamWithHttpInfo($keepaliveIsolatedMarginUserDataStreamRequest);
    }

    /**
     * Operation keepaliveIsolatedMarginUserDataStreamWithHttpInfo.
     *
     * Keepalive Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param KeepaliveIsolatedMarginUserDataStreamRequest $keepaliveIsolatedMarginUserDataStreamRequest (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function keepaliveIsolatedMarginUserDataStreamWithHttpInfo($keepaliveIsolatedMarginUserDataStreamRequest)
    {
        $request = $this->keepaliveIsolatedMarginUserDataStreamRequest($keepaliveIsolatedMarginUserDataStreamRequest);

        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();

            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }

            throw $e;
        }
    }

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

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

        $resourcePath = '/sapi/v1/userDataStream/isolated';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

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

        $headers = $this->headerSelector->selectHeaders(
            [],
            $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($keepaliveIsolatedMarginUserDataStreamRequest)) {
            if (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the body
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($keepaliveIsolatedMarginUserDataStreamRequest));
            } else {
                $httpBody = $keepaliveIsolatedMarginUserDataStreamRequest;
            }
        }

        $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();

        $query = ObjectSerializer::buildQuery($queryParams);

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

    /**
     * Operation keepaliveMarginUserDataStream.
     *
     * Keepalive Margin User Data Stream (USER_STREAM)
     *
     * @param KeepaliveMarginUserDataStreamRequest $keepaliveMarginUserDataStreamRequest keepaliveMarginUserDataStreamRequest (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function keepaliveMarginUserDataStream($keepaliveMarginUserDataStreamRequest)
    {
        $this->keepaliveMarginUserDataStreamWithHttpInfo($keepaliveMarginUserDataStreamRequest);
    }

    /**
     * Operation keepaliveMarginUserDataStreamWithHttpInfo.
     *
     * Keepalive Margin User Data Stream (USER_STREAM)
     *
     * @param KeepaliveMarginUserDataStreamRequest $keepaliveMarginUserDataStreamRequest (required)
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function keepaliveMarginUserDataStreamWithHttpInfo($keepaliveMarginUserDataStreamRequest)
    {
        $request = $this->keepaliveMarginUserDataStreamRequest($keepaliveMarginUserDataStreamRequest);

        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();

            return [null, $statusCode, $response->getHeaders()];
        } catch (ApiException $e) {
            switch ($e->getCode()) {
            }

            throw $e;
        }
    }

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

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

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

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

        $headers = $this->headerSelector->selectHeaders(
            [],
            $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($keepaliveMarginUserDataStreamRequest)) {
            if (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the body
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($keepaliveMarginUserDataStreamRequest));
            } else {
                $httpBody = $keepaliveMarginUserDataStreamRequest;
            }
        }

        $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();

        $query = ObjectSerializer::buildQuery($queryParams);

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

    /**
     * Operation startIsolatedMarginUserDataStream.
     *
     * Start Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param StartIsolatedMarginUserDataStreamRequest $startIsolatedMarginUserDataStreamRequest startIsolatedMarginUserDataStreamRequest (required)
     *
     * @return ApiResponse<StartIsolatedMarginUserDataStreamResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function startIsolatedMarginUserDataStream($startIsolatedMarginUserDataStreamRequest): ApiResponse
    {
        return $this->startIsolatedMarginUserDataStreamWithHttpInfo($startIsolatedMarginUserDataStreamRequest);
    }

    /**
     * Operation startIsolatedMarginUserDataStreamWithHttpInfo.
     *
     * Start Isolated Margin User Data Stream (USER_STREAM)
     *
     * @param StartIsolatedMarginUserDataStreamRequest $startIsolatedMarginUserDataStreamRequest (required)
     *
     * @return ApiResponse<StartIsolatedMarginUserDataStreamResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function startIsolatedMarginUserDataStreamWithHttpInfo($startIsolatedMarginUserDataStreamRequest): ApiResponse
    {
        $request = $this->startIsolatedMarginUserDataStreamRequest($startIsolatedMarginUserDataStreamRequest);

        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\MarginTrading\Model\StartIsolatedMarginUserDataStreamResponse',
                        $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\MarginTrading\Model\StartIsolatedMarginUserDataStreamResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\MarginTrading\Model\StartIsolatedMarginUserDataStreamResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

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

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

        $resourcePath = '/sapi/v1/userDataStream/isolated';
        $formParams = [];
        $queryParams = [];
        $headerParams = [];
        $httpBody = '';
        $multipart = false;

        $getters = $startIsolatedMarginUserDataStreamRequest::getters();
        $formParams = [];
        foreach ($getters as $property => $getter) {
            $value = $startIsolatedMarginUserDataStreamRequest->{$getter}();
            if (!empty($value)) {
                $formParams[$property] = $startIsolatedMarginUserDataStreamRequest->{$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($startIsolatedMarginUserDataStreamRequest)) {
            if (false !== stripos($headers['Content-Type'], 'application/json')) {
                // if Content-Type contains "application/json", json_encode the body
                $httpBody = Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($startIsolatedMarginUserDataStreamRequest));
            } else {
                $httpBody = $startIsolatedMarginUserDataStreamRequest;
            }
        }

        $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();

        $query = ObjectSerializer::buildQuery($queryParams);

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

    /**
     * Operation startMarginUserDataStream.
     *
     * Start Margin User Data Stream (USER_STREAM)
     *
     * @return ApiResponse<StartMarginUserDataStreamResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function startMarginUserDataStream(): ApiResponse
    {
        return $this->startMarginUserDataStreamWithHttpInfo();
    }

    /**
     * Operation startMarginUserDataStreamWithHttpInfo.
     *
     * Start Margin User Data Stream (USER_STREAM)
     *
     * @return ApiResponse<StartMarginUserDataStreamResponse>
     *
     * @throws ApiException              on non-2xx response or if the response body is not in the expected format
     * @throws \InvalidArgumentException
     */
    public function startMarginUserDataStreamWithHttpInfo(): ApiResponse
    {
        $request = $this->startMarginUserDataStreamRequest();

        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\MarginTrading\Model\StartMarginUserDataStreamResponse',
                        $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\MarginTrading\Model\StartMarginUserDataStreamResponse',
                $request,
                $response,
            );
        } catch (ApiException $e) {
            switch ($e->getCode()) {
                case 200:
                    $data = ObjectSerializer::deserialize(
                        $e->getResponseBody(),
                        '\Binance\Client\MarginTrading\Model\StartMarginUserDataStreamResponse',
                        $e->getResponseHeaders()
                    );
                    $e->setResponseObject($data);

                    throw $e;
            }

            throw $e;
        }
    }

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

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

        $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();

        $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;
    }
}
