PocketOption API (pocketoptionapi-async)

repository·main·Indexed 40 days ago

https://github.com/chipadevteam/pocketoptionapi

A modern async Python API for the PocketOption trading platform, version 2.0.1. It features the AsyncPocketOptionClient for managing persistent connections, real-time monitoring, and automated trading. Key capabilities include placing binary options orders via place_order(), retrieving historical candle data, and monitoring account balances. The library includes a testing framework and tools like get_ssid.py to extract the required full SSID authentication string from browser WebSocket traffic.

Tokens
12.4K
Snippets
54
Records
67
Agent score
97%

What's inside PocketOption API

  1. Correct SSID format for PocketOption API

    main

    When connecting to the PocketOption API, you must provide the complete authentication message as the ssid parameter, rather than just the raw session ID. Providing only the session ID often results in authentication timeouts.

    Correct Format (Complete Message): 42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}]

    Incorrect Format (Raw Session ID only): dxxxxxxxxxxxxxxxxxxxxxxxxxxxx

    # Correct usage
    SSID = '42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}]'
  2. Install the PocketOption API

    main

    To install the library, clone the repository and install the required dependencies using pip.

    For standard usage:

    git clone <repository-url>
    cd PocketOptionAPI
    pip install -r requirements.txt

    For development environments, install the development dependencies:

    pip install -r requirements-dev.txt
    # Clone the repository
    git clone <repository-url>
    cd PocketOptionAPI
    
    # Install dependencies
    pip install -r requirements.txt
    
    # For development
    pip install -r requirements-dev.txt
  3. How to extract your SSID for authentication

    main

    The API requires a complete authentication string (SSID) extracted from your browser's WebSocket traffic, rather than just a session ID.

    Steps to extract the SSID:

    1. Open PocketOption in your web browser.
    2. Open Developer Tools (press F12).
    3. Navigate to the Network tab.
    4. Filter the traffic by WebSocket (WS).
    5. Look for an authentication message that starts with 42["auth".
    6. Copy the entire message, including the 42["auth",{...}] wrapper.

    If you cannot find it manually, you can use the automatic SSID scraper located in the tools folder of the repository.

    42["auth",{"session":"abcd1234efgh5678","isDemo":1,"uid":12345,"platform":1}]
  4. Extract your SSID using get_ssid.py

    main

    The get_ssid.py tool automatically extracts your PocketOption session ID (SSID) by monitoring WebSocket traffic during the login process. The SSID is the authentication token required to use the PocketOption API.

    Prerequisites

    • Chrome browser installed on your system.
    • Python 3.8 or higher.
    • Dependencies installed via pip install -r requirements.txt (requires selenium>=4.0.0 and webdriver-manager>=4.0.0).

    Usage Steps

    1. Navigate to the tools directory:
      cd tools
    2. Run the script:
      python get_ssid.py
    3. A Chrome window will open. Log in to PocketOption with your credentials.
    4. Wait for the script to detect the WebSocket payload and redirect to the trading cabinet.
    5. Upon success, the SSID will be automatically saved to a .env file in the current directory.
    pip install -r requirements.txt
    cd tools
    python get_ssid.py
  5. How to retrieve the correct SSID from a browser

    main

    If you are experiencing authentication timeouts, you likely need to extract the full authentication message from your browser's developer tools:

    1. Open your browser and navigate to the PocketOption website.
    2. Open Developer Tools (press F12).
    3. Navigate to the Network tab.
    4. Apply a WS (WebSocket) filter to the network traffic.
    5. Look for an authentication message that starts with the prefix: 42["auth",{"session":"....
    6. Copy the entire message string to use as your ssid.
  6. Use ConnectionMonitor for real-time diagnostics

    main

    The ConnectionMonitor class provides advanced monitoring, diagnostics, and performance analysis for your PocketOption connection. It tracks connection health, latency (ping), message throughput, error rates, and system resource usage (CPU/Memory).

    To use it, initialize the monitor with your ssid, start the monitoring task, and optionally add event handlers to react to alerts or statistics updates.

    from pocketoptionapi_async.connection_monitor import ConnectionMonitor
    import asyncio
    
    async def main():
        ssid = 'YOUR_SSID_HERE'
        monitor = ConnectionMonitor(ssid, is_demo=True)
        
        # Add a handler for alerts
        async def on_alert(data):
            print(f"ALERT RECEIVED: {data['message']}")
        
        monitor.add_event_handler("alert", on_alert)
    
        # Start monitoring (this also connects the client)
        success = await monitor.start_monitoring(persistent_connection=True)
        
        if success:
            # Do your trading logic here...
            await asyncio.sleep(60)
            
            # Stop monitoring
            await monitor.stop_monitoring()
            
            # Generate a final report
            report = monitor.generate_diagnostics_report()
            print(f"Final Health Score: {report['health_score']}")
    
    asyncio.run(main())
  7. Troubleshoot Authentication timeouts and connection closures

    main

    If you encounter errors indicating that the WebSocket connection closed immediately or that there was an Authentication timeout (e.g., Failed to connect to region DEMO: Authentication timeout), it is almost certainly due to an incorrect SSID format.

    The Problem: You are likely providing only the session string (e.g., dxxxxxxxxxxxxxxx).

    The Solution: You must provide the complete SSID format including the JSON-RPC prefix and the authentication object.

    ✅ Correct format:

    SSID = '42["auth",{"session":"n1p5ah5u8t9438rbunpgrq0hlq","isDemo":1,"uid":84402008,"platform":1}]'

    ❌ Wrong format:

    SSID = 'dxxxxxxxxxxxxxxxxxxxxxxxxxxxx'  # This will fail
    # Correct format example
    SSID = '42["auth",{"session":"n1p5ah5u8t9438rbunpgrq0hlq","isDemo":1,"uid":84402008,"platform":1}]'
  8. Manually extract SSID via Chrome Developer Tools

    main

    If the get_ssid.py tool fails to find the SSID pattern in WebSocket logs, you can extract it manually:

    1. Open PocketOption in Google Chrome.
    2. Press F12 to open Developer Tools.
    3. Navigate to the Network tab.
    4. Filter the traffic by selecting WS (WebSocket).
    5. Log in to your account and navigate to a trading page.
    6. Search for messages containing the pattern 42["auth".
    7. Copy the complete message (e.g., 42["auth",{"session":"..."}]).
    8. Save this string to your .env file as SSID="your-copied-message".
  9. Troubleshoot Authentication Timeout errors

    main

    If you encounter an AuthenticationError or a generic Authentication timeout, check the following:

    • Invalid/Expired SSID: The server returned NotAuthorized. This means your SSID is either malformed or has expired. Get a fresh one using the browser DevTools method.
    • Format Mismatch: Ensure you are not passing just the session string. The library expects the full 42["auth", ...] JSON-like structure.
    • Empty/Malformed SSID: The library validates that the SSID is a non-empty string and follows the expected structure. If it is too short or missing required fields, an InvalidParameterError will be raised during initialization.
  10. Use your SSID with AsyncPocketOptionClient

    main

    Once you have obtained your SSID (either via the extraction tool or manual method), you can initialize the AsyncPocketOptionClient to interact with the API. You can either load the SSID from an environment variable or paste the string directly into your code.

    Security Warning: The SSID is sensitive authentication data. Never share it publicly and ensure your .env file is included in .gitignore.

    from pocketoptionapi_async import AsyncPocketOptionClient
    import asyncio
    
    async def main():
        # Load SSID from environment or paste it directly
        SSID = "42[\"auth\",{\"session\":\"...\",\"isDemo\":1,\"uid\":12345,\"platform\":1}]"
        
        client = AsyncPocketOptionClient(SSID, is_demo=True)
        await client.connect()
        
        balance = await client.get_balance()
        print(f"Balance: {balance.balance} {balance.currency}")
        
        await client.disconnect()
    
    asyncio.run(main())
  11. Check order win/loss status with check_win()

    main

    The check_win method monitors an active order to determine its outcome. It waits for the order to expire or for a result to be received via the websocket. If the order expires without a result being received, it returns a timeout status.

    Returns a dictionary containing:

    • result: `