PyQuotex

pyquotex is a Python library designed to easily integrate with the Quotex API, enabling automated trading operations. Fully open-source and licensed under MIT, the library provides features like order execution, balance checking, real-time market data collection, and more. Perfect for traders and developers looking to build efficient and customized solutions.

View the Project on GitHub cleitonleonel/pyquotex

WebSocket Documentation - PyQuotex

Table of Contents

WebSocket Management

PyQuotex uses the websocket-client library to establish and maintain WebSocket connections with the Quotex server. The main implementation is in the WebsocketClient class.

Initialization

self.wss = websocket.WebSocketApp(
    self.api.wss_url,
    on_message=self.on_message,
    on_error=self.on_error,
    on_close=self.on_close,
    on_open=self.on_open,
    on_ping=self.on_ping,
    on_pong=self.on_pong,
    header=self.headers
)

Stream Subscriptions

PyQuotex offers several methods to subscribe to different types of streams:

Candles Subscription

def start_candles_stream(self, asset, period=0):
    self.api.current_asset = asset
    self.api.subscribe_realtime_candle(asset, period)
    self.api.follow_candle(asset)

Market Sentiment Subscription

async def start_realtime_sentiment(self, asset, period=0):
    self.start_candles_stream(asset, period)
    while True:
        if self.api.realtime_sentiment.get(asset):
            return self.api.realtime_sentiment[asset]
        await asyncio.sleep(0.2)

Real-time Price Subscription

async def start_realtime_price(self, asset, period=0):
    self.start_candles_stream(asset, period)
    while True:
        if self.api.realtime_price.get(asset):
            return self.api.realtime_price
        await asyncio.sleep(0.2)

Available Streams

The system supports the following types of streams:

  1. Candles Stream
    • Real-time candle data
    • Historical candles
    • Candles in different time periods
  2. Price Stream
    • Real-time prices
    • Price updates by asset
  3. Sentiment Stream
    • Market sentiment
    • Buy/sell indicators
  4. Signals Stream
    • Trading signals
    • Indicator data

Event Handling

Main Events

  1. on_message ```python def on_message(self, wss, message): “”” Processes incoming WebSocket messages
    • Handles authorization data
    • Processes trading data
    • Updates balances
    • Handles signals and market sentiment “”” ```
  2. on_error ```python def on_error(self, wss, error): “”” Handles WebSocket connection errors
    • Logs errors
    • Updates connection status “”” ```
  3. on_open ```python def on_open(self, wss): “”” Initializes WebSocket connection
    • Sends initial messages
    • Sets up basic streams “”” ```
  4. on_close ```python def on_close(self, wss, close_status_code, close_msg): “”” Handles connection closure
    • Updates connection status
    • Prepares for reconnection if needed “”” ```

Automatic Reconnection

PyQuotex implements a robust automatic reconnection system:

Reconnection Handling

async def connect(attempts=5):
    check, reason = await client.connect()
    if not check:
        attempt = 0
        while attempt <= attempts:
            if not await client.check_connect():
                check, reason = await client.connect()
                if check:
                    print("Successfully reconnected!")
                    break
                else:
                    print("Reconnection error.")
                    attempt += 1

Reconnection Features

  1. Multiple Attempts
    • Configurable number of reconnection attempts
    • Wait between attempts
  2. Connection Status
    • Constant status monitoring
    • Global tracking variables
      check_websocket_if_connect = None
      check_websocket_if_error = False
      check_rejected_connection = False
      
  3. Stream Restoration
    • Automatic re-subscription to active streams
    • Application state maintenance

Best Practices

  1. Error Handling
    • Implement try-catch in critical operations
    • Log important errors and events
  2. Connection Status
    • Verify status before operations
    • Maintain appropriate wait time between reconnections
  3. Resource Cleanup
    • Properly close connections
    • Release resources when finishing