### Run Example Script Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Executes a sample Python script to test the PocketOptionAPI setup. If successful, it will display your account balance. ```python python examples/get_balance.py ``` -------------------------------- ### Install PocketOptionAPI Async Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/quickstart.html Install the library using pip. Ensure you have Python and pip installed. ```bash pip install pocketoptionapi-async ``` -------------------------------- ### Configure API Credentials Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Copies the example environment file and prompts the user to edit it with their specific API credentials, such as the SSID. ```bash cp .env.example .env nano .env ``` ```properties SSID = '42["auth",{"session":"your_session_here","isDemo":1,"uid":12345,"platform":1}]' ``` -------------------------------- ### Install PocketOption API Dependencies Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/README.md Installs the necessary dependencies for the PocketOption API and its development environment. ```bash git clone cd PocketOptionAPI pip install -r requirements.txt pip install -r requirements-dev.txt ``` -------------------------------- ### Install Dependencies Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/tools/README.md Install the required Python packages for the tools. Ensure you have pip and Python 3.8+. ```bash pip install -r requirements.txt ``` -------------------------------- ### Correct SSID Format Example Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md Shows the correct, complete format for providing an SSID, including session, demo status, UID, and platform. ```python SSID = '42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}]' ``` -------------------------------- ### Incorrect SSID Format Example Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md Illustrates the incorrect format for providing an SSID, which led to authentication timeouts. ```python SSID = 'dxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Wrong! ``` -------------------------------- ### Example Script for Correct SSID Usage Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md A Python script demonstrating how to correctly use the SSID, including instructions for obtaining it and handling errors. ```python import asyncio from pocketoptionapi_async.client import PocketOptionClient async def main(): # Replace with your actual SSID SSID = '42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}]' client = PocketOptionClient(SSID=SSID) try: await client.start() print("Client started successfully!") # Keep the client running or perform other actions await asyncio.sleep(60) # Example: run for 60 seconds except Exception as e: print(f"An error occurred: {e}") finally: await client.stop() print("Client stopped.") if __name__ == "__main__": asyncio.run(main()) ``` -------------------------------- ### Install Python and Git in Termux Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Installs Python and Git, essential tools for running PocketOptionAPI, within your Termux environment. ```bash pkg install python git ``` -------------------------------- ### Basic PocketOptionAPI Async Usage Example Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/quickstart.html Connect to Pocket Option, retrieve your balance, and disconnect using the AsyncPocketOptionClient. Replace 'your-ssid-here' with your actual SSID. ```python from pocketoptionapi_async import AsyncPocketOptionClient import asyncio async def main(): SSID = "your-ssid-here" client = AsyncPocketOptionClient(SSID, is_demo=True) await client.connect() balance = await client.get_balance() print(balance) await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Incorrect SSID Format Example Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/README.md Illustrates the incorrect format for the SSID, which will lead to authentication failures. Only the session ID is not sufficient. ```python SSID = 'dxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # This won't work! ``` -------------------------------- ### Get Connection Stats Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Connects to PocketOption and retrieves current connection statistics. Requires an SSID and is set to use a demo account. ```python from pocketoptionapi_async import AsyncPocketOptionClient async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() stats = await client.get_connection_stats() print(f"Connection Stats: {stats}") await client.disconnect() ``` -------------------------------- ### Get Candles as DataFrame Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Fetches historical candle data for a given asset and timeframe, returning it as a pandas DataFrame. Requires the pandas library to be installed. ```python from pocketoptionapi_async import AsyncPocketOptionClient async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() candles_df = await client.get_candles_dataframe(asset='EURUSD_otc', timeframe=60) print(candles_df) await client.disconnect() ``` -------------------------------- ### Use SSID with PocketOption API Client Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/tools/README.md Example of initializing an asynchronous PocketOption API client using an extracted SSID. This demonstrates connecting to the API, fetching balance, and disconnecting. ```python 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()) ``` -------------------------------- ### Get Connection Statistics Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Returns connection statistics and the current status of the client's connection to Pocket Option. ```APIDOC ## Get Connection Statistics ### Description Returns connection statistics and status as a dictionary. ### Method `client.get_connection_stats()` ### Endpoint N/A (Client method) ### Response #### Success Response - Dictionary containing connection statistics. ### Request Example ```python stats = client.get_connection_stats() print(stats) ``` ``` -------------------------------- ### Get Account Balance Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Fetches the current account balance, including the balance amount and currency. This is useful for monitoring trading capital. ```python from pocketoptionapi_async import AsyncPocketOptionClient async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() balance = await client.get_balance() print(f"Your balance is: {balance.balance}, currency: {balance.currency}") await client.disconnect() ``` -------------------------------- ### SSID Extraction Tool Output Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/tools/README.md Example log output indicating successful SSID extraction and saving to a .env file. This confirms the tool has found and stored your authentication token. ```log 2025-12-25 10:30:15 - INFO - ================================================================================ 2025-12-25 10:30:15 - INFO - PocketOption SSID Extractor Tool 2025-12-25 10:30:15 - INFO - ================================================================================ 2025-12-25 10:30:15 - INFO - INSTRUCTIONS: 2025-12-25 10:30:15 - INFO - 1. A Chrome browser will open shortly 2025-12-25 10:30:15 - INFO - 2. Please log in to PocketOption with your credentials ... 2025-12-25 10:31:45 - INFO - Found valid SSID string in WebSocket payload 2025-12-25 10:31:45 - INFO - ================================================================================ 2025-12-25 10:31:45 - INFO - SUCCESS! SSID successfully extracted and saved to .env file. 2025-12-25 10:31:45 - INFO - You can now use this SSID in your PocketOption API scripts. 2025-12-25 10:31:45 - INFO - ================================================================================ ``` -------------------------------- ### Get Connection Statistics Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieve statistics about the current connection status and other relevant metrics. This method does not require awaiting. ```python stats = client.get_connection_stats() print(stats) ``` -------------------------------- ### Grant Storage Permissions in Termux Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Use this command if you encounter permission denied errors during package installation in Termux. It prompts for storage access. ```bash termux-setup-storage ``` -------------------------------- ### Get Account Balance Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Fetch the current account balance and currency. The returned object contains balance, currency, and an indicator for demo account status. ```python balance = await client.get_balance() print(balance.balance, balance.currency) ``` -------------------------------- ### Update Termux Packages Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Run this command in Termux to update package lists and upgrade installed packages. Press 'Y' to confirm. ```bash pkg update && pkg upgrade ``` -------------------------------- ### Get Payout and Asset Metadata with get_payout() / get_asset_info() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Fetches the current payout percentage for an asset or its full metadata. A short delay after connecting might be necessary for payout data to become available. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() await asyncio.sleep(2) # allow payout data to arrive payout = client.get_payout("EURUSD_otc") print(f"EUR/USD OTC payout: {payout}%") info = client.get_asset_info("EURUSD_otc") if info: print(f"Asset info: {info}") await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Check Win Status of an Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Places an order (PUT in this example) and then checks its win/loss status using the order ID. This is useful for verifying trade outcomes. ```python from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() amount = float(input("Enter the amount to invest: ")) symbol = input("Enter the symbol (e.g., 'EURUSD_otc'): ") direction = OrderDirection.PUT order = await client.place_order(asset=symbol, amount=amount, direction=direction, duration=5) check_win = await client.check_win(order.order_id) print(f"Order placed successfully: {order}") print(f"Check win result: {check_win}") await client.disconnect() ``` -------------------------------- ### Get Account Balance Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Fetches your current account balance and currency. The returned object contains the balance amount, currency, and whether it's a demo account. ```APIDOC ## Get Account Balance ### Description Fetches your current account balance and currency. ### Method `await client.get_balance()` ### Endpoint N/A (Client method) ### Response #### Success Response - `Balance` object with `balance` (float), `currency` (str), and `is_demo` (bool). ### Request Example ```python balance = await client.get_balance() print(balance.balance, balance.currency) ``` ``` -------------------------------- ### Accessing Supported Symbols and Endpoints Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Use the `ASSETS` dictionary to map symbols to platform IDs and the `REGIONS` object to get WebSocket endpoint URLs. Import both from the package root. ```python from pocketoptionapi_async import ASSETS, REGIONS # List all OTC forex assets otc_forex = [sym for sym in ASSETS if sym.endswith("_otc") and not sym.startswith("#")] print(f"OTC forex symbols ({len(otc_forex)}): {otc_forex[:5]}") # OTC forex symbols (20): ['EURUSD_otc', 'GBPUSD_otc', 'USDJPY_otc', 'USDCHF_otc', 'USDCAD_otc'] # List demo region URLs demo_urls = REGIONS.get_demo_regions() print(f"Demo regions: {demo_urls}") # ['wss://demo-api-eu.po.market/...', 'wss://try-demo-eu.po.market/...'] # Get a specific region URL eu_url = REGIONS.get_region("EUROPA") print(f"Europa: {eu_url}") # Europa: wss://api-eu.po.market/socket.io/?EIO=4&transport=websocket # Full region dictionary all_regions = REGIONS.get_all_regions() print(f"Total regions: {len(all_regions)}") # Total regions: 19 ``` -------------------------------- ### Get Candles Data for Different Asset Types Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/assets-timeframes.html Demonstrates fetching candle data for various asset types including OTC forex, crypto, and US stocks. Note the specific asset symbol formatting for stocks (prefixed with '#'). ```python forex_candles = await client.get_candles("GBPUSD_otc", TimeFrame.H1, 24) crypto_candles = await client.get_candles("ETHUSD", TimeFrame.M15, 96) stock_candles = await client.get_candles("#AAPL", TimeFrame.D1, 30) ``` -------------------------------- ### Fetch Candles as pandas DataFrame with get_candles_dataframe() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Retrieves candle data and returns it as a pandas DataFrame, indexed by timestamp. This is useful for technical analysis. Requires pandas to be installed. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() df = await client.get_candles_dataframe( asset="EURUSD_otc", timeframe="5m", count=100, ) print(df.tail()) df["sma20"] = df["close"].rolling(20).mean() print(df[["close", "sma20"]].tail()) await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Service Health Monitoring with HealthChecker Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Utilize HealthChecker to run asynchronous health-check functions at intervals and get an overall health report. Register custom checks and start/stop monitoring as needed. Ensure the `health_checker` singleton is imported. ```python import asyncio from pocketoptionapi_async.monitoring import health_checker from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() # Register a custom health check async def check_connection(): return {"connected": client.is_connected} health_checker.register_health_check("websocket", check_connection) await health_checker.start_monitoring() await asyncio.sleep(35) # let at least one check cycle run report = health_checker.get_health_report() print(f"Overall status : {report['overall_status']}") # healthy / degraded / unhealthy print(f"Unhealthy services : {report['unhealthy_services']}") for svc, status in report["services"].items(): print(f" {svc}: {status['status']} (response {status.get('response_time', 'N/A'):.4f}s)") await health_checker.stop_monitoring() await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Get Active Orders Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieves a list of all currently active (open) orders on your account. The result includes order details and their current status. ```APIDOC ## Get Active Orders ### Description Returns a list of your currently active (open) orders. ### Method `await client.get_active_orders()` ### Endpoint N/A (Client method) ### Response #### Success Response - List of `OrderResult` objects. ### Request Example ```python orders = await client.get_active_orders() for order in orders: print(order.order_id, order.status) ``` ``` -------------------------------- ### Get Candles Data with TimeFrame Enum Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/assets-timeframes.html Fetches historical candle data for a given asset using the TimeFrame enum. Recommended for clarity and type safety. ```python from pocketoptionapi_async import AsyncPocketOptionClient, TimeFrame candles = await client.get_candles("EURUSD", TimeFrame.M5, 50) ``` -------------------------------- ### Get Active Orders Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieve a list of all currently open orders. The result is a list of OrderResult objects, each containing order details and status. ```python orders = await client.get_active_orders() for order in orders: print(order.order_id, order.status) ``` -------------------------------- ### Get Candles (List) Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Retrieves historical candle data for a specified asset and timeframe, returning a list of candle objects. Each candle object contains open, close, high, low, volume, and timestamp. ```python from pocketoptionapi_async import AsyncPocketOptionClient async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() candles = await client.get_candles(asset='EURUSD_otc', timeframe=60) for candle in candles: print(f"open: {candle.open}, close: {candle.close}, high: {candle.high}, low: {candle.low}, volume: {candle.volume}, timestamp: {candle.timestamp}") await client.disconnect() ``` -------------------------------- ### Get Connection Statistics with Async Client Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Use `get_connection_stats()` to retrieve detailed metrics about the WebSocket connection. This is useful for monitoring and building dashboards. Ensure the client is connected before calling this method. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() stats = client.get_connection_stats() print(f"Total connections : {stats['total_connections']}") print(f"Successful connects : {stats['successful_connections']}") print(f"Total reconnects : {stats['total_reconnects']}") print(f"Messages sent : {stats.get('total_messages_sent', 0)}") print(f"Messages received : {stats.get('total_messages_received', 0)}") print(f"Last ping : {stats['last_ping_time']}") await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### AsyncPocketOptionClient Initialization Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Demonstrates how to initialize the AsyncPocketOptionClient with various options including SSID, account type, and connection persistence. ```APIDOC ## AsyncPocketOptionClient — Client Initialization `AsyncPocketOptionClient` is the main entry point. It accepts the full Socket.IO authentication string (`ssid`), account type flags, and resilience options. The SSID must be the **complete** `42["auth",{...}]` string captured from the browser's WebSocket traffic. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"n1p5ah5u8t9438rbunpgrq0hlq","isDemo":1,"uid":84402008,"platform":1}]' async def main(): # Demo account, persistent keep-alive connection, auto-reconnect enabled client = AsyncPocketOptionClient( ssid=SSID, is_demo=True, # True = demo account, False = live persistent_connection=True, # keep-alive with 20-second pings auto_reconnect=True, enable_logging=True, ) connected = await client.connect() print(f"Connected: {connected}") # Connected: True print(f"Is connected: {client.is_connected}") # Is connected: True await client.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Initialize AsyncPocketOptionClient Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Create a new asynchronous client instance for Pocket Option. Specify your SSID, and optionally configure demo mode and logging. ```python from pocketoptionapi_async import AsyncPocketOptionClient client = AsyncPocketOptionClient("SSID", is_demo=True, enable_logging=True) ``` -------------------------------- ### README.md - Authentication Troubleshooting Section Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md Illustrates the content added to README.md for troubleshooting authentication timeout errors, including correct vs. incorrect SSID formats. ```markdown ## Authentication timeout or connection immediately closes **Problem**: Your connection to the PocketOption API times out or closes immediately after attempting to connect. **Cause**: This is almost always due to an incorrect SSID format. **Solution**: Ensure your SSID is in the complete, correct format. **Correct Format (✅)**: ```python SSID = '42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}]' ``` **Incorrect Format (❌)**: ```python SSID = 'dxxxxxxxxxxxxxxxxxxxxxxxxxxxx' # Only session ID ``` **How to get the correct SSID:** 1. Open PocketOption in your browser. 2. Open browser Developer Tools (F12). 3. Go to the "Network" tab. 4. Filter requests by "WS" (WebSockets). 5. Look for a message starting with `42["auth", ...]`. 6. Copy the entire message content and use it as your SSID. ``` -------------------------------- ### Get Active Orders Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Retrieves a list of all currently active orders. If no orders are active, it prints a message indicating so. ```python from pocketoptionapi_async import AsyncPocketOptionClient async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() orders = await client.get_active_orders() if orders: print("Active Orders:") for order in orders: print(f"Order ID: {order['id']}, Amount: {order['amount']}, Status: {order['status']}") else: print("No active orders found.") await client.disconnect() ``` -------------------------------- ### Initialize AsyncPocketOptionClient Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Instantiate the client with authentication details and connection options. Ensure the SSID is the complete string from browser traffic. Persistent connections and auto-reconnect can be enabled here. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"n1p5ah5u8t9438rbunpgrq0hlq","isDemo":1,"uid":84402008,"platform":1}]' async def main(): # Demo account, persistent keep-alive connection, auto-reconnect enabled client = AsyncPocketOptionClient( ssid=SSID, is_demo=True, # True = demo account, False = live persistent_connection=True, # keep-alive with 20-second pings auto_reconnect=True, enable_logging=True, ) connected = await client.connect() print(f"Connected: {connected}") # Connected: True print(f"Is connected: {client.is_connected}") # Is connected: True await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Get Candles as DataFrame Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieves historical candle data and returns it as a pandas DataFrame, which is useful for data analysis and manipulation. ```APIDOC ## Get Candles as DataFrame ### Description Retrieves candle data as a pandas DataFrame for easy analysis. ### Method `await client.get_candles_dataframe(asset, timeframe, ...)` ### Endpoint N/A (Client method) ### Parameters #### Path Parameters - **asset** (str) - Required - Symbol, e.g. `"EURUSD_otc"` - **timeframe** (int or str) - Required - Timeframe in seconds or string (e.g. `60` or `"1m"`) ### Response #### Success Response - `pandas.DataFrame` with OHLCV columns indexed by timestamp. ### Request Example ```python df = await client.get_candles_dataframe("EURUSD_otc", 60) print(df.head()) ``` ``` -------------------------------- ### Navigate to Tools Directory Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/tools/README.md Change the current directory to the 'tools' folder to run the scripts. ```bash cd tools ``` -------------------------------- ### AsyncPocketOptionClient Initialization Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Initializes a new asynchronous client for Pocket Option. This is the main entry point for all API operations. Ensure to use 'await' for all network operations. ```APIDOC ## AsyncPocketOptionClient Initialization ### Description Creates a new asynchronous client for Pocket Option. This is the main entry point for all API operations. All network operations must be awaited. ### Parameters #### Path Parameters - **ssid** (str) - Required - Your Pocket Option SSID cookie value - **is_demo** (bool) - Optional - Use demo account if True, real if False (default: True) - **enable_logging** (bool) - Optional - Enable logging output (default: True) ### Request Example ```python from pocketoptionapi_async import AsyncPocketOptionClient client = AsyncPocketOptionClient("SSID", is_demo=True, enable_logging=True) ``` ``` -------------------------------- ### connect() — Connect to PocketOption Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Establishes the WebSocket connection to PocketOption, attempting multiple region endpoints and performing authentication. Returns True on success. ```APIDOC ## connect() — Connect to PocketOption Establishes the WebSocket connection, tries every available region endpoint in order, performs the Socket.IO handshake, waits for authentication, and starts keep-alive tasks. Returns `True` on success. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True) # Regular connection (tries demo regions automatically for demo accounts) success = await client.connect() if not success: print("Connection failed – check your SSID or network") return print(f"Connected to region: {client.connection_info}") # ... do work ... await client.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Check Order Result with PocketOptionAPI Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Demonstrates how to place an order and then check its result using the asynchronous client. Ensure you have the necessary credentials and inputs. ```python from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() amount = float(input("Enter the amount to invest: ")) symbol = input("Enter the symbol (e.g., 'EURUSD_otc'): ") direction = OrderDirection.PUT order = await client.place_order(asset=symbol, amount=amount, direction=direction, duration=5) result = await client.check_order_result(order.order_id) if result: print(f"Order placed successfully: {result}") else: print("Order result is None, please check the order status manually.") await client.disconnect() ``` -------------------------------- ### Connect to PocketOption Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Establishes the WebSocket connection, including handshake and authentication. This method attempts connection across available regional endpoints. It returns True on success. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True) # Regular connection (tries demo regions automatically for demo accounts) success = await client.connect() if not success: print("Connection failed – check your SSID or network") return print(f"Connected to region: {client.connection_info}") # ... do work ... await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Place a Binary Options Trade with place_order() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Submits a CALL or PUT binary option order. Ensure the SSID is correctly formatted and the client is connected before placing an order. Handles OrderError exceptions. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection from pocketoptionapi_async.exceptions import OrderError SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() try: # Place a $10 CALL on EUR/USD OTC, expiring in 60 seconds result = await client.place_order( asset="EURUSD_otc", amount=10.0, direction=OrderDirection.CALL, # or OrderDirection.PUT duration=60, # seconds (min 5, max 43200) ) print(f"Order ID : {result.order_id}") print(f"Status : {result.status.value}") # active / win / lose print(f"Placed at : {result.placed_at}") print(f"Expires at: {result.expires_at}") print(f"Payout : {result.payout}") except OrderError as e: print(f"Order failed: {e}") finally: await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Clone PocketOptionAPI Repository Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/termux-setup.html Clones the PocketOptionAPI GitHub repository and navigates into the project directory. This is the first step to accessing the API's code. ```bash git clone https://github.com/ChipaDevTeam/PocketOptionAPI.git cd PocketOptionAPI ``` -------------------------------- ### Troubleshooting Authentication Errors Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/README.md Provides guidance on resolving 'Authentication timeout' or immediate connection closure errors by ensuring the SSID is in the correct, complete format. ```text WARNING | pocketoptionapi_async.websocket_client:receive_messages:395 - WebSocket connection closed WARNING | pocketoptionapi_async.client:_start_regular_connection:245 - Failed to connect to region DEMO: Authentication timeout ``` -------------------------------- ### Get Historical Candles Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieves historical candle (OHLC) data for a specified asset and timeframe. You can control the number of candles and the end time for the data retrieval. ```APIDOC ## Get Historical Candles ### Description Retrieves historical candle (OHLC) data for a given asset and timeframe. ### Method `await client.get_candles(asset, timeframe, count=100, end_time=None)` ### Endpoint N/A (Client method) ### Parameters #### Path Parameters - **asset** (str) - Required - Symbol, e.g. `"EURUSD_otc"` - **timeframe** (int or str) - Required - Timeframe in seconds or string (e.g. `60` or `"1m"`) - **count** (int) - Optional - Number of candles (default 100) - **end_time** (datetime) - Optional - End time (default now) ### Response #### Success Response - List of `Candle` objects. ### Request Example ```python candles = await client.get_candles("EURUSD_otc", 60) for candle in candles: print(candle.open, candle.close) ``` ``` -------------------------------- ### Place Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Places a binary options order. You can specify the asset, investment amount, direction (CALL or PUT), and duration of the order. ```APIDOC ## Place Order ### Description Places a binary options order (CALL/PUT) for a given asset, amount, direction, and duration. ### Method `await client.place_order(asset, amount, direction, duration)` ### Endpoint N/A (Client method) ### Parameters #### Path Parameters - **asset** (str) - Required - Symbol, e.g. `"EURUSD_otc"` - **amount** (float) - Required - Amount to invest - **direction** (OrderDirection) - Required - `CALL` or `PUT` - **duration** (int) - Required - Duration in seconds (minimum 5) ### Response #### Success Response - `OrderResult` object with order details and status. ### Request Example ```python from pocketoptionapi_async import OrderDirection order = await client.place_order( asset="EURUSD_otc", amount=1.0, direction=OrderDirection.CALL, duration=60 ) print(order.order_id, order.status) ``` ``` -------------------------------- ### Get Historical Candles Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieve historical OHLC candle data for a specified asset and timeframe. You can control the number of candles and the end time for the data retrieval. ```python candles = await client.get_candles("EURUSD_otc", 60) for candle in candles: print(candle.open, candle.close) ``` -------------------------------- ### Connect to Pocket Option Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Establishes a connection to Pocket Option using your SSID. This method must be awaited before any trading or data calls can be made. ```APIDOC ## Connect to Pocket Option ### Description Establishes a connection to Pocket Option using your SSID. Must be awaited before any trading or data calls. ### Method `await client.connect()` ### Endpoint N/A (Client method) ### Response #### Success Response - `True` if connected successfully. ### Request Example ```python await client.connect() ``` ``` -------------------------------- ### Connect to Pocket Option Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Establish a connection to Pocket Option using your SSID. This must be awaited before performing any trading or data retrieval operations. ```python await client.connect() ``` -------------------------------- ### Get Candles Data with Seconds Value Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/assets-timeframes.html Fetches historical candle data for a given asset by directly specifying the timeframe in seconds. Use when the TimeFrame enum is not suitable. ```python candles = await client.get_candles("BTCUSD", 300, 100) ``` -------------------------------- ### Get Candles as Pandas DataFrame Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Retrieve historical candle data and return it as a pandas DataFrame, indexed by timestamp and including OHLCV columns. This is useful for data analysis. ```python df = await client.get_candles_dataframe("EURUSD_otc", 60) print(df.head()) ``` -------------------------------- ### place_order() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Submits a CALL or PUT binary option order for a given asset, amount, and duration. Returns an OrderResult with order details or raises OrderError on failure. ```APIDOC ## place_order() — Place a Binary Options Trade Submits a CALL or PUT binary option order for a given asset, amount, and duration (in seconds). Returns an `OrderResult` with the server-assigned `order_id`, status, and payout details. Raises `OrderError` on failure. ### Parameters - **asset** (string) - Required - The asset symbol (e.g., "EURUSD_otc"). - **amount** (float) - Required - The trade amount. - **direction** (OrderDirection) - Required - The trade direction (CALL or PUT). - **duration** (int) - Required - The trade duration in seconds (min 5, max 43200). ### Returns - `OrderResult` - An object containing `order_id`, `status`, `placed_at`, `expires_at`, and `payout`. ### Raises - `OrderError` - If the order placement fails. ### Example ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection from pocketoptionapi_async.exceptions import OrderError SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() try: # Place a $10 CALL on EUR/USD OTC, expiring in 60 seconds result = await client.place_order( asset="EURUSD_otc", amount=10.0, direction=OrderDirection.CALL, # or OrderDirection.PUT duration=60, # seconds (min 5, max 43200) ) print(f"Order ID : {result.order_id}") print(f"Status : {result.status.value}") # active / win / lose print(f"Placed at : {result.placed_at}") print(f"Expires at: {result.expires_at}") print(f"Payout : {result.payout}") except OrderError as e: print(f"Order failed: {e}") finally: await client.disconnect() asyncio.run(main()) ``` ``` -------------------------------- ### Place a Binary Options Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/api.html Place a CALL or PUT order for a specified asset, amount, and duration. Ensure you import OrderDirection from the library. ```python from pocketoptionapi_async import OrderDirection order = await client.place_order( asset="EURUSD_otc", amount=1.0, direction=OrderDirection.CALL, duration=60 ) print(order.order_id, order.status) ``` -------------------------------- ### Correct SSID Format for Authentication Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/README.md Demonstrates the correct format for the SSID required for authenticating with the PocketOption API. Ensure the complete authentication string is used, not just the session ID. ```python SSID = '42["auth",{"session":"n1p5ah5u8t9438rbunpgrq0hlq","isDemo":1,"uid":84402008,"platform":1}]' ``` -------------------------------- ### Before: Confusing Authentication Timeout Error Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md This code demonstrates the previous behavior where an incorrectly formatted SSID led to a generic 'Authentication timeout' error, causing user confusion. ```python client = AsyncPocketOptionClient(ssid="wrong_format") await client.connect() # Error: Authentication timeout # User: "What? Why did it timeout?" ``` -------------------------------- ### List Open Positions with get_active_orders() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Fetches a list of all currently open (unsettled) orders. This is useful for monitoring multiple trades simultaneously. Requires the client to be connected. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() # Place two orders await client.place_order("EURUSD_otc", 5.0, OrderDirection.CALL, 60) await client.place_order("BTCUSD", 5.0, OrderDirection.PUT, 60) active = await client.get_active_orders() print(f"Open positions: {len(active)}") for o in active: print(f" {o.order_id[:8]}... | {o.asset} | {o.direction.value} | ${o.amount}") await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Run SSID Extraction Tool Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/tools/README.md Execute the Python script to automatically extract your PocketOption SSID. Follow the on-screen prompts, which involve logging into PocketOption via a spawned Chrome browser. ```bash python get_ssid.py ``` -------------------------------- ### Place a CALL Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/examples.html Places a CALL order on a specified asset with a given amount, direction, and duration. Ensure the asset symbol and investment amount are valid. ```python from pocketoptionapi_async import AsyncPocketOptionClient, OrderDirection async def main(): SSID = input("Enter your SSID: ") client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() amount = float(input("Enter the amount to invest: ")) symbol = input("Enter the symbol (e.g., 'EURUSD_otc'): ") direction = OrderDirection.CALL order = await client.place_order(asset=symbol, amount=amount, direction=direction, duration=60) print(f"Order placed successfully: {order.order_id}, amount: {order.amount}, direction: {order.direction}, duration: {order.duration}") await client.disconnect() ``` -------------------------------- ### Place PUT Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/assets-timeframes.html Places a PUT order for a specified asset with a given amount, direction, and duration. Verify asset availability and market hours. ```python order = await client.place_order( asset="BTCUSD", amount=25.0, direction=OrderDirection.PUT, duration=300 # 5 minutes ) ``` -------------------------------- ### PocketOption API WebSocket Client - Authentication Handling Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md Python code snippet showing enhancements to authentication error messages in the WebSocket client. ```python def _handle_auth_message(self): # Enhanced authentication error messages pass ``` -------------------------------- ### Centralized Error Tracking with ErrorMonitor Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Use ErrorMonitor to record errors, set up alert callbacks, and wrap operations with circuit breakers and retry policies. Ensure the `error_monitor` singleton is imported. ```python import asyncio from pocketoptionapi_async.monitoring import ( error_monitor, ErrorSeverity, ErrorCategory ) async def my_alert_handler(alert): print(f"ALERT! {alert['error_type']}: {alert['error_count']} errors in window") async def main(): error_monitor.add_alert_callback(my_alert_handler) # Record a manual error await error_monitor.record_error( error_type="order_timeout", severity=ErrorSeverity.HIGH, category=ErrorCategory.TRADING, message="Order did not settle within 30 s", context={"order_id": "abc-123"}, ) # Wrap a function with monitoring, circuit breaker, and retry async def fetch_data(): return {"price": 1.08450} result = await error_monitor.execute_with_monitoring( fetch_data, operation_name="fetch_price", category=ErrorCategory.DATA, use_circuit_breaker=True, use_retry=True, ) print(f"Price: {result['price']}") summary = error_monitor.get_error_summary(hours=1) print(f"Errors in last hour: {summary['total_errors']}") asyncio.run(main()) ``` -------------------------------- ### Retrieve Account Balance Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Fetches the current account balance. The result is cached for 60 seconds to reduce server load. Access balance, currency, demo status, and last updated time from the returned Pydantic model. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() balance = await client.get_balance() # Balance fields: balance (float), currency (str), is_demo (bool), last_updated (datetime) print(f"Balance : ${balance.balance:.2f}") # Balance : $10000.00 print(f"Currency: {balance.currency}") # Currency: USD print(f"Demo : {balance.is_demo}") # Demo : True print(f"Updated : {balance.last_updated}") await client.disconnect() asyncio.run(main()) ``` -------------------------------- ### Place CALL Order Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/docs/assets-timeframes.html Places a CALL order for a specified asset with a given amount, direction, and duration. Ensure the asset symbol and duration are correct. ```python from pocketoptionapi_async.models import OrderDirection order = await client.place_order( asset="EURUSD_otc", amount=10.0, direction=OrderDirection.CALL, duration=60 # 1 minute ) ``` -------------------------------- ### After: Clear Guidance on SSID Format Source: https://github.com/chipadevteam/pocketoptionapi/blob/main/FIX_SUMMARY.md This code shows the improved error handling. An invalid SSID now triggers a specific error message indicating the SSID is too short and provides the correct, complete format required for connection. ```python client = AsyncPocketOptionClient(ssid="wrong_format") # Error: SSID is too short. If you're having connection issues, # please use the complete SSID format: # 42["auth",{"session":"your_session","isDemo":1,"uid":12345,"platform":1}] # User: "Ah! I need to use the complete format from DevTools!" ``` -------------------------------- ### Fetch OHLC Candle Data with get_candles() Source: https://context7.com/chipadevteam/pocketoptionapi/llms.txt Fetches historical OHLC candle data for a given asset and timeframe. Supports string timeframes or raw seconds. Ensure the client is connected before calling. ```python import asyncio from pocketoptionapi_async import AsyncPocketOptionClient SSID = '42["auth",{"session":"abc123...","isDemo":1,"uid":12345,"platform":1}]' async def main(): client = AsyncPocketOptionClient(SSID, is_demo=True, enable_logging=False) await client.connect() candles = await client.get_candles( asset="EURUSD_otc", timeframe="1m", # or 60 (seconds) count=50, ) print(f"Received {len(candles)} candles") for c in candles[-3:]: print( f"{c.timestamp.strftime('%H:%M')} | " f"O:{c.open:.5f} H:{c.high:.5f} L:{c.low:.5f} C:{c.close:.5f}" ) await client.disconnect() asyncio.run(main()) ```