### Get Instruments by CFICode Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Demonstrates how to retrieve instruments based on their CFI codes, showing examples for fetching all stocks and all derivatives. ```python # Get all stocks stocks = pyRofex.get_instruments( 'by_cfi', cfi_code=[pyRofex.CFICode.STOCK] ) # Get all derivatives derivatives = pyRofex.get_instruments( 'by_cfi', cfi_code=[ pyRofex.CFICode.FUTURE, pyRofex.CFICode.CALL_FUTURE, pyRofex.CFICode.PUT_FUTURE ]) ``` -------------------------------- ### Install PyRofex Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/README.md Install the PyRofex library using pip. This is the first step before using any of its functionalities. ```python pip install pyRofex ``` -------------------------------- ### Python pyRofex Order Report Subscription Example Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket.md Demonstrates how to initialize the pyRofex library, set up a WebSocket connection with a custom handler, and subscribe to order reports. Includes examples for both snapshot-only and historical order retrieval. ```python import pyRofex pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET) def handle_order(msg): print(f"Order: {msg['order']['clientId']} - {msg['order']['status']}") pyRofex.init_websocket_connection(order_report_handler=handle_order) # Subscribe to order reports (snapshot only) pyRofex.order_report_subscription(snapshot=True) # Or include historical orders pyRofex.order_report_subscription(snapshot=False, account="ACC789") ``` -------------------------------- ### Example New Order Confirmation Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md An example JSON response confirming the submission of a new order. ```json { "order": { "clientId": "ORDER124", "status": "PENDING_NEW" } } ``` -------------------------------- ### Get Market Data with Market Enum Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of fetching market data by specifying the Market enum. Ensure the pyRofex library is imported. ```python market_data = pyRofex.get_market_data( ticker="DLR/ENE24", market=pyRofex.Market.ROFEX ) ``` -------------------------------- ### Example Account Position Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md An example of the JSON response structure when retrieving account positions. ```json { "positions": [ { "symbol": "DLR/ENE24", "quantity": 100, "avgPrice": 42.50, "currentPrice": 42.75 } ] } ``` -------------------------------- ### Example Order Status Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md An example JSON response when retrieving the status of a specific order. ```json { "order": { "clientId": "ORDER123", "status": "NEW", "filledQty": 50, "quantity": 100, "avgPrice": 42.50, "symbol": "DLR/ENE24" } } ``` -------------------------------- ### Install pyRofex Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Install and update the pyRofex library using pip. Ensure you are using a compatible version of the websocket-client. ```python pip install -U pyRofex ``` -------------------------------- ### Get Instruments by Market Segment Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Examples of fetching instruments filtered by specific market segments using the MarketSegment enum. This demonstrates how to retrieve instruments for Financial Derivatives (DDF) and dual segments. ```python # Get instruments in Financial Derivatives segment ddf_instruments = pyRofex.get_instruments( 'by_segments', market_segment=[pyRofex.MarketSegment.DDF], market=pyRofex.Market.ROFEX ) # Get instruments in both segments dual_instruments = pyRofex.get_instruments( 'by_segments', market_segment=[pyRofex.MarketSegment.DUAL], market=pyRofex.Market.ROFEX ) ``` -------------------------------- ### Example Order Cancellation Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md An example JSON response after requesting to cancel an order. ```json { "order": { "clientId": "CANCEL001", "status": "PENDING_NEW" } } ``` -------------------------------- ### Use Valid Endpoints for Get Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/errors.md Illustrates the correct usage of the `get_instruments` function in PyRofex by showing valid endpoint names and parameters. It contrasts incorrect usage with correct examples for 'all', 'details', 'detail', 'by_cfi', and 'by_segments'. ```python import pyRofex # Wrong endpoint try: instruments = pyRofex.get_instruments('all_instruments') except pyRofex.ApiException as e: print(f"Error: {e}") # Correct endpoints instruments = pyRofex.get_instruments('all') instruments = pyRofex.get_instruments('details') instruments = pyRofex.get_instruments('detail', ticker="DLR/ENE24", market=pyRofex.Market.ROFEX) instruments = pyRofex.get_instruments('by_cfi', cfi_code=[pyRofex.CFICode.STOCK]) instruments = pyRofex.get_instruments('by_segments', market_segment=[pyRofex.MarketSegment.DDF], market=pyRofex.Market.ROFEX) ``` -------------------------------- ### Example Account Report Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md An example of the JSON response structure for an account report, showing financial metrics. ```json { "account": { "accountId": "ACC123", "cashBalance": 500000.00, "availableBuyingPower": 450000.00, "maintenanceMarginReq": 25000.00, "netLiquidationValue": 525000.00 } } ``` -------------------------------- ### Initialize PyRofex with REMARKET Environment Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Configure the Websocket Client with handlers and start a Websocket connection with API. This snippet shows initialization for the REMARKET environment. ```python import pyRofex # Set the the parameter for the REMARKET environment pyRofex.initialize(user="sampleUser", password="samplePassword", account="sampleAccount", environment=pyRofex.Environment.REMARKET) ``` -------------------------------- ### Send Buy Order Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of sending a buy order using the Side.BUY enumeration. ```python # Buy order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.LIMIT, side=pyRofex.Side.BUY, price=42.50 ) ``` -------------------------------- ### Get Top of Book Bids and Offers Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Retrieves the best bid and offer prices for a given ticker. Use this to get the immediate buy and sell prices available in the market. ```python md = pyRofex.get_market_data( ticker="DLR/ENE24", entries=[pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS] ) ``` -------------------------------- ### Send Sell Order Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of sending a sell order using the Side.SELL enumeration. ```python # Sell order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.LIMIT, side=pyRofex.Side.SELL, price=43.00 ) ``` -------------------------------- ### Dynamic WebSocket Handler Management Example Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket.md Demonstrates how to dynamically add and remove market data handlers to a WebSocket connection. This allows for flexible management of data streams during runtime. ```python def handler1(msg): print("Handler 1") def handler2(msg): print("Handler 2") pyRofex.init_websocket_connection() # Add handlers dynamically pyRofex.add_websocket_market_data_handler(handler1) pyRofofex.add_websocket_market_data_handler(handler2) # Both handlers now receive market data # Remove one handler pyRofex.remove_websocket_market_data_handler(handler1) # Only handler2 receives market data ``` -------------------------------- ### Configuration Documentation Structure Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/COMPLETION_SUMMARY.txt Configuration documentation details parameter specifications, type and default values, purpose and usage, code examples, and best practices. ```APIDOC ## Configuration Documentation ### Parameter Specification - **paramName** (type) - Default: [default_value] - Description ### Purpose and Usage [Explanation of the parameter's purpose and how to use it] ### Code Examples ``` [Code example] ``` ### Best Practices [Recommended practices for configuration] ``` -------------------------------- ### Get All Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md A convenience wrapper for fetching all instruments using the 'all' endpoint. This simplifies the process of retrieving a comprehensive list of instruments. ```python def get_all_instruments(self) ``` -------------------------------- ### GET /rest/instruments/all Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve a list of all available instruments. This endpoint does not require any parameters. ```APIDOC ## GET /rest/instruments/all ### Description Retrieve all available instruments. ### Method GET ### Endpoint /rest/instruments/all ### Parameters None ### Response #### Success Response - **instruments** (array) - JSON object with instruments array ``` -------------------------------- ### Example Market Data Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Illustrates the structure of a typical market data response, showing bid and offer information. ```json { "marketData": { "BI": [ {"price": 42.50, "size": 100}, {"price": 42.45, "size": 200} ], "OF": [ {"price": 42.55, "size": 150} ] } } ``` -------------------------------- ### Example Market Segments Response Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Shows the expected JSON format for a response containing market segments. ```json { "segments": [ {"id": "DDF", "name": "Derivados Financieros"}, {"id": "DDA", "name": "Derivados Agropecuarios"}, {"id": "MERV", "name": "Matba-Rofex External Markets"} ] } ``` -------------------------------- ### Initializing WebSocket Connection with Custom Handlers Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/errors.md This snippet shows how to initialize the pyRofex library and establish a WebSocket connection, providing custom functions to handle both errors and exceptions asynchronously. This setup allows for robust management of WebSocket communication issues. ```python import pyRofex def handle_ws_error(msg): print(f"WebSocket error: {msg}") def handle_ws_exception(exc): print(f"WebSocket exception: {exc}") # Could implement reconnection logic here pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET) pyRofex.init_websocket_connection( error_handler=handle_ws_error, exception_handler=handle_ws_exception ) ``` -------------------------------- ### Get All Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Retrieves a list of all available instruments from the REST API. ```python # Gets available instruments list pyRofex.get_all_instruments() ``` -------------------------------- ### Get Detailed Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Retrieve comprehensive details for all available instruments. An optional environment parameter can be provided. ```python detailed = pyRofex.get_detailed_instruments() ``` -------------------------------- ### Get All Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Use this function to retrieve a list of all available instruments. The environment parameter can be specified if needed. ```python instruments = pyRofex.get_all_instruments() ``` -------------------------------- ### Send Limit Order Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of sending a limit order. The price parameter is required for this order type. ```python # Limit order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.LIMIT, side=pyRofex.Side.BUY, price=42.50 # Required for LIMIT ) ``` -------------------------------- ### Send Market Order Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of sending a market order. The price parameter is not used for this order type. ```python # Market order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.MARKET, side=pyRofex.Side.BUY ) ``` -------------------------------- ### Send Market to Limit Order Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Example of sending a market-to-limit order. The price parameter specifies the limit price if the order converts. ```python # Market to limit order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.MARKET_TO_LIMIT, side=pyRofex.Side.BUY, price=43.00 # Limit price if order converts ) ``` -------------------------------- ### WebSocketClient connect() Method Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket-client.md Establishes a WebSocket connection to ROFEX. It creates a WebSocketApp, starts a background thread for the connection, and waits for the connection to be established. Raises an ApiException if the connection fails within 5 seconds. ```python def connect(self) ``` -------------------------------- ### Retrieve All Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Fetches a list of all available instruments across all markets. Use this to get a comprehensive overview of tradable assets. ```Python pyRofex.get_all_instruments() ``` -------------------------------- ### Get Market Segments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Retrieves a list of valid market segments. Ensure the environment is initialized before calling. ```python import pyRofex pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET) segments = pyRofex.get_segments() print(segments) # {'segments': [...]} ``` -------------------------------- ### Initialize pyRofex with Environment Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Shows how to initialize the pyRofex library using either the demo (REMARKET) or production (LIVE) environment. ```python import pyRofex # Initialize with demo environment pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET) # Initialize with production pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.LIVE) ``` -------------------------------- ### Initialize and Use PyRofex Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/README.md Initialize the PyRofex library with your credentials and environment. This snippet demonstrates fetching market data, sending a limit order, and setting up a WebSocket for real-time market data subscriptions. ```python import pyRofex # Initialize pyRofex.initialize( user="your_username", password="your_password", account="your_account", environment=pyRofex.Environment.REMARKET ) # Get market data md = pyRofex.get_market_data( ticker="DLR/ENE24", entries=[pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS] ) # Send order order = pyRofex.send_order( ticker="DLR/ENE24", size=100, order_type=pyRofex.OrderType.LIMIT, side=pyRofex.Side.BUY, price=42.50 ) # WebSocket for real-time data def handle_market_data(msg): print(f"Market Data: {msg}") pyRofex.init_websocket_connection(market_data_handler=handle_market_data) pyRofex.market_data_subscription( tickers=["DLR/ENE24"], entries=[pyRofex.MarketDataEntry.BIDS, pyRofex.MarketDataEntry.OFFERS] ) ``` -------------------------------- ### initialize() Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/initialization.md Initializes the specified environment with user credentials and sets up REST and WebSocket clients. It validates the environment, stores credentials, creates client instances, and sets the default environment. Raises ApiException on authentication failure or invalid environment. ```APIDOC ## initialize() ### Description Initializes the specified environment with user credentials and sets up REST and WebSocket clients. ### Method `initialize` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **user** (str) - Required - Authentication username for the ROFEX API - **password** (str) - Required - Authentication password for the ROFEX API - **account** (str) - Required - Default trading account identifier - **environment** (Environment) - Required - Target environment (Environment.REMARKET or Environment.LIVE) - **proxies** (dict) - Optional - Dictionary mapping protocol (http/https) to proxy URLs for requests - **ssl_opt** (dict) - Optional - SSL options dictionary for WebSocket secure connections - **active_token** (str) - Optional - Pre-generated authentication token to avoid re-authentication ### Return Type None ### Raises - **ApiException** - Invalid environment specified - **ApiException** - Authentication fails with provided credentials ### Example ```python import pyRofex # Initialize with credentials pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.REMARKET ) # Initialize with pre-generated token pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.LIVE, active_token="existing_auth_token_xyz" ) # Initialize with proxy settings pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.REMARKET, proxies={ "http": "http://proxy.example.com:8080", "https": "https://proxy.example.com:8443" } ) ``` ``` -------------------------------- ### Get Instruments by Endpoint Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Retrieves instrument information using various endpoints and filter parameters. The environment must be initialized prior to use. Specific parameters are required based on the chosen endpoint. ```python import pyRofex pyRofex.initialize(user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET) # Get all instruments all_instruments = pyRofex.get_instruments('all') # Get instruments by CFI code stock_instruments = pyRofex.get_instruments( 'by_cfi', cfi_code=[pyRofex.CFICode.STOCK, pyRofex.CFICode.BOND] ) # Get instruments by market segment ddf_instruments = pyRofex.get_instruments( 'by_segments', market_segment=[pyRofex.MarketSegment.DDF], market=pyRofex.Market.ROFEX ) # Get detailed instrument information details = pyRofex.get_instruments('details') ``` -------------------------------- ### Initialize Multiple Environments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Configure and switch between REMARKET and LIVE environments. Use set_default_environment to control which environment is used by default for subsequent calls. ```python import pyRofex # Initialize REMARKET for testing pyRofex.initialize( user="test_user", password="test_pass", account="TEST_ACC", environment=pyRofex.Environment.REMARKET ) # Initialize LIVE for production pyRofex.initialize( user="prod_user", password="prod_pass", account="PROD_ACC", environment=pyRofex.Environment.LIVE ) # Use REMARKET by default pyRofex.set_default_environment(pyRofex.Environment.REMARKET) # These calls use REMARKET segments = pyRofex.get_segments() # These calls explicitly use LIVE segments = pyRofex.get_segments(environment=pyRofex.Environment.LIVE) # Switch default to LIVE pyRofex.set_default_environment(pyRofex.Environment.LIVE) # Now these use LIVE market_data = pyRofex.get_market_data(ticker="DLR/ENE24") ``` -------------------------------- ### Get Trade History Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves historical trade data for a specified instrument within a given date range. Requires the instrument's ticker, start and end dates, and market identifier. ```python def get_trade_history(self, ticker, start_date, end_date, market) ``` -------------------------------- ### Get Detailed Instruments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md A convenience wrapper for fetching detailed instrument information using the 'details' endpoint. This method provides access to in-depth data for instruments. ```python def get_detailed_instruments(self) ``` -------------------------------- ### Initialize PyRofex Environment Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/errors.md Demonstrates how to initialize the PyRofex environment. Ensure correct user, password, account, and environment parameters are provided. Catches ApiException for initialization failures. ```python import pyRofex try: pyRofex.initialize( user="your_username", password="your_password", account="your_account", environment=pyRofex.Environment.REMARKET ) except pyRofex.ApiException as e: print(f"Failed to initialize: {e}") # Check credentials, network connectivity ``` -------------------------------- ### Get All Available Market Data Entries Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/types.md Retrieves all available market data entries for a given ticker by omitting the entries parameter. ```python # Get all available entries md = pyRofex.get_market_data(ticker="DLR/ENE24") # entries=None means all ``` -------------------------------- ### Get All Orders Status Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-orders.md Retrieves the status of all orders for a specified account. Use the default account if none is provided. Requires the `pyRofex` library to be initialized. ```python import pyRofex # Get all orders for default account all_orders = pyRofex.get_all_orders_status() # Get all orders for specific account all_orders = pyRofex.get_all_orders_status(account="ACC456") # Filter for specific statuses for order in all_orders['orders']: if order['status'] == 'NEW': print(f"Open order: {order['clientId']} for {order['symbol']}") ``` -------------------------------- ### Get Instruments with Flexible Query Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Fetches instrument information using a flexible query system. Supports various endpoints like 'all', 'details', 'detail', 'by_cfi', and 'by_segments'. It automatically expands enums, handles list parameters by making multiple requests, and validates URL parameters. ```python def get_instruments(self, endpoint, **kwargs) ``` -------------------------------- ### Get Instruments by Market and Segments Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Retrieves instruments filtered by a specific market and a list of market segments. Supports multiple market segments. ```python # Alternative option to get instruments by given segments pyRofex.get_instruments('by_segments', market=pyRofex.Market.ROFEX, market_segment=[pyRofex.MarketSegment.DDF, pyRofex.MarketSegment.MERV]) ``` -------------------------------- ### Initialize WebSocket with Multiple Handlers Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/README.md Set up WebSocket connections with specific callback handlers for market data and order reports. Ensure you have defined the handler functions before calling this. ```python def market_data_handler(message): # Called when market data arrives print(f"Symbol: {message['symbol']}") def order_handler(message): # Called when order status changes print(f"Order: {message['order']['clientId']} - {message['order']['status']}") pyRofex.init_websocket_connection( market_data_handler=market_data_handler, order_report_handler=order_handler ) ``` -------------------------------- ### Initialize WebSocket Connection Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/errors.md Demonstrates the initialization of a WebSocket connection for PyRofex. Includes basic exception handling for connection establishment failures and suggests troubleshooting steps. ```python import pyRofex try: pyRofex.init_websocket_connection( market_data_handler=handle_md, exception_handler=handle_exception ) except pyRofex.ApiException as e: if "Connection could not be established" in str(e): print("WebSocket connection failed") # Check network, firewall, and API service status # Retry after delay ``` -------------------------------- ### Type Documentation Structure Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/COMPLETION_SUMMARY.txt Type documentation includes the complete definition as a code block, a table of fields/values with descriptions, usage examples, and cross-references to functions using the type. ```APIDOC ## Type Documentation ### Type Definition ```[language] [Complete type definition] ``` ### Fields/Values - **fieldName** (type) - Description ### Usage Examples ``` [Code example] ``` ### Cross-references - [Function name using this type] ``` -------------------------------- ### Get Account Report Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-account.md Retrieves a comprehensive account report including balances and summary information. Use this to extract key financial metrics for an account. ```python # Get account report report = pyRofex.get_account_report() # Get specific account report report = pyRofex.get_account_report(account="ACC789") # Extract key metrics cash = report.get('cashBalance', 0) buying_power = report.get('availableBuyingPower', 0) margin_req = report.get('maintenanceMarginReq', 0) nlv = report.get('netLiquidationValue', 0) print(f"Cash: {cash}") print(f"Available BP: {buying_power}") print(f"Margin Req: {margin_req}") print(f"Net Liquidation Value: {nlv}") ``` -------------------------------- ### Endpoint Documentation Structure Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/COMPLETION_SUMMARY.txt Endpoint documentation specifies the HTTP method and path, query/path parameters, request/response formats, status codes, usage examples, and authentication requirements. ```APIDOC ## Endpoint Documentation ### HTTP Method and Path [HTTP_METHOD] [ENDPOINT] ### Parameters #### Path Parameters - **param1** (type) - Required/Optional - Description #### Query Parameters - **param1** (type) - Required/Optional - Description ### Request Format ```json { "field1": "value" } ``` ### Response Format #### Success Response ([Status Code]) ```json { "field1": "value" } ``` #### Error Responses - **[Status Code]**: [Meaning] ### Usage Examples ``` [Code example] ``` ### Authentication Requirements [Authentication method] ``` -------------------------------- ### Initialize PyRofex with Interactive Credentials Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Sets up PyRofex by interactively prompting the user for their username, password, and account. This is useful for manual execution or when credentials are not stored. ```python import pyRofex from getpass import getpass # Interactive credential input user = input("Username: ") password = getpass("Password: ") pyRofex.initialize( user=user, password=password, account=input("Account: "), environment=pyRofex.Environment.REMARKET ) ``` -------------------------------- ### Initialize WebSocket Connection with Timeout Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Sets up the WebSocket connection with a specified exception handler and a 5-second timeout for establishment. This is useful for ensuring quick connection attempts. ```python import pyRofex def handle_exception(exc): print(f"Failed to connect: {exc}") pyRofex.initialize( user="trader", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET ) pyRofex.init_websocket_connection( exception_handler=handle_exception # Will raise exception if not connected in 5 seconds ) ``` -------------------------------- ### Get Account Positions Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-account.md Retrieves current position information for an account. Use this to get a summary of holdings for a specific or default account. ```python # Get positions for default account positions = pyRofex.get_account_position() # Get positions for specific account positions = pyRofex.get_account_position(account="ACC123") # Process positions for position in positions.get('positions', []): symbol = position['symbol'] qty = position['quantity'] avg_price = position['avgPrice'] print(f"{symbol}: {qty} contracts @ {avg_price}") ``` -------------------------------- ### Initialize pyRofex with Credentials Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/initialization.md Use this snippet to initialize the pyRofex library with your trading user credentials and specify the target environment. Ensure you have valid user, password, and account details. ```python import pyRofex # Initialize with credentials pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.REMARKET ) ``` -------------------------------- ### Send, Get Status, and Cancel Order Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Demonstrates sending a limit order, retrieving its status, and then cancelling it. Requires the ticker, side, size, price, and order type for sending an order. Order client ID is used for status checks and cancellations. ```python # Sends a Limit order to the market order = pyRofex.send_order(ticker="DLR/DIC23", side=pyRofex.Side.BUY, size=10, price=55.8, order_type=pyRofex.OrderType.LIMIT) # Gets the last order status for the previous order pyRofex.get_order_status(order["order"]["clientId"]) # Cancels the previous order cancel_order = pyRofex.cancel_order(order["order"]["clientId"]) # Checks the order status of the cancellation order pyRofex.get_order_status(cancel_order["order"]["clientId"]) ``` -------------------------------- ### Get All Available Market Data Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-market-data.md Retrieves all available market data entries for a given ticker. Use this when you need a comprehensive view of the instrument's market status, including trades, open interest, and prices. ```python full_md = pyRofex.get_market_data(ticker="DLR/ENE24") ``` -------------------------------- ### Get Last Price from Market Data Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Makes a request to the Rest API to get the last price for a given ticker. Use the MarketDataEntry enum to specify the data. ```python # Makes a request to the Rest API and get the last price # Use the MarketDataEntry enum to specify the data pyRofex.get_market_data(ticker="DLR/DIC23", entries=[pyRofex.MarketDataEntry.LAST]) ``` -------------------------------- ### Initialize PyRofex for Production with SSL Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Sets up PyRofex for a production environment with strict SSL validation, specifying certificate requirements and CA certificates path. This enhances security for live trading. ```python import pyRofex import ssl # Production setup with strict SSL validation ssl_options = { 'cert_reqs': ssl.CERT_REQUIRED, 'ca_certs': '/etc/ssl/certs/ca-bundle.crt' } pyRofex.initialize( user="prod_trader", password="production_password", account="PRODUCTION_ACCOUNT", environment=pyRofex.Environment.LIVE, ssl_opt=ssl_options ) ``` -------------------------------- ### Initialize and Set Default Environment Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/initialization.md Demonstrates initializing the pyRofex library with multiple environments and then switching the default environment using `set_default_environment`. Subsequent calls to `get_segments` will use the currently set default environment. ```python import pyRofex # Initialize REMARKET environment pyRofex.initialize( user="user1", password="pass1", account="ACC1", environment=pyRofex.Environment.REMARKET ) # Initialize LIVE environment separately pyRofex.initialize( user="user2", password="pass2", account="ACC2", environment=pyRofex.Environment.LIVE ) # Switch default to LIVE pyRofex.set_default_environment(pyRofex.Environment.LIVE) # This call uses LIVE environment segments = pyRofex.get_segments() # Switch back to REMARKET pyRofex.set_default_environment(pyRofex.Environment.REMARKET) # This call uses REMARKET environment segments = pyRofex.get_segments() ``` -------------------------------- ### Initialization Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/README.md Functions for initializing the Pyrofex client and setting default environments. ```APIDOC ## Initialization ### `initialize(user, password, account, environment, proxies=None, ssl_opt=None, active_token=None)` Initializes the Pyrofex client with user credentials and environment settings. ### `set_default_environment(environment)` Sets the default environment for subsequent operations. ``` -------------------------------- ### Initialize with Pre-Existing Token Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Use an existing authentication token during initialization. The user and password are still required for token refresh. ```python import pyRofex valid_token = "existing_auth_token_xyz" pyRofex.initialize( user="trader", password="secure_pass", # Still needed for refresh account="ACC001", environment=pyRofex.Environment.LIVE, active_token=valid_token ) # Token will be used immediately, authentication skipped ``` -------------------------------- ### GET /rest/order/all Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve all orders associated with a specific account. ```APIDOC ## GET /rest/order/all ### Description Retrieve all orders for account ### Method GET ### Endpoint /rest/order/all ### Parameters #### Query Parameters - **accountId** (string) - Yes - Account identifier ### Response #### Success Response (200) Array of order objects ``` -------------------------------- ### GET /rest/order/newSingleOrder Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Submit a new order to the market with specified parameters. ```APIDOC ## GET /rest/order/newSingleOrder ### Description Submit new order to market ### Method GET ### Endpoint /rest/order/newSingleOrder ### Parameters #### Query Parameters - **marketId** (string) - Yes - Market identifier (ROFX) - **symbol** (string) - Yes - Instrument symbol - **orderQty** (integer) - Yes - Order quantity - **ordType** (string) - Yes - Order type (limit, market, market_to_limit) - **side** (string) - Yes - Order side (buy, sell) - **timeInForce** (string) - Yes - Time modifier (Day, IOC, FOK, GTD) - **account** (string) - Yes - Account identifier - **cancelPrevious** (boolean) - Yes - Cancel previous orders (true/false) - **price** (float) - Conditional - Price (required for limit orders) - **expireDate** (string) - Conditional - Expiration date for GTD (YYYYMMDD) - **displayQty** (integer) - Conditional - Display quantity for iceberg - **iceberg** (boolean) - Conditional - Iceberg flag (true/false) ### Response #### Success Response (200) Order confirmation with clientId ### Response Example ```json { "order": { "clientId": "ORDER124", "status": "PENDING_NEW" } } ``` ``` -------------------------------- ### Get Account Position Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves the current positions for a specified account. ```python def get_account_position(self, account) ``` -------------------------------- ### Initialization Functions Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/INDEX.md Functions for initializing the Pyrofex system and setting default environments. ```APIDOC ## Initialization ### `initialize()` #### Description Initializes the Pyrofex system. ### `set_default_environment()` #### Description Sets the default environment for the Pyrofex system. ``` -------------------------------- ### Get All Orders by Account Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves all orders associated with a specific account. ```python def get_all_orders_by_account(self, account) ``` -------------------------------- ### Get All Segments Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Retrieves all available market segments from the REST API. ```python # Gets all segments pyRofex.get_segments() ``` -------------------------------- ### RestClient Constructor Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Initializes the RestClient with a specified environment and an optional pre-existing authentication token. If no token is provided, it attempts to authenticate. ```APIDOC ## Constructor RestClient ### Description Initializes the REST client with the specified environment and an optional active authentication token. If `active_token` is not provided, the client will attempt to authenticate by calling `update_token()`. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **environment** (Environment Enum) - Required - The environment to connect to. - **active_token** (str) - Optional - A pre-existing authentication token. ### Behavior 1. Initializes client with specified environment configuration. 2. If `active_token` is None, calls `update_token()` to authenticate. 3. If `active_token` is provided, uses it directly and skips authentication. 4. Sets the `initialized` flag to True after successful setup. ``` -------------------------------- ### GET /rest/order/cancelById Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Cancel an existing order using its client order ID. ```APIDOC ## GET /rest/order/cancelById ### Description Cancel existing order ### Method GET ### Endpoint /rest/order/cancelById ### Parameters #### Query Parameters - **clOrdId** (string) - Yes - Client order ID to cancel - **proprietary** (string) - Yes - Order proprietary ### Response #### Success Response (200) Cancellation order with new clientId ### Response Example ```json { "order": { "clientId": "CANCEL001", "status": "PENDING_NEW" } } ``` ``` -------------------------------- ### GET /rest/instruments/bySegment Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve instruments filtered by market segment and market ID. ```APIDOC ## GET /rest/instruments/bySegment ### Description Retrieve instruments filtered by market segment. ### Method GET ### Endpoint /rest/instruments/bySegment ### Parameters #### Query Parameters - **MarketSegmentID** (string) - Required - Market segment identifier (e.g., DDF) - **MarketID** (string) - Required - Market identifier (e.g., ROFX) ### Response #### Success Response - **instruments** (array) - Array of instruments in the specified segment ``` -------------------------------- ### RestClient Constructor Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Initializes the RestClient with an environment and an optional pre-existing authentication token. If no token is provided, it attempts to authenticate. ```python def __init__(self, environment, active_token=None) ``` -------------------------------- ### connect() Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket-client.md Establishes a WebSocket connection to the ROFEX environment. It handles thread creation and connection timeouts. ```APIDOC ## connect() ### Description Establishes a WebSocket connection to the ROFEX environment. It handles thread creation and connection timeouts. ### Method Signature `connect(self)` ### Behavior 1. Prevents duplicate connections if a thread is already alive. 2. Creates a `WebSocketApp` instance using the environment's WebSocket URL and specifies message, error, close, and open handlers. 3. Configures authentication using an `X-Auth-Token` header. 4. Starts a background thread to run the WebSocket connection indefinitely, with configurable heartbeat intervals and SSL options. 5. Waits for up to 5 seconds for the connection to be established. 6. Raises an `ApiException` if the connection is not successfully established within the timeout period. ### Raises - `ApiException`: "Connection could not be established." ``` -------------------------------- ### GET /rest/instruments/details Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve detailed information for all instruments. This endpoint does not require any parameters. ```APIDOC ## GET /rest/instruments/details ### Description Retrieve detailed information for all instruments. ### Method GET ### Endpoint /rest/instruments/details ### Parameters None ### Response #### Success Response - **instruments** (array) - JSON with detailed instrument specifications ``` -------------------------------- ### Initialize PyRofex for Testing Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Configures PyRofex for a testing environment using the REMARKET environment. This is suitable for development and testing without affecting live accounts. ```python import pyRofex # Testing setup with demo environment pyRofex.initialize( user="test_user", password="test_password", account="TEST_ACCOUNT_123", environment=pyRofex.Environment.REMARKET ) # All calls use demo environment ``` -------------------------------- ### GET /rest/order/id Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve the status of a specific order using its client order ID. ```APIDOC ## GET /rest/order/id ### Description Retrieve status of specific order ### Method GET ### Endpoint /rest/order/id ### Parameters #### Query Parameters - **clOrdId** (string) - Yes - Client order ID - **proprietary** (string) - Yes - Order proprietary (PBCP for REMARKET, api for LIVE) ### Response #### Success Response (200) Order object with current status **Status Values**: PENDING_NEW, NEW, PARTIALLY_FILLED, FILLED, CANCELLED, REJECTED, EXPIRED ### Response Example ```json { "order": { "clientId": "ORDER123", "status": "NEW", "filledQty": 50, "quantity": 100, "avgPrice": 42.50, "symbol": "DLR/ENE24" } } ``` ``` -------------------------------- ### GET /rest/instruments/detail Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve details for a specific instrument using its symbol and market ID. ```APIDOC ## GET /rest/instruments/detail ### Description Retrieve details for a specific instrument. ### Method GET ### Endpoint /rest/instruments/detail ### Parameters #### Query Parameters - **symbol** (string) - Required - Instrument symbol (e.g., DLR/MAR23) - **marketId** (string) - Required - Market identifier (e.g., ROFX) ### Response #### Success Response - **instrument** (object) - Single instrument object with details ``` -------------------------------- ### Initialize pyRofex with Proxy Settings Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/initialization.md Configure pyRofex initialization to use proxy servers for HTTP and HTTPS connections. This is necessary when operating in environments with network restrictions. ```python # Initialize with proxy settings pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.REMARKET, proxies={ "http": "http://proxy.example.com:8080", "https": "https://proxy.example.com:8443" } ) ``` -------------------------------- ### Get Account Report Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves a summary report of the account's financial status. ```python def get_account_report(self, account) ``` -------------------------------- ### GET /rest/data/getTrades Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve historical trade data for a specified instrument within a date range. ```APIDOC ## GET /rest/data/getTrades ### Description Retrieve historical trade data for an instrument. ### Method GET ### Endpoint /rest/data/getTrades ### Parameters #### Query Parameters - **marketId** (string) - Required - Market identifier - **symbol** (string) - Required - Instrument symbol - **dateFrom** (string) - Required - Start date in YYYY-MM-DD format - **dateTo** (string) - Required - End date in YYYY-MM-DD format ### Response #### Success Response - **trades** (array) - Array of trade objects ``` -------------------------------- ### WebSocketClient Constructor Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket-client.md Initializes the WebSocket client with a specified environment. It sets up internal handlers and connection states. ```APIDOC ## WebSocketClient Constructor ### Description Initializes the WebSocket client with a specified environment. It sets up internal handlers and connection states. ### Method Signature `__init__(self, environment)` ### Parameters #### Path Parameters - **environment** (Environment Enum) - Required - The environment to connect to. ### Initialization Details 1. Stores environment configuration. 2. Initializes empty handler lists for market data, order reports, and errors. 3. Sets the exception handler to None. 4. Initializes connection state variables (ws_connection, ws_thread, connected). ``` -------------------------------- ### GET /rest/instruments/byCFICode Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve instruments filtered by their CFI (Commodity Futures and Options) classification code. ```APIDOC ## GET /rest/instruments/byCFICode ### Description Retrieve instruments filtered by CFI classification code. ### Method GET ### Endpoint /rest/instruments/byCFICode ### Parameters #### Query Parameters - **CFICode** (string) - Required - CFI code (e.g., ESXXXX for Stock) ### Response #### Success Response - **instruments** (array) - Array of instruments matching the CFI code ``` -------------------------------- ### WebSocketClient Constructor Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/websocket-client.md Initializes the WebSocketClient with the specified environment. It sets up handlers for market data, order reports, and errors, and initializes the connection state. ```python def __init__(self, environment) ``` -------------------------------- ### GET /rest/segment/all Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/endpoints.md Retrieve all valid market segments available in the system. This endpoint does not require any parameters. ```APIDOC ## GET /rest/segment/all ### Description Retrieve all valid market segments. ### Method GET ### Endpoint /rest/segment/all ### Parameters None ### Response #### Success Response - **segments** (array) - JSON object with segments array ### Response Example ```json { "segments": [ {"id": "DDF", "name": "Derivados Financieros"}, {"id": "DDA", "name": "Derivados Agropecuarios"}, {"id": "MERV", "name": "Matba-Rofex External Markets"} ] } ``` ``` -------------------------------- ### Get Detailed Account Position Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves detailed account positions broken down by asset type. ```python def get_detailed_position(self, account) ``` -------------------------------- ### Get Market Segments Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/rest-client.md Retrieves a list of all valid market segments. This method requires no parameters. ```python def get_segments(self) ``` -------------------------------- ### Initialize ROFEX with Proxies Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md Configure ROFEX to use proxy servers for both REST and WebSocket connections. Ensure the proxy dictionary format matches the requests library. ```python proxies = { 'http': 'http://proxy.example.com:8080', 'https': 'https://proxy.example.com:8443' } pyRofex.initialize( user="user", password="pass", account="ACC", environment=pyRofex.Environment.REMARKET, proxies=proxies ) ``` -------------------------------- ### Get Detailed Instruments List Source: https://github.com/matbarofex/pyrofex/blob/master/README.rst Retrieves a detailed list of all available instruments from the REST API. ```python # Gets detailed instruments list pyRofex.get_detailed_instruments() ``` ```python # Alternative option to get detailed instruments list pyRofex.get_instruments('details') ``` -------------------------------- ### Initialization Functions Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/COMPLETION_SUMMARY.txt Functions used to initialize the PyRofex client and configure connection parameters. ```APIDOC ## Initialization Functions ### Description Functions to initialize the PyRofex library and set up client connections. ### Functions - **initialize_rest_client(api_key: str, api_secret: str, base_url: str = None, timeout: int = 30)** - Initializes the REST client with API credentials and optional base URL and timeout. - **initialize_websocket_client(api_key: str, api_secret: str, base_url: str = None, reconnect_interval: int = 5)** - Initializes the WebSocket client with API credentials and optional base URL and reconnect interval. ``` -------------------------------- ### Initialize pyRofex with Active Token Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/api-reference/initialization.md Initialize the pyRofex library using a pre-generated authentication token. This is useful to bypass re-authentication if you already have a valid token. ```python # Initialize with pre-generated token pyRofex.initialize( user="trader_user", password="secure_password", account="ACC123456", environment=pyRofex.Environment.LIVE, active_token="existing_auth_token_xyz" ) ``` -------------------------------- ### ROFEX Initialize Function Signature Source: https://github.com/matbarofex/pyrofex/blob/master/_autodocs/configuration.md The signature for the initialize function shows all available parameters. ```python def initialize(user, password, account, environment, proxies=None, ssl_opt=None, active_token=None) ```