den4ik2003

Untitled

Feb 6th, 2026
718
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.83 KB | None | 0 0
  1. import asyncio
  2. import sys
  3. import aiopg
  4. import time
  5. import json
  6. from configparser import ConfigParser
  7. from datetime import timezone, timedelta
  8.  
  9.  
  10. class TargetPriceFetcher:
  11.  
  12.     def __init__(self, path_to_config, max_connections=3):
  13.         parser = ConfigParser()
  14.         parser.read(path_to_config)
  15.  
  16.         self.db_params = {}
  17.         if parser.has_section('postgresql'):
  18.             params = parser.items('postgresql')
  19.             for param in params:
  20.                 self.db_params[param[0]] = param[1]
  21.  
  22.         self.pool = None
  23.         self.max_connections = max_connections
  24.  
  25.     async def init_pool(self):
  26.         if self.pool is None:
  27.             self.pool = await aiopg.create_pool(**self.db_params, minsize=1, maxsize=self.max_connections)
  28.  
  29.     async def get_target_prices_by_group(self, group_id):
  30.         """
  31.        Получает target_price записи для заданного group_id и возвращает список
  32.        в формате [{"target_price": value, "timestamp": timestamp}, ...]
  33.        отсортированный по возрастанию timestamp
  34.        """
  35.         query = f"""
  36.            SELECT target_price, EXTRACT(epoch FROM time) as timestamp
  37.            FROM target_price
  38.            WHERE group_id = {group_id}
  39.            ORDER BY time ASC
  40.        """
  41.  
  42.         result = await self.execute_select(query)
  43.  
  44.         if not result:
  45.             return []
  46.  
  47.         target_prices = []
  48.         for row in result:
  49.             row_str = row[0]
  50.             cleaned_str = row_str.strip('()')
  51.             parts = cleaned_str.split(',')
  52.  
  53.             if len(parts) >= 4:
  54.                 try:
  55.                     target_price = float(parts[1])
  56.                     timestamp = float(row[1])
  57.  
  58.                     target_prices.append({
  59.                         "target_price": target_price,
  60.                         "timestamp": timestamp
  61.                     })
  62.                 except (ValueError, IndexError) as e:
  63.                     print(f"Error parsing row {row}: {e}")
  64.                     continue
  65.  
  66.         return target_prices
  67.  
  68.     async def get_book_by_group(self, group_id):
  69.         """
  70.        Получает book записи для заданного group_id и возвращает список
  71.        в формате [{"bid_price": value, "ask_price": value, "timestamp": timestamp}, ...]
  72.        отсортированный по timestamp
  73.        """
  74.         query = f"""
  75.            SELECT bid_price, ask_price, EXTRACT(epoch FROM time) as timestamp
  76.            FROM book_{group_id}
  77.            ORDER BY time ASC
  78.        """
  79.  
  80.         result = await self.execute_select(query)
  81.  
  82.         if not result:
  83.             return []
  84.  
  85.         book_data = []
  86.         for row in result:
  87.             bid_price = float(row[0])
  88.             ask_price = float(row[1])
  89.             timestamp = float(row[2])
  90.  
  91.             book_data.append({
  92.                 "bid_price": bid_price,
  93.                 "ask_price": ask_price,
  94.                 "timestamp": timestamp
  95.             })
  96.  
  97.         return book_data
  98.  
  99.     async def execute_select(self, query):
  100.         try:
  101.             async with self.pool.acquire() as conn:
  102.                 async with conn.cursor() as cursor:
  103.                     await cursor.execute(query)
  104.                     return await cursor.fetchall()
  105.         except Exception as e:
  106.             print(f'[EXCEPTION] execute_select: {e}')
  107.             return []
  108.  
  109.     async def close_connection(self):
  110.         if self.pool:
  111.             self.pool.close()
  112.             await self.pool.wait_closed()
  113.             self.pool = None
  114.  
  115.  
  116. async def main():
  117.     if len(sys.argv) != 3:
  118.         print("Usage: python target_price_fetcher.py <config_path> <group_id>")
  119.         sys.exit(1)
  120.  
  121.     config_path = sys.argv[1]
  122.     group_id = int(sys.argv[2])
  123.  
  124.     fetcher = TargetPriceFetcher(config_path)
  125.     await fetcher.init_pool()
  126.  
  127.     try:
  128.         target_prices = await fetcher.get_target_prices_by_group(group_id)
  129.  
  130.         tp_filename = f"tp_{group_id}.json"
  131.         with open(tp_filename, 'w', encoding='utf-8') as f:
  132.             json.dump(target_prices, f, indent=2, ensure_ascii=False)
  133.  
  134.         print(f"Target price данные сохранены в файл: {tp_filename}")
  135.         print(f"Всего target price записей: {len(target_prices)}")
  136.  
  137.         book_data = await fetcher.get_book_by_group(group_id)
  138.  
  139.         book_filename = f"book_{group_id}.json"
  140.         with open(book_filename, 'w', encoding='utf-8') as f:
  141.             json.dump(book_data, f, indent=2, ensure_ascii=False)
  142.  
  143.         print(f"Book данные сохранены в файл: {book_filename}")
  144.         print(f"Всего book записей: {len(book_data)}")
  145.  
  146.     finally:
  147.         await fetcher.close_connection()
  148.  
  149.  
  150. if __name__ == "__main__":
  151.     asyncio.run(main())
  152.  
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment