Fyers API OHLC fetch slows down significantly after 75% progress despite using multithreading.

I’m using the following fetch_multiple_fyers_ohlc function to fetch OHLC data using the Fyers API. The function uses multithreading with adaptive concurrency to speed up the process. It works very fast initially — fetching around 75% of the data in just 15 seconds — but the remaining 25% takes an additional 55 seconds to complete.

Why is the function slowing down so much near the end?
How can I optimize it to maintain consistent speed or avoid this performance drop?

Here is the function code for reference:

def fetch_multiple_fyers_ohlc(symbols: List[str], fyers: fyersModel.FyersModel, max_workers: int = 10) -> List[Dict[str, Any]]:
    """Fetch OHLC data for multiple symbols using threading with adaptive concurrency control."""
    results = []
    success_count = 0
    error_count = 0
    rate_limit_count = 0
    
    # Adaptive concurrency: reduce workers if we hit rate limits frequently
    adaptive_workers = max_workers
    
    def fetch_single_symbol(symbol):
        return fetch_fyers_ohlc(symbol, fyers)
    
    # Monitor rate limit frequency and adjust concurrency
    def adjust_concurrency():
        nonlocal adaptive_workers
        if rate_limit_count > 0 and (rate_limit_count / (success_count + error_count)) > 0.1:  # More than 10% rate limit errors
            adaptive_workers = max(1, adaptive_workers - 1)
            print_status(f"High rate limit frequency detected. Reducing concurrency to {adaptive_workers} workers", "warning")
    
    with ThreadPoolExecutor(max_workers=adaptive_workers) as executor:
        future_to_symbol = {executor.submit(fetch_single_symbol, symbol): symbol for symbol in symbols}
        with tqdm(total=len(symbols), desc="Fetching OHLC", ncols=100, leave=False, dynamic_ncols=True) as pbar:
            for future in as_completed(future_to_symbol):
                try:
                    result = future.result()
                    results.append(result)
                    
                    # Update counters for real-time success rate
                    if result.get('status') == 'success':
                        success_count += 1
                    else:
                        error_count += 1
                        # Check if it's a rate limit error
                        if result.get('error') and ('rate limit' in result.get('error', '').lower() or 
                                                   'too many requests' in result.get('error', '').lower()):
                            rate_limit_count += 1
                    
                    # Update progress bar with current success rate
                    total_processed = success_count + error_count
                    success_rate = (success_count / total_processed) * 100 if total_processed > 0 else 0
                    pbar.set_postfix({
                        'success': f"{success_rate:.1f}%",
                        'workers': adaptive_workers,
                        'rate_limits': rate_limit_count
                    })
                    
                    # Periodically adjust concurrency based on rate limit frequency
                    if total_processed % 20 == 0:  # Check every 20 requests
                        adjust_concurrency()
                    
                except Exception as e:
                    symbol = future_to_symbol[future]
                    error_result = {"symbol": symbol, "status": "error", "error": str(e)}
                    results.append(error_result)
                    error_count += 1
                    
                    # Update progress bar
                    total_processed = success_count + error_count
                    success_rate = (success_count / total_processed) * 100 if total_processed > 0 else 0
                    pbar.set_postfix({
                        'success': f"{success_rate:.1f}%",
                        'workers': adaptive_workers,
                        'rate_limits': rate_limit_count
                    })
                    
                pbar.update(1)
    
    # Log final statistics
    print_status(f"Final fetch results: {success_count} successful, {error_count} failed, {rate_limit_count} rate limited out of {len(symbols)} symbols", "info")
    if rate_limit_count > 0:
        print_status(f"Rate limit frequency: {(rate_limit_count / len(symbols)) * 100:.1f}% - Consider increasing RATE_LIMIT_DELAY", "warning")
    
    return results

Its working after using web socket.

Thank you,

Fyers Team

@100276684910255442357 hi, did you solve live OHLC data for multiple symbols using websocket, i want to use webscoket as api historical data have limit but could not find OHLC live websocket code on API docs