Update bars cache with a new bar record. Args: symbol: Symbol name new_bar: New bar data dictionary to add to cache
(self, symbol: str, new_bar: Dict)
| 253 | return False |
| 254 | |
| 255 | def _update_cache(self, symbol: str, new_bar: Dict) -> None: |
| 256 | """Update bars cache with a new bar record. |
| 257 | |
| 258 | Args: |
| 259 | symbol: Symbol name |
| 260 | new_bar: New bar data dictionary to add to cache |
| 261 | """ |
| 262 | try: |
| 263 | # Convert new_bar to DataFrame row |
| 264 | new_row = pd.DataFrame([new_bar]) |
| 265 | |
| 266 | # Get current cache or create empty DataFrame |
| 267 | if symbol in self._cache and not self._cache[symbol].empty: |
| 268 | cached_df = self._cache[symbol] |
| 269 | |
| 270 | # Check if this bar already exists (by timestamp and id if available) |
| 271 | if 'id' in new_bar and 'id' in cached_df.columns: |
| 272 | if new_bar['id'] in cached_df['id'].values: |
| 273 | # Bar already in cache, skip |
| 274 | return |
| 275 | |
| 276 | # Append new bar to cache |
| 277 | cached_df = pd.concat([cached_df, new_row], ignore_index=True) |
| 278 | |
| 279 | # Sort by timestamp and id to maintain order |
| 280 | if 'timestamp' in cached_df.columns: |
| 281 | cached_df = cached_df.sort_values('timestamp', ascending=True) |
| 282 | if 'id' in cached_df.columns: |
| 283 | cached_df = cached_df.sort_values(['timestamp', 'id'], ascending=True) |
| 284 | |
| 285 | # Remove oldest bars if cache exceeds limit |
| 286 | if len(cached_df) > self._cache_limit: |
| 287 | cached_df = cached_df.tail(self._cache_limit).reset_index(drop=True) |
| 288 | |
| 289 | self._cache[symbol] = cached_df |
| 290 | else: |
| 291 | # Cache is empty, just set the new bar |
| 292 | self._cache[symbol] = new_row |
| 293 | |
| 294 | except Exception as e: |
| 295 | logger.warning(f"Failed to update bars cache for {symbol}: {e}") |
| 296 | # On error, invalidate cache to force reload from database next time |
| 297 | if symbol in self._cache: |
| 298 | del self._cache[symbol] |
| 299 | |
| 300 | async def get_recent_bars(self, symbol: str, limit: int = 200) -> pd.DataFrame: |
| 301 | """Get recent bars data for calculating technical indicators. |
no test coverage detected