den4ik2003

Untitled

Feb 6th, 2026
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 7.72 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.    Класс для извлечения данных о ценах из базы данных.
  13.  
  14.    Логика работы:
  15.    1. По имени биржи находит exchange_id в таблице exchanges
  16.    2. По паре (base_quote) и exchange_id находит symbol_id в таблице symbols
  17.    3. По symbol_id находит group_id в таблице id_group_relation
  18.    4. Извлекает target_price данные по group_id из таблицы target_price
  19.    5. Извлекает book данные по symbol_id из таблицы book_<symbol_id>
  20.    """
  21.  
  22.     def __init__(self, path_to_config, max_connections=3):
  23.         parser = ConfigParser()
  24.         parser.read(path_to_config)
  25.  
  26.         self.db_params = {}
  27.         if parser.has_section('postgresql'):
  28.             params = parser.items('postgresql')
  29.             for param in params:
  30.                 self.db_params[param[0]] = param[1]
  31.  
  32.         self.pool = None
  33.         self.max_connections = max_connections
  34.  
  35.     async def init_pool(self):
  36.         if self.pool is None:
  37.             self.pool = await aiopg.create_pool(**self.db_params, minsize=1, maxsize=self.max_connections)
  38.  
  39.     async def get_target_prices_by_group(self, group_id):
  40.         """
  41.        Получает target_price записи для заданного group_id и возвращает список
  42.        в формате [{"target_price": value, "timestamp": timestamp}, ...]
  43.        отсортированный по возрастанию timestamp
  44.        """
  45.         query = f"""
  46.            SELECT target_price, EXTRACT(epoch FROM time) as timestamp
  47.            FROM target_price
  48.            WHERE group_id = {group_id}
  49.            ORDER BY time ASC
  50.        """
  51.  
  52.         result = await self.execute_select(query)
  53.  
  54.         if not result:
  55.             return []
  56.  
  57.         target_prices = []
  58.         for row in result:
  59.             row_str = row[0]
  60.             cleaned_str = row_str.strip('()')
  61.             parts = cleaned_str.split(',')
  62.  
  63.             if len(parts) >= 4:
  64.                 try:
  65.                     target_price = float(parts[1])
  66.                     timestamp = float(row[1])
  67.  
  68.                     target_prices.append({
  69.                         "target_price": target_price,
  70.                         "timestamp": timestamp
  71.                     })
  72.                 except (ValueError, IndexError) as e:
  73.                     print(f"Error parsing row {row}: {e}")
  74.                     continue
  75.  
  76.         return target_prices
  77.  
  78.     async def get_exchange_id(self, exchange_name):
  79.         """Получает exchange_id по имени биржи"""
  80.         query = f"""
  81.            SELECT exchange_id
  82.            FROM exchanges
  83.            WHERE exchange_name = '{exchange_name}'
  84.        """
  85.         result = await self.execute_select(query)
  86.         return result[0][0] if result else None
  87.  
  88.     async def get_symbol_id(self, base, quote, exchange_id):
  89.         """Получает symbol_id по base, quote и exchange_id"""
  90.         query = f"""
  91.            SELECT symbol_id
  92.            FROM symbols
  93.            WHERE base = '{base}' AND quote = '{quote}' AND exchange_id = {exchange_id}
  94.        """
  95.         result = await self.execute_select(query)
  96.         return result[0][0] if result else None
  97.  
  98.     async def get_group_id(self, symbol_id):
  99.         """Получает group_id по symbol_id из таблицы id_group_relation"""
  100.         query = f"""
  101.            SELECT group_id
  102.            FROM id_group_relation
  103.            WHERE symbol_id = {symbol_id}
  104.        """
  105.         result = await self.execute_select(query)
  106.         return result[0][0] if result else None
  107.  
  108.     async def get_book_by_symbol(self, symbol_id):
  109.         """
  110.        Получает book записи для заданного symbol_id и возвращает список
  111.        в формате [{"bid_price": value, "ask_price": value, "timestamp": timestamp}, ...]
  112.        отсортированный по timestamp
  113.        """
  114.         query = f"""
  115.            SELECT bid_price, ask_price, EXTRACT(epoch FROM time) as timestamp
  116.            FROM book_{symbol_id}
  117.            ORDER BY time ASC
  118.        """
  119.  
  120.         result = await self.execute_select(query)
  121.  
  122.         if not result:
  123.             return []
  124.  
  125.         book_data = []
  126.         for row in result:
  127.             bid_price = float(row[0])
  128.             ask_price = float(row[1])
  129.             timestamp = float(row[2])
  130.  
  131.             book_data.append({
  132.                 "bid_price": bid_price,
  133.                 "ask_price": ask_price,
  134.                 "timestamp": timestamp
  135.             })
  136.  
  137.         return book_data
  138.  
  139.     async def execute_select(self, query):
  140.         try:
  141.             async with self.pool.acquire() as conn:
  142.                 async with conn.cursor() as cursor:
  143.                     await cursor.execute(query)
  144.                     return await cursor.fetchall()
  145.         except Exception as e:
  146.             print(f'[EXCEPTION] execute_select: {e}')
  147.             return []
  148.  
  149.     async def close_connection(self):
  150.         if self.pool:
  151.             self.pool.close()
  152.             await self.pool.wait_closed()
  153.             self.pool = None
  154.  
  155.  
  156. async def main():
  157.     if len(sys.argv) != 3:
  158.         print("Usage: python target_price_fetcher.py <symbol_pair> <exchange_name>")
  159.         print("Example: python target_price_fetcher.py CHEX_USDT binance")
  160.         sys.exit(1)
  161.  
  162.     symbol_pair = sys.argv[1]
  163.     exchange_name = sys.argv[2]
  164.  
  165.     if '_' not in symbol_pair:
  166.         print("Error: Symbol pair must be in format BASE_QUOTE (e.g., CHEX_USDT)")
  167.         sys.exit(1)
  168.  
  169.     base, quote = symbol_pair.split('_', 1)
  170.  
  171.     fetcher = TargetPriceFetcher('/home/ubuntu/app/database.ini')
  172.     await fetcher.init_pool()
  173.  
  174.     try:
  175.         exchange_id = await fetcher.get_exchange_id(exchange_name)
  176.         if exchange_id is None:
  177.             print(f"Error: Exchange '{exchange_name}' not found")
  178.             return
  179.  
  180.         print(f"Found exchange_id: {exchange_id} for exchange '{exchange_name}'")
  181.  
  182.         symbol_id = await fetcher.get_symbol_id(base, quote, exchange_id)
  183.         if symbol_id is None:
  184.             print(f"Error: Symbol '{base}/{quote}' not found for exchange '{exchange_name}'")
  185.             return
  186.  
  187.         print(f"Found symbol_id: {symbol_id} for symbol '{base}/{quote}'")
  188.  
  189.         group_id = await fetcher.get_group_id(symbol_id)
  190.         if group_id is None:
  191.             print(f"Error: Group not found for symbol_id {symbol_id}")
  192.             return
  193.  
  194.         print(f"Found group_id: {group_id} for symbol_id {symbol_id}")
  195.  
  196.         target_prices = await fetcher.get_target_prices_by_group(group_id)
  197.  
  198.         tp_filename = f"tp_{symbol_pair}_{exchange_name}.json"
  199.         with open(tp_filename, 'w', encoding='utf-8') as f:
  200.             json.dump(target_prices, f, indent=2, ensure_ascii=False)
  201.  
  202.         print(f"Target price данные сохранены в файл: {tp_filename}")
  203.         print(f"Всего target price записей: {len(target_prices)}")
  204.  
  205.         book_data = await fetcher.get_book_by_symbol(symbol_id)
  206.  
  207.         book_filename = f"book_{symbol_pair}_{exchange_name}.json"
  208.         with open(book_filename, 'w', encoding='utf-8') as f:
  209.             json.dump(book_data, f, indent=2, ensure_ascii=False)
  210.  
  211.         print(f"Book данные сохранены в файл: {book_filename}")
  212.         print(f"Всего book записей: {len(book_data)}")
  213.  
  214.     finally:
  215.         await fetcher.close_connection()
  216.  
  217.  
  218. if __name__ == "__main__":
  219.     asyncio.run(main())
  220.  
Advertisement
Add Comment
Please, Sign In to add comment