Esempio n. 1
0
def stoikov_mm(e, instrument_id, volatile, volume=5, delta=0):
    # Stay out of the markets until they calm down
    if volatile:
        return

    book = e.get_last_price_book(instrument_id)

    spread = get_spread(book)
    if spread is None or spread < 0.3 or spread < 5 * delta:
        print("Spread is too tight")
        make_orders(e, [
            Order(instrument_id, 2, volume, "bid", "limit"),
            Order(instrument_id, 100, volume, "ask", "limit")
        ])
        return False

    if spread > 1:
        delta = 0.1
        volume = 100

    best_ask = get_best_price(book, "ask")
    best_bid = get_best_price(book, "bid")

    make_orders(e, [
        Order(instrument_id, best_bid.price + delta, volume, "bid", "limit"),
        Order(instrument_id, best_ask.price - delta, volume, "ask", "limit")
    ])

    return True
Esempio n. 2
0
def list_orders(email=None):
    url = "/list-orders"
    for_user = session['user'].email
    if email:
        url += "/{}".format(email)
        for_user = email
    res_data = api_up(url, json={'status': ['complete', 'ordered']})
    if isinstance(res_data, list):
        res_data = sorted(res_data, reverse=True)

    complete_statuses = ['complete', 'unavailable', 'cancelled']

    backlog = 0
    order_info = []
    for orderid in res_data:
        order = api_up('/order/{}'.format(orderid))
        item_status = api_up('/item-status/{}'.format(orderid))
        item_status = item_status.get(orderid, {})
        item_status = map(lambda x: Scene(**x), item_status)
        count_ordered = len(item_status)
        count_complete = len(
            [s for s in item_status if s.status == 'complete'])
        count_error = len([s for s in item_status if s.status == 'error'])
        order.update(products_ordered=count_ordered)
        order.update(products_complete=count_complete)
        order.update(products_error=count_error)
        order_info.append(Order(**order))
        backlog += (
            count_ordered -
            len([s for s in item_status if s.status in complete_statuses]))

    return render_template('list_orders.html',
                           order_list=order_info,
                           for_user=for_user,
                           backlog=backlog)
    def trade(self):
        """Trading as described in Algorithm 1"""
        returns = self.returns([self.data, self.book])
        prices = self.get_prices(returns)
        orders = SortedList(key=lambda x: x.price)

        for i in np.arange(self.agent_num):
            orders.add(Order(agent_id=i, price=prices[i]))

        if not self.train:
            self.logger["initial orders"].append(
                [order.numpy() for order in orders])

        trades = []
        while len(orders) > 1:
            # Draw random agent's action
            idx_bid = np.random.randint(len(orders))
            bid = orders.pop(idx_bid)

            cash_left = self.book[bid.agent_id].numpy()
            ask = orders[0]
            _seller_stocks = self.book[self.agent_num + ask.agent_id].numpy()

            if bid.price >= ask.price and cash_left >= ask.price and _seller_stocks > 1:
                _quantity = (min(np.floor(cash_left /
                                          ask.price), _seller_stocks)
                             if ask.price > 0 else _seller_stocks)
                _trade = Trade(bid.agent_id, ask.agent_id, _quantity,
                               ask.price)

                self._execute_trade(_trade)
                trades.append(_trade)

            # Comment the following lines to prevent recomputation of utilities during trading.
            returns = self.returns([self.data, self.book])
            prices = self.get_prices(returns)
            orders_temp = SortedList(key=lambda x: x.price)

            for i in np.arange(len(orders)):
                orders_temp.add(
                    Order(agent_id=orders[i].agent_id,
                          price=prices[orders[i].agent_id]))
            orders = orders_temp

        if not self.train:
            self.logger["trades"].append(trades)
Esempio n. 4
0
def GetOrder(coinPair, orderId):
    data = bitfinex.order_status(order_id=orderId)
    status = 'open'
    if data['is_cancelled']:
        status = 'cancelled'
    elif not data['is_live']:  #若没有被取消,并且不能继续被填充(not live),
        status = 'done'  #则表示交易已完成(done)
    # print(data)
    return Order('bitfinex', orderId, data['side'], float(data['price']),
                 float(data['original_amount']), coinPair, status)
Esempio n. 5
0
def GetOrder(coinPair, orderId):
    data = json.loads(
        gate_trade.getOrder(str(orderId), toCoinPairStr(coinPair)))
    print(data)
    status = data['order']['message']
    if status == 'Success':
        status = 'done'
    return Order('gateio', orderId, data['order']['type'],
                 float(data['order']['initialRate']),
                 float(data['order']['initialAmount']), coinPair, status)
Esempio n. 6
0
def try_arbitrage(e, books, one, two):
    """Tries to buy from one and sell to two. one and two can be 'A' or 'B'."""
    assert one != two
    assert (one == "A") or (one == "B")
    assert (two == "A") or (two == "B")

    best_buy = get_best_price(books[one], "buy")
    volume = min(best_buy.volume,
                 sell_above(books[two], best_buy.price + 0.05), MAX_TRADE_SIZE)

    if volume > 0:
        make_orders(e, [
            Order(instrument_prefix + one, best_buy.price, volume, "bid",
                  "ioc"),
            Order(instrument_prefix + two, best_buy.price + 0.1, volume, "ask",
                  "ioc")
        ])

        return True

    return False
Esempio n. 7
0
    def trade(self):
        returns = self.returns([self.data, self.book])
        prices = self.get_prices(returns)
        """Trading as described in Algorithm 1"""
        orders = SortedList(key=lambda x: x.price)

        for i in np.arange(self.agent_num):
            orders.add(Order(agent_id=i, price=prices[i]))

        trades = []

        while len(orders) > 1:
            # Draw random agent's action
            bid = np.random.choice(orders)
            orders.remove(bid)
            cash_left = self.book[bid.agent_id].numpy()
            ask = orders[0]
            _seller_stocks = self.book[self.agent_num + ask.agent_id].numpy()

            if bid.price >= ask.price and cash_left >= ask.price and _seller_stocks > 1:
                _quantity = min(np.floor(cash_left / ask.price),
                                _seller_stocks)
                _trade = Trade(bid.agent_id, ask.agent_id, _quantity,
                               ask.price)

                self._execute_trade(_trade)
                trades.append(_trade)

            # Comment the following lines to prevent recomputation of utilities during trading.
            returns = self.returns([self.data, self.book])
            prices = self.get_prices(returns)
            orders_temp = SortedList(key=lambda x: x.price)

            for i in orders:
                orders_temp.add(Order(agent_id=i, price=prices[i]))
            orders = orders_temp
Esempio n. 8
0
def view_order(orderid):
    order_dict = Order(**api_up("/order/{}".format(orderid)))
    item_status = api_up('/item-status/{}'.format(orderid))
    item_status = item_status.get(orderid, {})
    scenes = map(lambda x: Scene(**x), item_status)

    statuses = {
        'complete': ['complete', 'unavailable'],
        'open':
        ['oncache', 'tasked', 'scheduled', 'processing', 'error', 'submitted'],
        'waiting': ['retry', 'onorder'],
        'error': ['error']
    }

    product_counts = {}
    for status in statuses:
        product_counts[status] = len(
            [s for s in scenes if s.status in statuses[status]])
    product_counts['total'] = len(scenes)

    # get away from unicode
    joptions = json.dumps(order_dict.product_opts)

    # sensor/products
    options_by_sensor = {}
    for key in order_dict.product_opts:
        _kval = order_dict.product_opts[key]
        if isinstance(_kval, dict) and 'products' in _kval:
            _spl = _kval['products']
            _out_spl = [conversions['products'][item] for item in _spl]
            options_by_sensor[key] = _out_spl

    options_list = [
        " {0}: {1} ,".format(sensor, ", ".join(options_by_sensor[sensor]))
        for sensor in options_by_sensor
    ]
    options_str = " ".join(options_list)

    return render_template('view_order.html',
                           order=order_dict,
                           scenes=scenes,
                           prod_str=options_str,
                           product_counts=product_counts,
                           product_opts=joptions)
Esempio n. 9
0
def GetOrder(coinPair, orderId):
    data = order_info(orderId)
    if data['data']['type']=='buy-limit':
        data['data']['type']='buy'
    elif data['data']['type']=='sell-limit':
        data['data']['type']='sell'
    print(data)
    status = data['status']
    if status == 'ok':
        status = 'done'
    return Order(
        'huobipro',
        orderId,
        data['data']['type'],
        float(data['data']['price']),
        float(data['data']['amount']),
        coinPair,
        status,
    )
Esempio n. 10
0
def pizza():
    incoming_msg = request.values.get('Body', '')
    resp = MessagingResponse()
    msg = resp.message()
    responded = False
    if 'exit' == incoming_msg:
        if 'user' in session:
            Order.deleteFromStore(session['user'])
        session.clear()
        msg.body(
            "Your order has been cancelled. Thank you for trying out The Pizza Bot and have a good day!"
        )
        responded = True

    elif 'menu' == incoming_msg:
        msg.body("Here is the menu for the day: ")
        printMenuToUser(resp)
        responded = True

    elif 'pizza' == incoming_msg:
        # return a pizza quote, ask for user address and create session for user
        session.clear()
        createUser()
        msg.body(
            'Pizza party coming right up! Please enter your address to view the closest restaurants delivering pizza.'
        )
        responded = True

    elif 'done' == incoming_msg:
        msg.body("Please type in the phone number you can be reached at: ")
        session['orderStatus'] = 'complete'
        responded = True

    else:
        if 'user' in session:
            # user enters address
            if 'location' not in session:
                location = str(incoming_msg)

                # save the location of the user in order
                session['location'] = location

                # convert incoming location to http-request friendly
                prepped_location = location.replace(' ', '+')

                # grab coordinates of user location
                r = requests.get(
                    f'https://maps.googleapis.com/maps/api/geocode/json?address={prepped_location}&key={googleApiKey}'
                )
                if r.status_code == 200:
                    geo_details = r.json(
                    )['results'][0]['geometry']['location']
                    latitude = geo_details['lat']
                    longitude = geo_details['lng']

                    # check for available pizza places within 5km
                    r = requests.get(
                        f'https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={latitude},{longitude}&rankby=distance&keyword=pizza&key={googleApiKey}'
                    )
                    if r.status_code == 200:
                        results = r.json()['results']
                        if results == []:
                            resp.message(
                                "We're so sorry. There are no available locations close to you."
                            )
                        else:
                            # pick top 3 pizza locations
                            pprint(results)
                            places = [
                                place for place in results
                                if ('opening_hours' in place) and
                                (place['opening_hours']['open_now']
                                 or place['business_status'] == 'OPERATIONAL')
                                and results.index(place) < 3
                            ]
                            if places != []:
                                msg.body(
                                    "Here are the 3 closest available locations. Please select a location using the number in front of the location: "
                                )
                                count = 1
                                for place in places:
                                    message = f"{count} - {place['name']} - {place['vicinity']}"
                                    resp.message(message)
                                    count += 1
                                order = Order(id=session['user'],
                                              orderLocation=location,
                                              possible_locations=places,
                                              phone_no=None)
                                order.store()
                                session['places'] = True
                            else:
                                resp.message(
                                    "There are no open locations within 5km of you."
                                )

                else:
                    msg.body('Could not find your location. Please try again.')
                responded = True
            else:
                # user picks an order location
                if 'orderLocation' not in session:
                    # grab user location choice and add to order
                    location_choice = int(incoming_msg)
                    order_dict = Order.getOrder(session['user'])
                    possible_locations = order_dict['possible_locations']
                    order_dict['address'] = session['location']

                    # save user order location choice to store
                    selected_location = possible_locations[location_choice - 1]
                    order_dict['orderLocation'] = selected_location
                    order = Order.orderFromStore(order_dict=order_dict)
                    order.store()
                    session['orderLocation'] = True

                    # respond to user
                    msg.body(
                        f'You have selected {selected_location["name"]} and your location has been saved'
                    )
                    msg.body("You can type menu to print the menu for the day")
                    printMenuToUser(twilResp=resp)
                    responded = True
                else:
                    if 'orderStatus' in session:
                        order_dict = Order.getOrder(session['user'])
                        order_dict['phone_no'] = incoming_msg
                        msg.body("Here is your cart: ")
                        for item in order_dict['cart']:
                            if "drink" in item:
                                drinks = cartCleanReplace(
                                    item['drink'].replace("choice", ""))
                                resp.message(f"Drinks - {drinks}")
                            if "pizza" in item:
                                toppings = cartCleanReplace(
                                    item['pizza'].replace("toppings", ""))
                                resp.message(f"Pizza with - {toppings}")
                        order = Order.orderFromStore(order_dict=order_dict)
                        order.completeOrder()
                        order.store()
                        resp.message(
                            "Your order has been succesfully submitted and will be delivered shortly."
                            + " Thank you for trying out The Pizza Bot!")
                        session.clear()
                        responded = True
                    else:
                        val = ''
                        try:
                            val = int(str(incoming_msg))
                        except ValueError as err:
                            val = str(incoming_msg).replace(
                                ',', ' ').strip().split(" ")
                            for value in val:
                                try:
                                    value = int(value)
                                except ValueError as err:
                                    val.remove(value)
                            val = [int(value) for value in val]

                        if 'pizza' in session:
                            order_pizza = Pizza(toppings=val)
                            order_dict = Order.getOrder(id=session['user'])
                            order = Order.orderFromStore(order_dict=order_dict)
                            pizza_dict = {
                                'pizza': (json.dumps(order_pizza.__dict__))
                            }
                            order.addToCart(pizza_dict)
                            order.store()
                            msg.body(
                                f"Your pizza has been added to your cart!")
                            session.pop('pizza')
                            resp.message(
                                "Remember you can type 'done' to complete your order! You can text 'menu' to see the menu again!"
                            )
                            printMenuToUser(twilResp=resp)
                            responded = True
                        elif 'drinks' in session:
                            order_drink = Drink(choice=val)
                            order_dict = Order.getOrder(id=session['user'])
                            order = Order.orderFromStore(order_dict=order_dict)
                            drink_dict = {
                                'drink': (json.dumps(order_drink.__dict__))
                            }
                            order.addToCart(drink_dict)
                            order.store()
                            msg.body(
                                f"Your drink(s) has/have been added to your cart!"
                            )
                            session.pop('drinks')
                            resp.message(
                                "Remember you can type 'done' to complete your order! You can text 'menu' to see the menu again!"
                            )
                            printMenuToUser(twilResp=resp)
                            responded = True
                        else:
                            if int(incoming_msg) == 1:
                                session['pizza'] = True
                                msg.body(
                                    "You have selected Pizza. Please select the toppings you would like separated by commas. "
                                    +
                                    "For example, for extra cheese and pepperoni, text - 1, 2"
                                )
                                printPizzaToppings(twilResp=resp)
                                responded = True
                            if int(incoming_msg) == 2:
                                session['drinks'] = True
                                msg.body(
                                    "You have selected Drinks. They all come in 75cl bottles."
                                    +
                                    " Please select the drink you would like separated by commas. "
                                    +
                                    " For example, for Coke and Fanta, text - 1, 2"
                                )
                                printDrinksMenu(twilResp=resp)
                                responded = True

    if not responded:
        if 'user' in session:
            msg.body(
                "Seems like an invalid command was used! Please follow the last prompt"
            )
        else:
            msg.body(
                "Hi there! I'm The Pizza Bot! I'm here to help you order delicious pizza! "
                + "You can begin an order with the command: pizza. " +
                "You can complete an order with the command: done. " +
                "You can see my available items on the menu at any time with the command: menu. "
                +
                "You can cancel the process at any time by texting the command: exit."
            )
    return str(resp)
Esempio n. 11
0
def bondSellExec(prices):
    price = prices.getStockBuy('BOND')
    if price[0] > 1000:
        order = Order('add', 0, 'BOND', 'SELL', price[0], price[1])
        print(order.getOrderString(), file=prices.exchange)
        print(order.getOrderString())
Esempio n. 12
0
def bondBuyExec(prices):
    price = prices.getStockSell('BOND')
    if price[0] < 1000:
        order = Order('add', 0, 'BOND', 'BUY', price[0], price[1])
        print(order.getOrderString(), file=prices.exchange)
        print(order.getOrderString())