Beispiel #1
0
def random_order():
    global me
    values = request.get_json()
    print(values)
    # Check that the required fields are in the POST'ed data
    required = ['number', 'midpoint']
    if not all(k in values for k in required):
        return 'Missing values', 400

    orders = []

    me.orderbook.bids *= 0
    me.orderbook.asks *= 0

    for i in range(int(values["number"])):
        #for i in range(100):
        #print(i)
        side = random.choice(["buy", "sell"])
        print(side + str(i))
        price = random.gauss(int(values["midpoint"]), 5)
        #price = random.gauss(8000, 50)
        quantity = random.expovariate(0.05)
        #orders.append({'id': 0, 'type': 'limit', 'side': side, 'price': price, 'quantity': quantity})
        orders.append(engine.Order(0, 'limit', side, price, quantity))

    for order in orders:
        me.process(order)

    response = {
        'message':
        f'Generated {values["number"]} Orders with midpoint {values["midpoint"]} '
    }
    return jsonify(response), 201
def direct_benchmark(nr_of_orders, midpoint=100):

    # Instancia de engine (motor emparejamiento)
    engine = m_engine.MatchingEngine()

    # Se declara el tamaño del libro de ordenes
    orderbook_size = len(engine.orderbook)

    # Se define el arreglo de ordenes
    orders = []
    count_bid = 0
    count_ask = 0
    #  bucle para crear un libro de ordenes tipo limite (Venta y Compra) aleatorio asignado a un arreglo de objetos
    #  tipo engine.order.
    for i in range(nr_of_orders):
        # Establece de manera aleatoria si es compra o venta
        side = random.choice(["buy", "sell"])
        if side == "buy":
            count_bid += 1
        else:
            count_ask += 1

        # Establece de manera aleatoria el precio utilizando la funcion de gauss con punto medio 100 variacion entre 95 y 105.
        price = random.gauss(midpoint, 5)
        # Establece un valor aleatorio para la cantidad de activos en la orden.
        quantity = random.expovariate(0.05)
        # Construye la orden segun los datos obtenidos y lo adiciona al arreglo order
        orders.append(m_engine.Order("Null", "limit", side, price, quantity))

    # Comienza a medir el tiempo de emparejamiento.
    start = timer()
    # Bucle que envia a procesamiento orden por orden.
    for order in orders:
        # envio orden a procesamiento del emparejador.
        engine.process(order)
    # Mide el tiempo de emparejamiento despues de ejecutar el total de ordenes.
    end = timer()
    t = end - start
    # Indica el tiempo utilizado para procesar el total del numero de ordenes.

    print('Ordenes de compra: {0}, Ordenes de venta: {1}'.format(
        count_bid, count_ask))
    print('{0} ordenes procesadas en {1:.2f} segundos,'.format(
        nr_of_orders, t))
    print(
        "a una tasa promedio de {0:.0f} orders/second o {1:.2f} microsegundos/order,"
        .format((nr_of_orders / t), (t / nr_of_orders) * 1000 * 1000))
    print(
        'ordenes tipo limite sin emparejamiento: {0} y ordenes emparejadas {1}.'
        .format(len(engine.orderbook) - orderbook_size, len(engine.trades)))
    print(
        'ordenes de compra sin emparejar: {0}, ordenes de venta sin emparejar: {1}'
        .format(engine.orderbook.getSizeOfBids(),
                engine.orderbook.getSizeOfAsks()))
 def handle(self):
     while True:
         data = self.request.recv(1024).strip()
         if not data:
             break
         data = json.loads(data.decode('utf-8'))
         order = engine.Order(data['id'],
                              data['type'],
                              data['side'],
                              data['price'],
                              data['quantity'])
         self.server.matching_engine.process(order)
         self.request.sendall("ACK".encode("utf-8"))
Beispiel #4
0
def new_order():
    global me
    values = request.get_json()
    print(values)
    # Check that the required fields are in the POST'ed data
    required = ['side', 'price', 'quantity']
    if not all(k in values for k in required):
        return 'Missing values', 400
    order=engine.Order(0,'limit',values["side"],int(values["price"]),int(values["quantity"]))
    me.process(order)

    print("no of bids" + str(len(me.orderbook.bids)))
    print("no of asks"+ str(len(me.orderbook.asks)))
    response = {'message': f'Received {values["side"]} Order at $ {values["price"]} for {values["quantity"]} '}
    return jsonify(response), 201
Beispiel #5
0
 def handle(self):
     while True:
         data = self.request.recv(1024).strip()
         if not data:
             break
         data = json.loads(data.decode('utf-8'))
         order = engine.Order(data['id'], data['type'], data['side'],
                              data['price'], data['quantity'])
         self.server.matching_engine.process(order)
         serialized_order = self.server.matching_engine.orderbook.bids
         #print(serialized_order)
         for bid in self.server.matching_engine.orderbook.bids:
             print(bid)
             print(json.dumps(bid.price))
         for ask in self.server.matching_engine.orderbook.asks:
             #print(ask)
             print('ask')
         self.request.sendall("ACK".encode("utf-8"))
Beispiel #6
0
def direct_benchmark(nr_of_orders, midpoint=100):
    engine = m_engine.MatchingEngine()

    orderbook_size = len(engine.orderbook)
    orders = []
    for i in range(nr_of_orders):
        side = random.choice(["buy", "sell"])
        price = random.gauss(midpoint, 5)
        quantity = random.expovariate(0.05)
        orders.append(m_engine.Order("Null", "limit", side, price, quantity))

    start = timer()
    for order in orders:
        engine.process(order)
    end = timer()
    t = end - start
    print('{0} orders processed over {1:.2f} seconds,'.format(nr_of_orders, t))
    print(
        "at an average speed of {0:.0f} orders/second or {1:.2f} microseconds/order,"
        .format((nr_of_orders / t), (t / nr_of_orders) * 1000 * 1000))
    print('resulting in {0} new orders in the book and {1} trades.'.format(
        len(engine.orderbook) - orderbook_size, len(engine.trades)))
Beispiel #7
0
# me.process(order)
# order = engine.Order(0,'limit','sell',151,100)
# me.process(order)
# order = engine.Order(0,'limit','sell',150,105)
# me.process(order)

nr_of_orders=200
midpoint=100

orders = []
for i in range(nr_of_orders):
	side = random.choice(["buy", "sell"])
	price = random.gauss(midpoint, 5)
	quantity = random.expovariate(0.05)
	#orders.append({'id': 0, 'type': 'limit', 'side': side, 'price': price, 'quantity': quantity})
	orders.append(engine.Order(0,'limit',side,price,quantity))
	

for order in orders:
	me.process(order)

for bid in me.orderbook.bids:
	print(bid)

for ask in me.orderbook.asks:
	print(ask)

bid_x=[order.price for order in me.orderbook.bids] 
bid_y=[order.quantity for order in me.orderbook.bids] 

ask_x=[order.price for order in me.orderbook.asks]