BinaryOptionsTools-v2 icon indicating copy to clipboard operation
BinaryOptionsTools-v2 copied to clipboard

Multi-Asset Candle Feed Not Working Reliably - get_candles_live()

Open trader842 opened this issue 2 months ago • 10 comments

Description

I’m facing an issue when trying to use this library for multiple assets/symbols simultaneously.

My requirement is relatively simple: I need to fetch the latest closed candle information for multiple instruments every 60 seconds so I can build a multi-instrument trading bot.

For example, every 60 seconds, I need to fetch the latest completed 1-minute candle for all configured symbols, something like:

  • EURUSD — latest closed M1 candle
  • GBPUSD — latest closed M1 candle
  • USDJPY — latest closed M1 candle
  • XAUUSD — latest closed M1 candle
  • etc.

I m using - get_candles_live()

However, when requesting candle/feed data for multiple symbols, the library appears to struggle after some requests. It seems there may be some rate limit, API limitation, connection handling issue, or subscription/data-feed limitation when working with multiple assets.

I’m not trying to continuously stream large amounts of historical data. The requirement is only to retrieve the latest closed candle once per 60-second interval for each instrument.

Is multi-asset candle retrieval supported by the library? If so, is there a recommended way to handle this without running into rate/API limitations?

If needed, I can share my current code and the required files so the issue can be reproduced and investigated.

Thanks!

trader842 avatar Oct 05 '26 11:10 trader842

PO can be a bit picky sometimes, ill look into this whenever I can. However, ill say using a real ssid works much better than a demo ssid. You can fetch candles using the live ssid and submit trade(s) on the demo (for testing purposes)

If you could provide a code snippet that would greatly assist with the debugging process. Also make sure you unsubscribe afterwards, I don't believe it is done automatically but id have to recheck the codebase and possibly implement whenever i have freetime lol.

Thanks, Six

sixtysixx avatar Oct 06 '26 11:10 sixtysixx

Sorry for a bit delay mate i have attached the code snippet below, so this is the below code which bugs for get_candles_live, though i have tried to solve it using the subscribe symbol method that works efficiently

`import asyncio import aiohttp import pandas as pd import logging from datetime import datetime from contextlib import aclosing

from BinaryOptionsToolsV2.pocketoption.asynchronous import PocketOptionAsync

--- Configuration ---

TELEGRAM_BOT_TOKEN = TELEGRAM_CHAT_ID =

FAST_EMA = 9 SLOW_EMA = 21 TIMEFRAME = 60 # 60 seconds = M1

--- Boolean Options ---

SEND_TIMESTAMP_TELEGRAM = True # Option 1: Send timestamp in Telegram message with HH:MM:SS PRINT_EMA_ON_ALERT = True # Option 2: Print candle time and EMA values in console on alert/crossover

List of assets to monitor

MONITOR_ASSETS = [ "EURUSD_otc", "GBPUSD_otc", "AUDCAD_otc", "USDCAD_otc", "USDJPY_otc", "EURJPY_otc", "GBPJPY_otc", "USDCHF_otc", "AUDUSD_otc", "NZDUSD_otc", "EURGBP_otc", "EURCHF_otc", "GBPAUD_otc",
"AUDJPY_otc", "AUDCHF_otc", "NZDJPY_otc", "CADJPY_otc", "CADCHF_otc", "CHFJPY_otc" ]

---------------------

logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(levelname)s | %(message)s") logger = logging.getLogger(name)

async def send_telegram_alert(message: str, proxy: str = None): """ Sends a message asynchronously via Telegram Bot API using the OS's native DNS resolver. """ url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage" payload = { "chat_id": TELEGRAM_CHAT_ID, "text": message, "parse_mode": "Markdown" }

# Force aiohttp to use Python's built-in threaded resolver instead of aiodns
connector = aiohttp.TCPConnector(resolver=aiohttp.ThreadedResolver())

try:
    async with aiohttp.ClientSession(connector=connector) as session:
        async with session.post(url, json=payload, proxy=proxy, timeout=10) as response:
            if response.status != 200:
                error_text = await response.text()
                logger.error(f"Telegram API responded with error {response.status}: {error_text}")
except Exception as e:
    logger.error(f"Failed to send Telegram alert: {e}")

def check_ema_crossover(df: pd.DataFrame, asset: str) -> str: """Calculates EMAs and checks for a crossover on the most recently closed candles.""" if len(df) < SLOW_EMA + 2: return None

# Calculate EMA 9 and EMA 21
df['ema_fast'] = df['close'].ewm(span=FAST_EMA, adjust=False).mean()
df['ema_slow'] = df['close'].ewm(span=SLOW_EMA, adjust=False).mean()

# Check the last two closed candles
prev_fast = df['ema_fast'].iloc[-2]
prev_slow = df['ema_slow'].iloc[-2]
curr_fast = df['ema_fast'].iloc[-1]
curr_slow = df['ema_slow'].iloc[-1]

# Extract open prices for both candles
prev_open = df['open'].iloc[-2] if 'open' in df.columns else 0.0
curr_open = df['open'].iloc[-1] if 'open' in df.columns else 0.0

# Format current candle open time for the global print
raw_time = df['time'].iloc[-1] if 'time' in df.columns else None
try:
    ts = int(float(raw_time))
    if ts > 10_000_000_000:
        ts = ts // 1000
    readable_time = datetime.fromtimestamp(ts).strftime('%H:%M:%S')
except (ValueError, TypeError):
    readable_time = str(raw_time)

# Print unconditionally when a 60 second timeframe completes
print(f"{asset} : {curr_open} : {readable_time}")

signal = None

# Fast crosses ABOVE Slow -> Bullish
if prev_fast <= prev_slow and curr_fast > curr_slow:
    signal = "🟢 *BULLISH* (Buy / Call)"
# Fast crosses BELOW Slow -> Bearish
elif prev_fast >= prev_slow and curr_fast < curr_slow:
    signal = "🔴 *BEARISH* (Sell / Put)"
    
# Option 2: Print formatted candle time, Open prices, and EMA values
if signal and PRINT_EMA_ON_ALERT:
    print(f"\n[{asset}] Crossover Triggered!")
    print(f"  Candle Time : {readable_time}")
    print(f"  Previous    : Open = {prev_open:.5f} | Fast EMA = {prev_fast:.5f} | Slow EMA = {prev_slow:.5f}")
    print(f"  Current     : Open = {curr_open:.5f} | Fast EMA = {curr_fast:.5f} | Slow EMA = {curr_slow:.5f}\n")
    
return signal

async def stream_asset(client: PocketOptionAsync, asset: str): """ Subscribes to live candles for a single asset without delay, evaluating EMA crossover as soon as each new candle closes. """ last_processed_candle_time = None

try:
    generator = client.get_candles_live(
        asset, period=TIMEFRAME, hours=1.0, max_rows=60
    )
    
    async with aclosing(generator) as stream:
        async for closed, forming in stream:
            if not closed:
                continue
            
            # Identify the latest closed candle to prevent duplicate alerts on the same candle
            latest_candle = closed[-1]
            latest_time = latest_candle.get("time")
            
            if latest_time != last_processed_candle_time:
                last_processed_candle_time = latest_time
                
                df = pd.DataFrame.from_dict(closed)
                if 'time' in df.columns:
                    df = df.sort_values(by='time').reset_index(drop=True)
                    
                crossover_signal = check_ema_crossover(df, asset)
                
                if crossover_signal:
                    # Option 1: Format Telegram message with HH:MM:SS timestamp
                    if SEND_TIMESTAMP_TELEGRAM:
                        current_time_str = datetime.now().strftime("%H:%M:%S")
                        msg = (
                            f"🔔 **EMA Crossover Alert**\n"
                            f"Asset: `{asset}`\n"
                            f"Signal: {crossover_signal}\n"
                            f"Timeframe: M1\n"
                            f"Time: `{current_time_str}`"
                        )
                    else:
                        msg = (
                            f"🔔 **EMA Crossover Alert**\n"
                            f"Asset: `{asset}`\n"
                            f"Signal: {crossover_signal}\n"
                            f"Timeframe: M1"
                        )
                        
                    logger.info(f"Signal generated for {asset}: {crossover_signal}")
                    await send_telegram_alert(msg)
                    
except Exception as e:
    logger.error(f"Error in stream for {asset}: {e}")

async def main(ssid: str): logger.info("Connecting to Pocket Option using SSID...") async with PocketOptionAsync(ssid) as client: await asyncio.sleep(2) # Connection stabilization logger.info(f"Connected: {client.is_connected()} | Demo: {client.is_demo()}") logger.info(f"Current Balance: {await client.balance()}") logger.info(f"Starting simultaneous live streams for {len(MONITOR_ASSETS)} assets (staggered to prevent rate limits)...")

    # STAGGERED INITIALIZATION: Add a 1-second delay between subscribing to each asset
    tasks = []
    for asset in MONITOR_ASSETS:
        tasks.append(asyncio.create_task(stream_asset(client, asset)))
        await asyncio.sleep(1) # <--- This 1 second delay prevents PO from dropping your subscriptions

    await asyncio.gather(*tasks)

if name == "main": session_id = input("Please enter your ssid: ") # session_id = "42["auth",{"session":"0e6jh644ugldq79lkdf2kqkjci","isDemo":1,"uid":116494624,"platform":2,"isFastHistory":true,"isOptimized":true}]"

try:
    asyncio.run(main(session_id))
except KeyboardInterrupt:
    print("\nBot stopped by user.")` 

trader842 avatar Oct 17 '26 09:10 trader842

Okay, sounds good. Ill take a look in about and hour or two. Ive gotta get ready for dinner and when im back ill start seeing if there can be anything added or changed.

Thanks, Six

sixtysixx avatar Oct 18 '26 01:10 sixtysixx

Let me know if the new version fixes it

sixtysixx avatar Oct 21 '26 06:10 sixtysixx

Hi Six,

Thanks for the v0.2.16 fix — unfortunately it doesn't fully solve this for our use case, which is a larger-scale version of the same symptom (we're tracking ~78 symbols, vs the ~19 in the snippet above).

Setup: Python, BinaryOptionsToolsV2 v0.2.16 (already the latest), PocketOption (sync) client, Windows.

What we tried and observed:

  1. Single symbol with a persistent get_candles_live() stream: works fine, stays fresh indefinitely.
  2. Multiple symbols queued sequentially behind a shared lock (one get_candles_live() stream opened/consumed/closed at a time, never more than 1 concurrently): once we get past ~10 symbols in the rotation, the ones waiting their turn start failing with Subscription stream timed out after 60s — even though only one stream was ever open at a time from our side. It looks like each opened stream keeps a background task alive on your end regardless of whether we're actively reading from it, and that accumulates until something times out.
  3. Natural "warm-up" test on our real app (no code changes, just watching it run after a full restart, 10 minutes, zero manual intervention): out of 78 symbols, only 3 spontaneously went from stale (~2h old historical window) to live-updating. The other 75 stayed frozen at the same stale window, growing stale in lockstep with wall-clock time, for the full 10 minutes we watched.

This makes it feel like there's a hard ceiling on how many symbols can have an actively "warm"/live subscription at once (somewhere around 2-10, in our observations), independent of how the client code sequences its calls. For a multi-instrument bot that needs to monitor dozens of pairs (even if it only trades a handful at a time), this is the main blocker right now.

Questions:

  • Is there a server-side (PocketOption) or library-side cap on concurrent/recently-opened subscriptions per session that we should be designing around, rather than treating as a bug?
  • Is explicit unsubscribe (you mentioned above it's not automatic) expected to free up a slot immediately, or is there a cooldown before a closed subscription's "slot" becomes available again?
  • Any guidance on the intended pattern for monitoring many symbols when only a few need to be tradeable at once (e.g. is a rotating pool of subscriptions the recommended approach, or is there a bulk/multi-symbol API we're missing)?

Happy to share a minimal repro script if useful.

Thanks, Cavaliere

CavalierMax avatar Oct 30 '26 15:10 CavalierMax

Hi Six,

Thanks for the v0.2.16 fix — unfortunately it doesn't fully solve this for our use case, which is a larger-scale version of the same symptom (we're tracking ~78 symbols, vs the ~19 in the snippet above).

Setup: Python, BinaryOptionsToolsV2 v0.2.16 (already the latest), PocketOption (sync) client, Windows.

What we tried and observed:

  1. Single symbol with a persistent get_candles_live() stream: works fine, stays fresh indefinitely.
  2. Multiple symbols queued sequentially behind a shared lock (one get_candles_live() stream opened/consumed/closed at a time, never more than 1 concurrently): once we get past ~10 symbols in the rotation, the ones waiting their turn start failing with Subscription stream timed out after 60s — even though only one stream was ever open at a time from our side. It looks like each opened stream keeps a background task alive on your end regardless of whether we're actively reading from it, and that accumulates until something times out.
  3. Natural "warm-up" test on our real app (no code changes, just watching it run after a full restart, 10 minutes, zero manual intervention): out of 78 symbols, only 3 spontaneously went from stale (~2h old historical window) to live-updating. The other 75 stayed frozen at the same stale window, growing stale in lockstep with wall-clock time, for the full 10 minutes we watched.

This makes it feel like there's a hard ceiling on how many symbols can have an actively "warm"/live subscription at once (somewhere around 2-10, in our observations), independent of how the client code sequences its calls. For a multi-instrument bot that needs to monitor dozens of pairs (even if it only trades a handful at a time), this is the main blocker right now.

Questions:

  • Is there a server-side (PocketOption) or library-side cap on concurrent/recently-opened subscriptions per session that we should be designing around, rather than treating as a bug?
  • Is explicit unsubscribe (you mentioned above it's not automatic) expected to free up a slot immediately, or is there a cooldown before a closed subscription's "slot" becomes available again?
  • Any guidance on the intended pattern for monitoring many symbols when only a few need to be tradeable at once (e.g. is a rotating pool of subscriptions the recommended approach, or is there a bulk/multi-symbol API we're missing)?

Happy to share a minimal repro script if useful.

Thanks, Cavaliere

If u require it for multiple symbol live feed u can try it with subscribe symbol chunk i monitor around 40+ symbol and it works flawlessly never got the issue

trader842 avatar Oct 30 '26 19:10 trader842

Please download and install the wheel on my fork. It should appear in around 10 minutes. Let me know if this fixes your issue.

sixtysixx avatar Oct 31 '26 00:10 sixtysixx

https://github.com/sixtysixx/BinaryOptionsTools-v2/releases

sixtysixx avatar Oct 31 '26 00:10 sixtysixx

Hi Six,

Tested the new wheel on your fork (v0.2.17, win_amd64) — candles_many() fixes it completely for our use case.

Setup: isolated venv (not touching our main project env, just in case), real SSID, 78 OTC/forex symbols pulled live via active_assets() (same scale as our production bot).

Result of a single candles_many(symbols, period=5, count=5) call:

  • 78/78 symbols present in the result
  • 78/78 fresh (19-24s delay, vs. the ~2h stale window we were stuck at with get_candles_live()/get_candles()/stream_candles())
  • Call took ~16s for all 78 symbols together
  • Zero Subscription stream timed out errors

This confirms the docstring's claim exactly — polling snapshots instead of holding a live stream per symbol removes the ceiling we were hitting. This is exactly the API we needed; no rotating-pool workaround required on our side.

For context, we also tried the already-released stream_candles() on 0.2.16/0.2.17 first, hoping its "gap-free live candles" design would help — it hit the identical stale-window symptom as get_candles_live() (fixed ~2h-old timestamp, never advancing), so that one's not a fix for this.

We're migrating our price feed to candles_many() now. Thanks for building this — huge unblock for us.

Cavaliere

CavalierMax avatar Oct 31 '26 14:10 CavalierMax

Okay, sweet. Glad I could help. If you have any other issues, comments, or concerns feel free to open another gh issue.

I'll push to main once I do a more proper review, afterwards being published to pypi.

Thanks, Six

sixtysixx avatar Oct 31 '26 17:10 sixtysixx