# coding: utf-8

"""
    PowerBot - Webservice for algotrading

    # TERMS AND CONDITIONS The PowerBot system provides B2B services for trading at intraday power markets. By using the PowerBot service, each user agrees to the terms and conditions of this licence: 1. The user confirms that they are familiar with the exchanges trading system and all relevant rules, is professionally qualified and in possession of a trading license for the relevant exchange. 2. The user will comply with the exchanges market rules (e.g. [EPEX Spot Market Rules](https://www.epexspot.com/en/downloads#rules-fees-processes) or [Nord Pool Market Rules](https://www.nordpoolgroup.com/trading/Rules-and-regulations/)) and will not endanger the exchange system at any time with heavy load from trading algorithms or by other use. 3. The user is aware of limits imposed by the exchange. 4. The user is solely liable for actions resulting from the use of PowerBot.   # INTRODUCTION PowerBot is a web-based software service enabling algorithmic trading on intraday power exchanges such as EPEX, Nord Pool, HUPX, BSP Southpool, TGE, OPCOM or ETPA. The service is straightforward to integrate in an existing software environment and provides a variety of programming interfaces for development of individual trading algorithms and software tools. Besides enabling fully automated intraday trading, it can be used to create tools for human traders providing relevant information and trading opportunities or can be integrated in existing software tools. For further details see https://www.powerbot-trading.com  ## Knowledge Base In addition to this API guide, please find the documentation at https://docs.powerbot-trading.com - the password will be provided by the PowerBot team. If not, please reach out to us at support@powerbot-trading.com  ## Endpoints The PowerBot service is available at the following REST endpoints:  | Instance      | Base URL for REST Endpoints                                      | |---------------|------------------------------------------------------------------| | EPEX          | https://staging.powerbot-trading.com/playground/epex/v2/api      | | Nord Pool     | https://staging.powerbot-trading.com/playground/nordpool/v2/api  | | HUPX          | https://staging.powerbot-trading.com/playground/hupx/v2/api      | | BSP Southpool | https://staging.powerbot-trading.com/playground/southpool/v2/api | | TGE           | https://staging.powerbot-trading.com/playground/tge/v2/api       | | IBEX          | https://staging.powerbot-trading.com/playground/ibex/v2/api      | | CROPEX        | https://staging.powerbot-trading.com/playground/cropex/v2/api    | | OPCOM         | https://staging.powerbot-trading.com/playground/opcom/v2/api     | | ETPA          | https://staging.powerbot-trading.com/playground/etpa/v2/api      | | BRM           | https://staging.powerbot-trading.com/playground/brm/v2/api       |  Access to endpoints is secured via an API Key, which needs to be passed as an \"api_key\" header in each request.   Notes on API Keys:  * API keys are specific to Test, Staging or Production.  * API keys are generated by the system administrator and need to be requested.  ## How to generate API clients (libraries) This OpenAPI specification can be used to generate API clients (programming libraries) for a wide range of programming languages using tools like [OpenAPI Generator](https://openapi-generator.tech/). A detailed guide can be found in the [knowledge base](https://docs.powerbot-trading.com/articles/getting-started/generating-clients/).  ## PowerBot Python client For Python, a ready-made client is also available on PyPI and can be downloaded locally via:  ```shell   pip install powerbot-client ```  ## Errors The API uses standard HTTP status codes to indicate the success or failure of the API call. The body of the response will be in JSON format as follows:  ``` {   \"message\": \"... an error message ...\" } ```  ## Paging The API uses offset and limit parameters for paged operations. An X-Total-Count header is added to responses to indicate the total number of items in a paged response.  ## API Rate Limiting The API limits the number of concurrent calls to 50 - when that limit is reached, the client will receive 503 http status codes (service unavailable) with the following text:  ``` {   \"message\": \"API rate limit exceeded\" } ``` Clients should ensure that they stay within the limit for concurrent API calls.    ## Additional code samples Additional information and code samples demonstrating the use of the API can be found at in our [knowledge base](https://docs.powerbot-trading.com/docs/programmatic-access/)  # noqa: E501

    The version of the OpenAPI document: 2.21.0-rc1
    Contact: office@powerbot-trading.com
    Generated by: https://openapi-generator.tech
"""


from __future__ import absolute_import

import re  # noqa: F401

# python 2 and python 3 compatibility library
import six

from powerbot_asyncio_client.api_client import ApiClient
from powerbot_asyncio_client.exceptions import (  # noqa: F401
    ApiTypeError,
    ApiValueError
)


class TradesApi(object):
    """NOTE: This class is auto generated by OpenAPI Generator
    Ref: https://openapi-generator.tech

    Do not edit the class manually.
    """

    def __init__(self, api_client=None):
        if api_client is None:
            api_client = ApiClient()
        self.api_client = api_client

    def add_internal_trade(self, new_internal_trade, **kwargs):  # noqa: E501
        """Add internal trade  # noqa: E501

        This method allows you to manually register an internal trade between two portfolios. Internal trades are usually created by the system to prevent cross-trades, but this method allows you to register them manually.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.add_internal_trade(new_internal_trade, async_req=True)
        >>> result = thread.get()

        :param new_internal_trade: (required)
        :type new_internal_trade: NewInternalTrade
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: InternalTrade
        """
        kwargs['_return_http_data_only'] = True
        return self.add_internal_trade_with_http_info(new_internal_trade, **kwargs)  # noqa: E501

    def add_internal_trade_with_http_info(self, new_internal_trade, **kwargs):  # noqa: E501
        """Add internal trade  # noqa: E501

        This method allows you to manually register an internal trade between two portfolios. Internal trades are usually created by the system to prevent cross-trades, but this method allows you to register them manually.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.add_internal_trade_with_http_info(new_internal_trade, async_req=True)
        >>> result = thread.get()

        :param new_internal_trade: (required)
        :type new_internal_trade: NewInternalTrade
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _return_http_data_only: response data without head status code
                                       and headers
        :type _return_http_data_only: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: tuple(InternalTrade, status_code(int), headers(HTTPHeaderDict))
        """

        local_var_params = locals()

        all_params = [
            'new_internal_trade'
        ]
        all_params.extend(
            [
                'async_req',
                '_return_http_data_only',
                '_preload_content',
                '_request_timeout',
                '_request_auth',
                '_content_type',
                '_headers'
            ]
        )

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method add_internal_trade" % key
                )
            local_var_params[key] = val
        del local_var_params['kwargs']
        # verify the required parameter 'new_internal_trade' is set
        if self.api_client.client_side_validation and local_var_params.get('new_internal_trade') is None:  # noqa: E501
            raise ApiValueError("Missing the required parameter `new_internal_trade` when calling `add_internal_trade`")  # noqa: E501

        collection_formats = {}

        path_params = {}

        query_params = []

        header_params = dict(local_var_params.get('_headers', {}))

        form_params = []
        local_var_files = {}

        body_params = None
        if 'new_internal_trade' in local_var_params:
            body_params = local_var_params['new_internal_trade']
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # HTTP header `Content-Type`
        content_types_list = local_var_params.get('_content_type',
            self.api_client.select_header_content_type(
                ['application/json'],
                'POST', body_params))  # noqa: E501
        if content_types_list:
                header_params['Content-Type'] = content_types_list

        # Authentication setting
        auth_settings = ['api_key_security']  # noqa: E501

        response_types_map = {
            200: "InternalTrade",
        }

        return self.api_client.call_api(
            '/internal-trades', 'POST',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_types_map=response_types_map,
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get('_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats,
            _request_auth=local_var_params.get('_request_auth'))

    def get_internal_trades(self, **kwargs):  # noqa: E501
        """List internal trades  # noqa: E501

        List the internal trades you have carried out. Internal trades occur when the server detects a cross-trade between two of your orders and the option \"internal trading\" in market options is activated (either \"default_yes\" or \"default_no\").  The server checks for cross-trades before an order is sent to the market. If the order matches with one of your orders at the market, this order is (partially) taken from the market and the server registers an internal trade, for which an internal_trade_id is created.  It depends on the field \"internal trading\" being true for the orders involved and the setting internal_trading in market options not being set to inactive, if the server detects cross-trades.  As with GET /trades, this method allows you to filter for a wide range of parameters and uses pagination. Please be aware that you may see only one leg of the internal trade, if the other leg belongs to another tenant or portfolio.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.get_internal_trades(async_req=True)
        >>> result = thread.get()

        :param portfolio_id:
        :type portfolio_id: list[str]
        :param offset: Offset when loading a list of items
        :type offset: int
        :param limit: Limits the number of loaded items
        :type limit: int
        :param internal_trade_id: Filters request to only show the internal trade with this id (i.e. shows a single internal trade or none)
        :type internal_trade_id: str
        :param contract_id: Show only those trades related to a specific contract
        :type contract_id: list[str]
        :param from_execution_time: from timestamp is 'inclusive' (i.e. >=)
        :type from_execution_time: datetime
        :param to_execution_time: to timestamp is 'exclusive' (i.e. <)
        :type to_execution_time: datetime
        :param from_api_timestamp: from timestamp is 'inclusive' (i.e. >=)
        :type from_api_timestamp: datetime
        :param to_api_timestamp: to timestamp is 'exclusive' (i.e. <)
        :type to_api_timestamp: datetime
        :param delivery_within_start:
        :type delivery_within_start: datetime
        :param delivery_within_end:
        :type delivery_within_end: datetime
        :param delivery_area: The delivery area.
        :type delivery_area: str
        :param txt: Filter for the buy/sell order text.
        :type txt: str
        :param strategy_ids: Filter for the buy/sell strategy id.
        :type strategy_ids: list[str]
        :param txt_matching_mode:
        :type txt_matching_mode: TextMatchingMode
        :param sort_by: Sorts by the given field and order. Separate multiple sorting options with a comma (\",\")
        :type sort_by: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: list[InternalTrade]
        """
        kwargs['_return_http_data_only'] = True
        return self.get_internal_trades_with_http_info(**kwargs)  # noqa: E501

    def get_internal_trades_with_http_info(self, **kwargs):  # noqa: E501
        """List internal trades  # noqa: E501

        List the internal trades you have carried out. Internal trades occur when the server detects a cross-trade between two of your orders and the option \"internal trading\" in market options is activated (either \"default_yes\" or \"default_no\").  The server checks for cross-trades before an order is sent to the market. If the order matches with one of your orders at the market, this order is (partially) taken from the market and the server registers an internal trade, for which an internal_trade_id is created.  It depends on the field \"internal trading\" being true for the orders involved and the setting internal_trading in market options not being set to inactive, if the server detects cross-trades.  As with GET /trades, this method allows you to filter for a wide range of parameters and uses pagination. Please be aware that you may see only one leg of the internal trade, if the other leg belongs to another tenant or portfolio.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.get_internal_trades_with_http_info(async_req=True)
        >>> result = thread.get()

        :param portfolio_id:
        :type portfolio_id: list[str]
        :param offset: Offset when loading a list of items
        :type offset: int
        :param limit: Limits the number of loaded items
        :type limit: int
        :param internal_trade_id: Filters request to only show the internal trade with this id (i.e. shows a single internal trade or none)
        :type internal_trade_id: str
        :param contract_id: Show only those trades related to a specific contract
        :type contract_id: list[str]
        :param from_execution_time: from timestamp is 'inclusive' (i.e. >=)
        :type from_execution_time: datetime
        :param to_execution_time: to timestamp is 'exclusive' (i.e. <)
        :type to_execution_time: datetime
        :param from_api_timestamp: from timestamp is 'inclusive' (i.e. >=)
        :type from_api_timestamp: datetime
        :param to_api_timestamp: to timestamp is 'exclusive' (i.e. <)
        :type to_api_timestamp: datetime
        :param delivery_within_start:
        :type delivery_within_start: datetime
        :param delivery_within_end:
        :type delivery_within_end: datetime
        :param delivery_area: The delivery area.
        :type delivery_area: str
        :param txt: Filter for the buy/sell order text.
        :type txt: str
        :param strategy_ids: Filter for the buy/sell strategy id.
        :type strategy_ids: list[str]
        :param txt_matching_mode:
        :type txt_matching_mode: TextMatchingMode
        :param sort_by: Sorts by the given field and order. Separate multiple sorting options with a comma (\",\")
        :type sort_by: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _return_http_data_only: response data without head status code
                                       and headers
        :type _return_http_data_only: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: tuple(list[InternalTrade], status_code(int), headers(HTTPHeaderDict))
        """

        local_var_params = locals()

        all_params = [
            'portfolio_id',
            'offset',
            'limit',
            'internal_trade_id',
            'contract_id',
            'from_execution_time',
            'to_execution_time',
            'from_api_timestamp',
            'to_api_timestamp',
            'delivery_within_start',
            'delivery_within_end',
            'delivery_area',
            'txt',
            'strategy_ids',
            'txt_matching_mode',
            'sort_by'
        ]
        all_params.extend(
            [
                'async_req',
                '_return_http_data_only',
                '_preload_content',
                '_request_timeout',
                '_request_auth',
                '_content_type',
                '_headers'
            ]
        )

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method get_internal_trades" % key
                )
            local_var_params[key] = val
        del local_var_params['kwargs']

        if self.api_client.client_side_validation and 'offset' in local_var_params and local_var_params['offset'] < 0:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `offset` when calling `get_internal_trades`, must be a value greater than or equal to `0`")  # noqa: E501
        if self.api_client.client_side_validation and 'limit' in local_var_params and local_var_params['limit'] > 500:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `limit` when calling `get_internal_trades`, must be a value less than or equal to `500`")  # noqa: E501
        if self.api_client.client_side_validation and 'limit' in local_var_params and local_var_params['limit'] < 1:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `limit` when calling `get_internal_trades`, must be a value greater than or equal to `1`")  # noqa: E501
        collection_formats = {}

        path_params = {}

        query_params = []
        if local_var_params.get('portfolio_id') is not None:  # noqa: E501
            query_params.append(('portfolio_id', local_var_params['portfolio_id']))  # noqa: E501
            collection_formats['portfolio_id'] = 'csv'  # noqa: E501
        if local_var_params.get('offset') is not None:  # noqa: E501
            query_params.append(('offset', local_var_params['offset']))  # noqa: E501
        if local_var_params.get('limit') is not None:  # noqa: E501
            query_params.append(('limit', local_var_params['limit']))  # noqa: E501
        if local_var_params.get('internal_trade_id') is not None:  # noqa: E501
            query_params.append(('internal_trade_id', local_var_params['internal_trade_id']))  # noqa: E501
        if local_var_params.get('contract_id') is not None:  # noqa: E501
            query_params.append(('contract_id', local_var_params['contract_id']))  # noqa: E501
            collection_formats['contract_id'] = 'csv'  # noqa: E501
        if local_var_params.get('from_execution_time') is not None:  # noqa: E501
            query_params.append(('from_execution_time', local_var_params['from_execution_time']))  # noqa: E501
        if local_var_params.get('to_execution_time') is not None:  # noqa: E501
            query_params.append(('to_execution_time', local_var_params['to_execution_time']))  # noqa: E501
        if local_var_params.get('from_api_timestamp') is not None:  # noqa: E501
            query_params.append(('from_api_timestamp', local_var_params['from_api_timestamp']))  # noqa: E501
        if local_var_params.get('to_api_timestamp') is not None:  # noqa: E501
            query_params.append(('to_api_timestamp', local_var_params['to_api_timestamp']))  # noqa: E501
        if local_var_params.get('delivery_within_start') is not None:  # noqa: E501
            query_params.append(('delivery_within_start', local_var_params['delivery_within_start']))  # noqa: E501
        if local_var_params.get('delivery_within_end') is not None:  # noqa: E501
            query_params.append(('delivery_within_end', local_var_params['delivery_within_end']))  # noqa: E501
        if local_var_params.get('delivery_area') is not None:  # noqa: E501
            query_params.append(('delivery_area', local_var_params['delivery_area']))  # noqa: E501
        if local_var_params.get('txt') is not None:  # noqa: E501
            query_params.append(('txt', local_var_params['txt']))  # noqa: E501
        if local_var_params.get('strategy_ids') is not None:  # noqa: E501
            query_params.append(('strategy_ids', local_var_params['strategy_ids']))  # noqa: E501
            collection_formats['strategy_ids'] = 'multi'  # noqa: E501
        if local_var_params.get('txt_matching_mode') is not None:  # noqa: E501
            query_params.append(('txt_matching_mode', local_var_params['txt_matching_mode']))  # noqa: E501
        if local_var_params.get('sort_by') is not None:  # noqa: E501
            query_params.append(('sort_by', local_var_params['sort_by']))  # noqa: E501

        header_params = dict(local_var_params.get('_headers', {}))

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = ['api_key_security']  # noqa: E501

        response_types_map = {
            200: "list[InternalTrade]",
        }

        return self.api_client.call_api(
            '/internal-trades', 'GET',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_types_map=response_types_map,
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get('_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats,
            _request_auth=local_var_params.get('_request_auth'))

    def get_trades(self, **kwargs):  # noqa: E501
        """List external trades  # noqa: E501

        Allows you to retrieve the trades (deals) you have executed at the exchange. Each trade at the exchange consists of a buy and sell leg (based on the buy and sell order that were involved in the trade), whereby usually only one leg belongs to you and is therefore visible. In case of a cros-trade, both legs are visible.  This method provides a wide range of filtering options (array of portfolios, trade_id, order_id, txt etc). Please note that this method uses pagination. To fetch trades executed in a given time window, please use from_execution_time and to_execution_time (UTC), not api_timestamp (which indicates the time the server has received the trade confirmation, which can be delayed and might be updated).  Please be aware that some exchange systems may report executed trades slightly delayed. If you would like to know in real time if you have made a trade or not, we recommend to rely on the execution status of orders instead of trades or to use the NetPos attribute.  The option \"active_only\" (default yes) filters for trades that are market active by the exchange system, meaning no recalled or cancelled trades are delivered. The filter \"txt\" allows you to filter for trades that involve an order with a custom text in the txt attribute.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.get_trades(async_req=True)
        >>> result = thread.get()

        :param portfolio_id:
        :type portfolio_id: list[str]
        :param delivery_areas:
        :type delivery_areas: list[str]
        :param offset: Offset when loading a list of items
        :type offset: int
        :param limit: Limits the number of loaded items
        :type limit: int
        :param trade_id: Filters request to only show the trade with this trade_id (shows a single trade or none)
        :type trade_id: str
        :param ord_id: Limit the trades to those which are related to a particular order_id
        :type ord_id: str
        :param active_only: Show only those trades which are active (no rejected, recalled or cancelled trades)
        :type active_only: bool
        :param cl_ordr_id: Show only those trades related to orders with a specific 'client order id' (something like 'your reference' which you can submit) together with an order
        :type cl_ordr_id: str
        :param txt: Show only those trades related to orders with a specific 'custom text'. Similar to the clOrdrId, you can submit a string inside the 'txt' attribute of an order which helps you to identify trades originating from a specific order at a later point in time
        :type txt: str
        :param strategy_ids: Filter by strategy ID.
        :type strategy_ids: list[str]
        :param txt_matching_mode:
        :type txt_matching_mode: TextMatchingMode
        :param contract_id: Show only those trades related to a specific contract
        :type contract_id: list[str]
        :param from_api_timestamp: from timestamp when system has received the trade; from timestamp is 'inclusive' (i.e. >=)
        :type from_api_timestamp: datetime
        :param to_api_timestamp: to timestamp is 'exclusive' (i.e. <)
        :type to_api_timestamp: datetime
        :param delivery_within_start: can only be used together with delivery_within_end
        :type delivery_within_start: datetime
        :param delivery_within_end: can only be used together with delivery_within_start
        :type delivery_within_end: datetime
        :param delivery_area: The delivery area.
        :type delivery_area: str
        :param user_code: the exchange's user code
        :type user_code: str
        :param from_execution_time: from timestamp is 'inclusive' (i.e. >=)
        :type from_execution_time: datetime
        :param to_execution_time: to timestamp is 'exclusive' (i.e. <)
        :type to_execution_time: datetime
        :param sort_by: Sorts by the given field and order. Separate multiple sorting options with a comma (\",\")
        :type sort_by: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: list[Trade]
        """
        kwargs['_return_http_data_only'] = True
        return self.get_trades_with_http_info(**kwargs)  # noqa: E501

    def get_trades_with_http_info(self, **kwargs):  # noqa: E501
        """List external trades  # noqa: E501

        Allows you to retrieve the trades (deals) you have executed at the exchange. Each trade at the exchange consists of a buy and sell leg (based on the buy and sell order that were involved in the trade), whereby usually only one leg belongs to you and is therefore visible. In case of a cros-trade, both legs are visible.  This method provides a wide range of filtering options (array of portfolios, trade_id, order_id, txt etc). Please note that this method uses pagination. To fetch trades executed in a given time window, please use from_execution_time and to_execution_time (UTC), not api_timestamp (which indicates the time the server has received the trade confirmation, which can be delayed and might be updated).  Please be aware that some exchange systems may report executed trades slightly delayed. If you would like to know in real time if you have made a trade or not, we recommend to rely on the execution status of orders instead of trades or to use the NetPos attribute.  The option \"active_only\" (default yes) filters for trades that are market active by the exchange system, meaning no recalled or cancelled trades are delivered. The filter \"txt\" allows you to filter for trades that involve an order with a custom text in the txt attribute.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.get_trades_with_http_info(async_req=True)
        >>> result = thread.get()

        :param portfolio_id:
        :type portfolio_id: list[str]
        :param delivery_areas:
        :type delivery_areas: list[str]
        :param offset: Offset when loading a list of items
        :type offset: int
        :param limit: Limits the number of loaded items
        :type limit: int
        :param trade_id: Filters request to only show the trade with this trade_id (shows a single trade or none)
        :type trade_id: str
        :param ord_id: Limit the trades to those which are related to a particular order_id
        :type ord_id: str
        :param active_only: Show only those trades which are active (no rejected, recalled or cancelled trades)
        :type active_only: bool
        :param cl_ordr_id: Show only those trades related to orders with a specific 'client order id' (something like 'your reference' which you can submit) together with an order
        :type cl_ordr_id: str
        :param txt: Show only those trades related to orders with a specific 'custom text'. Similar to the clOrdrId, you can submit a string inside the 'txt' attribute of an order which helps you to identify trades originating from a specific order at a later point in time
        :type txt: str
        :param strategy_ids: Filter by strategy ID.
        :type strategy_ids: list[str]
        :param txt_matching_mode:
        :type txt_matching_mode: TextMatchingMode
        :param contract_id: Show only those trades related to a specific contract
        :type contract_id: list[str]
        :param from_api_timestamp: from timestamp when system has received the trade; from timestamp is 'inclusive' (i.e. >=)
        :type from_api_timestamp: datetime
        :param to_api_timestamp: to timestamp is 'exclusive' (i.e. <)
        :type to_api_timestamp: datetime
        :param delivery_within_start: can only be used together with delivery_within_end
        :type delivery_within_start: datetime
        :param delivery_within_end: can only be used together with delivery_within_start
        :type delivery_within_end: datetime
        :param delivery_area: The delivery area.
        :type delivery_area: str
        :param user_code: the exchange's user code
        :type user_code: str
        :param from_execution_time: from timestamp is 'inclusive' (i.e. >=)
        :type from_execution_time: datetime
        :param to_execution_time: to timestamp is 'exclusive' (i.e. <)
        :type to_execution_time: datetime
        :param sort_by: Sorts by the given field and order. Separate multiple sorting options with a comma (\",\")
        :type sort_by: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _return_http_data_only: response data without head status code
                                       and headers
        :type _return_http_data_only: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: tuple(list[Trade], status_code(int), headers(HTTPHeaderDict))
        """

        local_var_params = locals()

        all_params = [
            'portfolio_id',
            'delivery_areas',
            'offset',
            'limit',
            'trade_id',
            'ord_id',
            'active_only',
            'cl_ordr_id',
            'txt',
            'strategy_ids',
            'txt_matching_mode',
            'contract_id',
            'from_api_timestamp',
            'to_api_timestamp',
            'delivery_within_start',
            'delivery_within_end',
            'delivery_area',
            'user_code',
            'from_execution_time',
            'to_execution_time',
            'sort_by'
        ]
        all_params.extend(
            [
                'async_req',
                '_return_http_data_only',
                '_preload_content',
                '_request_timeout',
                '_request_auth',
                '_content_type',
                '_headers'
            ]
        )

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method get_trades" % key
                )
            local_var_params[key] = val
        del local_var_params['kwargs']

        if self.api_client.client_side_validation and 'offset' in local_var_params and local_var_params['offset'] < 0:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `offset` when calling `get_trades`, must be a value greater than or equal to `0`")  # noqa: E501
        if self.api_client.client_side_validation and 'limit' in local_var_params and local_var_params['limit'] > 500:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `limit` when calling `get_trades`, must be a value less than or equal to `500`")  # noqa: E501
        if self.api_client.client_side_validation and 'limit' in local_var_params and local_var_params['limit'] < 1:  # noqa: E501
            raise ApiValueError("Invalid value for parameter `limit` when calling `get_trades`, must be a value greater than or equal to `1`")  # noqa: E501
        collection_formats = {}

        path_params = {}

        query_params = []
        if local_var_params.get('portfolio_id') is not None:  # noqa: E501
            query_params.append(('portfolio_id', local_var_params['portfolio_id']))  # noqa: E501
            collection_formats['portfolio_id'] = 'csv'  # noqa: E501
        if local_var_params.get('delivery_areas') is not None:  # noqa: E501
            query_params.append(('delivery_areas', local_var_params['delivery_areas']))  # noqa: E501
            collection_formats['delivery_areas'] = 'csv'  # noqa: E501
        if local_var_params.get('offset') is not None:  # noqa: E501
            query_params.append(('offset', local_var_params['offset']))  # noqa: E501
        if local_var_params.get('limit') is not None:  # noqa: E501
            query_params.append(('limit', local_var_params['limit']))  # noqa: E501
        if local_var_params.get('trade_id') is not None:  # noqa: E501
            query_params.append(('trade_id', local_var_params['trade_id']))  # noqa: E501
        if local_var_params.get('ord_id') is not None:  # noqa: E501
            query_params.append(('ordId', local_var_params['ord_id']))  # noqa: E501
        if local_var_params.get('active_only') is not None:  # noqa: E501
            query_params.append(('active_only', local_var_params['active_only']))  # noqa: E501
        if local_var_params.get('cl_ordr_id') is not None:  # noqa: E501
            query_params.append(('clOrdrId', local_var_params['cl_ordr_id']))  # noqa: E501
        if local_var_params.get('txt') is not None:  # noqa: E501
            query_params.append(('txt', local_var_params['txt']))  # noqa: E501
        if local_var_params.get('strategy_ids') is not None:  # noqa: E501
            query_params.append(('strategy_ids', local_var_params['strategy_ids']))  # noqa: E501
            collection_formats['strategy_ids'] = 'multi'  # noqa: E501
        if local_var_params.get('txt_matching_mode') is not None:  # noqa: E501
            query_params.append(('txt_matching_mode', local_var_params['txt_matching_mode']))  # noqa: E501
        if local_var_params.get('contract_id') is not None:  # noqa: E501
            query_params.append(('contract_id', local_var_params['contract_id']))  # noqa: E501
            collection_formats['contract_id'] = 'csv'  # noqa: E501
        if local_var_params.get('from_api_timestamp') is not None:  # noqa: E501
            query_params.append(('from_api_timestamp', local_var_params['from_api_timestamp']))  # noqa: E501
        if local_var_params.get('to_api_timestamp') is not None:  # noqa: E501
            query_params.append(('to_api_timestamp', local_var_params['to_api_timestamp']))  # noqa: E501
        if local_var_params.get('delivery_within_start') is not None:  # noqa: E501
            query_params.append(('delivery_within_start', local_var_params['delivery_within_start']))  # noqa: E501
        if local_var_params.get('delivery_within_end') is not None:  # noqa: E501
            query_params.append(('delivery_within_end', local_var_params['delivery_within_end']))  # noqa: E501
        if local_var_params.get('delivery_area') is not None:  # noqa: E501
            query_params.append(('delivery_area', local_var_params['delivery_area']))  # noqa: E501
        if local_var_params.get('user_code') is not None:  # noqa: E501
            query_params.append(('user_code', local_var_params['user_code']))  # noqa: E501
        if local_var_params.get('from_execution_time') is not None:  # noqa: E501
            query_params.append(('from_execution_time', local_var_params['from_execution_time']))  # noqa: E501
        if local_var_params.get('to_execution_time') is not None:  # noqa: E501
            query_params.append(('to_execution_time', local_var_params['to_execution_time']))  # noqa: E501
        if local_var_params.get('sort_by') is not None:  # noqa: E501
            query_params.append(('sort_by', local_var_params['sort_by']))  # noqa: E501

        header_params = dict(local_var_params.get('_headers', {}))

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = ['api_key_security']  # noqa: E501

        response_types_map = {
            200: "list[Trade]",
        }

        return self.api_client.call_api(
            '/trades', 'GET',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_types_map=response_types_map,
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get('_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats,
            _request_auth=local_var_params.get('_request_auth'))

    def recall_trade(self, trade_id, **kwargs):  # noqa: E501
        """Recall external trade  # noqa: E501

        Attempts to recall a trade. Note that this may fail depending on the conditions set by the market operations. Check the trade's state after attempting to recall a trade.  Please be aware of the exchange market rules on trade recall. Usually, trade recalls are limited to a short time frame and are subject to high fees.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.recall_trade(trade_id, async_req=True)
        >>> result = thread.get()

        :param trade_id: The unique trade_id of the trade you would like to recall (required)
        :type trade_id: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: list[Trade]
        """
        kwargs['_return_http_data_only'] = True
        return self.recall_trade_with_http_info(trade_id, **kwargs)  # noqa: E501

    def recall_trade_with_http_info(self, trade_id, **kwargs):  # noqa: E501
        """Recall external trade  # noqa: E501

        Attempts to recall a trade. Note that this may fail depending on the conditions set by the market operations. Check the trade's state after attempting to recall a trade.  Please be aware of the exchange market rules on trade recall. Usually, trade recalls are limited to a short time frame and are subject to high fees.  # noqa: E501
        This method makes a synchronous HTTP request by default. To make an
        asynchronous HTTP request, please pass async_req=True

        >>> thread = api.recall_trade_with_http_info(trade_id, async_req=True)
        >>> result = thread.get()

        :param trade_id: The unique trade_id of the trade you would like to recall (required)
        :type trade_id: str
        :param async_req: Whether to execute the request asynchronously.
        :type async_req: bool, optional
        :param _return_http_data_only: response data without head status code
                                       and headers
        :type _return_http_data_only: bool, optional
        :param _preload_content: if False, the urllib3.HTTPResponse object will
                                 be returned without reading/decoding response
                                 data. Default is True.
        :type _preload_content: bool, optional
        :param _request_timeout: timeout setting for this request. If one
                                 number provided, it will be total request
                                 timeout. It can also be a pair (tuple) of
                                 (connection, read) timeouts.
        :param _request_auth: set to override the auth_settings for an a single
                              request; this effectively ignores the authentication
                              in the spec for a single request.
        :type _request_auth: dict, optional
        :type _content_type: string, optional: force content-type for the request
        :return: Returns the result object.
                 If the method is called asynchronously,
                 returns the request thread.
        :rtype: tuple(list[Trade], status_code(int), headers(HTTPHeaderDict))
        """

        local_var_params = locals()

        all_params = [
            'trade_id'
        ]
        all_params.extend(
            [
                'async_req',
                '_return_http_data_only',
                '_preload_content',
                '_request_timeout',
                '_request_auth',
                '_content_type',
                '_headers'
            ]
        )

        for key, val in six.iteritems(local_var_params['kwargs']):
            if key not in all_params:
                raise ApiTypeError(
                    "Got an unexpected keyword argument '%s'"
                    " to method recall_trade" % key
                )
            local_var_params[key] = val
        del local_var_params['kwargs']
        # verify the required parameter 'trade_id' is set
        if self.api_client.client_side_validation and local_var_params.get('trade_id') is None:  # noqa: E501
            raise ApiValueError("Missing the required parameter `trade_id` when calling `recall_trade`")  # noqa: E501

        collection_formats = {}

        path_params = {}
        if 'trade_id' in local_var_params:
            path_params['trade_id'] = local_var_params['trade_id']  # noqa: E501

        query_params = []

        header_params = dict(local_var_params.get('_headers', {}))

        form_params = []
        local_var_files = {}

        body_params = None
        # HTTP header `Accept`
        header_params['Accept'] = self.api_client.select_header_accept(
            ['application/json'])  # noqa: E501

        # Authentication setting
        auth_settings = ['api_key_security']  # noqa: E501

        response_types_map = {
            200: "list[Trade]",
        }

        return self.api_client.call_api(
            '/trade/{trade_id}', 'DELETE',
            path_params,
            query_params,
            header_params,
            body=body_params,
            post_params=form_params,
            files=local_var_files,
            response_types_map=response_types_map,
            auth_settings=auth_settings,
            async_req=local_var_params.get('async_req'),
            _return_http_data_only=local_var_params.get('_return_http_data_only'),  # noqa: E501
            _preload_content=local_var_params.get('_preload_content', True),
            _request_timeout=local_var_params.get('_request_timeout'),
            collection_formats=collection_formats,
            _request_auth=local_var_params.get('_request_auth'))
