import time


def run_exchange(
        exchange,
        order_q,
        trader_qs,
        kill_q,
        start_event,
        start_time,
        sess_length,
        virtual_end,
        process_verbose):
    """
    Function for running of the exchange.
    :param exchange: Exchange object
    :param order_q: Queue on which new orders are sent to the queue
    :param trader_qs: Queues by which traders receive updates from the exchange
    :param kill_q: Queue where orders to be removed from the exchange are placed
    :param start_event: Event indicating if the exchange is active
    :param start_time: float, represents the start t (seconds since 1970)
    :param sess_length: int, number of seconds the
    :param virtual_end: The number of virtual seconds the trading day lasts for
    :param process_verbose: Flag indicating whether additional information about order processing should be printed
                            to console
    :return: Returns 0 on completion of trading day
    """
    completed_coid = {}
    start_event.wait()
    while start_event.isSet():

        virtual_time = (time.time() - start_time) * (virtual_end / sess_length)

        while kill_q.empty() is False:
            exchange.del_order(virtual_time, kill_q.get())

        order = order_q.get()
        if order.coid in completed_coid:
            if completed_coid[order.coid]:
                continue
        else:
            completed_coid[order.coid] = False

        (trade, lob) = exchange.process_order2(virtual_time, order, process_verbose)

        if trade is not None:
            completed_coid[order.coid] = True
            completed_coid[trade['counter']] = True
            for q in trader_qs:
                q.put([trade, order, lob])
    return 0