예제 #1
0
def get_config(
    session_id: str,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> dict:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.CONFIG

    request = requests.Request(method='GET', url=url)
    prepped = session.prepare_request(request)
    prepped.headers['cookie'] = 'JSESSIONID=' + session_id

    try:
        response = session.send(prepped, verify=False)
        response = response.json()
    except Exception as e:
        logger.fatal(e)
        return False

    if type(response) != dict:
        return False

    return response.get('data', False)
예제 #2
0
파일: utils.py 프로젝트: muraig/fastapi-vue
def check_port_open(host: str,
                    port: int,
                    retries: int,
                    interval: int = 5,
                    logger: logging.Logger = None):

    if logger is None:
        logger = logging.getLogger("PortCheck")

    for count in range(1, retries + 1):
        s = socket.socket()
        try:
            s.connect((host, port))
            logger.info(f"Connected to {host} on port {port}")
            return True
        except socket.error:
            logger.error(
                f"Cannot connect to {host}:{port}, retrying..({count}/{retries})"
            )
            time.sleep(interval)
        finally:
            s.close()
    else:
        logger.fatal(f"Connection to InfluxDB at {host}:{port} failed")
        return False
예제 #3
0
def subprocess_error_dump(logger: logging.Logger,
                          e: subprocess.CalledProcessError) -> None:
    logger.fatal(
        "CalledProcessError encountered: "
        "errcode = %s "
        "cmd = '%s' "
        "stdout = '%s' "
        "stderr = '%s'", e.returncode, e.cmd, e.stdout, e.stderr)
예제 #4
0
def check_order(
    order: Order,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[Order.CheckingResponse, bool]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.ORDER_CHECK
    url = f'{url};jsessionid={session_id}'

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    order_dict = payload_handler.order_to_api(order=order)

    request = requests.Request(
        method='POST',
        url=url,
        json=order_dict,
        params=params,
    )
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    if isinstance(response_dict, dict) \
            and 'data' in response_dict \
            and 'confirmationId' in response_dict['data']:
        if raw is True:
            response = response_dict
        else:
            response = payload_handler.checking_response_to_grpc(
                payload=response_dict, )
    else:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        response = False

    return response
예제 #5
0
def check_order(
    order: Order,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[Order.CheckingResponse, bool]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = URLs.ORDER_CHECK
    url = f'{url};jsessionid={session_id}?intAccount={int_account}&sessionId={session_id}'

    order_dict = {
        'buySell': order.action,
        'orderType': order.order_type,
        'price': order.price,
        'productId': order.product_id,
        'size': order.size,
        'timeType': order.time_type,
    }

    request = requests.Request(method='POST', url=url, json=order_dict)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    if \
        isinstance(response_dict, dict) \
        and 'data' in response_dict \
        and 'confirmationId' in response_dict['data']:

        if raw == True:
            response = response_dict
        else:
            response = payload_handler.checking_response_to_grpc(
                payload=response_dict, )
    else:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        response = False

    return response
예제 #6
0
def get_session_id(
    user_token:int,
    session:requests.Session=None,
    logger:logging.Logger=None,
)->str:
    """ Retrieve the "session_id" necessary to access the data-stream.

    Args:
        user_token (int):
            User identifier in Degiro's API.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        str: Session id
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()
    
    url = Endpoint.URL
    url = f'{url}/request_session'
    version = Endpoint.VERSION
    
    parameters = {'version': version, 'userToken': user_token}
    data = '{"referrer":"https://trader.degiro.nl"}'

    request = requests.Request(
        method='POST',
        url=url,
        data=data,
        params=parameters
    )
    prepped = session.prepare_request(request=request)

    try:
        response = session.send(request=prepped, verify=False)
        response_dict = response.json()
    except Exception as e:
        logger.fatal(e)
        return False
    
    logger.info('get_session_id:response_dict: %s', response_dict)

    if 'sessionId' in response_dict:
        return response_dict['sessionId']
    else:
        return None
예제 #7
0
def delete_order(
    order_id: str,
    session_id: str,
    credentials: Credentials,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> bool:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.ORDER_DELETE
    url = f'{url}/{order_id};jsessionid={session_id}'

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    request = requests.Request(method='DELETE', url=url, params=params)
    prepped = session.prepare_request(request)
    response = None

    try:
        response = session.send(prepped, verify=False)
    except Exception as e:
        logger.fatal(response.status_code)
        logger.fatal(response.text)
        logger.fatal(e)
        return False

    return response.status_code == 200
예제 #8
0
def begin(filename=None, failopen=False):
    if not filename:
        unique = os.environ['LOGNAME']
        cmd = os.path.basename(sys.argv[0])
        filename = "/tmp/%s-%s.lock" % (unique, cmd)

    if os.path.exists(filename):
        log.warn("Lockfile found!")
        f = open(filename, "r")
        pid = None
        try:
            pid = int(f.read())
        except ValueError:
            pass
        f.close()
        if not pid:
            log.error("Invalid lockfile contents.")
        else:
            try:
                os.getpgid(pid)
                log.error(
                    "Aborting! Previous process ({pid}) is still alive. Remove lockfile manually if in error: {path}"
                    .format(pid=pid, path=filename))
                sys.exit(1)
            except OSError:
                if failopen:
                    log.fatal(
                        "Aborting until stale lockfile is investigated: {path}"
                        .format(path=filename))
                    sys.exit(1)
                log.error("Lockfile is stale.")
        log.info("Removing old lockfile.")
        os.unlink(filename)

    f = open(filename, "w")
    f.write(str(os.getpid()))
    f.close()

    global lockfile
    lockfile = filename
예제 #9
0
def get_favourites_list(
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, Favourites]:
    """ Retrieve the lists of favourite products.

    Args:
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        Favourites: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = URLs.PRODUCT_FAVOURITES_LISTS

    params = dict()
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw == True:
            response = response_dict
        else:
            response = payload_handler.favourites_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #10
0
def begin(filename=None, failopen=False):
    if not filename:
        unique = os.environ['LOGNAME']
        cmd = os.path.basename(sys.argv[0])
        filename = "/tmp/%s-%s.lock" % (unique, cmd)

    if os.path.exists(filename):
        log.warn("Lockfile found!")
        f = open(filename, "r")
        pid = None
        try:
            pid = int(f.read())
        except ValueError:
            pass
        f.close()
        if not pid:
            log.error("Invalid lockfile contents.")
        else:
            try:
                os.getpgid(pid)
                log.error("Aborting! Previous process ({pid}) is still alive. Remove lockfile manually if in error: {path}".format(pid=pid, path=filename))
                sys.exit(1)
            except OSError:
                if failopen:
                    log.fatal("Aborting until stale lockfile is investigated: {path}".format(path=filename))
                    sys.exit(1)
                log.error("Lockfile is stale.")
        log.info("Removing old lockfile.")
        os.unlink(filename)

    f = open(filename, "w")
    f.write(str(os.getpid()))
    f.close()

    global lockfile
    lockfile = filename
예제 #11
0
def get_financial_statements(
    product_isin: str,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, FinancialStatements]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = f'{urls.FINANCIAL_STATEMENTS}/{product_isin}'

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    prepped.headers['cookie'] = 'JSESSIONID=' + session_id

    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.financial_statements_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal('error')
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #12
0
def get_top_news_preview(
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, TopNewsPreview]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.TOP_NEWS_PREVIEW

    params = {
        'intAccount': credentials.int_account,
        'sessionId': session_id,
    }

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    prepped.headers['cookie'] = 'JSESSIONID=' + session_id

    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.top_news_preview_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal('error')
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #13
0
def get_news_by_company(
    request: NewsByCompany.Request,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, NewsByCompany]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.NEWS_BY_COMPANY

    params = payload_handler.news_by_company_request_to_api(request=request, )
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    prepped.headers['cookie'] = 'JSESSIONID=' + session_id

    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.news_by_company_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal('error')
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #14
0
def update_order(
    order: Order,
    session_id: str,
    credentials: Credentials,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> bool:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    order_id = order.id
    url = urls.ORDER_UPDATE
    url = f'{url}/{order_id};jsessionid={session_id}'

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    order_dict = {
        'buySell': order.action,
        'orderType': order.order_type,
        'price': order.price,
        'productId': order.product_id,
        'size': order.size,
        'timeType': order.time_type,
    }

    request = requests.Request(
        method='PUT',
        url=url,
        json=order_dict,
        params=params,
    )
    prepped = session.prepare_request(request)
    response = None

    try:
        response = session.send(prepped, verify=False)
    except Exception as e:
        logger.fatal(response.status_code)
        logger.fatal(response.text)
        logger.fatal(e)
        return False

    return response.status_code == 200
예제 #15
0
def get_agenda(
    request: Agenda.Request,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, Agenda]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.AGENDA
    params = payload_handler.agenda_request_to_api(request=request, )
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    req = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(req)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.agenda_to_grpc(
                request=request,
                payload=response_dict,
            )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #16
0
def get_chart(
    request: Chart.Request,
    user_token: int,
    override: Dict[str, str] = None,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Chart:
    """ Fetches chart's data.

    Args:
        request (Chart.Request):
            Example :
                request = Chart.Request()
                request.requestid = '1'
                request.resolution = Chart.Resolution.PT1M
                request.culture = 'fr-FR'
                request.series.append('issueid:360148977')
                request.series.append('price:issueid:360148977')
                request.series.append('ohlc:issueid:360148977')
                request.series.append('volume:issueid:360148977')
                request.period = Chart.Period.P1D
                request.tz = 'Europe/Paris'
        user_token (int):
            User identifier in Degiro's API.
        override (Dict[str], optional):
            Overrides the request sent to Degiro's API.
            Example :
                override = {
                    'period':'P6D',
                }
            Defaults to None.
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        Chart: Data of the chart.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.CHART
    params = pb_handler.chart_request_to_api(request=request)
    params['format'] = 'json'
    params['callback'] = ''
    params['userToken'] = user_token

    if override is not None:
        for key, value in override.items():
            params[key] = value

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = json.loads(response_raw.text)

        if raw is True:
            response = response_dict
        else:
            response = pb_handler.api_to_chart(payload=response_dict)

    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #17
0
def get_products_config(
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, ProductSearch.Config]:
    """ Fetch the product search config table.

    No credentials or logging seems to be required for this endpoint.
    Just adding the credentials and session_id because the website is
    doing it.

    Args:
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        ProductSearch.Config: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.PRODUCTS_CONFIG

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.products_config_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #18
0
def product_search(
    request: Union[ProductSearch.RequestBonds, ProductSearch.RequestETFs,
                   ProductSearch.RequestFunds, ProductSearch.RequestFutures,
                   ProductSearch.RequestLeverageds,
                   ProductSearch.RequestLookup, ProductSearch.RequestOptions,
                   ProductSearch.RequestStocks,
                   ProductSearch.RequestWarrants, ],
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, ProductSearch]:
    """ Search products.

    Args:
        request (StockList.Request):
            List of options that we want to retrieve from the endpoint.
            Example 1:
                request = ProductSearch.RequestLookup(
                    search_text='APPLE',
                    limit=10,
                    offset=0,
                )
            Example 2:
                request = ProductSearch.RequestStocks(
                    indexId=5,
                    isInUSGreenList=False,
                    stockCountryId=886,
                    offset=0,
                    limit=100,
                    requireTotal=True,
                    sortColumns='name',
                    sortTypes='asc',
                )
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        ProductSearch: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = __PRODUCT_SEARCH_REQUEST_URL_MATCHING[request.DESCRIPTOR.full_name]

    params = payload_handler.product_search_request_to_api(request=request, )
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.product_search_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #19
0
def get_session_id(
    credentials: Credentials,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> str:
    """ Establish a connection with Degiro's Trading API.

    Args:
        credentials (Credentials):
            credentials.int_account (int)
                Account unique identifer in Degiro's system.
                It is optional.
            credentials.password (str)
                Password used to log in the website.
                It is mandatory.
            credentials.username (str)
                Username used to log in the website.
                It is mandatory.
            credentials.totp_secret is optional.
                Secret code for Two-factor Authentication (2FA).
                It is optional.
        session (requests.Session, optional):
            If you one wants to reuse existing "Session" object.
            Defaults to None.
        logger (logging.Logger, optional):
            If you one wants to reuse existing "Logger" object.
            Defaults to None.

    Raises:
        ConnectionError: Connection failed.

    Returns:
        str: Session id
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    if credentials.HasField('oneof_2fa') is True:
        url = urls.LOGIN + '/totp'
        username = credentials.username
        password = credentials.password

        if credentials.HasField('totp_secret_key') is True:
            totp_secret_key = credentials.totp_secret_key
            one_time_password = str(otp.get_totp(totp_secret_key))
        else:
            one_time_password = credentials.one_time_password

        payload_dict = {
            'username': username,
            'password': password,
            'isPassCodeReset': False,
            'isRedirectToMobile': False,
            'queryParams': {},
            'oneTimePassword': one_time_password,
        }
    else:
        url = urls.LOGIN
        username = credentials.username
        password = credentials.password

        payload_dict = {
            'username': username,
            'password': password,
            'isPassCodeReset': False,
            'isRedirectToMobile': False,
            'queryParams': {},
        }

    request = requests.Request(
        method='POST',
        url=url,
        json=payload_dict,
    )
    prepped = session.prepare_request(request)

    response = None
    try:
        response = session.send(prepped, verify=False)
        response_dict = response.json()
    except Exception as e:
        logger.fatal('response:%s', response)
        raise ConnectionError(e)

    logger.info('get_session_id:response_dict: %s', response_dict)

    if 'sessionId' in response_dict:
        return response_dict['sessionId']
    elif 'status' in response_dict and response_dict['status'] == 6:
        logger.fatal('response_dict:%s', response_dict)
        raise ConnectionError(
            '2FA is enabled, please provide the "totp_secret".')
    else:
        logger.fatal('response_dict:%s', response_dict)
        raise ConnectionError('No session id returned.')
예제 #20
0
def get_account_overview(
    request: AccountOverview.Request,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, AccountOverview]:
    """ Retrieve information about the account.

    Args:
        request (AccountOverview.Request):
            List of options that we want to retrieve from the endpoint.
            Example :
                from_date = AccountOverview.Request.Date(
                    year=2020,
                    month=10,
                    day=15,
                )
                from_date = AccountOverview.Request.Date(
                    year=2020,
                    month=10,
                    day=16,
                )
                request = AccountOverview.Request(
                    from_date=from_date,
                    to_date=to_date,
                )
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        AccountOverview: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = urls.ACCOUNT_OVERVIEW
    params = payload_handler.account_overview_request_to_api(request=request, )
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.account_overview_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #21
0
def subscribe(
    request:Request,
    session_id:str,
    session:requests.Session=None,
    logger:logging.Logger=None,
)->bool:
    """ Add/remove metric from the data-stream.

    Args:
        request (Request):
            List of subscriptions & unsubscriptions to do.
            Example :
            request = Request()
            request.subscriptions['360015751'].extend([
                'LastPrice',
                'LastVolume',
            ])
            request.subscriptions['AAPL.BATS,E'].extend([
                'LastPrice',
                'LastVolume',
            ])
            request.unsubscriptions['360015751'].extend([
                'LastPrice',
                'LastVolume',
            ])
        session_id (str):
            API's session id.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Raises:
        BrokenPipeError:
            A new "session_id" is required.

    Returns:
        bool:
            Whether or not the subscription succeeded.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    url = Endpoint.URL
    url = f'{url}/{session_id}'

    data = pb_handler.request_to_api(request=request)

    logger.info('subscribe:data %s', data[:100])

    session_request = requests.Request(method='POST', url=url, data=data)
    prepped = session.prepare_request(request=session_request)

    try:
        response = session.send(request=prepped, verify=False)

        if response.text == '[{"m":"sr"}]' :
            raise BrokenPipeError('A new "session_id" is required.')
        else:
            response = True
    except Exception as e:
        logger.fatal(e)
        return False

    return response
예제 #22
0
def get_products_info(
    request: ProductsInfo.Request,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, ProductsInfo]:
    """ Search for products using their ids.

    Args:
        request (ProductsInfo.Request):
            List of products ids.
            Example :
                request = ProductsInfo.Request()
                request.products.extend([96008, 1153605, 5462588])
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        ProductsInfo: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.PRODUCTS_INFO

    params = {
        'intAccount': int_account,
        'sessionId': session_id,
    }

    payload = payload_handler.products_info_to_api(request=request)

    request = requests.Request(
        method='POST',
        url=url,
        json=payload,
        params=params,
    )

    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.products_info_to_grpc(
                payload=response_dict, )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #23
0
 def fatal(self, msg, *args, **kwargs):
     kwargs = self.configKeys(**kwargs)
     return OriginalLogger.fatal(self, msg, *args, **kwargs)
예제 #24
0
def get_update(
    request_list: Update.RequestList,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, Update]:
    """ Retrieve information from Degiro's Trading Update endpoint.

    Args:
        request (Update.RequestList):
            List of options that we want to retrieve from the endpoint.
            Example :
                request = Update.RequestList()
                request.list.extend(
                    [
                        Update.Request(
                            option=Update.Option.ALERTS,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.CASHFUNDS,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.HISTORICALORDERS,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.ORDERS,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.PORTFOLIO,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.TOTALPORTFOLIO,
                            last_updated=0,
                        ),
                        Update.Request(
                            option=Update.Option.TRANSACTIONS,
                            last_updated=0,
                        ),
                    ]
                )
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        Update: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.UPDATE
    url = f'{url}/{int_account};jsessionid={session_id}'

    params = payload_handler.update_request_list_to_api(
        request_list=request_list)
    params['intAccount'] = int_account
    params['sessionId'] = session_id

    request = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(request)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_dict = response_raw.json()

        if raw is True:
            response = response_dict
        else:
            response = payload_handler.update_to_grpc(payload=response_dict, )
    except Exception as e:
        logger.fatal('error')
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response
예제 #25
0
def get_cash_account_report(
    request: CashAccountReport.Request,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[dict, CashAccountReport]:
    """ Retrieve information about the account in a specific format.

    Args:
        request (CashAccountReport.Request):
            List of options that we want to retrieve from the endpoint.
            Example :
                from_date = CashAccountReport.Request.Date(
                    year=2020,
                    month=10,
                    day=15,
                )
                from_date = CashAccountReport.Request.Date(
                    year=2020,
                    month=10,
                    day=16,
                )
                request = CashAccountReport.Request(
                    format=CashAccountReport.Format.CSV,
                    country='FR',
                    lang='fr',
                    from_date=from_date,
                    to_date=to_date,
                )
        session_id (str):
            API's session id.
        credentials (Credentials):
            Credentials containing the parameter "int_account".
        raw (bool, optional):
            Whether are not we want the raw API response.
            Defaults to False.
        session (requests.Session, optional):
            This object will be generated if None.
            Defaults to None.
        logger (logging.Logger, optional):
            This object will be generated if None.
            Defaults to None.

    Returns:
        CashAccountReport: API response.
    """

    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    format = CashAccountReport.Format.Name(request.format)
    url = f'{urls.CASH_ACCOUNT_REPORT}/{format}'
    params = payload_handler.cash_account_report_request_to_api(
        request=request, )
    params['intAccount'] = credentials.int_account
    params['sessionId'] = session_id

    req = requests.Request(method='GET', url=url, params=params)
    prepped = session.prepare_request(req)
    response_raw = None

    try:
        response_raw = session.send(prepped, verify=False)
        response_text = response_raw.text

        if raw is True:
            response = response_text
        else:
            response = payload_handler.cash_account_report_to_grpc(
                request=request,
                payload=response_text,
            )
    except Exception as e:
        logger.fatal(response_raw.status_code)
        logger.fatal(response_raw.text)
        logger.fatal(e)
        return False

    return response