π‘ 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
- Connects to the PocketOption WebSocket using an
ssid
. - Subscribes to price updates.
- Validates incoming messages using a regex.
- Streams data asynchronously with a timeout.
- 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