Heuristic:24mlight A Share investment Agent Proxy Rotation Backoff
| Knowledge Sources | |
|---|---|
| Domains | Optimization, Infrastructure, Finance |
| Last Updated | 2026-10-10 14:00 GMT |
Overview
Proxy rotation with exponential backoff and jitter to mitigate AkShare API rate limiting, connection failures, and IP blocking.
Description
The ProxyManager class implements a round-robin proxy rotation strategy for outbound HTTP calls to AkShare/BaoStock. It cycles through a list of proxy URLs (configured via AKSHARE_PROXY_LIST), applies each proxy by temporarily setting HTTP_PROXY/HTTPS_PROXY environment variables, and restores the original values afterward. On failure, it retries with exponential backoff (base_delay * 2^(attempt-1)) capped at max_delay, plus random jitter to avoid thundering herd effects. A "direct" proxy entry means no proxy (bypass), and NO_PROXY="*" is set to ensure direct connections.
Usage
Use this heuristic when:
- AkShare API calls fail with
RemoteDisconnectedorProxyError - AkShare rate-limits or blocks your IP address
- You need reliable data fetching from Chinese financial data APIs
- Running backtests that make many sequential API calls
The Insight (Rule of Thumb)
- Action: Set
AKSHARE_PROXY_LISTto a comma/semicolon-separated list of proxy URLs, optionally includingdirectfor direct connections. - Value: Defaults:
max_attempts=3,base_delay=1s,max_delay=15s,jitter=0.5s. - Trade-off: Proxy rotation adds latency (backoff delays) but significantly improves reliability of data fetching.
- Compatibility:
"direct"entry bypasses proxy;AKSHARE_PROXY_FORCE_DIRECT=trueoverrides everything to force direct connections.
Reasoning
AkShare and BaoStock are free Chinese financial data APIs that may throttle or block IPs making frequent requests. During backtesting, the system makes hundreds of sequential API calls. Without proxy rotation, a single blocked IP can halt the entire backtest. The round-robin strategy distributes load across multiple IPs, while exponential backoff with jitter prevents synchronized retry storms that could trigger additional rate limiting.
The ProxyManager.from_env() factory reads all configuration from environment variables, with sensible defaults (direct only, 3 attempts, 1-15s backoff). The allow_direct=true default ensures a direct connection is always tried first before falling back to proxies.
Code Evidence
Proxy rotation and backoff from src/network/proxy_manager.py:100-125:
def _sleep(self, attempt: int) -> None:
delay = min(self.base_delay * (2 ** (attempt - 1)), self.max_delay)
if self.jitter:
delay += random.uniform(0, self.jitter)
time.sleep(delay)
def run(self, func: Callable[[], any], label: str):
last_exc: Optional[Exception] = None
for attempt in range(1, self.max_attempts + 1):
proxy = self._next_proxy()
with self._apply_proxy(proxy):
try:
return func()
except Exception as exc:
last_exc = exc
self._log("warning", f"{label} attempt {attempt}/{self.max_attempts} failed "
f"using proxy {proxy or 'DIRECT'}: {exc}")
if attempt < self.max_attempts:
self._sleep(attempt)
if last_exc:
raise last_exc
Environment-based configuration from src/network/proxy_manager.py:36-66:
@classmethod
def from_env(cls, logger=None) -> "ProxyManager":
force_direct = os.getenv("AKSHARE_PROXY_FORCE_DIRECT", "false").lower() in ("1", "true", "yes")
if force_direct:
proxies = ["direct"]
else:
raw = os.getenv("AKSHARE_PROXY_LIST", "").replace(";", ",")
proxies = [item.strip() for item in raw.split(",") if item.strip()]
allow_direct = os.getenv("AKSHARE_PROXY_ALLOW_DIRECT", "true").lower() in ("1", "true", "yes")
if allow_direct and "direct" not in [p.lower() for p in proxies]:
proxies.insert(0, "direct")