Exemplo n.º 1
0
def confirm_order(
    confirmation_id: str,
    order: Order,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[Order.ConfirmationResponse, bool]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = URLs.ORDER_CONFIRM
    url = f'{url}/{confirmation_id};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 'orderId' in response_dict['data']:

        if raw == True:
            order.id = response_dict['data']['orderId']
            response = response_dict
        else:
            order.id = response_dict['data']['orderId']
            response = payload_handler.confirmation_response_to_grpc(
                payload=response_dict, )
    else:
        response = False

    return response
Exemplo n.º 2
0
def confirm_order(
    confirmation_id: str,
    order: Order,
    session_id: str,
    credentials: Credentials,
    raw: bool = False,
    session: requests.Session = None,
    logger: logging.Logger = None,
) -> Union[Order.ConfirmationResponse, bool]:
    if logger is None:
        logger = build_logger()
    if session is None:
        session = build_session()

    int_account = credentials.int_account
    url = urls.ORDER_CONFIRM
    url = f'{url}/{confirmation_id};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 'orderId' in response_dict['data']:
        if raw is True:
            order.id = response_dict['data']['orderId']
            response = response_dict
        else:
            order.id = response_dict['data']['orderId']
            response = payload_handler.confirmation_response_to_grpc(
                payload=response_dict, )
    else:
        response = False

    return response
def setup_update_orders(update: Update, payload: dict):
    """ Build an "Order" object using "dict" returned by the API.
    Parameters:
        order {dict}
            Order dict straight from Degiro's API
    Returns:
        {Order}
    """

    if 'orders' in payload:
        update.orders.last_updated = \
            payload['orders']['lastUpdated']

        for order in payload['orders']['value']:
            order_dict = dict()
            for attribute in order['value']:
                if 'name' in attribute \
                        and 'value' in attribute \
                        and attribute['name'] in __ORDER_MATCHING:
                    order_dict[__ORDER_MATCHING[attribute['name']]] = \
                        attribute['value']

            order_dict['action'] = \
                __ACTION_MATCHING[order_dict['action']]
            update.orders.values.append(Order(**order_dict))
Exemplo n.º 4
0
def on_price_update(symbol, last_price):
    preorders = load(open(PREORDERS_FILE, 'r'))

    for preorder in preorders:
        if preorder['product_ticker'] != symbol:
            continue

        if is_order_valid(preorder, last_price):
            logger.info(
                f'creating {preorder["action"]} order for {preorder["product_ticker"]}: ${preorder["price"]} x {preorder["amount"]}.'
            )
            order = Order(
                action=Order.Action.SELL if preorder['action'] == 'SELL' else Order.Action.BUY,
                order_type=Order.OrderType.LIMIT,
                price=preorder['price'],
                product_id=preorder['product_id'],
                size=preorder['amount'],
                time_type=Order.TimeType.GOOD_TILL_CANCELED \
                            if preorder['time_type'] == 'GOOD_TILL_CANCELED' \
                            else Order.TimeType.GOOD_TILL_DAY
            )

            trading_api_mutex.acquire()
            try:
                checking_response = trading_api.check_order(order=order)
                if checking_response != False:
                    confirmation_response = trading_api.confirm_order(
                        confirmation_id=checking_response.confirmation_id,
                        order=order)

                    if confirmation_response != False:
                        logger.info('created order.')
                        preorder['order_created'] = True
                        preorder['order_created_utc'] = datetime.utcnow(
                        ).isoformat()
                        dump(preorders,
                             open(PREORDERS_FILE, 'w'),
                             indent=4,
                             sort_keys=True)
                    else:
                        logger.warning(
                            'order creation failed due to invalid price.')
                else:
                    # insufficient funds or shares
                    logger.warning(
                        'order creation failed due to insufficient funds or shares. order canceled.'
                    )
                    preorder['preorder_canceled'] = True
                    dump(preorders,
                         open(PREORDERS_FILE, 'w'),
                         indent=4,
                         sort_keys=True)
            except e:
                logger.error('unable to create order due to an exception.')
                logger.error(e)
            finally:
                trading_api_mutex.release()
def checking_response_to_grpc(payload: dict) -> Order.CheckingResponse:
    checking_response = Order.CheckingResponse()
    checking_response.response_datetime.GetCurrentTime()
    json_format.ParseDict(
        js_dict=payload['data'],
        message=checking_response,
        ignore_unknown_fields=True,
        descriptor_pool=None,
    )

    return checking_response
def confirmation_response_to_grpc(
    payload: dict, ) -> Order.ConfirmationResponse:
    confirmation_response = Order.ConfirmationResponse()
    confirmation_response.response_datetime.GetCurrentTime()
    json_format.ParseDict(
        js_dict=payload['data'],
        message=confirmation_response,
        ignore_unknown_fields=False,
        descriptor_pool=None,
    )

    return confirmation_response
Exemplo n.º 7
0
    int_account=int_account,
    username=username,
    password=password,
)

# SETUP TRADING API
trading_api = TradingAPI(credentials=credentials)

# ESTABLISH CONNECTION
trading_api.connect()

# SETUP ORDER
order = Order(
    action=Order.Action.BUY,
    order_type=Order.OrderType.LIMIT,
    price=10,
    product_id=71981,
    size=1,
    time_type=Order.TimeType.GOOD_TILL_DAY,
)

# FETCH CHECKING_RESPONSE
checking_response = trading_api.check_order(order=order)

# EXTRACT CONFIRMATION_ID
confirmation_id = checking_response.confirmation_id

# EXTRACT OTHER DATA
free_space_new = checking_response.free_space_new
response_datetime = checking_response.response_datetime
transaction_fees = checking_response.transaction_fees
transaction_opposite_fees = checking_response.transaction_opposite_fees