Exemple #1
0
def _populate_db():
    """ Populates database with three users each with one order """
    with app.app_context():
        for i in range(1, 4):
            user = User(
                username="******".format(i),
                api_public="79z47uUikMoPe2eADqfJzRB{}".format(i),
                api_secret="j9ey6Lk2xR6V-qJRfN-HqD2nfOGme0FnBddp1cxqK6k8Gbjd")

            order = Orders(
                order_id='00000000-0000-0000-0000-00000000000{}'.format(i),
                order_price=3567.5,
                order_size=1,
                order_side='Buy',
                order_symbol="XBTUSD")

            user.orders.append(order)
            db.session.add(user)
        # adds a real user that has valid apikey for bitmex related stuff
        user = User(
            username="******",
            api_public="79z47uUikMoPe2eADqfJzRBu",
            api_secret="j9ey6Lk2xR6V-qJRfN-HqD2nfOGme0FnBddp1cxqK6k8Gbjd")

        order = Orders(order_id='00000000-0000-0000-0000-000000000000',
                       order_price=3567.5,
                       order_size=1,
                       order_side='Buy',
                       order_symbol="XBTUSD")
        user.orders.append(order)
        db.session.add(user)
        db.session.commit()
def _get_order(number=1):
    """ Creates order model """
    return Orders(
        order_id='00000000-0000-0000-0000-00000000000{}'.format(number),
        order_price=3567.5,
        order_size=1,
        order_side='Buy',
        order_symbol="XBTUSD")
Exemple #3
0
def show_order(order_id: int) -> Any:
    """Func for show orders."""
    try:
        new_order = Orders()
        resp = str(new_order.show_order(order_id))
    except Exception:
        return Response('Неправильный запрос', status=400)
    if request.method == 'GET':
        if resp == '[]':
            return Response('Объект не найден в базе', status=404)
        return str(resp)
    if request.method == 'PUT':
        json_from_request = json.loads(request.data.decode('utf-8'))
        if resp == '[]':
            return Response('Объект не найден в базе', status=404)
        print(striper(resp)['status'])
        print(json_from_request['status'])
        if striper(resp)['status'] == 'not_accepted' and json_from_request[
                'status'] in ['in progress', 'cancelled']:
            new_order.update_orders_not_accepted(
                order_id, json_from_request['status'],
                json_from_request['date_created'],
                json_from_request['driver_id'], json_from_request['client_id'])
            return Response('Изменено', status=200)
        elif striper(resp)['status'] == 'in progress' and json_from_request[
                'status'] in ['done', 'cancelled']:
            new_order.update_orders(order_id, json_from_request['status'])
            return Response('Изменено', status=200)
        return Response('Неверная последовательность статусов', status=400)
Exemple #4
0
def get_orders():
    orders_dict = {
        'status': 'success',
        'orders': [],
    }
    orders = Orders.getAll()

    if not orders:
        response_object = {
            'status': 'success',
            'message': 'No content available'
        }
        return jsonify(response_object), 204

    for order in orders:

        single_order_dict = {
            'id': order.id,
            'products': [],
            'cost': 0.0,
            'customer': Customers.get_shipment_info(order.customer_id),
            'dateCreated': order.datetimecreated,
            'status': order.getStatus(),
            'tracking code': order.tracking_website
        }

        for id in Orders.getProducts(order.id):
            item = OrderDetails.get(id)
            single_order_dict[
                'cost'] = item.item_cost * item.quantity + single_order_dict[
                    'cost']
            product = Products.get(item.product_id)

            item_dict = {
                'product': product.name if product else 'DELETED PRODUCT',
                'quantity': item.quantity,
                'price': item.item_cost
            }

            single_order_dict['products'].append(item_dict)

        orders_dict['orders'].append(single_order_dict)

    return jsonify(orders_dict), 200
Exemple #5
0
def order() -> Response:
    """Func for add  orders."""
    try:
        new_order = Orders()
        json_from_request = json.loads(request.data.decode('utf-8'))
    except Exception:
        return Response('Произошла ошибка', status=400)
    if request.method == 'POST':
        try:
            new_order.insert_order(json_from_request['address_from'],
                                   json_from_request['address_to'],
                                   json_from_request['client_id'],
                                   json_from_request['driver_id'],
                                   json_from_request['date_created'],
                                   json_from_request['status'])
            return Response('Created', status=201)
        except ValueError:
            return Response('Неправильный запрос', status=400)
    else:
        return Response('Неправильный запрос', status=400)
def buy_market(symbol, amount):
    ticker = symbol
    qty = quantity(symbol=ticker, amount=amount)
    detail = client.order_market_buy(symbol=ticker, quantity=qty)
    avg_price_buy = float(detail['cummulativeQuoteQty']) / float(
        detail['origQty'])
    #save order in database
    detail = Orders.save_buy_order(
        collection="Buy_orders",
        symbol=detail["symbol"],
        orderId=detail["orderId"],
        origQty=detail["origQty"],
        cummulativeQuoteQty=detail["cummulativeQuoteQty"],
        avgPrice=avg_price_buy)
    return ticker, avg_price_buy, detail
def oco_order_sell(symbol, avg_price, pct_sl):
    quantity = get_balance(symbol=symbol)
    tp, trigger, sl = risk_calculator(symbol=symbol,
                                      avg_price=avg_price,
                                      pct_sl=pct_sl)
    detail = client.create_oco_order(symbol=symbol,
                                     side="SELL",
                                     stopLimitTimeInForce="GTC",
                                     quantity=quantity,
                                     stopPrice=trigger,
                                     stopLimitPrice=sl,
                                     price=tp)
    # save order in database
    detail = Orders.save_oco_order(
        collection="OCO_orders",
        symbol=detail["orderReports"][0]["symbol"],
        orderId=detail["orderReports"][0]["orderId"],
        origQty=detail["orderReports"][0]["origQty"],
        take_profit=tp,
        stop_limit=sl,
        trigger_price=trigger)
    return detail, tp, trigger, sl
Exemple #8
0
    def post(self, apikey):
        """ posts new order to BitMEX test net and adds the order
            and its information to database.
        """
        acc = User.query.filter_by(api_public=apikey).first()
        if not acc:
            return create_error_response(
                404, "Account does not exist",
                "Account with api-key '{}' does not exist.".format(apikey))
        if not authorize(acc, request):
            return create_error_response(401, "Unauthorized",
                                         "No API-key or wrong API-key")

        if not request.json:
            return create_error_response(415, "Unsupported media type",
                                         "Requests must be JSON")
        try:
            validate(request.json, MasonControls.order_schema())
        except ValidationError as e:
            return create_error_response(400, "Invalid JSON document", str(e))

        # post to bitmex websocket api
        # Receive order id with other data
        # add the order then to our own database
        url = '/api/v1/order'

        data = {
            "symbol": request.json["symbol"],
            "orderQty": request.json["size"],
            "price": request.json["price"],
            "side": request.json["side"]
        }

        headers = generate_headers(request.headers["api_secret"],
                                   acc.api_public, url, "POST", data)

        res = requests.post('https://testnet.bitmex.com' + url,
                            json=data,
                            headers=headers)
        # print(res.text)
        json_response = json.loads(res.text)
        order = Orders(order_id=json_response["orderID"],
                       order_size=json_response["orderQty"],
                       order_side=json_response["side"],
                       order_symbol=json_response["symbol"],
                       order_price=json_response["price"],
                       user=acc)
        try:
            db.session.add(order)
            db.session.commit()

        except ValueError:
            return create_error_response(409, "Already exists", "")

        return Response(status=201,
                        headers={
                            "Location":
                            api.url_for(OrderResource,
                                        apikey=apikey,
                                        orderid=json_response["orderID"])
                        })
Exemple #9
0
def purchase_products():
    data = request.get_json()
    returning_customer = data.get('returningCustomer')
    email = data.get('email')
    products_selected = data.get('items')
    password = data.get('password')
    first_name = data.get('firstName')
    last_name = data.get('lastName')
    address = data.get('address')
    appartment = data.get('appartment')
    city = data.get('city')
    state = data.get('state')
    country = data.get('country')
    zip_code = data.get('zipCode')
    phone_number = data.get('phoneNumber')

    # Validate products selected
    if products_selected is None:
        return jsonify({
            'status': 'failure',
            'message': 'no products found'
        }), 400
    else:
        for item in products_selected:
            if not Products.get(item['id']):
                return jsonify({
                    'status': 'failure',
                    'message': 'one or more invalid products'
                }), 400

    customer_id = None
    if returning_customer:
        if email is None or password is None:
            return jsonify({
                'status': 'failure',
                'message': 'Missing email or password'
            }), 400

        customer_id = Customers.get_customer_id(email, password)
    else:
        if (first_name is None or last_name is None or email is None
                or address is None or city is None or country is None
                or zip_code is None or phone_number is None):
            return jsonify({
                'status': 'failure',
                'message': 'Missing important information'
            }), 400

        customer_id = Customers.add(first_name, last_name, email, password,
                                    address, appartment, city, country, state,
                                    zip_code, phone_number)

    product_orders = []
    for item in products_selected:
        if item['quantity'] > 0:
            product = Products.get(item['id'])
            order_id = OrderDetails.new(product.id, item['quantity'],
                                        product.price)
            product_orders.append(order_id)

    if customer_id is not None and product_orders is not None:
        Orders.new(customer_id, product_orders)
    else:
        return jsonify({'status': 'failure'}), 500

    return jsonify({'status': 'success'}), 200