Esempio n. 1
0
 def get_market_qty(self, ticker):
     # TODO implement
     ticker_entries = [
         pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS
     ]
     full_book = pyRofex.get_market_data(ticker, ticker_entries)
     market_qty = float(
         full_book.get('marketData').get('OF')[0].get('size'))
     return market_qty
def market_data_handler(message):
    global quoting_price
    global quoting_qty
    global order_sent

    try:
        ticker = message.get('instrumentId').get('symbol')
        ticker_entries = [
            pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS
        ]

        if ticker:
            full_book = pyRofex.get_market_data(ticker,
                                                ticker_entries,
                                                depth=10)
            # trade_history = pyRofex.get_trade_history(ticker, dt.date(2020, 1, 1), dt.date.today())
            # trade_history_df = pd.DataFrame.from_dict(trade_history.get('trades')).drop('servertime', axis=1)
            # trade_history_df = trade_history_df[['symbol', 'price', 'size', 'datetime']]
            # print(f"Trade History {ticker}")
            # print(pprint.pprint(trade_history_df))

            print(f"Full book for {ticker}")
            print(pprint.pprint(full_book.get('marketData')))
            market_price = float(
                full_book.get('marketData').get('BI')[0].get('price'))
            quoting_price = market_price + 0.05
            market_qty = int(
                full_book.get('marketData').get('OF')[0].get('size'))
            quoting_qty = market_qty

        if order_sent < 1:
            send_buy_order("GGALOct20", quoting_price, quoting_qty)
            order_sent += 1
        """    
        print(message.get('instrumentId'))
        instrument_df = pd.DataFrame(message)
        bid_series = message.get('marketData').get('BI')
        bid_series = pd.DataFrame.from_dict(bid_series)
        ask_series = message.get('marketData').get('OF')
        ask_series = pd.DataFrame.from_dict(ask_series)
        print(bid_series)
        print(ask_series)
        print(instrument_df)
        """
    except Exception:
        traceback.print_exc()
Esempio n. 3
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
Esempio n. 4
0
 def get_last_price(self):
     try:
         lp = pyRofex.get_market_data(ticker=self.date_symbol,
                                      entries=[
                                          pyRofex.MarketDataEntry.BIDS,
                                          pyRofex.MarketDataEntry.LAST
                                      ])
     except Exception as e:
         self.print('Error al buscar último precio : {}'.format(e))
     if lp['status'] != 'ERROR':
         self.print('Último precio operado: ${}'.format(
             str(round(lp["marketData"]["LA"]["price"],
                       2)).replace('.', ',')))
         return lp["marketData"]["LA"]["price"]
     elif lp['description'][-18:] == "ROFX doesn't exist":
         self.print('Símbolo inválido')
         return False
     else:
         # otro tipo de error
         self.print('Error al buscar último precio')
         return False
Esempio n. 5
0
@author: agarcia20
"""

import pyRofex
import json

# Set the the parameter for the REMARKET environment
pyRofex.initialize(user="******",
                   password="******",
                   account="REM3328",
                   environment=pyRofex.Environment.REMARKET)

# Gets all segments
#p = pyRofex.get_segments()
#print(json.dumps(p, indent=1))
# Gets available instruments list
#p = pyRofex.get_all_instruments()
#print(json.dumps(p, indent=1))

# Gets detailed instruments list
#p = pyRofex.get_detailed_instruments()
#print(json.dumps(p, indent=1))

# Makes a request to the Rest API and get the last price
# Use the MarketDataEntry enum to specify the data
p = pyRofex.get_market_data(ticker="I.RFX20",
                            entries=[pyRofex.MarketDataEntry.LAST])
#p = pyRofex.get_market_data(ticker="I.RFX20")

print(json.dumps(p, indent=1))
Esempio n. 6
0
# 1-Initialize the environment
pyRofex.initialize(user="******",
                   password="******",
                   account="XXXXXXX",
                   environment=pyRofex.Environment.REMARKET)

# 2-Set the instrument to use
instrument = "DODic19"

# 3-Get the two Best Bids and Best Offers for the instrument (using depth parameter)
entries = [
    pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS,
    pyRofex.MarketDataEntry.LAST
]
market_data = pyRofex.get_market_data(instrument, entries, depth=2)

print("Market Data Response for {0}: {1}".format(instrument, market_data))

# 4-Get all available entries for the instrument
entries = [
    pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS,
    pyRofex.MarketDataEntry.LAST, pyRofex.MarketDataEntry.CLOSING_PRICE,
    pyRofex.MarketDataEntry.OPENING_PRICE, pyRofex.MarketDataEntry.HIGH_PRICE,
    pyRofex.MarketDataEntry.LOW_PRICE,
    pyRofex.MarketDataEntry.SETTLEMENT_PRICE,
    pyRofex.MarketDataEntry.NOMINAL_VOLUME,
    pyRofex.MarketDataEntry.TRADE_EFFECTIVE_VOLUME,
    pyRofex.MarketDataEntry.TRADE_VOLUME, pyRofex.MarketDataEntry.OPEN_INTEREST
]
market_data = pyRofex.get_market_data(instrument, entries)
Esempio n. 7
0
    4-Check the order status
    5-If order status is PENDING_NEW then we keep checking the status until the market accept or reject the order
    6-If the status is NEW, cancel the order
"""
import time

import pyRofex

# 1-Initialize the environment
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
Esempio n. 8
0
    sys.exit()



# Inicializo la conexion Websocket
try:
    pyRofex.init_websocket_connection()
except:
    print("Error al establecer una conexion websocket")
    sys.exit()



#Obtengo la MARKET_DATA
print("Consultando simbolo")
md = pyRofex.get_market_data(instrumento, [pyRofex.MarketDataEntry.BIDS,
                                           pyRofex.MarketDataEntry.LAST])


#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")
Esempio n. 9
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("~$")
Esempio n. 10
0
    def process_market_data_message(self, message):
        """
        TODO Later this should evaluate every possible action triggerd by specific MarketData messages
        Prints book and MarketData for each updated Ticker whenever the market changes.
        :param message: Message received. Comes as a JSON.
        :type message: Dict.
        """

        try:
            ticker = message.get('instrumentId').get('symbol')
            ticker_entries = [
                pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS
            ]
            full_book = pyRofex.get_market_data(ticker,
                                                ticker_entries,
                                                depth=10)

            if len(full_book.get('marketData').get('BI')) !=0\
                    and len(full_book.get('marketData').get('OF')) != 0:
                bid_book = full_book.get('marketData').get('BI')
                bid_book_df = pd.DataFrame().from_dict(bid_book)
                bid_book_df.columns = ['BP', 'BS']

                ask_book = full_book.get('marketData').get('OF')
                ask_book_df = pd.DataFrame().from_dict(ask_book)
                ask_book_df.columns = ['OP', 'OS']

                last_trade = [message.get('marketData').get('LA')]

                full_book_df = pd.concat([bid_book_df, ask_book_df], axis=1)
                full_book_df = full_book_df[['BS', 'BP', 'OP', 'OS']]
                full_book_df.fillna(0, inplace=True)
                lk.acquire()
                print(dash_line)
                msg_centered = f"{ticker} - MarketData".ljust(width, ' ')
                md_header = f"\033[0;30;47m{msg_centered}\033[1;37;40m"
                print(md_header)
                print("   BID         ASK")
                print(full_book_df)
                print("\nTop:", full_book_df['BS'].iloc[0],
                      full_book_df['BP'].iloc[0], full_book_df['OP'].iloc[0],
                      full_book_df['OS'].iloc[0])
                lk.release()

            else:
                empty_MD = pd.DataFrame.from_dict({
                    'BS': [0],
                    'BP': [0],
                    'OP': [0],
                    'OS': [0]
                })
                lk.acquire()
                print(dash_line)
                print(f"----------- {ticker} - MarketData ".ljust(width, '-'))
                print("   BID              ASK")
                print(empty_MD)
                lk.release()

        except Exception:
            traceback.print_exc()
            pass
# Obtenemos una lista de los instrumentos y contamos cuantos son
instruments = pyRofex.get_all_instruments()
print("Número de instrumentos:: {0}".format(len(instruments['instruments'])))

# Obtenemos una lista detallada e imprimimos detalles:
detailed = pyRofex.get_detailed_instruments()
for i in range(5):
    print("#### DETALLE para {0}: {1}".format(detailed['instruments'][i]['instrumentId']['symbol'],
                                                  detailed['instruments'][i]))
    print("#### FIN DE DETALLE ####")

#%% ########### MARKET DATA #############
# Realiza un pedido a la API Rest para obtener el último precio, bids y offers del instrumento
entries = [pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS, pyRofex.MarketDataEntry.LAST]
ticker = "DONov20"
market_data = pyRofex.get_market_data(ticker=ticker,entries=entries, depth=5)

print("Respuesta al pedido de market data para {0}: {1}".format(ticker, market_data))
#%%

# Obtener toda la info del instrumento:
entries = [
    pyRofex.MarketDataEntry.BIDS,
    pyRofex.MarketDataEntry.OFFERS,
    pyRofex.MarketDataEntry.LAST,
    pyRofex.MarketDataEntry.CLOSING_PRICE,
    pyRofex.MarketDataEntry.OPENING_PRICE,
    pyRofex.MarketDataEntry.HIGH_PRICE,
    pyRofex.MarketDataEntry.LOW_PRICE,
    pyRofex.MarketDataEntry.SETTLEMENT_PRICE,
    pyRofex.MarketDataEntry.NOMINAL_VOLUME,
 def get_market_data(self, ticker, entries):
     """ retrieve market data"""
     return pyRofex.get_market_data(ticker, entries, depth=2)
Esempio n. 13
0
user = args.U
password = args.P
account = args.A

try:

    print("Iniciando Sesion en Remarkets")

    pyRofex.initialize(user=user,
                       password=password,
                       account=account,
                       environment=pyRofex.Environment.REMARKET)

    #consulto el ultimo precio del ticker
    print("Consultando Simbolo", ticker)
    UPO = pyRofex.get_market_data(ticker=ticker,
                                  entries=[pyRofex.MarketDataEntry.LAST])

    if UPO["status"] == "ERROR":
        print("Ticker invalido")
        print("Cerrando sesión en Remarkets")
        pyRofex.close_websocket_connection()
    else:

        if UPO["marketData"]["LA"] == None:
            print("No hay ultimo precio operado")
        else:
            print("Ultimo Precio Operado", UPO["marketData"]["LA"]['price'])

        print("Consultando BID")

        #consulto la ultima oferta