예제 #1
0
    def handle_player_registration(self, event):
        print('handling registration')
        query = ExchangeDbQuery.get_all_player_names_query()
        rows, cols = self._conn.select(query)
        if not rows or not cols:
            return None
        player_names = [
            rows[i][cols.index('player_name')] for i in range(len(rows))
        ]
        if event._player_name not in player_names:
            player_id = str(uuid.uuid4())
            query = ExchangeDbQuery.insert_new_user_to_db_query().format(
                player_id, event._player_name)
            self._conn.execute(query)
        else:
            query = ExchangeDbQuery.get_player_id_for_name_query().format(
                event._player_name)
            rows, cols = self._conn.select(query)
            if not rows or not cols:
                return None
            else:
                player_id = rows[0][cols.index('player_id')]

        return ExchangeRegistrationEvent(self._exchange_id, Status.Confirm,
                                         player_id)
예제 #2
0
 def update_order_quantity(self, order_id, quantity, book_name):
     if quantity == 0:
         self._conn.execute(
             ExchangeDbQuery._delete_zero_quantity_query().format(
                 book_name, order_id))
     else:
         self._conn.execute(
             ExchangeDbQuery._update_modified_quantity_query().format(
                 book_name, quantity, order_id))
예제 #3
0
 def _get_best_price(self, book_name):
     direcion = book_name.split('_')[3]
     if direcion == 'buy':
         query = ExchangeDbQuery.best_buy_price_query().format(book_name)
     else:
         query = ExchangeDbQuery.best_sell_price_query().format(book_name)
     try:
         self._conn.execute(query)
         price = self._conn._cursor.fetchone()[0]
         return price
     except Exception as e:
         print("Error ", e)
         return None
예제 #4
0
    def match_order(self, book_name):
        symbol = book_name.split('_')[2]
        while True:
            if self.if_trade_possible(book_name):
                try:
                    sell_top_level_query = ExchangeDbQuery.get_sell_top_level_query(
                    ).format(book_name + '_sell')
                    self._conn.execute(sell_top_level_query)
                    sell_order = self._conn._cursor.fetchone()

                    sell_player_id = sell_order[1]
                    sell_order_id = sell_order[2]
                    sell_quantity = sell_order[4]
                    sell_price = sell_order[5]

                    buy_top_level_query = ExchangeDbQuery.get_buy_top_level_query(
                    ).format(book_name + '_buy')
                    self._conn.execute(buy_top_level_query)
                    buy_order = self._conn._cursor.fetchone()

                    buy_player_id = buy_order[1]
                    buy_order_id = buy_order[2]
                    buy_quantity = buy_order[4]
                    buy_price = buy_order[5]

                    trade_quantity = 0

                    if buy_quantity >= sell_quantity:
                        buy_quantity -= sell_quantity
                        trade_quantity = sell_quantity
                        sell_quantity = 0

                    else:
                        sell_quantity -= buy_quantity
                        trade_quantity = buy_quantity
                        buy_quantity = 0

                    time_stamp = self._get_curr_time()
                    self.update_order_quantity(sell_order_id, sell_quantity,
                                               book_name + '_sell')
                    self.update_order_quantity(buy_order_id, buy_quantity,
                                               book_name + '_buy')

                    self.update_trade_info(symbol, buy_order_id, sell_order_id,
                                           time_stamp, buy_price,
                                           sell_quantity, buy_quantity,
                                           trade_quantity)
                except:
                    continue
예제 #5
0
    def _insert_into_order_book(self, order):
        order = order.split('_')

        player_id = order[0]
        order_id = order[1]
        order_type = order[2]
        time_stamp = order[3]
        symbol = order[4]
        direcion = order[5]
        quantity = int(order[6])
        price = float(order[7])

        if order_type == 'MarketOrder':
            d = "buy" if direcion == "sell" else "sell"
            bn = self.BOOK_EXTENSION + '_' + symbol + '_' + d
            p = self._get_best_price(bn)
            if p == None:
                return Status.REJECT
            else:
                price = p

        book_name = self.BOOK_EXTENSION + '_' + symbol + '_' + direcion

        query = ExchangeDbQuery.insert_order_into_order_book_query().format(
            book_name, player_id, order_id, time_stamp, quantity, price)
        try:
            self._conn.execute(query)
            return Status.ACCEPT
        except Exception as e:
            print("Error :", e)
            return Status.REJECT
예제 #6
0
 def get_symbol_id_from_db(self, symbol):
     query = ExchangeDbQuery.get_symbol_id_for_name_query().format(symbol)
     rows, cols = self._conn.select(query)
     if not rows or not cols:
         return None
     symbol_id = rows[0][cols.index('symbol_id')]
     return symbol_id
예제 #7
0
 def update_trade_info(self, symbol, buy_order_id, sell_order_id,
                       time_stamp, trade_price, sell_quantity, buy_quantity,
                       trade_quantity):
     query = ExchangeDbQuery._insert_into_trade_table().format(
         symbol, buy_order_id, sell_order_id, time_stamp, trade_quantity,
         trade_price)
     self._conn.execute(query)
예제 #8
0
    def _get_all_symbols(self):
        query = ExchangeDbQuery.fetch_symbols_from_db_query()
        rows, cols = self._conn.select(query)
        if not rows or not cols:
            raise Exception("DbError")

        symbols = [rows[i][cols.index('symbol_id')] for i in range(len(rows))]
        return symbols
예제 #9
0
    def _get_all_players(self):
        query = ExchangeDbQuery.fetch_player_id_query()
        rows, cols = self._conn.select(query)
        if not rows or not cols:
            raise Exception("DbError")

        players = [rows[i][cols.index('player_id')] for i in range(len(rows))]
        return players
예제 #10
0
 def _plot_stock_price(self):
     query = ExchangeDbQuery.select_price_from_trade_table_query()
     self._conn.execute(query)
     p = self._conn._cursor.fetchall()
     price = [i[0] for i in p]
     t = list(range(len(price)))
     plt.plot(t, price)
     plt.xlabel("Timesteps:{}".format(len(t)))
     plt.show()
예제 #11
0
 def _get_best_sell_price(self, book_name):
     try:
         query = ExchangeDbQuery.best_sell_price_query().format(book_name +
                                                                '_sell')
         self._conn.execute(query)
         price = self._conn._cursor.fetchone()[0]
         return price
     except Exception as e:
         return None
예제 #12
0
 def _clear_all_order_books(self):
     symbols = self._get_all_symbols()
     direcion = ['buy', 'sell']
     for i in symbols:
         book_name = '_'.join((self.BOOK_EXTENSION, str(i)))
         for j in direcion:
             bn = '_'.join((book_name, j))
             query = ExchangeDbQuery._clear_table_query().format(bn)
             self._conn.execute(query)
예제 #13
0
    def _verify_order(self, order_id):
        query = ExchangeDbQuery.fetch_order_from_db_query().format(order_id)
        rows, cols = self._conn.select(query)
        if not rows or not cols:
            raise Exception("DbError")

        orders = [rows[i][cols.index('order_id')] for i in range(len(rows))]
        if order_id not in orders:
            return False
        return True
예제 #14
0
    def handle_mod_orders(self, event):
        status = Status.Error
        reply_event = ExchangeOrderEvent(self._exchange_id, status)
        if not self._verify_order():
            reply_event._status = Status.Reject
            reply_event._message = Reply.OrderFailureReject
            return reply_event

        query = ExchangeDbQuery.update_order_in_orders_table_query().format(
            event._price,
            event._quantity * Direction[self._event.direction].value,
            event._order_id)
        self._conn.execute(query)

        return self._modify_order_in_order_book(event)
예제 #15
0
    def get_order_info(self, order_id):
        query = ExchangeDbQuery.get_all_info_of_order().query(order_id)
        rows, cols = self._conn.select(query)
        if not rows or not cols:
            return None, None, None, None

        symbol_id = rows[0][cols.index('symbol_id')]
        price = rows[0][cols.index('price')]
        quantitiy = rows[0][cols.index('quantitiy')]
        if quantitiy < 0:
            direction = 'SHORT'
        else:
            direction = 'LONG'

        return symbol_id, price, direction, quantitiy
예제 #16
0
    def handle_new_orders(self, event):
        status = Status.Error
        reply_event = ExchangeOrderEvent(self._exchange_id, status)
        if not self._verify_symbol(event._symbol):
            reply_event._status = Status.Reject
            reply_event._message = Reply.SymbolFailureReject
            return reply_event

        order_id = self._add_order_to_order_book(event)
        if order_id:
            symbol_id = self.get_symbol_id_from_db(event._symbol)
            query = ExchangeDbQuery.add_order_to_orders_table_query().format(
                event._sender_id, order_id, symbol_id, event._price,
                event._quantity * Direction[event._direction].value)
            self._conn.execute(query)
            return ExchangeOrderEvent(self._exchange_id, Status.Confirm,
                                      order_id)
            self._exchange.check_symbol_for_trade(symbol_id)
        else:
            return ExchangeOrderEvent(self._exchange_id, Status.Reject)
예제 #17
0
 def _get_all_symbols(self):
     query = ExchangeDbQuery._select_symbols_query()
     self._conn.execute(query)
     row = self._conn._cursor.fetchall()
     symbol_list = [str(i[0]) for i in row]
     return symbol_list
예제 #18
0
 def _clear_players_orders_table(self):
     query = ExchangeDbQuery._clear_table_query().format('players_orders')
     self._conn.execute(query)
예제 #19
0
 def _clear_trade_table(self):
     query = ExchangeDbQuery._clear_table_query().format('TRADE')
     self._conn.execute(query)