示例#1
0
def place_order(bid):
    print("Ingresando orden a: $" + bid)
    pyRofex.send_order(ticker=args.ticker,
                       side=pyRofex.Side.BUY,
                       size=1,
                       price=bid,
                       order_type=pyRofex.OrderType.LIMIT)
示例#2
0
 def _send_order(self, side, px, size):
     self.state = States.WAITING_ORDERS
     order = pyRofex.send_order(ticker=self.instrument,
                                side=side,
                                size=size,
                                price=round(px, 6),
                                order_type=pyRofex.OrderType.LIMIT,
                                cancel_previous=True)
     self.my_order[order["order"]["clientId"]] = None
     print("sending %s order %s@%s - id: %s" %
           (side, size, px, order["order"]["clientId"]))
def send_buy_order(ticker, price, qty):
    order = pyRofex.send_order(ticker=ticker,
                               side=pyRofex.Side.BUY,
                               size=qty,
                               price=price,
                               order_type=pyRofex.OrderType.LIMIT)

    print("Send Order Response:")
    pprint.pprint(order)
    order_status = pyRofex.get_order_status(order["order"]["clientId"])
    print("Order Status Response:")
    pprint.pprint(order_status)
示例#4
0
def performBid(md):
    simbolo = md['instrumentId']['symbol']
    if hasBids(md):
        bidAmount = hasBids(md) - 0.01
    else:
        bidAmount = ORDER_FIXED_AMOUNT
    order = pyRofex.send_order(ticker=simbolo,
                               side=pyRofex.Side.BUY,
                               size=1,
                               price=bidAmount,
                               order_type=pyRofex.OrderType.LIMIT)
    orderStatus = pyRofex.get_order_status(order["order"]["clientId"])
    if orderStatus['status'] == 'OK':
        return orderStatus
    else:
        return False
示例#5
0
    def get_ingresar_orden(self, buy):
        cont = 0
        self.print('Consultando BID')
        try:
            md = pyRofex.get_market_data(
                ticker=self.date_symbol,
                entries=[pyRofex.MarketDataEntry.BIDS])
        except Exception as e:
            self.print('Error al buscar BIDs : {}'.format(e))
            logging.error('Error al buscar BIDs : {}'.format(e))

        if md["marketData"]["BI"][0]["price"]:
            self.print('Precio de BID: ${}'.format(
                str(round(md["marketData"]["BI"][0]["price"],
                          2)).replace('.', ',')))
            entrada = round(
                float(md["marketData"]["BI"][0]["price"]) - 0.01, 2)
        else:
            self.print('No hay BIDs activos')
            entrada = float(buy)

        order = pyRofex.send_order(ticker=self.date_symbol,
                                   side=pyRofex.Side.BUY,
                                   size=1,
                                   price=entrada,
                                   order_type=pyRofex.OrderType.LIMIT)

        if order['status'] == 'ERROR':
            self.print('Error al realizar una órden: {}'.format(
                order['description']))
            return False

        order_status = pyRofex.get_order_status(order["order"]["clientId"])

        while True:
            if order_status["order"]['status'] == 'NEW':
                self.print('Ingresando orden a ${}'.format(entrada))
                return True
            else:
                # TODO: control de errores para otros posibles estados
                time.sleep(1)
                cont += 1

            if cont == self.timeout:
                self.print('Orden cancelada por TIMEOUT')
                return False
示例#6
0
    def placer_order(self, ticker, order_side, order_price, order_qty):
        # TODO implement
        # TODO Atento al parametro cancel_previous

        if order_side.lower() == 'buy':
            order_side = pyRofex.Side.BUY
        elif order_side.lower() == 'sell':
            order_side = pyRofex.side.BUY
        else:
            raise IncorrectOrderSide

        if logging.getLevelName('DEBUG') > 1:
            logging.debug(
                f'ROFEXClient: Sending {str(order_side).split(".")[-1]} order.'
            )

        try:
            order = pyRofex.send_order(ticker=ticker,
                                       side=order_side,
                                       size=order_qty,
                                       price=order_price,
                                       order_type=pyRofex.OrderType.LIMIT)
            lk.acquire()
            print(dash_line)
            print(f"----------- Send Order Response: ".ljust(width, '-'))
            pprint(order)
            active_orders.append(order)
            lk.release()

            order_status = pyRofex.get_order_status(order["order"]["clientId"])
            lk.acquire()
            print(dash_line)
            print(f"----------- Order Status Response: ".ljust(width, '-'))
            pprint(order_status)
            lk.release()

        except Exception as e:
            if logging.getLevelName('DEBUG') > 1:
                logging.debug(f'ROFEXClient ERROR: En exception occurred {e}')

            error_msg = "\033[0;30;47mERROR: Check log file for detailed error message.\033[1;37;40m"
            print(error_msg)
            print(dash_line)
    def send_order(self, ticker, order_price):
        """ send order"""
        logging.info("Ingresando orden a ${}".format(order_price))
        try:
            order = pyRofex.send_order(ticker=ticker,
                                       side=pyRofex.Side.BUY,
                                       size=10,
                                       price=order_price,
                                       order_type=pyRofex.OrderType.LIMIT)

            #estado Orden
            order_status = self.get_order_status(order)
            logging.info("Estado orden:")
            logging.info("Status: {}".format(order_status["status"]))
            logging.info("Order ID: {}".format(
                order_status["order"]["orderId"]))
            logging.info("Descripción: {}".format(
                order_status["order"]["text"]))

        except Exception as e:
            logging.error("No se pudo enviar la orden")
示例#8
0

def error_handler(message):
    print("Error Message Received: {0}".format(message))


def exception_handler(e):
    print("Exception Occurred: {0}".format(e.message))


# 3-Initialize Websocket Connection with the handlers
pyRofex.init_websocket_connection(order_report_handler=order_report_handler,
                                  error_handler=error_handler,
                                  exception_handler=exception_handler)

# 4-Subscribes to receive order report for the default account
pyRofex.order_report_subscription()

# 5-Subscribes to an invalid account
pyRofex.order_report_subscription(account="InvalidAccount")

# 6-Send an order to check that order_report_handler is called
pyRofex.send_order(ticker="DODic19",
                   side=pyRofex.Side.BUY,
                   size=10,
                   order_type=pyRofex.OrderType.MARKET)

# 7-Wait 5 sec then close the connection
time.sleep(1)
pyRofex.close_websocket_connection()
示例#9
0
pyRofex.initialize(user="******",
                   password="******",
                   account="XXXXXXX",
                   environment=pyRofex.Environment.REMARKET)

# 2-Get the best bid offer in the market for DODic19
md = pyRofex.get_market_data(ticker="DODic19",
                             entries=[pyRofex.MarketDataEntry.BIDS])

# Print the response
print("Market Data Response: {0}".format(md))

# 3-Send a Buy Limit Order for DODic19 with the same price as the best bid
order = pyRofex.send_order(ticker="DODic19",
                           side=pyRofex.Side.BUY,
                           size=10,
                           price=md["marketData"]["BI"][0]["price"],
                           order_type=pyRofex.OrderType.LIMIT)

# Print the response
print("Send Order Response: {0}".format(order))

# 4-Check the order status
order_status = pyRofex.get_order_status(order["order"]["clientId"])

# Print the response
print("Order Status Response: {0}".format(order_status))

# 5-If order status is PENDING_NEW then we keep checking the status until
# the market accept or reject the order or timeout is reach
timeout = 5  # Time out 5 seconds
示例#10
0
#Check del simbolo
if md["status"] == "ERROR" and md["description"] == "Security {0}:ROFX doesn't exist".format(instrumento):
    print("Simbilo invalido")
    logout()

try:
    print("Ultimo precio operado: ${0}".format(md["marketData"]["LA"]["price"]))
except:
    print("Ultimo precio operado: None")

#CONSULTO EL PRECIO DEL BID
print("Consultando BID")

try:
#Si exitsen entradas, creo una a $0,01 menos que el precio del BID
    bi = md["marketData"]["BI"][0]["price"]
    print("Precio del BID: ${0}".format(bi))
    print("Ingresando orden a ${0}".format(bi-0.01))
    chk = pyRofex.send_order(instrumento, side=pyRofex.Side.BUY, size=1, price=bi-0.01, order_type=pyRofex.OrderType.LIMIT)
#Chequeo que la orden se haya realizado con exito
    check_order_send(chk)
except:
#Si no existen entradas, creo una a $75,25
    print("No hay BIDs activos")
    print("Ingresando orden a $75,25")
    chk = pyRofex.send_order(instrumento, side=pyRofex.Side.BUY, size=1, price=75.25, order_type=pyRofex.OrderType.LIMIT)
#Chequeo que la orden se haya realizado con exito
    check_order_send(chk)

logout()
示例#11
0
def iniciar(ticker2, REMARKETS_USER, REMARKET_PASS, REMARKET_ACCOUNT):
    def error_handler(message):
        print("Simbolo invalido")

    def market_data_handler(message):
        print("se ha reportado una solicutud al market data")

    def exception_handler(e):
        print("Exception Ocurred")

    def order_report_handler(message):
        print("se ha reportado una orden")

    print("~$ python challenge.py ", ticker2, " -u ", REMARKETS_USER, " -p ",
          REMARKET_PASS)
    print("Iniciando sesion en Remarket")
    # bloque try/except para autencticacion de password
    try:
        pyRofex.initialize(user=REMARKETS_USER,
                           password=REMARKET_PASS,
                           account=REMARKET_ACCOUNT,
                           environment=pyRofex.Environment.REMARKET)
    except:
        print("Error de autenticacion")
        print("~$")
        print("por favor vuelva a ingresar sus credenciales")
        exit()
    else:
        pyRofex.init_websocket_connection(
            market_data_handler=market_data_handler,
            error_handler=error_handler,
            order_report_handler=order_report_handler,
            exception_handler=exception_handler)

    print("Consultando simbolo")

    md = pyRofex.get_market_data(
        ticker=ticker2,
        entries=[pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.LAST])
    # capturar el key error de market data
    try:
        lp = md["marketData"]["LA"]["price"]
    except KeyError:
        print("Símbolo inválido")
    else:
        lp = md["marketData"]["LA"]["price"]
        print("Último precio operado:  $", lp)
        print("consultando BID")
        try:
            md["marketData"]["BI"][0]["price"]
        except KeyError:
            # In this case, replace the constant value of 75.25 by a value that when talking about the September dollar the value is 75.25 in the bid offered.
            # But if we talk about another asset (another instrument) this remains at a competitive value for supply / demand.
            pyRofex.send_order(ticker=ticker2,
                               side=pyRofex.Side.BUY,
                               size=1,
                               price=lp - 0.91,
                               order_type=pyRofex.OrderType.LIMIT)
            print("No hay Bids Activos")
            bido = lp - 0.91
            print("ingresando orden :$", bido)

        else:
            pyRofex.send_order(ticker=ticker2,
                               side=pyRofex.Side.BUY,
                               size=1,
                               price=md["marketData"]["BI"][0]["price"] - 0.01,
                               order_type=pyRofex.OrderType.LIMIT)
            bid = md["marketData"]["BI"][0]["price"]
            bido = bid - 0.01
            print("Precio de BID: $", bid)
            print("ingresando orden :$", bido)
    print("cerrando sesion en Remarket")
    time.sleep(5)
    pyRofex.close_websocket_connection()
    print("~$")
示例#12
0
    pyRofex.MarketDataEntry.LAST
]
#%%
# Nos subscribimos para recibir mensajes
pyRofex.market_data_subscription(tickers=instruments, entries=entries, depth=5)

# Nos subscribimos a un instrumento inválido y vemos un error
#pyRofex.market_data_subscription(tickers=["InvalidInstrument"],
#                                 entries=entries)

#%%
# Subscribes to receive order report messages (default account will be used) **
pyRofex.order_report_subscription()

# Envía una orden límite de compra para el DONov20
order = pyRofex.send_order(ticker="DONov20",
                           side=pyRofex.Side.BUY,
                           size=10,
                           price=81.30,
                           order_type=pyRofex.OrderType.LIMIT)

# Esperar 5 segunos
time.sleep(5)

#%%
# Cancelar la orden
cancel_order = pyRofex.cancel_order(order["order"]["clientId"])

#%%
pyRofex.close_websocket_connection()
print("Market data más completa para {0}: {1}".format(ticker, market_data))

#%%

# Obtener datos históricos desde el comienzo del año hasta hoy
end = datetime.date.today()
start = datetime.date(year=end.year, month=1, day=1)
historic_trades = pyRofex.get_trade_history(ticker=ticker, start_date=start, end_date=end)
print("Datos históricos {0} from {1} to {2}: {3}".format(ticker, start, end, historic_trades))

#%% Manejo de órdenes

# Envía una orden límite de compra para el instrumento
order = pyRofex.send_order(ticker=ticker,
                           side=pyRofex.Side.BUY,
                           size=10,
                           price=81.10,
                           order_type=pyRofex.OrderType.LIMIT)

# Print the response
print("Respuesta del envío de orden: {0}".format(order))

# Ver cómo quedó la orden
order_status = pyRofex.get_order_status(order["order"]["clientId"])

# Mostrarlo
print("Respuesta del estado de la orden: {0}".format(order_status))

# si la orden se queda en PENDING_NEW continuar 'poleando' hasta que se coloque
timeout = 5 # Time out 5 seconds