def __init__(self, instrument, size, spread): # Define variables self.instrument = instrument self.comision = 0 self.initial_size = size self.buy_size = size self.sell_size = size self.spread = spread self.tick = 0.001 self.my_order = dict() self.last_md = None self.state = States.WAITING_MARKET_DATA # Initialize the environment pyRofex.initialize(user="******", password="******", account="XXXXXXX", environment=pyRofex.Environment.REMARKET) # Initialize Websocket Connection with the handler pyRofex.init_websocket_connection( market_data_handler=self.market_data_handler, order_report_handler=self.order_report_handler) # Subscribes for Market Data pyRofex.market_data_subscription(tickers=[self.instrument], entries=[ pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS ]) # Subscribes to receive order report for the default account pyRofex.order_report_subscription()
def __init__(self, date_symbol, remarkets_account, remarkets_user, remarkets_pass, verbose=True, timeout=10, *args, **kwargs): self.timeout = timeout self.date_symbol = date_symbol self.status = 'OK' self.verbose = verbose try: pyRofex.initialize(user=remarkets_user, password=remarkets_pass, account=remarkets_account, environment=pyRofex.Environment.REMARKET) except Exception as e: self.print(remarkets_pass) self.print(remarkets_user) self.print(remarkets_account) self.print('Error de autentificación : {}'.format(e)) self.status = 'ERROR'
def __init__(self, simbolo): pyRofex.initialize(user='******', password='******', account='sampleAccount', environment=pyRofex.Environment.REMARKET) self.simbolo = simbolo[:3].upper()
def open_connection(self): """estabilsh connection""" logging.info("Iniciando sesión en Remarkets") try: pyRofex.initialize(user=self.user, password=self.password, account=self.account, environment=pyRofex.Environment.REMARKET) except Exception as e: logging.critical("No se pudo establecer conexion con ROFEX")
def connect(self, user, password, account, environment): """ Implements Connection to ROFEX DMA Server. (demo = reMarkets; live = ROFEX) Initializes environment and WebSocket Connection :param user: User. :type user: Str. :param password: User Password. :type password: Str. :param account: Account provided by Market Authority. :type account: Str. :param environment: Market environment. :type environment: Str. """ clear_screen() print(dash_line) message = f'Connecting to {environment} DMA server' print(message.center(width)) print(dash_line) if logging.getLevelName('DEBUG') > 1: logging.debug( f'ROFEXClient: Starting connection to {environment} DMA Server ' ) try: # Initialize Environment pyRofex.initialize(user=user, password=password, account=account, environment=environment) # Initialize WebSocket Cnnection with Handlers pyRofex.init_websocket_connection( market_data_handler=self.market_data_handler, error_handler=self.error_handler, exception_handler=self.exception_handler) except Exception as e: if logging.getLevelName('DEBUG') > 1: logging.debug(f'ROFEXClient ERROR: En exception occurred {e}') error_msg = "\033[0;30;47mERROR: CONNECTION ERROR. Check log file " \ "for detailed error message.\033[1;37;40m" print(error_msg) print(dash_line)
# -*- coding: utf-8 -*- """ Created on Thu Mar 26 14:16:50 2020 @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])
import pyRofex import pandas as pd import matplotlib.pyplot as plt from _datetime import datetime pyRofex.initialize(user='******', password='******', account='sampleAccount', environment=pyRofex.Environment.REMARKET) def buscarInstrumentos(c): l = len(c) a = listarInstrumentos() b = a['instruments'] print(b) for i in b: if i['instrumentId']['symbol'][:l] == c: print(i['instrumentId']['symbol']) def listarSegmentos(): segments = pyRofex.get_segments() return segments
# Leer los argumentos de la línea de comando args = parser.parse_args() if args.simbolo: instruments.append(args.simbolo) if args.usuario: REMARKETS_USER = args.usuario if args.password: REMARKETS_PASSWORD = args.password if args.cuenta: REMARKETS_ACCOUNT = args.cuenta #Intentar conexión con credenciales proporcionadas try: pyRofex.initialize(user=REMARKETS_USER, password=REMARKETS_PASSWORD, account=REMARKETS_ACCOUNT, environment=pyRofex.Environment.REMARKET) except: print("Error: revisa tu usuario, contraseña y cuenta") #MD último precio def hasLastPrice(md): if md['marketData']['LA']: return md['marketData']['LA']['price'] else: return None #MD bids def hasBids(md):
import pyRofex from datetime import date from typing import List, Union, Dict import pandas as pd user = "******" #os.environ["user"] password = "******" account = "REM3901" pyRofex.initialize(user=user, password=password, account=account, environment=pyRofex.Environment.REMARKET) def get_trade_history(trade_symbol: str): resp = pyRofex.get_trade_history(trade_symbol, "2020-01-01", date.today()) df = pd.DataFrame(resp["trades"]) del_columns = ["symbol", "servertime", "size"] df.drop(del_columns, inplace=True, axis=1) di = df.to_json(orient='records') return di
import xlwings as xw import numpy as np import config '''----------- Excel sheets --------------''' wb = xw.Book('EPGB V3.3.1 FE_Primary.xlsb') shtTickers = wb.sheets('Tickers') shtData = wb.sheets('Primary') shtOpciones = wb.sheets('Opciones') '''----------- Connect to rofex --------------''' RFX_Environment = pyRofex.Environment.LIVE pyRofex.initialize(user=config.COMITENTE, password=config.PASSWORD, account=config.COMITENTE, environment=RFX_Environment) '''----------- Get all Tickers --------------''' rng = shtTickers.range('A2:C500').expand() tickers = pd.DataFrame(rng.value, columns=['ticker', 'symbol', 'strike']) opciones = tickers.copy() opciones = opciones.set_index('ticker') opciones['bidSize'] = 0 opciones['bid'] = 0 opciones['ask'] = 0 opciones['asksize'] = 0 calls = pd.DataFrame() puts = pd.DataFrame()
"MERV - XMEV - GD29D - CI", "MERV - XMEV - GD30D - CI", "MERV - XMEV - GD35D - CI", "MERV - XMEV - GD38D - CI", "MERV - XMEV - GD41D - CI", "MERV - XMEV - GD46D - CI", "MERV - XMEV - TO23 - 48hs", "MERV - XMEV - TO26 - 48hs", "MERV - XMEV - PARP - 48hs", "MERV - XMEV - TX26 - 48hs", "MERV - XMEV - TX28 - 48hs", "MERV - XMEV - TC23 - 48hs" ] prices = pd.DataFrame(columns=["Last", "Bid", "Ask"], index=instrumentos).fillna(0) prices.index.name = "Instrumento" # Initialize the environment pyRofex.initialize(user="******", password="******", account="aqui_va_tu_cuenta", environment=pyRofex.Environment.LIVE) def market_data_handler(message): global prices prices.loc[message["instrumentId"]["symbol"]] = [ message["marketData"]["LA"]["price"], message["marketData"]["OF"][0]["price"], message["marketData"]["BI"][0]["price"] ] # Initialize Websocket Connection with the handlers pyRofex.init_websocket_connection(market_data_handler=market_data_handler)
parser = argparse.ArgumentParser() parser.add_argument("ticker", help="Ticker de MATBA ROFEX") parser.add_argument("-u", dest="username", help="Usuario de Remarkets", required=True) parser.add_argument("-p", dest="password", help="Passowrd de Remarkets", required=True) parser.add_argument("-a", dest="account", help="Cuenta de Remarkets", required=True) args = parser.parse_args() print("Iniciando sesión en Remarkets") try: pyRofex.initialize(user=args.username, password=args.password, account=args.account, environment=pyRofex.Environment.REMARKET) open_connection() except Exception as e: if (str(e) == "Authentication fails. Incorrect User or Password"): print("Error en la autenticación, usuario o password incorrectos") else: print(str(e))
#Check de los argumentos if len(sys.argv)!=8 or sys.argv[2]!="-u" or sys.argv[4]!="-p" or sys.argv[6]!="-a": print("Argumentos invalidos!") sys.exit() instrumento=sys.argv[1] #inicializo el environment print("Iniciando sesion en Remarkets") try: pyRofex.initialize( user=sys.argv[3], password=sys.argv[5], account=sys.argv[7], environment = pyRofex.Environment.REMARKET) except: print("Usuario y/o contraseña incorrectos") sys.exit() # Inicializo la conexion Websocket try: pyRofex.init_websocket_connection() except: print("Error al establecer una conexion websocket") sys.exit()
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("~$")
with open('config.json') as f: cfg = json.load(f) ''' estructura del json de config: { "user":"******", "password":"******", "account":"account" } ''' #%% # Detalles de la cuenta de test: pyRofex.initialize(user=cfg["user"], password=cfg["password"], account=cfg["account"], environment=pyRofex.Environment.REMARKET) #%% # Primero hay que definir las funciones callback que van a ser invocadas para cada evento def market_data_handler(message): print("Mensaje de Market Data recibido: {0}".format(message)) def order_report_handler(message): print("Mensaje de Reporte de Orden recibido: {0}".format(message)) def error_handler(message):
Created on Tue Jun 30 00:27:55 2020 @author: amazz """ import pyRofex import pandas as pd from datetime import datetime import config prices = pd.DataFrame(columns=["Time", 'symbol', "last"]) prices.set_index('Time', inplace=True) # Set the the parameter for the REMARKET environment pyRofex.initialize(user=config.username, password=config.password, account=config.account, environment=pyRofex.Environment.REMARKET) # First we define the handlers that will process the messages and exceptions. def market_data_handler(message): global prices print("Market Data Message Received: {0}".format(message)) print('datetime {}, symbol {}, last {}'.format( datetime.fromtimestamp(message["timestamp"] / 1000), message['instrumentId']['symbol'], message["marketData"]["LA"]["price"])) last = message["marketData"]["LA"]["price"] symbol = message['instrument']['symbol'] print('datetime {}, symbol {}, last {}'.format(
Steps: 1-Initialize the environment 2-Defines the handlers that will process the messages and exceptions. 3-Initialize Websocket Connection with the handlers 4-Subscribes to receive order report for the default account 5-Subscribes to an invalid account 6-Send an order to check that order_report_handler is called 7-Wait 5 sec then close the connection """ import time import pyRofex # 1-Initialize the environment pyRofex.initialize(user="******", password="******", account="XXXXXXX", environment=pyRofex.Environment.REMARKET) # 2-Defines the handlers that will process the messages and exceptions. def order_report_handler(message): print("Order Report Message Received: {0}".format(message)) def error_handler(message): print("Error Message Received: {0}".format(message)) def exception_handler(e): print("Exception Occurred: {0}".format(e.message))
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) # 1-Initialize the environment pyRofex.initialize(user="******", password="******", account="REM5018", environment=pyRofex.Environment.REMARKET) # 2-Defines the handlers that will process the messages and exceptions. 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 ]