Skip to content

usmanch96/pypocketoption

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

3 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

PocketOption API - Asynchronous Python Wrapper (pypocketoption)

Python Version License Format

PyPocketOption Logo

An asynchronous, high-frequency, and robust PocketOption API Python wrapper for the Pocket Option binary options trading platform. Utilizing Socket.IO (EIO=4) and automated browser session harvesting, this library provides a high-level Pocket Option API client to stream real-time quotes, manage active positions, fetch extensive historical candles, and automate Pocket Option trading bot algorithms.

Maintained by @usmanch069.


✨ Features

  • Asynchronous Execution: Fully built on asyncio for speed and non-blocking operation.
  • Robust Connection Lifecycle: Automatic reconnection loop with exponential backoff.
  • Lazy Event Loop Safe: Compatible with Python 3.10+ event loop patterns.
  • Smart Session Harvesting: Undetected Selenium browser integration to safely harvest cookies/SSID and bypass Cloudflare/reCAPTCHA.
  • Precision Time Sync: Synchronizes clock offsets with broker server time using Exponential Moving Average (EMA) smoothing.
  • Candle Fetching Engines:
    • Standard pagination retrieval (get_candles_history).
    • High-performance parallel chunk retrieval (get_candles_history_parallel).
    • Hybrid worker-based historical fetcher (get_historical_candles).
  • Live Stream Tracking: Re-subscribes to active quote streams automatically after reconnection.
  • Limit/Pending Orders: Client-side limit orders matching custom trigger boundaries (touch, cross_above, cross_below, etc.).
  • EMA-Smoothed Payouts: Fast calculation and retrieval of highest-payout assets.

πŸš€ Installation

Install the package in editable mode from your local workspace:

pip install -e .

Make sure your configuration .env file contains your credentials:

PocketOption_EMAIL=your_email@example.com
PocketOption_PASSWORD=your_secure_password

⚑ Quick Start

Here is a simple example showing how to connect, fetch balance information, stream live prices, place a trade, and wait for the trade outcome.

import asyncio
import logging
from pypocketoption import PocketOption

# Set up logging for detailed protocol tracking
logging.basicConfig(level=logging.INFO)

async def main():
    # Credentials are automatically loaded from your .env file
    async with PocketOption(is_demo=True, headless=False) as client:
        # 1. Fetch balance
        balance = await client.get_balance()
        print(f"πŸ’° Current Balance: {balance.balance} {balance.currency} (Demo: {balance.is_demo})")

        # 2. Get the highest payout currency pairs
        high_payouts = client.get_highest_payout_assets(min_payout=80.0, category="currency")
        if not high_payouts:
            print("No active assets with > 80% payout found.")
            return
            
        target_asset = high_payouts[0]["symbol"]
        print(f"πŸ“ˆ Selected Asset: {target_asset} ({high_payouts[0]['payout']}% payout)")

        # 3. Setup a candle updater stream callback
        def on_candle(symbol, period, candle, is_closed):
            if is_closed:
                print(f"πŸ•―οΈ [{symbol}] Closed Candle | O: {candle.open} | H: {candle.high} | L: {candle.low} | C: {candle.close}")

        client.on_candle_update = on_candle
        client.setup_candle_stream(target_asset, periods=[60])

        # 4. Start streaming live prices
        await client.start_realtime_price(target_asset, timeframe=60)
        print(f"πŸ“‘ Subscribed to live quotes for {target_asset}. Waiting for ticks...")
        await asyncio.sleep(5)  # Let it stream ticks for 5 seconds

        # 5. Place a 1-minute CALL (UP) trade of $1
        print("πŸ”” Placing CALL trade...")
        try:
            order = await client.buy(amount=1.0, asset=target_asset, action="call", duration=60)
            print(f"πŸš€ Trade Placed! Request ID: {order.order_id} | Expires at: {order.expires_at}")

            # 6. Wait for position settlement
            print("βŒ› Waiting for trade settlement...")
            result = await client.check_win(order.order_id, timeout=120)
            print(f"🏁 Trade Outcome: {result.status.value} | Payout: {result.profit} USD")
        except Exception as e:
            print(f"❌ Trade failed: {e}")

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

πŸ“ˆ Client-Side Pending/Limit Orders

You can place pending limit orders that automatically trigger trades when price action conditions are met:

# Place a pending order for EURUSD_otc when price is greater than or equal to 1.10200
pending_id = client.buy_pending(
    amount=5.0,
    asset="EURUSD_otc",
    action="call",
    strike_price=1.10200,
    duration=60,
    comparison="gte",
    timeframe=60
)

# Cancel it if needed before it triggers
client.cancel_pending_order(pending_id)

πŸ“š Advanced History Retrieval

pypocketoption offers three distinct retrieval engines designed to load historical candle data seamlessly:

# 1. Page-based Sequential History
candles = await client.get_candles_history(asset="EURUSD_otc", timeframe=60, days=2.0)

# 2. Pre-calculated parallel history (super-fast)
candles = await client.get_candles_history_parallel(asset="EURUSD_otc", timeframe=60, days=5.0, concurrency=10)

# 3. Worker-based block fetcher (robust, gap-resistant)
candles = await client.get_historical_candles(asset="EURUSD_otc", amount_of_seconds=86400, period=60, max_workers=5)

πŸ› οΈ Configuration & Session Management

  • SSID Session Caching: Successful sessions are automatically cached locally to session.json to prevent launching Selenium on subsequent runs. Cache validity is checked against a 24-hour expiration threshold.
  • Headless Mode: Set headless=True during client initialization to run Chromium invisibly on headless environments (like Linux VPS or CI pipelines).
  • Regions: Supports multiple geographical endpoints to minimize latency:
    • REGIONS["EUROPA"]
    • REGIONS["UNITED_STATES"]
    • REGIONS["HONGKONG"]
    • REGIONS["ASIA"]

πŸ‘¨β€πŸ’» Author

Developed and maintained by @usmanch069. Feel free to reach out for support, custom bot builds, or general inquiries.


πŸ” PocketOption API - Search Optimization & FAQ

What is the PocketOption API?

The PocketOption API is an un-official client library that allows developers to interface with the Pocket Option trading platform programmatically. Since Pocket Option does not offer an official public API key option for retail automated trading, this library uses a secure WebSocket connection over Socket.IO and automated browser profiles to manage session tokens (SSID).

How do I build a Pocket Option Trading Bot in Python?

You can build a fully automated Pocket Option trading bot using pypocketoption. By using the buy() and sell_option() functions, combined with live WebSocket streams via start_realtime_price(), your bot can run technical analysis indicators (e.g., EMA, RSI, MACD) and execute trades within milliseconds.

Does this support Pocket Option Demo and Live accounts?

Yes. The Pocket Option Python API client supports both environments. Simply set the parameter is_demo=True or is_demo=False during initialization. The same SSID session token can be utilized for both accounts.

Can I run this Pocket Option API on a VPS?

Yes. You can configure Chromium to run in headless=True mode, allowing you to deploy your PocketOption bot to any virtual private server (VPS) running Linux (e.g., Ubuntu, Debian) or Docker containers.

Target SEO Keywords

  • PocketOption API
  • Pocket Option Python API
  • Pocket Option Trading Bot
  • Pocket Option WebSocket API
  • Pocket Option API Key
  • Pocket Option Automated Trading
  • Pocket Option Algorithmic Trading Bot
  • Pocket Option Library Python
  • Pocket Option API Wrapper

πŸ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.