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 websockets (asynchronous) library to maintain high-performance connections with the Quotex server. The core implementation is split between WebsocketClient and QuotexAPI.

Initialization and Heartbeat

The connection is kept alive through a Heartbeat system that sends a “tick” message every 5 seconds, ensuring the server doesn’t close the session due to inactivity.

from pyquotex.global_value import WebsocketStatus

# Heartbeat implemented in QuotexAPI._on_open
async def heartbeat():
    while self.state.status == WebsocketStatus.CONNECTED:
        try:
            await self.websocket.send('42["tick"]')
        except Exception:
            break
        await asyncio.sleep(5)

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 (Async)

  1. _on_message ```python async def _on_message(self, msg): “”” Processes raw WebSocket messages asynchronously.
    • Automatic JSON/Socket.IO extraction
    • Clock synchronization (server_timestamp)
    • Event triggering via EventRegistry “”” ```
  2. Time Synchronization The bot automatically synchronizes its internal clock with the timestamps received in price messages, ensuring that expiration calculations are precise, regardless of the local timezone.

7. WebSocket

PyQuotex utilizes an advanced WebSocket architecture to ensure commercial-grade stability and performance.

Auto-Reconnection Supervisor

The connection is monitored by a dedicated supervisor (_websocket_supervisor) that performs automatic reconnections with Exponential Backoff. If the socket drops, the system re-authenticates and reopens the connection without manual intervention.

# The Supervisor manages the connection lifecycle automatically
await client.connect() 

Message Dispatcher

To maximize processing speed, we implemented a hashmap-based dispatch system (O(1)). Instead of long if/elif chains, the system directly invokes the modular handler responsible for the event, drastically reducing execution latency.

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