payouts() has no per-symbol filter and may contend with price-feed polling on the shared event loop
Hi Six,
Follow-up from #141 (the candles_many() fix worked great, thanks again). Found a related issue while using payouts().
Setup: same production bot as #141 — Python, BinaryOptionsToolsV2 v0.2.17 (your fork wheel), PocketOption (sync) client, Windows, ~78-430 OTC/forex symbols across several concurrent rooms.
What we're seeing: payouts() always returns the payout for every asset in the catalog, with no way to filter it down to a specific list of symbols. We only need the ~80-100 symbols we're actually displaying/trading, not the full catalog.
Because the sync PocketOption wrapper runs every call (candles_many, payout, payouts, buy/sell, etc.) through a single shared background asyncio event loop (self._run(coro) → run_coroutine_threadsafe(..., self._loop)), a periodic payouts() poll (we were calling it every 20s to refresh a UI table) appears to compete with our candles_many() price-feed polling for that same loop. Shortly after adding it, we started seeing our price feed stall:
WARNING Feed prezzi live: timeframe 60s bloccato da oltre 90s senza risposta, libero per un nuovo tentativo.
WARNING Feed prezzi live: timeframe 5s bloccato da oltre 90s senza risposta, libero per un nuovo tentativo.
Removing the payouts() polling makes the stalls go away. We also know from #141 that opening a second concurrent PocketOption client (a second WebSocket connection) to isolate payout polling from price polling is not a safe workaround — we'd hit the connection-hang issue that pushed us to a single shared client in the first place.
Questions:
- Is there (or could there be) a filtered variant, e.g.
payouts(assets: list[str]), so a caller only pays the cost of the symbols it actually needs instead of the whole catalog every time? - Independent of filtering, is
payouts()expected to be "heavy" enough to noticeably delay other coroutines queued on the same client's event loop, or does this point to something else worth investigating on your side?
Happy to share more log excerpts or a minimal repro if useful.
Thanks, Cavaliere
Correction/addendum after reading the actual source (python/BinaryOptionsToolsV2/pocketoption/asynchronous.py, v0.2.17 tag):
async def payouts(self) -> Dict[str, int]:
return json.loads(await self.client.payout())
async def payout(self, asset: str) -> Optional[int]:
return (await self.payouts()).get(asset)
So payout(asset) is implemented as "fetch everything via payouts(), then .get(asset) locally" — there is no cheaper single-symbol path at all. This changes my read of the problem:
- It's not really about our own
payouts()UI-polling call specifically — every singlepayout(symbol)call also always fetches the whole catalog internally. In our bot that call gates every real order dispatch (one per trading signal, across every running room), so this happens far more often than our 20s UI poll ever did. - I also checked the Rust side (
crates/bindings_pyo3/src/pocketoption.rspayout()): it reads from an in-memoryRwLock<Option<Assets>>already kept in sync by the client's background connection, not a fresh network round-trip — so the "whole catalog" part is a local read + JSON serialize/deserialize, not a broker round-trip. Cheaper than I assumed, but it still runs on the same shared background event loop ascandles_many()/order calls, and happens very frequently (every signal, on every room). - Separately, I noticed
candles_many()(python/BinaryOptionsToolsV2/pocketoption/synchronous.py) isn't a single batched broker call — it's a Python-level loop issuing oneself.candles(asset, ...)round-trip per symbol, sequentially, on the same shared event loop. With several hundred symbols polled across multiple rooms, that sequential cost (we measured ~200ms/symbol ≈ 16s for 78 symbols) could plausibly be the real explanation for our "Subscription stuck for >90s, retrying" self-recovering warnings, independent of payout entirely.
So the more useful questions, updated:
- Is there any plan for a single-symbol
payout(asset)path that doesn't serialize/deserialize the whole catalog, now thatpayouts()already exists for the all-assets case? - For
candles_many(): is the one-round-trip-per-symbol design intentional (vs. a single batched server request), and is there a ceiling on how many symbols it's realistically meant to be called with per invocation?
Sorry for the back-and-forth — wanted to correct the earlier theory with what the source actually shows instead of leaving a wrong lead in the issue.
* Is there any plan for a single-symbol `payout(asset)` path that doesn't serialize/deserialize the whole catalog, now that `payouts()` already exists for the all-assets case?
I can get this added. To be frank, a majority of this is generated with AI. But I Believe it is a broker limitation, as PO updates all asset payouts periodically if I recall correctly.
* For `candles_many()`: is the one-round-trip-per-symbol design intentional (vs. a single batched server request), and is there a ceiling on how many symbols it's realistically meant to be called with per invocation?
There shouldnt be a ceiling, and if there is it is likely 4 due to only having 4 active charts at a time (multipane window). Its worth demo SSIDs can be prone to rate limiting and/or unresponsiveness - if youre using a demo SSID, id recommend to only submit trades/status checks with the designated SSID- otherwise the real SSID can be used for everything else to prevent any incoming issues.
Sorry for the back-and-forth — wanted to correct the earlier theory with what the source actually shows instead of leaving a wrong lead in the issue.
No problem, I need to organize the codebase anyway to hopefully prevent any (further) confusion.
Hopefully that all makes sense- been awake for way too long and was just about to get to bed.
Best, Six
Hopefully that all makes sense- been awake for way too long and was just about to get to bed.
Oops, didnt mean to close.
Tested this live tonight on our production bot (demo SSID, ~430 symbol/room pairs across 5 rooms):
-
Confirms your diagnosis exactly — measured ~200ms/symbol sequential round-trip inside a single
candles_many()call (16-20s for a ~78-90 symbol batch), causing our poll loop (every 2.5s, one call in flight per timeframe) to only get fresh data every ~16-20s instead of every ~2.5s. Daily trade count across every room dropped ~10x the day this shipped, same win rate — pure throughput loss, not a strategy issue. -
Tried splitting one big
candles_many()call into several smaller concurrent calls (15 symbols each) on the same client, hoping parallel smaller round-trips would finish faster than one big sequential one. Made it worse: several chunks got stuck waiting >90s simultaneously, confirming there's no real concurrency available this way — they just queue behind each other on the same shared event loop, with the added overhead of more Python-side scheduling.
Questions:
- Is a true batched server-side multi-symbol endpoint (one round trip for N symbols) on the roadmap, or is the per-symbol sequential loop a PocketOption API constraint?
- On your SSID tip: we're a demo/paper-trading bot, so by definition all our data comes from a demo SSID. Would opening a second, separate connection using a real-account SSID purely for
candles_many()/status polling (while keeping the demo SSID only for order placement) help with the per-call latency — and is that safe, given opening two connections from the same process has hung for us before (different accounts, not just same account)?
Happy to share more data/timestamps if useful.
Hi,
* Is a true batched server-side multi-symbol endpoint (one round trip for N symbols) on the roadmap, or is the per-symbol sequential loop a PocketOption API constraint?
I honestly don't remember / cant recall. Im running on one monster energy can after being awake for over 24 hours and am on the way home. Ill probably crash and let you know on Wednesday, probably. Id have the check websocket exports and such.
* On your SSID tip: we're a demo/paper-trading bot, so by definition all our data comes from a demo SSID. Would opening a second, separate connection using a real-account SSID purely for `candles_many()`/status polling (while keeping the demo SSID only for order placement) help with the per-call latency — and is that safe, given opening two connections from the same process has hung for us before (different accounts, not just same account)?
You can try. Im not 100% sure so im going to avoid promising anything hence my current stance.
Ive created 0.2.18 on my fork, still need to review but you're welcome to test it out.
Best, Six
Follow-up with a new data point, possibly related to the same root cause.
Tonight we also tested whether opening two PocketOption connections (two different accounts, different uid) at the same time in the same process hangs, since we need that for the real-SSID-for-data-only idea mentioned above. Good news: it doesn't — both stayed responsive concurrently, no deadlock.
While testing candles_many() at our real symbol-count scale (~80-108 OTC symbols) on one of those connections, we reconnected/closed that same real account 5-6 times in about 15 minutes (one short-lived script per test). After that:
n=1 symbol: 30.0s -> 0 results
n=5 symbols: 148.9s -> 0 results
n=10/20/40: instant -> 0 results, no exception
Console showed Error: Core(ChannelReceiver(Closed)) right before this started. The first two calls got progressively slower (30s, then ~149s) before the connection apparently gave up entirely and started returning empty results instantly with no error raised.
This looks like it could be the same channel/event-loop issue behind the shutdown-time RuntimeError: Event loop is closed flood we've mentioned before, but here it happened on a real account mid-session, not during shutdown, and seemingly triggered by reconnecting too many times too quickly rather than by closing the process.
Questions:
- Is there a known minimum interval (or max reconnect rate) between opening new sessions on the same account before the server/library starts degrading the channel like this?
- Once a connection reaches this state, is there any way to detect it (other than noticing calls return empty/instant) and recover without a full process restart?
Happy to share the exact timestamps/script if useful for reproducing.
Another data point, this time a full production freeze rather than just the per-call latency we described above.
Context: our bot ran fine for days before migrating from get_candles() (per-symbol, capped at ~10 concurrent "live" symbols before timing out) to candles_many() on Oct 31. Since that migration, we've seen the per-call latency issue described above, and now also this: after about 8 hours of continuous operation (same process, same single candles_many()-based polling loop, demo account, ~430 symbol/room pairs across 5 rooms), the feed went from "slow with occasional >90s stuck warnings" to completely unresponsive — zero candles, zero trades, for 2+ hours before we noticed and restarted the process.
Timeline (local time):
- 23:08 → ~07:50: steady trickle of "stuck >90s, retrying" warnings, roughly 1-2/minute the whole time (our own baseline symptom from the per-symbol-sequential design mentioned above)
- 07:50 → 09:56: total silence, not even a retry warning — the poll loop itself seems to have stopped producing anything
- 09:56: one last isolated pair of warnings, then nothing until we manually restarted at ~10:05
We also ruled out our own earlier test (opening a second connection with a different account, see above) as the cause — that test completed by 01:05, a clean 6+ hours before the freeze started, and the warning rate didn't change at all around that window.
Before the candles_many() migration, running the old per-symbol approach for similarly long sessions, we never saw a full stop like this — only the known "some symbols never go live past ~10 concurrent streams" staleness issue, not a complete halt.
Question: is there a known failure mode where the underlying connection/channel degrades to the point of going fully silent after many hours of continuous candles_many() polling, and is there a recommended way to detect that state and recover (reconnect) without restarting the whole process? Right now our only recovery is a full process restart.
Hello, sorry to interrupt @CavalierMax but could you write some minimal code scripts that cause this issue so I can check them out and possibly check Pocket Option's websockets connections to see if there is a fix to do to the library or a fix on those scripts.
Also something that might help is to check the tracing module of the library, they are some bindings with the logging library used on the rust side of the code and might help get some insights. It should be pretty easy to use, only a cupple of lines of code if i remember correctly it's something like this:
from BinaryOptionsToolsV2.tracing import start_logs
# In the main function
start_logs(".", "INFO")
Thanks
Another data point, this time isolating demo-vs-real latency directly (separate from the reconnect-degradation data point above).
Setup: two PocketOption connections open at once in the same process, different accounts (different uid) — one demo, one real — both idle otherwise (no rapid reconnects this time, each opened once and left alone).
Result over a sustained test run:
- Real account:
candles_many()stayed at a constant ~1s per call, even scaled up to 108 OTC symbols. - Demo account: same call on the same process, unpredictable spikes from 30s up to 149s, with no pattern we could tie to symbol count, time of day, or anything on our side.
- No interference between the two connections either way (consistent with what we reported above) — the demo account's instability happened independently of the real one running alongside it.
Given everything else about our setup (code, polling cadence, symbol list) was identical between the two connections in this test, this points to the demo environment itself being rate-limited/deprioritized server-side, separate from the candles_many() sequential-round-trip cost and from the reconnect-degradation issue described above. Flagging it in case it's useful context for why some users see this a lot worse than others depending on account type — and in case there's a known difference in how demo vs real traffic is handled upstream that would explain it.
Follow-up with something more concrete, after digging into it on our side the last couple of days.
What we found: it's not just contention/slowness on the shared loop — when a call on it hangs (no exception, no return, e.g. the payouts()/candles_many() stalls above), there is no way to cancel it or give it a real timeout from the Python side. We tried wrapping our own calls with a wall-clock timeout (QTimer/asyncio.wait_for-style, give up after 90s) — that only stops us from waiting; the underlying coroutine/thread on your shared loop keeps running (or hanging) regardless, since there's no cancellation hook exposed.
That turned a previously harmless quirk into a real resource leak on our end: we moved from "one new thread per call" (any hang just leaked a thread silently) to a fixed-size worker pool (to stop that leak from exhausting OS resources over long sessions). But now, every call that hangs on your shared loop permanently costs us one of those fixed workers, with no way to reclaim it short of restarting our whole process. Once enough of those accumulate, every subsequent call — candles_many, payouts, buy/sell, even our own reconnect attempts — queues behind the dead ones and fails the same way, which looks exactly like a dead connection even when the WS might still be fine for a fresh client.
What would help, either one:
- A real per-call timeout parameter (e.g.
candles_many(symbols, timeframe, timeout_seconds=...), same forpayout(s)/buy/sell) that actually cancels the underlying Rust-side task/future when it fires, not just something the caller has to emulate by abandoning the wait. - Failing that, some way to detect from the outside that the shared loop/connection is wedged (a lightweight
client.is_responsive()/ health-check call that itself can't hang, or a client-side watchdog that resets the WS automatically after N seconds of silence) — so we can rebuild the client ourselves instead of guessing from symptoms.
Happy to share the exact log sequences (stuck calls on multiple symbol batches simultaneously, 5+ minutes straight, immediately before we give up and restart) if that helps narrow it down on your end.
Thanks, Cavaliere
I apologize for the delayed response.
Im still on vacation but will be returning tomorrow. You can try my fork, again. It could very well be a broker issue/limitation. Im not very involved with similar platforms due to the high risk high reward system and highly skewed uncertainty. But in the meantime Id appreciate some logs and specifications.
BOTv2 Build #: Python environment (3.12 or higher preferred): Installation method (clone and build | direct download from GitHub releases or artifacts): Code Snippet(s) related to the issue:
Best, Six
Please retry using the new version (0.2.18).
Best. Six