Skip to main content

⚡ PocketOption API SDK (Unofficial)

PyPI version PyPI - Python Version Downloads License GitHub stars

🌐 Available languages: 🇬🇧 English | 🇷🇺 Русский

Asynchronous Python SDK for interacting with the PocketOption API (unofficial).

Fully type-hinted, built on pydantic, with middleware and event support.

Supports Python 3.13+ and is fully asynchronous (asyncio + aiohttp).

⚠️ Disclaimer

⚠️ This project is not a trading bot.

⚠️ It is not affiliated with PocketOption and is intended for integrations and analytical purposes only.

⚠️ Investing in financial instruments carries risks. Past performance does not guarantee future returns, and asset values may fluctuate due to market conditions and movements in underlying instruments. Any forecasts or illustrations are for informational purposes only and do not constitute guarantees or investment advice. This project is not an invitation or recommendation to invest. Before making investment decisions, consult financial, legal, and tax professionals to determine whether such products suit your goals, risk tolerance, and personal circumstances.

P.S. Their demo mode is surprisingly fun to play around with 😎

🚀 Features

  • 🔌 Connects to PocketOption WebSocket API (via socket.io)

  • 🔐 Session-based authentication

  • 💹 Order and trade management (demo / real account)

  • 📊 Market stream subscriptions

  • 💾 Built-in in-memory storages (MemoryCandleStorage, MemoryDealsStorage)

  • ⚙️ Middleware chain for event and request interception

  • 💬 Event model with decorators (@client.on.*)

  • ✅ Strict type hints

🔑 Getting Session ID and UID

To interact with the API, you need a valid session payload from the browser.

  1. Open Pocket Option in your browser
  2. Open Developer Tools
  3. Go to the Network tab
  4. Filter by WebSocket (WS)
  5. Find a request to {region}...
  6. Fimd message containing 42["auth"
  7. Copy the session and uid

Example:

42["auth",{"session":"abcd1234efgh5678","isDemo":1,"uid":1234589,"platform":1}]

⚙️ Usage Example

import asyncio
import logging
import os
import random

from pocket_option import PocketOptionClient
from pocket_option.constants import Regions
from pocket_option.contrib.default_init import default_init
from pocket_option.models import (
    Asset,
    AuthorizationData,
    DealAction,
    UpdateCloseValueItem,
)

logging.basicConfig(
    level=logging.DEBUG,
    format="%(asctime)s | %(levelname)s | %(message)s",
)

logger = logging.getLogger(__name__)
rng = random.SystemRandom()
client = PocketOptionClient(logger=True)

ASSET = Asset.AUDCAD_otc
TRADE_AMOUNT = 10
EXPIRATION_TIME = 60
CANDLE_PERIOD = 30
OPTION_TYPE = 100
IS_DEMO = 1

default_init(
    client,
    authorization=AuthorizationData.model_validate(
        {
            "session": os.environ["PO_SESSION"],
            "isDemo": IS_DEMO,
            "uid": int(os.environ["PO_UID"]),
            "platform": 2,
            "isFastHistory": True,
            "isOptimized": True,
        },
    ),
    sub_assets=[ASSET],
    sub_period=CANDLE_PERIOD,
)


@client.on.update_close_value
async def on_update_close_value(
    assets: list[UpdateCloseValueItem],
):
    logger.debug("Assets updated: %s", assets)


def get_signal() -> DealAction | None:
    return rng.choice(
        [
            DealAction.CALL,
            DealAction.PUT,
            None,
        ],
    )


async def execute_trade(direction: DealAction):
    logger.info(
        "Opening %s trade",
        direction.name,
    )
    deal = await client.deals.open_deal(
        asset=ASSET,
        amount=TRADE_AMOUNT,
        action=direction,
        is_demo=IS_DEMO,
        option_type=OPTION_TYPE,
        time=EXPIRATION_TIME,
    )
    logger.info(
        "Deal opened: %s",
        deal,
    )
    result = await client.deals.check_deal_result(
        wait_time=EXPIRATION_TIME + 5,
        deal=deal,
    )
    logger.info(
        "Deal result: %s",
        result,
    )


async def trader_loop():
    await client.authorized_event.wait()
    logger.info("Trader started")
    while True:
        try:
            signal = get_signal()
            if signal is None:
                await asyncio.sleep(5)
                continue
            await execute_trade(signal)
            await asyncio.sleep(5)
        except Exception:
            logger.exception("Trading error")
            await asyncio.sleep(10)


async def main():
    try:
        await client.connect(Regions.DEMO)
        await trader_loop()
    except KeyboardInterrupt:
        logger.info("Stopping...")
    finally:
        await client.disconnect()


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

📜 License

MIT License — do whatever you want, but at your own risk.

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

pocket_option-0.2.9.tar.gz (25.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

pocket_option-0.2.9-py3-none-any.whl (30.8 kB view details)

Uploaded Python 3

File details

Details for the file pocket_option-0.2.9.tar.gz.

File metadata

  • Download URL: pocket_option-0.2.9.tar.gz
  • Upload date:
  • Size: 25.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.3 CPython/3.14.3 Windows/11

File hashes

Hashes for pocket_option-0.2.9.tar.gz
Algorithm Hash digest
SHA256 145502fd0a6f8107cff048ab62533a61e190d9e6cd727cce31e80e19f74ad6f3
MD5 3370e9201a94f7fea67505920ba54573
BLAKE2b-256 c3a068cbb87dee095e4dea400f4c24116c210ba72b6262344ff1cc55f2883c32

See more details on using hashes here.

File details

Details for the file pocket_option-0.2.9-py3-none-any.whl.

File metadata

  • Download URL: pocket_option-0.2.9-py3-none-any.whl
  • Upload date:
  • Size: 30.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: poetry/2.3.3 CPython/3.14.3 Windows/11

File hashes

Hashes for pocket_option-0.2.9-py3-none-any.whl
Algorithm Hash digest
SHA256 c363b6d350f558dd3f55b12c4faa0e2584d3e3e651855d6759b8fe517594b810
MD5 9941324df81821e875e363812168f173
BLAKE2b-256 ca113ab8869b04036a833afa64cff41fa831f74e73f5de78ada30d499538bc3a

See more details on using hashes here.

Release history Release notifications | RSS feed

0.4.0

2 files

0.3.0

2 files

This release

0.2.9 This release

2 files

0.2.8

2 files

0.2.7

2 files

0.2.6

2 files

0.1.6

2 files

0.1.5

2 files

0.1.4

2 files

0.1.3

2 files

0.1.2

2 files

0.1.1

2 files

0.1.0

2 files

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page