Streaming PocketOption Prices in Python (Async)

Streaming PocketOption Prices in Python (Async)

πŸ“‘ Streaming PocketOption Prices in Python (Async)

This guide demonstrates how to use the BinaryOptionsToolsV2 package to subscribe to live price data from PocketOption using WebSockets. We’ll also validate incoming data and handle timeouts.


πŸ“¦ Requirements

Ensure you have the following package installed (via pip or locally):

  • BinaryOptionsToolsV2
  • Python 3.7+
  • Internet connection
  • An active ssid (session token) from PocketOption

🧠 What This Script Does

  1. Connects to the PocketOption WebSocket using an ssid.
  2. Subscribes to price updates.
  3. Validates incoming messages using a regex.
  4. Streams data asynchronously with a timeout.
  5. Handles connection and stream errors gracefully.

πŸ§ͺ Code Walkthrough

πŸ“ Imports and Setup

from BinaryOptionsToolsV2.pocketoption import PocketOptionAsync
from BinaryOptionsToolsV2.validator import Validator
from datetime import timedelta
import asyncio
  • PocketOptionAsync: Handles WebSocket connections.
  • Validator: Ensures incoming messages match a pattern.
  • timedelta: Used to set a timeout duration.
  • asyncio: Enables asynchronous operations.

πŸš€ The main() Function

async def main(ssid: str):
    api = PocketOptionAsync(ssid)    
    await asyncio.sleep(5)  # Wait for connection to establish
  • We initialize the API client with the provided ssid.
  • The sleep(5) gives time for the WebSocket connection to establish fully.

βœ… Validating Price Updates

    validator = Validator.regex(r'{"price":\d+\.\d+}')
  • A regex pattern ensures the message contains a "price" key with a float value, e.g., {"price":74.54}.

πŸ”„ Creating the WebSocket Stream

    stream = await api.create_raw_iterator(
        '42["price/subscribe"]',  
        validator,
        timeout=timedelta(minutes=5)
    )
  • The message '42["price/subscribe"]' is used to subscribe to price updates.
  • validator checks the format of each incoming message.
  • timeout is set to 5 minutes β€” after which the stream ends if inactive.

πŸ“‘ Reading Streamed Data

    try:
        async for message in stream:
            print(f"Received message: {message}")
  • Messages that pass validation are printed in real time.
  • This part uses asynchronous iteration (async for).

πŸ›‘ Error Handling

    except TimeoutError:
        print("Stream timed out after 5 minutes")
    except Exception as e:
        print(f"Error processing stream: {e}")
  • Catches timeout and general exceptions to ensure graceful exit.

🏁 Running the Script

if __name__ == '__main__':
    ssid = input('Please enter your ssid: ')
    asyncio.run(main(ssid))
  • Prompts the user for the PocketOption session token (ssid) and launches the script.

πŸ’‘ Final Thoughts

This script is a powerful starting point for building tools that interact with PocketOption in real-time. You can expand it by:

  • Logging prices to a database
  • Creating visual charts
  • Automating alerts or trades based on price action

Leave a Reply

Your email address will not be published. Required fields are marked *