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

PyQuotex Documentation

This documentation covers the main use cases and implementation examples of the PyQuotex library to interact with the Quotex platform.

Basic Examples

Initialization and Connection

from quotexapi.stable_api import Quotex

# Initialize the client
client = Quotex(
    email="your@email.com",
    password="your_password",
    lang="en"  # Default language
)

# Connect to the server
async def connect():
    check_connect, message = await client.connect()
    if check_connect:
        print("Successfully connected")
        balance = await client.get_balance()
        print(f"Current balance: {balance}")
    client.close()

Get Profile Information

async def get_profile():
    check_connect, message = await client.connect()
    if check_connect:
        profile = await client.get_profile()
        print(f"""
        User: {profile.nick_name}
        Demo Balance: {profile.demo_balance}
        Real Balance: {profile.live_balance}
        Country: {profile.country_name}
        """)
    client.close()

Common Use Cases

1. Perform a Simple Operation

async def operate():
    check_connect, message = await client.connect()
    if check_connect:
        # Operation parameters
        amount = 50  # Amount
        asset = "EURUSD_otc"  # Currency pair
        direction = "call"  # call=up, put=down
        duration = 60  # Duration in seconds

        # Check if the asset is available
        asset_name, asset_data = await client.get_available_asset(asset, force_open=True)

        if asset_data[2]:  # Check if the market is open
            status, buy_info = await client.buy(amount, asset_name, direction, duration)
            if status:
                # Wait for result
                win = await client.check_win(buy_info["id"])
                profit = client.get_profit()
                print(f"Result: {'Win' if win else 'Loss'} of {profit}")

    client.close()

2. Real-Time Price Monitoring

async def monitor_prices():
    check_connect, message = await client.connect()
    if check_connect:
        asset = "EURUSD_otc"

        # Start price stream
        await client.start_realtime_price(asset, 60)

        # Continuously monitor
        while True:
            prices = await client.get_realtime_price(asset)
            if prices:
                last_price = prices[-1]
                print(f"Time: {last_price['time']} Price: {last_price['price']}")
            await asyncio.sleep(1)

1. Error Handling and Reconnection

async def connect_with_retries(max_attempts=5):
    attempts = 0
    while attempts < max_attempts:
        try:
            check_connect, message = await client.connect()
            if check_connect:
                return True
            attempts += 1
            print(f"Retrying connection ({attempts}/{max_attempts})")
            await asyncio.sleep(5)
        except Exception as e:
            print(f"Connection error: {e}")
            attempts += 1
    return False

2. Base Class for Trading

class TradingBot:
    def __init__(self, email, password):
        self.client = Quotex(email=email, password=password)
        self.connected = False

    async def start(self):
        self.connected = await self.connect_with_retries()
        if self.connected:
            await self.configure_account()

    async def configure_account(self):
        # Set demo mode by default
        self.client.set_account_mode("PRACTICE")

    async def close(self):
        self.client.close()
        self.connected = False

Example Scripts

1. Basic Trading Bot

import asyncio
from quotexapi.stable_api import Quotex

class SimpleBot:
    def __init__(self):
        self.client = Quotex(
            email="your@email.com",
            password="your_password"
        )
        self.running = False

    async def start(self):
        check_connect, _ = await self.client.connect()
        if check_connect:
            self.running = True
            await self.trading_loop()

    async def trading_loop(self):
        while self.running:
            try:
                # Get market data
                sentiment = await self.client.get_realtime_sentiment("EURUSD_otc")
                if sentiment.get("sentiment", {}).get("buy", 0) > 70:
                    # Execute operation if sentiment is very bullish
                    await self.execute_operation("EURUSD_otc", "call", 50, 60)

                await asyncio.sleep(60)  # Wait 1 minute
            except Exception as e:
                print(f"Trading loop error: {e}")
                await asyncio.sleep(5)

    async def execute_operation(self, asset, direction, amount, duration):
        status, buy_info = await self.client.buy(amount, asset, direction, duration)
        if status:
            result = await self.client.check_win(buy_info["id"])
            print(f"Operation {'won' if result else 'lost'}")

    async def stop(self):
        self.running = False
        self.client.close()

# Use the bot
async def main():
    bot = SimpleBot()
    await bot.start()

if __name__ == "__main__":
    asyncio.run(main())

2. Market Monitor

import asyncio
import datetime

async def monitor_market():
    client = Quotex(
        email="your@email.com",
        password="your_password"
    )

    check_connect, _ = await client.connect()
    if check_connect:
        assets = ["EURUSD", "GBPUSD", "USDJPY"]

        while True:
            for asset in assets:
                try:
                    # Get asset data
                    price = await client.get_realtime_price(asset)
                    sentiment = await client.get_realtime_sentiment(asset)

                    # Save or display information
                    timestamp = datetime.datetime.now()
                    print(f"""
                    {timestamp} - {asset}:
                    Price: {price[-1]['price'] if price else 'N/A'}
                    Buy Sentiment: {sentiment.get('sentiment', {}).get('buy', 'N/A')}%
                    Sell Sentiment: {sentiment.get('sentiment', {}).get('sell', 'N/A')}%
                    """)

                except Exception as e:
                    print(f"Error monitoring {asset}: {e}")

            await asyncio.sleep(5)  # Update every 5 seconds

if __name__ == "__main__":
    asyncio.run(monitor_market())

Important Considerations

  1. Risk Management: Always implement risk controls and stop-loss limits.
  2. Demo Mode: Test strategies in demo mode before using real money.
  3. Error Handling: Implement robust error handling and reconnections.
  4. API Limitations: Consider API limitations and wait times.

Security Notes