From e3f34cd57c16719f603838d058b16d4ad2c516a8 Mon Sep 17 00:00:00 2001 From: cuizhan <3971687@qq.com> Date: Tue, 9 Dec 2025 17:32:01 +0800 Subject: [PATCH] =?UTF-8?q?refactor:=20ORM=E6=A8=A1=E5=9E=8B=E9=87=8D?= =?UTF-8?q?=E6=9E=84=20+=20=E6=9C=8D=E5=8A=A1=E7=AE=A1=E7=90=86=E5=99=A8?= =?UTF-8?q?=20+=20QMT=E6=95=B0=E6=8D=AE=E4=B8=8B=E8=BD=BD=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 主要变更: - 重构 models: 统一使用 SQLAlchemy ORM,分离 Pydantic schemas - 新增 service_manager: 服务启动/停止统一管理 - 新增 data_downloader: 基于 xtquant 的数据下载服务 - 简化 main.py: 只启动必要服务 (Redis, Database) - 更新 .gitignore: 排除 xtquant 数据目录 --- .gitignore | 5 + configs/settings.yaml | 10 +- learning_matirals/MA实盘.py | 259 ++++++++++++ learning_matirals/XTDataSynchronizer.py | 284 +++++++++++++ .../download_data_from_xtquant.py | 7 + scripts/test_data_download.py | 165 ++++++++ src/console/windows/main_window.py | 29 +- src/console/windows/pages/dashboard_page.py | 28 +- src/console/windows/pages/logs_page.py | 6 +- src/console/windows/pages/services_page.py | 64 ++- src/console/windows/pages/settings_page.py | 16 +- src/console/windows/pages/strategies_page.py | 35 +- src/core/config.py | 2 + src/core/database.py | 45 +- src/core/models/__init__.py | 78 +++- src/core/models/balance_log.py | 92 +++++ src/core/models/base.py | 145 +++++++ src/core/models/kline.py | 172 ++++++++ src/core/models/market.py | 100 ----- src/core/models/order.py | 224 ++++++---- src/core/models/pairing.py | 167 ++++++++ src/core/models/position.py | 240 ++++++++--- src/core/models/signal.py | 165 ++++++-- src/core/models/symbol_strategy.py | 113 ----- src/core/schemas/__init__.py | 39 ++ src/core/schemas/kline.py | 53 +++ src/core/schemas/order.py | 73 ++++ src/core/schemas/pairing.py | 68 ++++ src/core/schemas/position.py | 53 +++ src/core/schemas/signal.py | 59 +++ src/core/service_manager.py | 321 +++++++++++++++ src/core_service/routes/order.py | 3 +- src/core_service/routes/pairing.py | 3 +- src/core_service/services/balance_service.py | 214 ++++------ src/core_service/services/order_service.py | 385 ++++++------------ src/core_service/services/pairing_service.py | 235 ++++------- src/core_service/services/position_service.py | 162 +++----- src/data_service/services/kline_service.py | 127 +++--- src/gateway/routes/account.py | 3 +- src/gateway/routes/trading.py | 3 +- src/main.py | 224 ++-------- src/qmt_adapter/services/__init__.py | 20 + src/qmt_adapter/services/data_downloader.py | 332 +++++++++++++++ src/strategy_engine/routes/signal.py | 2 +- src/strategy_engine/services/base_strategy.py | 2 +- .../services/signal_manager.py | 156 +++---- .../services/strategy_executor.py | 2 +- 47 files changed, 3462 insertions(+), 1528 deletions(-) create mode 100644 learning_matirals/MA实盘.py create mode 100644 learning_matirals/XTDataSynchronizer.py create mode 100644 learning_matirals/download_data_from_xtquant.py create mode 100644 scripts/test_data_download.py create mode 100644 src/core/models/balance_log.py create mode 100644 src/core/models/base.py create mode 100644 src/core/models/kline.py delete mode 100644 src/core/models/market.py create mode 100644 src/core/models/pairing.py delete mode 100644 src/core/models/symbol_strategy.py create mode 100644 src/core/schemas/__init__.py create mode 100644 src/core/schemas/kline.py create mode 100644 src/core/schemas/order.py create mode 100644 src/core/schemas/pairing.py create mode 100644 src/core/schemas/position.py create mode 100644 src/core/schemas/signal.py create mode 100644 src/core/service_manager.py create mode 100644 src/qmt_adapter/services/data_downloader.py diff --git a/.gitignore b/.gitignore index 06edf66..e498b22 100644 --- a/.gitignore +++ b/.gitignore @@ -8,7 +8,12 @@ __pycache__/ *.so*.py[cod]*.py[cod] +# XtQuant 数据目录 +data/datadir/ +data/data/ +# Dump files +*.dmp # Virtual Environment*$py.class*$py.class diff --git a/configs/settings.yaml b/configs/settings.yaml index 1f0ac2b..49dc535 100644 --- a/configs/settings.yaml +++ b/configs/settings.yaml @@ -57,7 +57,15 @@ qmt: # 资金账号 account_id: "" # 是否启用模拟模式 - simulation: true + simulation: false + # 数据中心 Token (用于 xtquant 独立数据下载,从迅投申请) + data_token: "e83d8eec5226c0b4db4a1d40830e09e4ffe73e15" + # 优化地址列表 (可选) + optimize_addresses: + - "115.231.218.73:55310" + - "115.231.218.79:55310" + - "218.16.123.11:55310" + - "218.16.123.27:55310" # 日志配置 logging: diff --git a/learning_matirals/MA实盘.py b/learning_matirals/MA实盘.py new file mode 100644 index 0000000..ef0d11e --- /dev/null +++ b/learning_matirals/MA实盘.py @@ -0,0 +1,259 @@ +#coding:gbk +import pandas as pd +import numpy as np +import talib +from datetime import datetime,timedelta +import requests +import json +import time + + +class TradeHelper: + def __init__(self): + self.periods = ['1m','5m','1d'] + self.accId = "510800046918" + self.fields = ["open","high","low","close","volume","amount"] + self.headers = { + "Content-Type": "application/json; charset=UTF-8" + } + self.api = "http://localhost:5000/api/v1" + self.state = {} + self.stocks ={} + + def initialize(self,C): + print('Start function "TradeHelper.initialize"') + url = self.api + "/trade/all_stocks" + self.stocks = json.loads(requests.get(url,headers = self.headers).text) + C.set_universe(list(self.stocks.keys())) + print(f'Done function "initialize". count={len(self.stocks.keys())}') + + def get_history_data_byperiod(self,C, stock, period,start_time,end_time,count=-1): + try: + prices = C.get_market_data_ex(helper.fields,[stock], + start_time = start_time, end_time = end_time, + period = period,count=count,dividend_type='front',fill_data=True,subscribe=True) + if stock in prices and len(prices[stock].index)==0: + print(f'Download history data. stock={stock}, period={period}, base_eriod={period}') + download_history_data(stock, period,start_time,end_time) + prices = C.get_market_data_ex(self.fields,[stock], + start_time = start_time, end_time = end_time, + period = period,count=count,dividend_type='front',fill_data=True,subscribe=True) + print(f'Retrieved {len(prices[stock].index)} items after download') + return self.convert_to_kdata(stock, period, prices[stock]) + except BaseException as error: + print(f'Error occured on get history data. stock={stock}, period={period}, Error={error}') + return None + + def convert_to_kdata(self, stock, period, prices): + kdata = [] + for index,row in prices.iterrows(): + kdata.append({ + "code": stock, + "datetime":index, + "period": period, + "open":row['open'], + "high":row['high'], + "low":row['low'], + "close":row['close'], + "volume":row['volume'], + "amount":row['amount'] + }) + return kdata + + def detect_bs_signal(self,C): + kdata = [] + bartime = timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") + + #period = '1m' + #prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()), \ + # start_time = "", end_time = bartime, \ + # period = period,count=1,dividend_type='none',fill_data=True,subscribe=True) + #for stock in prices.keys(): + # for item in self.convert_to_kdata(stock, period, prices[stock]): + # kdata.append(item) + + period = '5m' + prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()),start_time = "", end_time = bartime, + period = period,count=1,dividend_type='front',fill_data=True,subscribe=True) + for stock in prices.keys(): + for item in self.convert_to_kdata(stock, period, prices[stock]): + kdata.append(item) + + period ='1d' + prices = C.get_market_data_ex(helper.fields,list(self.stocks.keys()),start_time = "", end_time = bartime, + period = period,count=1,dividend_type='front',fill_data=True,subscribe=True) + for stock in prices.keys(): + for item in self.convert_to_kdata(stock, period, prices[stock]): + kdata.append(item) + acct_info = get_trade_detail_data(self.accId,'stock', 'account') + url = self.api + "/bssignal/detect" + data = json.dumps({ + 'realTime': bartime, + 'kdata':kdata, + 'positionInfos': self.get_position_infos(C), + 'allowTrade': True, + 'account':{ + 'Balance': acct_info[0].m_dBalance, + 'available': acct_info[0].m_dAvailable, + } + }) + + if len(kdata)==0: + return None + responseBody = requests.post(url,data = data,headers=self.headers).text + return json.loads(responseBody) + + def get_can_use_volume(self,stock, C): + for item in get_trade_detail_data(self.accId, 'stock', 'position',"TRADEHELPER"): + position_stock = f"{item.m_strInstrumentID}.{item.m_strExchangeID}" + if position_stock == stock: + return item.m_nCanUseVolume + return 0 + + def get_position_infos(self,C): + position_infos = [] + for item in get_trade_detail_data(self.accId, 'stock', 'position',"TRADEHELPER"): + stock = f"{item.m_strInstrumentID}.{item.m_strExchangeID}" + position_infos.append({"code":stock, + "canUseVolume":item.m_nCanUseVolume, + "volume":item.m_nVolume, + "price":item.m_dOpenPrice, + "profit":item.m_dPositionProfit, + "profitRate":item.m_dProfitRate}) + return position_infos + + def sync_order_details(self,C,dealInfo): + print(f'Start function "sync_order_details".') + stock = f'{dealInfo.m_strInstrumentID}.{dealInfo.m_strExchangeID}' + url = url = self.api + f"/trade/dealsync/{stock}/{dealInfo.m_strOrderSysID}" + barRealTime = timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") + data = json.dumps({ + 'dealPrice': dealInfo.m_dPrice, + 'bsDirection': dealInfo.m_nOffsetFlag, + 'dealTime':dealInfo.m_strTradeTime, + 'dealDate':dealInfo.m_strTradeDate, + 'barRealTime': barRealTime, + 'volume': dealInfo.m_nVolume + }) + print(f'requestUrl:{url} requestBody:{data}') + responseBody = requests.patch(url,data = data,headers=self.headers).text + print(f'Done {responseBody}') + + + +helper = TradeHelper() + +def init(C): + print(f'Start function "init".') + helper.initialize(C) + C.set_account(helper.accId) + print(C.get_universe()) + print(f'Done function "init".') + + +def handlebar(C): + if C.is_last_bar()==False: + return + else: + print(f'Start function "handlebar", Bar:{get_bar_realtime(C,1)}') + signals = helper.detect_bs_signal(C) + if signals ==None: + print('Invalid BSSignal..') + return + acct_info = get_trade_detail_data(helper.accId,'stock', 'account') + print(f"balance {round(acct_info[0].m_dBalance,2)}, m_dAvailable:{round(acct_info[0].m_dAvailable,2)}") + for stock in signals: + bsas = signals[stock] + limit = bsas["limit"] + amount =min(acct_info[0].m_dBalance * limit,acct_info[0].m_dAvailable) + volume = bsas["volume"] + #½¨²Ö + if bsas["direction"]==48: + if amount>=20000: + passorder(23, 1102, helper.accId, stock, 5, 0,amount, 2, C) + print(f"ÂòÈë {stock}") + else: + print(f'[ÂòÈë]¿ÉÓÃ×ʽð²»×ã. µ±ǰ¿ÉÓÃ×ʽð:{amount}') + elif bsas["direction"]==51: #¼ӲÖ + # °´ {amount} ½ð¶î¼ӲÖ + if amount>=20000: + passorder(23, 1102, helper.accId, stock, 5, 0,amount, 2, C) + print('append') + else: + print(f'[¼ӲÖ]¿ÉÓÃ×ʽð²»×ã. µ±ǰ¿ÉÓÃ×ʽð:{amount}') + elif bsas["direction"]==52: #¼õ²Ö + # # °´ {volume} ³ֹÉÊýÁ¿ ¼õ²Ö + passorder(24, 1101, helper.accId, stock, 14, -1, volume, '¼õ²ÖģÐÍ', 2, '', C) + elif bsas["direction"]==49: + volume = helper.get_can_use_volume(stock,C) + if volume > 0: + passorder(24, 1101, helper.accId, stock, 14, -1, volume, '¼õ²ÖģÐÍ', 2, '', C) + else: + pass + + + + + +def get_bar_realtime(C,mode = 0): + if mode == 1: + return timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y-%m-%d %H:%M:%S") + else: + return timetag_to_datetime(C.get_bar_timetag(C.barpos),"%Y%m%d%H%M%S") + +def deal_callback(C, dealInfo): + helper.sync_order_details(C,dealInfo) + print('=========== dealInfo ============================================') + print("×ʽðÕ˺Å" ,dealInfo.m_strAccountID) + print("½»Ò×Ëù´úÂë" ,dealInfo.m_strExchangeID) + print("½»Ò×ËùÃû³Æ" ,dealInfo.m_strExchangeName) + print("ƷÖִúÂë" ,dealInfo.m_strProductID) + print("ƷÖÖÃû³Æ" ,dealInfo.m_strProductName) + print("֤ȯ´úÂë" ,dealInfo.m_strInstrumentID) + print("֤ȯÃû³Æ" ,dealInfo.m_strInstrumentName) + print("³ɽ»±àºÅ" ,dealInfo.m_strTradeID) + print("ÈÎÎñºÅ" ,dealInfo.m_nTaskId) + print("ϵ¥ÒýÓ㬵ÈÓڹÉƱµÄÄڲ¿ίÍкÅ" ,dealInfo.m_strOrderRef) + print("ºÏͬ±àºţ¬±¨µ¥±àºţ¬ίÍкÅ" ,dealInfo.m_strOrderSysID) + print("¿ªƽ£¬¹ÉƱµÄÂòÂô" ,dealInfo.m_nOffsetFlag) + print("³ɽ»¾ù¼Û" ,dealInfo.m_dPrice) + print("³ɽ»Á¿" ,dealInfo.m_nVolume) + print("³ɽ»ÈÕÆÚ" ,dealInfo.m_strTradeDate) + print("³ɽ»ʱ¼ä" ,dealInfo.m_strTradeTime) + print("ÊÖÐø·Ñ" ,dealInfo.m_dComssion) + print("³ɽ»¶î" ,dealInfo.m_dTradeAmount) + print("ºÏԼ±àºÅ" ,dealInfo.m_strCompactNo) + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/learning_matirals/XTDataSynchronizer.py b/learning_matirals/XTDataSynchronizer.py new file mode 100644 index 0000000..1c34412 --- /dev/null +++ b/learning_matirals/XTDataSynchronizer.py @@ -0,0 +1,284 @@ +import time +import pandas as pd +import numpy as np +from datetime import datetime, timedelta +import json +import requests +from xtquant import xtdata +from xtquant import xtdatacenter as xtdc + +import schedule + +class XTDataSynchronizer: + def __init__(self): + xtdc.set_token('e83d8eec5226c0b4db4a1d40830e09e4ffe73e15') + xtdc.init() + xtdc.set_allow_optmize_address(['115.231.218.73:55310', '115.231.218.79:55310', '218.16.123.11:55310', '218.16.123.27:55310']) + xtdata.download_sector_data() + xtdata.download_history_contracts() + self.headers = { + "Content-Type": "application/json; charset=UTF-8" + } + self.api = "http://localhost:5000/api/v1" + self.fields = ["open","high","low","close","volume","amount"] + self.concepts = self.get_concepts() + self.start_time =(datetime.now() - timedelta(days=120)).strftime("%Y%m%d") + self.end_time = (datetime.now() + timedelta(days=1)).strftime("%Y%m%d") #'20240311' + self.download(self.concepts) + + def run(self): + for concept in self.concepts: + xtdata.subscribe_quote(concept, period='1d', start_time='', end_time='', count=1, callback=None) + schedule.clear() + schedule.every(60*2).seconds.do(self.sync) + now = datetime.now().strftime('%Y-%m-%d%H:%M:%S') + while True: + schedule.run_pending() + + + def download(self, stocks): + for stock in stocks: + xtdata.download_history_data(stock, '1d', self.start_time, self.end_time) + + def get_concepts(self): + url = f"{self.api}/trade/all_concepts" + concepts = [] + conceptDtos = json.loads(requests.get(url,headers = self.headers).text) + for concept in conceptDtos: + concepts.append(concept['conceptCode']) + print(f'concepts: {conceptDtos}') + return concepts + + def get_stocks(self): + url = f"{self.api}/trade/all_stocks" + stocks = [] + stockdtos = json.loads(requests.get(url,headers = self.headers).text) + for stock in stockdtos: + stocks.append(stock) + print(stocks) + return stocks + + + def get_xt_concept_infos(self): + concepts=[] + xt_sector_index_list = xtdata.get_stock_list_in_sector("概念指数") + for sector in xt_sector_index_list: + detail = xtdata.get_instrument_detail(sector) + InstrumentName = detail['InstrumentName'].replace("\r\n","") + concepts.append(f"{detail['InstrumentID']}.{detail['ExchangeID']}") + print(f",('{detail['InstrumentID']}.{detail['ExchangeID']}','{InstrumentName}')") + return concepts + + def get_stocks_in_sector(self,selector_code): + #f = open("D:\Workspace\stocks.txt", "a") + sector = xtdata.get_instrument_detail(selector_code) + sector_code = f"{sector['InstrumentID']}.{sector['ExchangeID']}" + sector_name = sector['InstrumentName'].replace("\r\n","") + stocks =[] + #f.write(f",('{sector_code}','{sector_name}','[]',1,2)\r") + print(f"--,('{sector_code}','{sector_name}','[]',1,2)") + for stock in xtdata.get_stock_list_in_sector(selector_code): + if stock.startswith('688') or stock.startswith('300') or \ + stock.startswith('900') or stock.endswith('.BJ') or stock.startswith('301'): + continue + detail = xtdata.get_instrument_detail(stock) + stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}" + stock_name = detail['InstrumentName'] + if stock_name.startswith('ST') or stock_name.startswith('*ST'): + continue + #concept = f'["000001.SH"]' + #if stock_code.endswith('.SZ'): + # concept=f'["399001.SZ"]' + concept = f'["{selector_code}"]' + #print(f",('{stock_code}','{stock_name}','{concept}',1,1,1)") + #f.write(f",('{stock_code}','{stock_name}','{concept}',1,1,1)\r") + stocks.append(stock_code) + #print(f"Stocks -> {len(stocks)}") + #f.close() + return stocks + + def sync(self,include_history=False): + calendars = [] + if include_history: + calendars = xtdata.get_trading_calendar('SH', self.start_time , self.end_time) + else: + self.start_time = (datetime.now() - timedelta(days=20)).strftime("%Y%m%d") + calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time)).iloc[-2:] + + for calendar in calendars: + print(f'Start sync kdata. bartime:{calendar}') + prices = xtdata.get_market_data_ex(field_list =self.fields , \ + stock_list = self.concepts, period = '1d', \ + start_time = calendar, end_time = calendar, \ + count = -1, dividend_type = 'none', fill_data = True) + for sector in prices.keys(): + kdata=[] + for item in self.convert_to_kdata(sector, '1d', prices[sector]): + kdata.append(item) + url = self.api + "/trade/kdata/sync" + data = json.dumps({'kdata':kdata}) + print(data) + responseBody = requests.post(url,data = data,headers=self.headers).text + print(responseBody) + + + def convert_to_kdata(self, stock, period, prices): + kdata = [] + for index,row in prices.iterrows(): + kdata.append({ + "code": stock, + "datetime":index, + "period": period, + "open":row['open'], + "high":row['high'], + "low":row['low'], + "close":row['close'], + "volume":row['volume'], + "amount":row['amount'] + }) + return kdata + + def convert_to_kdata2(self, stock, period, index, row): + if np.isnan(np.mean(row['open'])): + return None + + return { + "code": stock, + "datetime":index, + "period": period, + "open":row['open'], + "high":row['high'], + "low":row['low'], + "close":row['close'], + "volume":row['volume'], + "amount":row['amount'] + } + + + + def list_potential_stocks(self,concepts): + calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time)).iloc[-2:] + existing=[] + for concept in concepts: + detail = xtdata.get_instrument_detail(concept) + concept_name = detail['InstrumentName'] + stocks = self.get_stocks_in_sector(concept) + for stock in stocks: + if stock.startswith('688') or stock.startswith('300') or \ + stock.startswith('900') or stock.endswith('.BJ') or stock.startswith('301'): + continue + xtdata.download_history_data(stock, '1d', calendars.values[0], calendars.values[-1]) + + prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '1d', \ + start_time = calendars.values[0], end_time = calendars.values[-1], \ + count = -1, dividend_type = 'none', fill_data = True) + print(f"--{concept} {concept_name}") + for stock in prices.keys(): + if stock in existing: + continue + change_rate = (prices[stock].iloc[1]['close'] - prices[stock].iloc[0]['close']) / prices[stock].iloc[0]['close'] + if change_rate >=0.09: + detail = xtdata.get_instrument_detail(stock) + stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}" + stock_name = detail['InstrumentName'] + conceptx = f'["{concept}"]' + print(f",('{stock_code}','{stock_name}','{conceptx}',1,1,1)") + existing.append(stock) + + + def list_concept_data(self,concepts): + self.concepts=concepts + self.download(self.concepts) + self.sync(True) + + def sync_history(self): + stocks = self.get_stocks() + if len(stocks) == 0: + print("没有需要同步的股票代码") + return + + print(f"{self.start_time}, {self.end_time}") + calendars = pd.Series(xtdata.get_trading_calendar('SH', self.start_time , self.end_time)) + for stock in stocks: + xtdata.download_history_data(stock, '1d', calendars.values[0], calendars.values[-1]) + xtdata.download_history_data(stock, '5m', calendars.values[0], calendars.values[-1]) + + min5_prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '5m', \ + start_time = calendars.values[0], end_time = calendars.values[-1], \ + count = -1, dividend_type = 'front', fill_data = True) + + daily_prices = xtdata.get_market_data_ex(field_list =self.fields , stock_list = stocks, period = '1d', \ + start_time = calendars.values[0], end_time = calendars.values[-1], \ + count = -1, dividend_type = 'front', fill_data = True) + #convert_to_kdata2(self, stock, period, index, row): + for index in min5_prices[stocks[0]].index: + kdata = [] + for stock in min5_prices.keys(): + tempKdata = self.convert_to_kdata2(stock,'5m', index, min5_prices[stock].loc[index]) + if tempKdata is not None: + kdata.append(self.convert_to_kdata2(stock,'5m', index, min5_prices[stock].loc[index])) + + for stock in daily_prices.keys(): + daily_index = index[0:8] + tempKdata = self.convert_to_kdata2(stock,'1d',daily_index, daily_prices[stock].loc[daily_index]) + if tempKdata is not None: + kdata.append(self.convert_to_kdata2(stock,'1d',daily_index, daily_prices[stock].loc[daily_index])) + data = json.dumps({ + 'realTime': index, + 'kdata':kdata, + 'positionInfos': [], + 'allowTrade': False, + 'account':{ + 'Balance': 0, + 'available': 0, + } + }) + + url = self.api + "/bssignal/detect" + responseBody = requests.post(url,data = data,headers=self.headers).text + #time.sleep(2) + print(index) + + def get_kdata(self, stock,period): + url = f"{self.api}/trade/kdata/{period}/{stock}/100" + kdata = json.loads(requests.get(url,headers = self.headers).text) + index = [] + open=[] + high=[] + low=[] + close=[] + spike = [] + for item in kdata: + index.append(pd.to_datetime(item["dateTime"])) + open.append(item["open"]) + high.append(item["high"]) + low.append(item["low"]) + close.append(item["close"]) + spike.append(item["spike"]) + data = { + "DateTime":pd.Series(index), + "Open":pd.Series(open), + "High":pd.Series(high), + "Low":pd.Series(low), + "Close":pd.Series(close), + "Spike":pd.Series(spike) + } + df = pd.DataFrame(data) + df.set_index("DateTime",inplace=True) + return df + + def get_ret(self): + ret_sector_data = xtdata.get_stock_list_in_sector("沪深基金") + for stock in ret_sector_data: + detail = xtdata.get_instrument_detail(stock) + stock_code = f"{detail['InstrumentID']}.{detail['ExchangeID']}" + stock_name = detail['InstrumentName'] + print(f"('{stock_code}','{stock_name}','[]',1,1)") + + + + + + + + diff --git a/learning_matirals/download_data_from_xtquant.py b/learning_matirals/download_data_from_xtquant.py new file mode 100644 index 0000000..9a38d99 --- /dev/null +++ b/learning_matirals/download_data_from_xtquant.py @@ -0,0 +1,7 @@ +import sys + +from XTDataSynchronizer import XTDataSynchronizer +synchronizer = XTDataSynchronizer() +synchronizer.sync_history() +#sleep(5) +exit() diff --git a/scripts/test_data_download.py b/scripts/test_data_download.py new file mode 100644 index 0000000..22de632 --- /dev/null +++ b/scripts/test_data_download.py @@ -0,0 +1,165 @@ +""" +测试数据下载服务 + +下载两只股票的数据: +- 159915.SZ: 沪深300ETF +- 601288.SH: 农业银行 +""" + +import asyncio +import sys +from pathlib import Path + +# 添加项目根目录到 Python 路径 +project_root = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(project_root)) + +from src.qmt_adapter.services.data_downloader import data_downloader + + +async def test_download(): + """测试下载历史数据""" + + # 要下载的股票 + stocks = ["159915.SZ", "601288.SH"] + + print("=" * 60) + print("测试 XtQuant 数据下载服务") + print("=" * 60) + + # 1. 初始化 + print("\n[1] 初始化数据下载器...") + result = await data_downloader.init() + print(f"初始化结果: {result}") + + # 2. 获取股票信息 + print("\n[2] 获取股票信息...") + for stock in stocks: + info = await data_downloader.get_stock_info(stock) + print(f" {stock}: {info}") + + # 3. 获取交易日历 + print("\n[3] 获取最近交易日历...") + calendars = await data_downloader.get_trading_calendar() + print(f" 交易日数量: {len(calendars)}") + if calendars: + print(f" 最近5个交易日: {calendars[-5:]}") + + # 4. 下载日K线数据 + print("\n[4] 下载日K线数据 (最近30天)...") + daily_data = await data_downloader.download_history( + stocks=stocks, + period="1d", + days=30, + ) + + for stock, klines in daily_data.items(): + print(f"\n {stock}: {len(klines)} 条K线") + if klines: + print(f" 第一条: {klines[0]}") + print(f" 最后一条: {klines[-1]}") + + # 5. 下载5分钟K线数据 + print("\n[5] 下载5分钟K线数据 (最近5天)...") + min5_data = await data_downloader.download_history( + stocks=stocks, + period="5m", + days=5, + ) + + for stock, klines in min5_data.items(): + print(f"\n {stock}: {len(klines)} 条K线") + if klines: + print(f" 第一条: {klines[0]}") + print(f" 最后一条: {klines[-1]}") + + # 6. 获取实时行情 + print("\n[6] 获取实时行情...") + realtime = await data_downloader.download_realtime(stocks) + + for stock, tick in realtime.items(): + print(f"\n {stock}:") + print(f" 最新价: {tick.get('last_price')}") + print(f" 开盘价: {tick.get('open')}") + print(f" 最高价: {tick.get('high')}") + print(f" 最低价: {tick.get('low')}") + print(f" 成交量: {tick.get('volume')}") + + print("\n" + "=" * 60) + print("测试完成!") + print("=" * 60) + + return daily_data, min5_data + + +async def test_save_to_database(): + """测试保存到数据库""" + from src.core.database import db + from src.core.models import get_kline_model + from decimal import Decimal + from datetime import datetime + + stocks = ["159915.SZ", "601288.SH"] + + print("\n" + "=" * 60) + print("测试保存K线数据到数据库") + print("=" * 60) + + # 连接数据库 + print("\n[1] 连接数据库...") + await db.connect() + + # 下载数据 + print("\n[2] 下载日K线数据...") + daily_data = await data_downloader.download_history( + stocks=stocks, + period="1d", + days=30, + ) + + # 保存到数据库 + print("\n[3] 保存到数据库...") + Kline1d = get_kline_model("1d") + + async with db.session() as session: + for stock, klines in daily_data.items(): + for kline in klines: + # 解析时间 + time_str = kline["time"] + if len(time_str) == 8: # YYYYMMDD + kline_time = datetime.strptime(time_str, "%Y%m%d") + else: + kline_time = datetime.strptime(time_str[:14], "%Y%m%d%H%M%S") + + # 创建 ORM 对象 + obj = Kline1d( + symbol=kline["symbol"], + time=kline_time, + open=Decimal(str(kline["open"])), + high=Decimal(str(kline["high"])), + low=Decimal(str(kline["low"])), + close=Decimal(str(kline["close"])), + volume=kline["volume"], + amount=Decimal(str(kline["amount"])), + ) + session.add(obj) + + print(f" {stock}: 准备保存 {len(klines)} 条K线") + + await session.commit() + print(" 保存完成!") + + # 断开数据库 + await db.disconnect() + + print("\n" + "=" * 60) + print("数据库测试完成!") + print("=" * 60) + + +if __name__ == "__main__": + # 运行测试 + asyncio.run(test_download()) + + # 如果需要测试保存到数据库,取消下面的注释 + # asyncio.run(test_save_to_database()) diff --git a/src/console/windows/main_window.py b/src/console/windows/main_window.py index dcbecc8..d033d2a 100644 --- a/src/console/windows/main_window.py +++ b/src/console/windows/main_window.py @@ -63,7 +63,7 @@ class MainWindow(QMainWindow): self._content_stack = QStackedWidget() self._content_stack.setStyleSheet(""" QStackedWidget { - background-color: #f5f5f5; + background-color: #f7f7f7; } """) @@ -81,6 +81,11 @@ class MainWindow(QMainWindow): self._services_page._restart_all ) + # 连接服务运行数量变化信号 + self._services_page.running_count_changed.connect( + self._on_running_count_changed + ) + self._content_stack.addWidget(self._dashboard_page) self._content_stack.addWidget(self._services_page) self._content_stack.addWidget(self._strategies_page) @@ -98,7 +103,7 @@ class MainWindow(QMainWindow): frame.setFixedWidth(200) frame.setStyleSheet(""" QFrame { - background-color: #2c3e50; + background-color: #1a1a1a; } """) @@ -115,7 +120,7 @@ class MainWindow(QMainWindow): color: white; font-size: 24px; font-weight: bold; - background-color: #1a252f; + background-color: #0d0d0d; } """) layout.addWidget(logo_label) @@ -129,18 +134,18 @@ class MainWindow(QMainWindow): outline: none; } QListWidget::item { - color: #bdc3c7; + color: #999999; padding: 15px 20px; border-left: 3px solid transparent; } QListWidget::item:hover { - background-color: #34495e; + background-color: #2d2d2d; color: white; } QListWidget::item:selected { - background-color: #3498db; + background-color: #1a365d; color: white; - border-left: 3px solid #2980b9; + border-left: 3px solid #2d4a7c; } """) @@ -222,6 +227,16 @@ class MainWindow(QMainWindow): # 这里后续添加实际的状态检测逻辑 pass + def _on_running_count_changed(self, running: int, total: int) -> None: + """服务运行数量变化回调""" + self._services_label.setText(f"运行中服务: {running}/{total}") + if running == total: + self._services_label.setStyleSheet("color: #1a365d; font-weight: bold;") + elif running > 0: + self._services_label.setStyleSheet("color: #666666; font-weight: bold;") + else: + self._services_label.setStyleSheet("color: #999999;") + def _update_time(self) -> None: """更新时间显示""" from datetime import datetime diff --git a/src/console/windows/pages/dashboard_page.py b/src/console/windows/pages/dashboard_page.py index 94affd0..a376dba 100644 --- a/src/console/windows/pages/dashboard_page.py +++ b/src/console/windows/pages/dashboard_page.py @@ -38,7 +38,7 @@ class DashboardPage(QWidget): QLabel { font-size: 24px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) layout.addWidget(title) @@ -49,20 +49,20 @@ class DashboardPage(QWidget): # 服务状态卡片 self._services_card = self._create_stat_card( - "运行中服务", "0 / 5", "#3498db", "⚙️" + "运行中服务", "0 / 5", "#1a365d", "⛙️" ) cards_layout.addWidget(self._services_card) # 策略数量卡片 - self._strategies_card = self._create_stat_card("活跃策略", "0", "#2ecc71", "📈") + self._strategies_card = self._create_stat_card("活跃策略", "0", "#2d3748", "📈") cards_layout.addWidget(self._strategies_card) # 今日订单卡片 - self._orders_card = self._create_stat_card("今日订单", "0", "#e74c3c", "📝") + self._orders_card = self._create_stat_card("今日订单", "0", "#1a1a1a", "📝") cards_layout.addWidget(self._orders_card) # 今日盈亏卡片 - self._pnl_card = self._create_stat_card("今日盈亏", "¥0.00", "#9b59b6", "💰") + self._pnl_card = self._create_stat_card("今日盈亏", "¥0.00", "#4a5568", "💰") cards_layout.addWidget(self._pnl_card) layout.addLayout(cards_layout) @@ -83,7 +83,7 @@ class DashboardPage(QWidget): QLabel { font-size: 16px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) quick_layout.addWidget(quick_title) @@ -92,19 +92,19 @@ class DashboardPage(QWidget): buttons_layout.setSpacing(15) start_all_btn = QPushButton("🚀 一键启动全部") - start_all_btn.setStyleSheet(self._get_button_style("#27ae60")) + start_all_btn.setStyleSheet(self._get_button_style("#1a365d")) start_all_btn.setFixedHeight(45) start_all_btn.clicked.connect(self.start_all_requested.emit) buttons_layout.addWidget(start_all_btn) stop_all_btn = QPushButton("⏹️ 一键停止全部") - stop_all_btn.setStyleSheet(self._get_button_style("#e74c3c")) + stop_all_btn.setStyleSheet(self._get_button_style("#4a5568")) stop_all_btn.setFixedHeight(45) stop_all_btn.clicked.connect(self.stop_all_requested.emit) buttons_layout.addWidget(stop_all_btn) restart_all_btn = QPushButton("🔄 重启全部服务") - restart_all_btn.setStyleSheet(self._get_button_style("#3498db")) + restart_all_btn.setStyleSheet(self._get_button_style("#2d3748")) restart_all_btn.setFixedHeight(45) restart_all_btn.clicked.connect(self.restart_all_requested.emit) buttons_layout.addWidget(restart_all_btn) @@ -130,7 +130,7 @@ class DashboardPage(QWidget): QLabel { font-size: 16px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) status_layout.addWidget(status_title) @@ -214,7 +214,7 @@ class DashboardPage(QWidget): frame = QFrame() frame.setStyleSheet(""" QFrame { - background-color: #f8f9fa; + background-color: #f0f0f0; border-radius: 6px; padding: 10px; } @@ -225,21 +225,21 @@ class DashboardPage(QWidget): layout.setContentsMargins(15, 10, 15, 10) # 状态指示灯 - status_color = "#27ae60" if running else "#95a5a6" + status_color = "#1a365d" if running else "#999999" status_dot = QLabel("●") status_dot.setStyleSheet(f"color: {status_color}; font-size: 14px;") layout.addWidget(status_dot) # 服务名 name_label = QLabel(f"{name}") - name_label.setStyleSheet("font-weight: bold; color: #2c3e50;") + name_label.setStyleSheet("font-weight: bold; color: #1a1a1a;") layout.addWidget(name_label) layout.addStretch() # 端口 port_label = QLabel(f":{port}") - port_label.setStyleSheet("color: #7f8c8d;") + port_label.setStyleSheet("color: #666666;") layout.addWidget(port_label) return frame diff --git a/src/console/windows/pages/logs_page.py b/src/console/windows/pages/logs_page.py index 1589c56..812ec66 100644 --- a/src/console/windows/pages/logs_page.py +++ b/src/console/windows/pages/logs_page.py @@ -45,7 +45,7 @@ class LogsPage(QWidget): QLabel { font-size: 24px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) header_layout.addWidget(title) @@ -113,13 +113,13 @@ class LogsPage(QWidget): status_layout = QHBoxLayout() self._status_label = QLabel("就绪") - self._status_label.setStyleSheet("color: #7f8c8d;") + self._status_label.setStyleSheet("color: #666666;") status_layout.addWidget(self._status_label) status_layout.addStretch() self._line_count_label = QLabel("行数: 0") - self._line_count_label.setStyleSheet("color: #7f8c8d;") + self._line_count_label.setStyleSheet("color: #666666;") status_layout.addWidget(self._line_count_label) layout.addLayout(status_layout) diff --git a/src/console/windows/pages/services_page.py b/src/console/windows/pages/services_page.py index 91f1b2a..d2ca446 100644 --- a/src/console/windows/pages/services_page.py +++ b/src/console/windows/pages/services_page.py @@ -26,6 +26,7 @@ class ServiceChecker(QThread): """服务检查线程""" status_updated = pyqtSignal(str, bool) # service_name, is_running + check_completed = pyqtSignal(int, int) # running_count, total_count def __init__(self, services: list) -> None: super().__init__() @@ -34,6 +35,7 @@ class ServiceChecker(QThread): def run(self) -> None: """运行检查""" + running_count = 0 for name, port in self._services: if not self._running: break @@ -46,8 +48,13 @@ class ServiceChecker(QThread): except Exception: is_running = False + if is_running: + running_count += 1 self.status_updated.emit(name, is_running) + # 检查完成后发送运行数量 + self.check_completed.emit(running_count, len(self._services)) + def stop(self) -> None: """停止检查""" self._running = False @@ -56,6 +63,9 @@ class ServiceChecker(QThread): class ServicesPage(QWidget): """服务管理页面""" + # 运行服务数量变化信号 + running_count_changed = pyqtSignal(int, int) # running_count, total_count + SERVICES = [ ("gateway", "Gateway", 8001, "API 网关"), ("core_service", "Core Service", 8010, "核心服务"), @@ -67,6 +77,7 @@ class ServicesPage(QWidget): def __init__(self) -> None: super().__init__() self._processes: Dict[str, subprocess.Popen] = {} + self._running_count = 0 self._init_ui() # 状态检查定时器 @@ -91,7 +102,7 @@ class ServicesPage(QWidget): QLabel { font-size: 24px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) header_layout.addWidget(title) @@ -100,17 +111,17 @@ class ServicesPage(QWidget): # 全局操作按钮 start_all_btn = QPushButton("🚀 启动全部") - start_all_btn.setStyleSheet(self._get_button_style("#27ae60")) + start_all_btn.setStyleSheet(self._get_button_style("#1a365d")) start_all_btn.clicked.connect(self._start_all) header_layout.addWidget(start_all_btn) stop_all_btn = QPushButton("⏹️ 停止全部") - stop_all_btn.setStyleSheet(self._get_button_style("#e74c3c")) + stop_all_btn.setStyleSheet(self._get_button_style("#4a5568")) stop_all_btn.clicked.connect(self._stop_all) header_layout.addWidget(stop_all_btn) refresh_btn = QPushButton("🔄 刷新状态") - refresh_btn.setStyleSheet(self._get_button_style("#3498db")) + refresh_btn.setStyleSheet(self._get_button_style("#2d3748")) refresh_btn.clicked.connect(self._check_services) header_layout.addWidget(refresh_btn) @@ -142,19 +153,20 @@ class ServicesPage(QWidget): self._table.setStyleSheet(""" QTableWidget { background-color: white; - border: 1px solid #ddd; + border: 1px solid #e0e0e0; border-radius: 8px; - gridline-color: #eee; + gridline-color: #f0f0f0; } QTableWidget::item { padding: 10px; } QHeaderView::section { - background-color: #f8f9fa; + background-color: #f7f7f7; padding: 10px; border: none; - border-bottom: 1px solid #ddd; + border-bottom: 1px solid #e0e0e0; font-weight: bold; + color: #1a1a1a; } """) @@ -199,19 +211,19 @@ class ServicesPage(QWidget): btn_layout.setSpacing(5) start_btn = QPushButton("启动") - start_btn.setStyleSheet(self._get_small_button_style("#27ae60")) + start_btn.setStyleSheet(self._get_small_button_style("#1a365d")) start_btn.setProperty("service_key", key) start_btn.clicked.connect(lambda checked, k=key: self._start_service(k)) btn_layout.addWidget(start_btn) stop_btn = QPushButton("停止") - stop_btn.setStyleSheet(self._get_small_button_style("#e74c3c")) + stop_btn.setStyleSheet(self._get_small_button_style("#4a5568")) stop_btn.setProperty("service_key", key) stop_btn.clicked.connect(lambda checked, k=key: self._stop_service(k)) btn_layout.addWidget(stop_btn) log_btn = QPushButton("日志") - log_btn.setStyleSheet(self._get_small_button_style("#9b59b6")) + log_btn.setStyleSheet(self._get_small_button_style("#2d3748")) log_btn.clicked.connect(lambda checked, k=key: self._view_logs(k)) btn_layout.addWidget(log_btn) @@ -224,8 +236,14 @@ class ServicesPage(QWidget): services = [(name, port) for _, name, port, _ in self.SERVICES] self._checker = ServiceChecker(services) self._checker.status_updated.connect(self._on_status_updated) + self._checker.check_completed.connect(self._on_check_completed) self._checker.start() + def _on_check_completed(self, running: int, total: int) -> None: + """检查完成回调,更新运行数量""" + self._running_count = running + self.running_count_changed.emit(running, total) + def _on_status_updated(self, name: str, is_running: bool) -> None: """状态更新回调""" for row in range(self._table.rowCount()): @@ -234,11 +252,11 @@ class ServicesPage(QWidget): if name_item is not None and name_item.text() == name: if status_item is not None: if is_running: - status_item.setText("✅ 运行中") - status_item.setForeground(QColor("#27ae60")) + status_item.setText("● 运行中") + status_item.setForeground(QColor("#1a365d")) else: - status_item.setText("⭕ 已停止") - status_item.setForeground(QColor("#95a5a6")) + status_item.setText("○ 已停止") + status_item.setForeground(QColor("#999999")) break def _start_service(self, service_key: str) -> None: @@ -250,11 +268,15 @@ class ServicesPage(QWidget): return try: - # 启动进程 + # 静默启动进程(不弹出黑色命令行窗口) + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + startupinfo.wShowWindow = subprocess.SW_HIDE proc = subprocess.Popen( ["python", "-m", "src.main", service_key], cwd=str(self._get_project_root()), - creationflags=subprocess.CREATE_NEW_CONSOLE, + startupinfo=startupinfo, + creationflags=subprocess.CREATE_NO_WINDOW, ) self._processes[service_key] = proc @@ -317,11 +339,15 @@ class ServicesPage(QWidget): return False try: - # 启动进程 + # 静默启动进程(不弹出黑色命令行窗口) + startupinfo = subprocess.STARTUPINFO() + startupinfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW + startupinfo.wShowWindow = subprocess.SW_HIDE proc = subprocess.Popen( ["python", "-m", "src.main", service_key], cwd=str(self._get_project_root()), - creationflags=subprocess.CREATE_NEW_CONSOLE, + startupinfo=startupinfo, + creationflags=subprocess.CREATE_NO_WINDOW, ) self._processes[service_key] = proc diff --git a/src/console/windows/pages/settings_page.py b/src/console/windows/pages/settings_page.py index 90c7f7e..e139936 100644 --- a/src/console/windows/pages/settings_page.py +++ b/src/console/windows/pages/settings_page.py @@ -40,7 +40,7 @@ class SettingsPage(QWidget): QLabel { font-size: 24px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) layout.addWidget(title) @@ -49,21 +49,23 @@ class SettingsPage(QWidget): tab_widget = QTabWidget() tab_widget.setStyleSheet(""" QTabWidget::pane { - border: 1px solid #ddd; + border: 1px solid #e0e0e0; border-radius: 8px; background-color: white; } QTabBar::tab { - background-color: #f8f9fa; + background-color: #f7f7f7; padding: 10px 20px; margin-right: 2px; border-top-left-radius: 6px; border-top-right-radius: 6px; + color: #666666; } QTabBar::tab:selected { background-color: white; - border: 1px solid #ddd; + border: 1px solid #e0e0e0; border-bottom: none; + color: #1a1a1a; } """) @@ -98,7 +100,7 @@ class SettingsPage(QWidget): save_btn.setFixedWidth(100) save_btn.setStyleSheet(""" QPushButton { - background-color: #3498db; + background-color: #1a365d; color: white; border: none; border-radius: 6px; @@ -106,7 +108,7 @@ class SettingsPage(QWidget): font-weight: bold; } QPushButton:hover { - background-color: #2980b9; + background-color: #2d4a7c; } """) save_btn.clicked.connect(self._save_config) @@ -224,7 +226,7 @@ class SettingsPage(QWidget): # 提示 tip = QLabel("提示: QMT 路径为 Mini QMT 的 userdata_mini 目录") - tip.setStyleSheet("color: #7f8c8d; font-size: 12px;") + tip.setStyleSheet("color: #666666; font-size: 12px;") layout.addWidget(tip) layout.addStretch() diff --git a/src/console/windows/pages/strategies_page.py b/src/console/windows/pages/strategies_page.py index edf77e2..03c1ef6 100644 --- a/src/console/windows/pages/strategies_page.py +++ b/src/console/windows/pages/strategies_page.py @@ -103,14 +103,14 @@ class AddPairingDialog(QDialog): confirm_btn.setFixedWidth(80) confirm_btn.setStyleSheet(""" QPushButton { - background-color: #3498db; + background-color: #1a365d; color: white; border: none; border-radius: 4px; padding: 8px; } QPushButton:hover { - background-color: #2980b9; + background-color: #2d4a7c; } """) confirm_btn.clicked.connect(self._on_confirm) @@ -234,7 +234,7 @@ class StrategiesPage(QWidget): QLabel { font-size: 24px; font-weight: bold; - color: #2c3e50; + color: #1a1a1a; } """) header_layout.addWidget(title) @@ -245,7 +245,7 @@ class StrategiesPage(QWidget): add_btn = QPushButton("➕ 新建配对") add_btn.setStyleSheet(""" QPushButton { - background-color: #27ae60; + background-color: #1a365d; color: white; border: none; border-radius: 6px; @@ -254,7 +254,7 @@ class StrategiesPage(QWidget): font-weight: bold; } QPushButton:hover { - background-color: #219a52; + background-color: #2d4a7c; } """) add_btn.clicked.connect(self._add_pairing) @@ -287,19 +287,20 @@ class StrategiesPage(QWidget): self._table.setStyleSheet(""" QTableWidget { background-color: white; - border: 1px solid #ddd; + border: 1px solid #e0e0e0; border-radius: 8px; - gridline-color: #eee; + gridline-color: #f0f0f0; } QTableWidget::item { padding: 10px; } QHeaderView::section { - background-color: #f8f9fa; + background-color: #f7f7f7; padding: 10px; border: none; - border-bottom: 1px solid #ddd; + border-bottom: 1px solid #e0e0e0; font-weight: bold; + color: #1a1a1a; } """) @@ -336,9 +337,9 @@ class StrategiesPage(QWidget): status_item = QTableWidgetItem(status) status_item.setTextAlignment(Qt.AlignmentFlag.AlignCenter) if status == "运行中": - status_item.setForeground(QColor("#27ae60")) + status_item.setForeground(QColor("#1a365d")) else: - status_item.setForeground(QColor("#95a5a6")) + status_item.setForeground(QColor("#999999")) self._table.setItem(row, 2, status_item) # 初始资金 @@ -354,9 +355,9 @@ class StrategiesPage(QWidget): Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter ) if pnl >= 0: - pnl_item.setForeground(QColor("#e74c3c")) + pnl_item.setForeground(QColor("#1a365d")) else: - pnl_item.setForeground(QColor("#27ae60")) + pnl_item.setForeground(QColor("#666666")) self._table.setItem(row, 4, pnl_item) # 操作按钮 @@ -367,19 +368,19 @@ class StrategiesPage(QWidget): if status == "运行中": pause_btn = QPushButton("暂停") - pause_btn.setStyleSheet(self._get_small_button_style("#f39c12")) + pause_btn.setStyleSheet(self._get_small_button_style("#4a5568")) btn_layout.addWidget(pause_btn) else: start_btn = QPushButton("启动") - start_btn.setStyleSheet(self._get_small_button_style("#27ae60")) + start_btn.setStyleSheet(self._get_small_button_style("#1a365d")) btn_layout.addWidget(start_btn) edit_btn = QPushButton("编辑") - edit_btn.setStyleSheet(self._get_small_button_style("#3498db")) + edit_btn.setStyleSheet(self._get_small_button_style("#2d3748")) btn_layout.addWidget(edit_btn) delete_btn = QPushButton("删除") - delete_btn.setStyleSheet(self._get_small_button_style("#e74c3c")) + delete_btn.setStyleSheet(self._get_small_button_style("#666666")) btn_layout.addWidget(delete_btn) self._table.setCellWidget(row, 5, btn_widget) diff --git a/src/core/config.py b/src/core/config.py index 3149939..07ecc1d 100644 --- a/src/core/config.py +++ b/src/core/config.py @@ -108,6 +108,8 @@ class QMTConfig(BaseModel): session_id: int = 123456 account_id: str = "" simulation: bool = True + data_token: str = "" # XtQuant 数据中心 Token + optimize_addresses: list[str] = [] # 数据中心优化地址 class LoggingFileConfig(BaseModel): diff --git a/src/core/database.py b/src/core/database.py index 0c8a006..adf5390 100644 --- a/src/core/database.py +++ b/src/core/database.py @@ -8,64 +8,23 @@ QTrade 数据库模块 """ from contextlib import asynccontextmanager -from datetime import datetime from typing import AsyncIterator, Optional -from sqlalchemy import MetaData, text +from sqlalchemy import text from sqlalchemy.ext.asyncio import ( AsyncEngine, AsyncSession, async_sessionmaker, create_async_engine, ) -from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column from .config import settings from .logger import get_logger +from .models.base import Base # 从 models 导入 Base logger = get_logger(__name__) -# 表命名规范 -convention = { - "ix": "ix_%(column_0_label)s", - "uq": "uq_%(table_name)s_%(column_0_name)s", - "ck": "ck_%(table_name)s_%(constraint_name)s", - "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", - "pk": "pk_%(table_name)s", -} - -metadata = MetaData(naming_convention=convention) - - -class Base(DeclarativeBase): - """ - ORM 基类 - - 所有数据模型继承此类 - """ - - metadata = metadata - - -class TimestampMixin: - """ - 时间戳混入类 - - 提供 created_at 和 updated_at 字段 - """ - - created_at: Mapped[datetime] = mapped_column( - default=datetime.now, - comment="创建时间", - ) - updated_at: Mapped[datetime] = mapped_column( - default=datetime.now, - onupdate=datetime.now, - comment="更新时间", - ) - - class Database: """ 异步数据库管理器 diff --git a/src/core/models/__init__.py b/src/core/models/__init__.py index 5d43cb4..4a5ce7a 100644 --- a/src/core/models/__init__.py +++ b/src/core/models/__init__.py @@ -1,14 +1,76 @@ """ -QTrade Data Models +QTrade ORM 模型 -数据模型模块,定义所有业务数据结构: -- market: 行情数据模型 +数据库 ORM 模型模块,定义所有数据库表结构: +- base: ORM 基类和通用混入 +- kline: K线数据模型 +- pairing: 股票-策略配对模型 - order: 订单模型 - position: 持仓模型 -- symbol_strategy: 股票-策略配对模型 +- signal: 交易信号模型 +- balance_log: 资金变动日志模型 """ -from .market import * -from .order import * -from .position import * -from .symbol_strategy import * +# ORM 基类 +from .base import Base, TimestampMixin + +# K线模型 +from .kline import ( + KlineBase, + Kline1m, + Kline5m, + Kline15m, + Kline30m, + Kline60m, + Kline1d, + KLINE_MODELS, + get_kline_model, +) + +# 配对模型 +from .pairing import Pairing, PairingStatus + +# 订单模型 +from .order import Order, OrderSide, OrderType, OrderStatus + +# 持仓模型 +from .position import Position + +# 信号模型 +from .signal import Signal, SignalSide, SignalStatus + +# 资金日志模型 +from .balance_log import BalanceLog, BalanceLogType + +__all__ = [ + # ORM 基类 + "Base", + "TimestampMixin", + # K线 + "KlineBase", + "Kline1m", + "Kline5m", + "Kline15m", + "Kline30m", + "Kline60m", + "Kline1d", + "KLINE_MODELS", + "get_kline_model", + # 配对 + "Pairing", + "PairingStatus", + # 订单 + "Order", + "OrderSide", + "OrderType", + "OrderStatus", + # 持仓 + "Position", + # 信号 + "Signal", + "SignalSide", + "SignalStatus", + # 资金日志 + "BalanceLog", + "BalanceLogType", +] diff --git a/src/core/models/balance_log.py b/src/core/models/balance_log.py new file mode 100644 index 0000000..5a346f4 --- /dev/null +++ b/src/core/models/balance_log.py @@ -0,0 +1,92 @@ +""" +资金日志 ORM 模型 + +包含: +- BalanceLogType: 资金变动类型枚举 +- BalanceLog: 资金变动日志表 +""" + +from datetime import datetime +from decimal import Decimal +from enum import Enum + +from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base + + +class BalanceLogType(str, Enum): + """资金变动类型""" + + DEPOSIT = "deposit" # 入金 + WITHDRAW = "withdraw" # 出金 + BUY = "buy" # 买入冻结/扣款 + SELL = "sell" # 卖出到账 + COMMISSION = "commission" # 手续费 + DIVIDEND = "dividend" # 分红 + ADJUST = "adjust" # 人工调整 + + +class BalanceLog(Base): + """ + 资金变动日志表 + + 记录配对账户的每一笔资金变动 + """ + + __tablename__ = "balance_logs" + + # 主键 + id: Mapped[int] = mapped_column( + primary_key=True, autoincrement=True, comment="日志ID" + ) + + # 关联 + pairing_id: Mapped[str] = mapped_column( + String(32), + ForeignKey("pairings.id", ondelete="CASCADE"), + nullable=False, + comment="配对ID", + ) + order_id: Mapped[str | None] = mapped_column(String(32), comment="关联订单ID") + + # 变动信息 + type: Mapped[str] = mapped_column(String(20), nullable=False, comment="变动类型") + amount: Mapped[Decimal] = mapped_column( + Numeric(16, 2), nullable=False, comment="变动金额" + ) + balance_before: Mapped[Decimal] = mapped_column( + Numeric(16, 2), comment="变动前余额" + ) + balance_after: Mapped[Decimal] = mapped_column(Numeric(16, 2), comment="变动后余额") + + # 说明 + reason: Mapped[str | None] = mapped_column(Text, comment="变动原因") + + # 时间 + created_at: Mapped[datetime] = mapped_column( + DateTime, default=datetime.now, comment="创建时间" + ) + + __table_args__ = ( + Index("ix_balance_logs_pairing_id", "pairing_id"), + Index("ix_balance_logs_type", "type"), + Index("ix_balance_logs_created_at", "created_at"), + ) + + def to_dict(self) -> dict: + """转换为字典""" + return { + "id": self.id, + "pairing_id": self.pairing_id, + "order_id": self.order_id, + "type": self.type, + "amount": float(self.amount), + "balance_before": float(self.balance_before) + if self.balance_before + else None, + "balance_after": float(self.balance_after) if self.balance_after else None, + "reason": self.reason, + "created_at": self.created_at.isoformat() if self.created_at else None, + } diff --git a/src/core/models/base.py b/src/core/models/base.py new file mode 100644 index 0000000..64941fc --- /dev/null +++ b/src/core/models/base.py @@ -0,0 +1,145 @@ +""" +ORM 模型基类 + +提供: +- Base: SQLAlchemy 声明式基类 +- ModelMixin: 通用方法混入 (to_dict, to_json, from_dict) +- TimestampMixin: 时间戳字段混入 +""" + +import json +from datetime import datetime +from decimal import Decimal +from enum import Enum +from typing import Any, TypeVar + +from sqlalchemy import MetaData +from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column + +# 表命名规范 +convention = { + "ix": "ix_%(column_0_label)s", + "uq": "uq_%(table_name)s_%(column_0_name)s", + "ck": "ck_%(table_name)s_%(constraint_name)s", + "fk": "fk_%(table_name)s_%(column_0_name)s_%(referred_table_name)s", + "pk": "pk_%(table_name)s", +} + +metadata = MetaData(naming_convention=convention) + +T = TypeVar("T", bound="Base") + + +class Base(DeclarativeBase): + """ + ORM 声明式基类 + + 所有数据模型继承此类 + """ + + metadata = metadata + + def to_dict(self, exclude: set[str] | None = None) -> dict[str, Any]: + """ + 转换为字典 + + Args: + exclude: 要排除的字段名集合 + + Returns: + 字典形式的数据 + """ + exclude = exclude or set() + result = {} + + for column in self.__table__.columns: + if column.name in exclude: + continue + + value = getattr(self, column.name) + + # 类型转换 + if isinstance(value, datetime): + value = value.isoformat() + elif isinstance(value, Decimal): + value = float(value) + elif isinstance(value, Enum): + value = value.value + + result[column.name] = value + + return result + + def to_json( + self, exclude: set[str] | None = None, indent: int | None = None + ) -> str: + """ + 转换为 JSON 字符串 + + Args: + exclude: 要排除的字段名集合 + indent: JSON 缩进 + + Returns: + JSON 字符串 + """ + return json.dumps(self.to_dict(exclude), ensure_ascii=False, indent=indent) + + @classmethod + def from_dict(cls: type[T], data: dict[str, Any]) -> T: + """ + 从字典创建实例 + + Args: + data: 字典数据 + + Returns: + 模型实例 + """ + # 只取模型定义的字段 + valid_keys = {c.name for c in cls.__table__.columns} + filtered_data = {k: v for k, v in data.items() if k in valid_keys} + return cls(**filtered_data) + + def update_from_dict( + self, data: dict[str, Any], exclude: set[str] | None = None + ) -> None: + """ + 从字典更新实例 + + Args: + data: 字典数据 + exclude: 要排除的字段名集合 + """ + exclude = exclude or {"id", "created_at"} + valid_keys = {c.name for c in self.__table__.columns} + + for key, value in data.items(): + if key in exclude: + continue + if key in valid_keys: + setattr(self, key, value) + + def __repr__(self) -> str: + """字符串表示""" + class_name = self.__class__.__name__ + pk = getattr(self, "id", None) + return f"<{class_name}(id={pk})>" + + +class TimestampMixin: + """ + 时间戳混入类 + + 提供 created_at 和 updated_at 字段 + """ + + created_at: Mapped[datetime] = mapped_column( + default=datetime.now, + comment="创建时间", + ) + updated_at: Mapped[datetime] = mapped_column( + default=datetime.now, + onupdate=datetime.now, + comment="更新时间", + ) diff --git a/src/core/models/kline.py b/src/core/models/kline.py new file mode 100644 index 0000000..e8ddb35 --- /dev/null +++ b/src/core/models/kline.py @@ -0,0 +1,172 @@ +""" +K线数据 ORM 模型 + +包含: +- KlineBase: K线基类 +- Kline1m, Kline5m, Kline15m, Kline30m, Kline60m, Kline1d: 各周期K线表 +""" + +from datetime import datetime as dt +from decimal import Decimal +from typing import ClassVar + +from sqlalchemy import BigInteger, DateTime, Index, Numeric, String +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base + + +class KlineBase: + """ + K线基类 + + 定义K线的通用字段,各周期表继承此类 + """ + + # 周期标识,子类覆盖 + period: ClassVar[str] = "" + + id: Mapped[int] = mapped_column(BigInteger, primary_key=True, autoincrement=True) + symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码") + time: Mapped[dt] = mapped_column(DateTime, nullable=False, comment="K线时间") + + open: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="开盘价" + ) + high: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="最高价" + ) + low: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="最低价" + ) + close: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="收盘价" + ) + volume: Mapped[int] = mapped_column(BigInteger, default=0, comment="成交量") + amount: Mapped[Decimal] = mapped_column( + Numeric(20, 2), default=Decimal(0), comment="成交额" + ) + + def to_dict(self) -> dict: + """转换为字典""" + return { + "id": self.id, + "symbol": self.symbol, + "time": self.time.isoformat() if self.time else None, + "open": float(self.open), + "high": float(self.high), + "low": float(self.low), + "close": float(self.close), + "volume": self.volume, + "amount": float(self.amount) if self.amount else 0, + "period": self.period, + } + + +class Kline1m(KlineBase, Base): + """1分钟K线""" + + __tablename__ = "kline_1m" + period: ClassVar[str] = "1m" + + __table_args__ = ( + Index("ix_kline_1m_symbol", "symbol"), + Index("ix_kline_1m_time", "time"), + Index("ix_kline_1m_symbol_time", "symbol", "time", unique=True), + ) + + +class Kline5m(KlineBase, Base): + """5分钟K线""" + + __tablename__ = "kline_5m" + period: ClassVar[str] = "5m" + + __table_args__ = ( + Index("ix_kline_5m_symbol", "symbol"), + Index("ix_kline_5m_time", "time"), + Index("ix_kline_5m_symbol_time", "symbol", "time", unique=True), + ) + + +class Kline15m(KlineBase, Base): + """15分钟K线""" + + __tablename__ = "kline_15m" + period: ClassVar[str] = "15m" + + __table_args__ = ( + Index("ix_kline_15m_symbol", "symbol"), + Index("ix_kline_15m_time", "time"), + Index("ix_kline_15m_symbol_time", "symbol", "time", unique=True), + ) + + +class Kline30m(KlineBase, Base): + """30分钟K线""" + + __tablename__ = "kline_30m" + period: ClassVar[str] = "30m" + + __table_args__ = ( + Index("ix_kline_30m_symbol", "symbol"), + Index("ix_kline_30m_time", "time"), + Index("ix_kline_30m_symbol_time", "symbol", "time", unique=True), + ) + + +class Kline60m(KlineBase, Base): + """60分钟(1小时)K线""" + + __tablename__ = "kline_60m" + period: ClassVar[str] = "60m" + + __table_args__ = ( + Index("ix_kline_60m_symbol", "symbol"), + Index("ix_kline_60m_time", "time"), + Index("ix_kline_60m_symbol_time", "symbol", "time", unique=True), + ) + + +class Kline1d(KlineBase, Base): + """日K线""" + + __tablename__ = "kline_1d" + period: ClassVar[str] = "1d" + + __table_args__ = ( + Index("ix_kline_1d_symbol", "symbol"), + Index("ix_kline_1d_time", "time"), + Index("ix_kline_1d_symbol_time", "symbol", "time", unique=True), + ) + + +# K线模型映射表,方便根据周期获取对应模型 +KLINE_MODELS: dict[str, type[Base]] = { + "1m": Kline1m, + "5m": Kline5m, + "15m": Kline15m, + "30m": Kline30m, + "60m": Kline60m, + "1d": Kline1d, +} + + +def get_kline_model(period: str) -> type[Base]: + """ + 根据周期获取K线模型类 + + Args: + period: 周期 (1m, 5m, 15m, 30m, 60m, 1d) + + Returns: + 对应的K线模型类 + + Raises: + ValueError: 不支持的周期 + """ + if period not in KLINE_MODELS: + raise ValueError( + f"不支持的K线周期: {period}, 支持: {list(KLINE_MODELS.keys())}" + ) + return KLINE_MODELS[period] diff --git a/src/core/models/market.py b/src/core/models/market.py deleted file mode 100644 index 6f47f14..0000000 --- a/src/core/models/market.py +++ /dev/null @@ -1,100 +0,0 @@ -""" -行情数据模型 - -包含: -- Quote: 实时行情 -- KlineData: K线数据 -""" - -from datetime import datetime as dt -from decimal import Decimal -from typing import Optional - -from pydantic import BaseModel, Field - - -class Quote(BaseModel): - """ - 实时行情数据 - - 来源: QMT 推送 / 回测数据回放 - """ - - symbol: str = Field(..., description="股票代码") - name: Optional[str] = Field(None, description="股票名称") - - # 价格 - price: Decimal = Field(..., description="最新价") - open: Decimal = Field(..., description="开盘价") - high: Decimal = Field(..., description="最高价") - low: Decimal = Field(..., description="最低价") - pre_close: Decimal = Field(..., description="昨收价") - - # 成交 - volume: int = Field(..., description="成交量") - amount: Decimal = Field(..., description="成交额") - - # 买卖盘 - bid_price1: Optional[Decimal] = Field(None, description="买一价") - bid_volume1: Optional[int] = Field(None, description="买一量") - ask_price1: Optional[Decimal] = Field(None, description="卖一价") - ask_volume1: Optional[int] = Field(None, description="卖一量") - - # 时间 - timestamp: dt = Field(default_factory=dt.now, description="行情时间") - - @property - def change(self) -> Decimal: - """涨跌额""" - return self.price - self.pre_close - - @property - def change_pct(self) -> Decimal: - """涨跌幅 (%)""" - if self.pre_close == 0: - return Decimal(0) - return (self.price - self.pre_close) / self.pre_close * 100 - - class Config: - json_encoders = { - Decimal: lambda v: float(v), - dt: lambda v: v.isoformat(), - } - - -class KlineData(BaseModel): - """ - K线数据 - - 按周期分表存储: klines_1m, klines_5m, klines_15m, klines_30m, klines_60m, klines_1d, klines_1w - """ - - symbol: str = Field(..., description="股票代码") - period: str = Field(..., description="周期: 1m, 5m, 15m, 30m, 60m, 1d, 1w") - - # OHLCV - open: Decimal = Field(..., description="开盘价") - high: Decimal = Field(..., description="最高价") - low: Decimal = Field(..., description="最低价") - close: Decimal = Field(..., description="收盘价") - volume: int = Field(..., description="成交量") - amount: Decimal = Field(..., description="成交额") - - # 时间 - datetime: dt = Field(..., description="K线时间") - - class Config: - json_encoders = { - Decimal: lambda v: float(v), - dt: lambda v: v.isoformat(), - } - - -class KlineQuery(BaseModel): - """K线查询参数""" - - symbol: str = Field(..., description="股票代码") - period: str = Field(..., description="周期") - start_time: Optional[dt] = Field(None, description="开始时间") - end_time: Optional[dt] = Field(None, description="结束时间") - limit: int = Field(default=100, ge=1, le=1000, description="返回数量") diff --git a/src/core/models/order.py b/src/core/models/order.py index e1640fc..77da648 100644 --- a/src/core/models/order.py +++ b/src/core/models/order.py @@ -1,98 +1,132 @@ """ -订单数据模型 +订单 ORM 模型 包含: -- Order: 订单 -- OrderCreate: 创建订单请求 -- OrderUpdate: 更新订单请求 +- OrderSide: 订单方向枚举 +- OrderType: 订单类型枚举 +- OrderStatus: 订单状态枚举 +- Order: 订单表 """ -from datetime import datetime as dt +from datetime import datetime from decimal import Decimal from enum import Enum -from typing import Optional -from pydantic import BaseModel, Field +from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base, TimestampMixin class OrderSide(str, Enum): """订单方向""" - BUY = "BUY" # 买入 - SELL = "SELL" # 卖出 + BUY = "buy" # 买入 + SELL = "sell" # 卖出 class OrderType(str, Enum): """订单类型""" - LIMIT = "LIMIT" # 限价单 - MARKET = "MARKET" # 市价单 + LIMIT = "limit" # 限价单 + MARKET = "market" # 市价单 class OrderStatus(str, Enum): """订单状态""" - PENDING = "PENDING" # 待提交 - SUBMITTED = "SUBMITTED" # 已提交 - PARTIAL = "PARTIAL" # 部分成交 - FILLED = "FILLED" # 全部成交 - CANCELLED = "CANCELLED" # 已撤销 - REJECTED = "REJECTED" # 已拒绝 - FAILED = "FAILED" # 失败 + PENDING = "pending" # 待提交 + SUBMITTED = "submitted" # 已提交 + PARTIAL = "partial" # 部分成交 + FILLED = "filled" # 全部成交 + CANCELLED = "cancelled" # 已撤销 + REJECTED = "rejected" # 已拒绝 + FAILED = "failed" # 失败 -class Order(BaseModel): +class Order(TimestampMixin, Base): """ - 订单数据 + 订单表 + + 记录所有交易订单 """ - # 订单标识 - id: str = Field(..., description="订单ID") - external_id: Optional[str] = Field(None, description="外部订单ID (QMT)") + __tablename__ = "orders" - # 配对关系 - pairing_id: str = Field(..., description="配对ID") - strategy_id: str = Field(..., description="策略ID") + # 主键 + id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="订单ID") + + # 外部订单ID (QMT/券商返回) + external_id: Mapped[str | None] = mapped_column(String(64), comment="外部订单ID") + + # 关联 + pairing_id: Mapped[str] = mapped_column( + String(32), + ForeignKey("pairings.id", ondelete="CASCADE"), + nullable=False, + comment="配对ID", + ) + signal_id: Mapped[str | None] = mapped_column(String(32), comment="信号ID") # 订单内容 - symbol: str = Field(..., description="股票代码") - side: OrderSide = Field(..., description="订单方向") - order_type: OrderType = Field(OrderType.LIMIT, description="订单类型") - price: Decimal = Field(..., description="委托价格") - quantity: int = Field(..., description="委托数量") + symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码") + side: Mapped[str] = mapped_column(String(10), nullable=False, comment="订单方向") + order_type: Mapped[str] = mapped_column( + String(20), default=OrderType.LIMIT.value, comment="订单类型" + ) + price: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="委托价格" + ) + quantity: Mapped[int] = mapped_column(nullable=False, comment="委托数量") # 成交信息 - filled_quantity: int = Field(default=0, description="成交数量") - filled_amount: Decimal = Field(default=Decimal(0), description="成交金额") - avg_price: Optional[Decimal] = Field(None, description="成交均价") + filled_quantity: Mapped[int] = mapped_column(default=0, comment="成交数量") + filled_amount: Mapped[Decimal] = mapped_column( + Numeric(16, 2), default=Decimal(0), comment="成交金额" + ) + avg_price: Mapped[Decimal | None] = mapped_column( + Numeric(10, 3), comment="成交均价" + ) + commission: Mapped[Decimal] = mapped_column( + Numeric(10, 2), default=Decimal(0), comment="手续费" + ) # 状态 - status: OrderStatus = Field(default=OrderStatus.PENDING, description="订单状态") - message: Optional[str] = Field(None, description="状态消息") + status: Mapped[str] = mapped_column( + String(20), default=OrderStatus.PENDING.value, comment="订单状态" + ) + message: Mapped[str | None] = mapped_column(Text, comment="状态消息") # 时间 - created_at: dt = Field(default_factory=dt.now, description="创建时间") - updated_at: dt = Field(default_factory=dt.now, description="更新时间") - submitted_at: Optional[dt] = Field(None, description="提交时间") - filled_at: Optional[dt] = Field(None, description="成交时间") + submitted_at: Mapped[datetime | None] = mapped_column(DateTime, comment="提交时间") + filled_at: Mapped[datetime | None] = mapped_column(DateTime, comment="成交时间") + cancelled_at: Mapped[datetime | None] = mapped_column(DateTime, comment="撤销时间") + + __table_args__ = ( + Index("ix_orders_pairing_id", "pairing_id"), + Index("ix_orders_symbol", "symbol"), + Index("ix_orders_status", "status"), + Index("ix_orders_created_at", "created_at"), + Index("ix_orders_external_id", "external_id"), + ) @property def is_active(self) -> bool: - """订单是否活跃""" + """订单是否活跃(可撤销)""" return self.status in ( - OrderStatus.PENDING, - OrderStatus.SUBMITTED, - OrderStatus.PARTIAL, + OrderStatus.PENDING.value, + OrderStatus.SUBMITTED.value, + OrderStatus.PARTIAL.value, ) @property def is_finished(self) -> bool: """订单是否已结束""" return self.status in ( - OrderStatus.FILLED, - OrderStatus.CANCELLED, - OrderStatus.REJECTED, - OrderStatus.FAILED, + OrderStatus.FILLED.value, + OrderStatus.CANCELLED.value, + OrderStatus.REJECTED.value, + OrderStatus.FAILED.value, ) @property @@ -100,37 +134,81 @@ class Order(BaseModel): """未成交数量""" return self.quantity - self.filled_quantity - class Config: - json_encoders = { - Decimal: lambda v: float(v), - dt: lambda v: v.isoformat(), - } + @property + def order_amount(self) -> Decimal: + """订单金额""" + return self.price * self.quantity + def fill( + self, quantity: int, price: Decimal, commission: Decimal = Decimal(0) + ) -> None: + """ + 成交处理 -class OrderCreate(BaseModel): - """创建订单请求""" + Args: + quantity: 成交数量 + price: 成交价格 + commission: 手续费 + """ + if quantity <= 0: + return - pairing_id: str = Field(..., description="配对ID") - symbol: str = Field(..., description="股票代码") - side: OrderSide = Field(..., description="订单方向") - order_type: OrderType = Field(default=OrderType.LIMIT, description="订单类型") - price: Decimal = Field(..., description="委托价格") - quantity: int = Field(..., gt=0, description="委托数量") + # 更新成交数量和金额 + new_filled = self.filled_quantity + quantity + new_amount = self.filled_amount + price * quantity + self.filled_quantity = new_filled + self.filled_amount = new_amount + self.avg_price = new_amount / new_filled if new_filled > 0 else None + self.commission += commission -class OrderUpdate(BaseModel): - """更新订单请求""" + # 更新状态 + if self.filled_quantity >= self.quantity: + self.status = OrderStatus.FILLED.value + self.filled_at = datetime.now() + elif self.filled_quantity > 0: + self.status = OrderStatus.PARTIAL.value - status: Optional[OrderStatus] = Field(None, description="订单状态") - filled_quantity: Optional[int] = Field(None, description="成交数量") - filled_amount: Optional[Decimal] = Field(None, description="成交金额") - avg_price: Optional[Decimal] = Field(None, description="成交均价") - external_id: Optional[str] = Field(None, description="外部订单ID") - message: Optional[str] = Field(None, description="状态消息") + self.updated_at = datetime.now() + def cancel(self, message: str | None = None) -> bool: + """ + 撤销订单 -class OrderCancel(BaseModel): - """撤销订单请求""" + Args: + message: 撤销原因 - order_id: str = Field(..., description="订单ID") - reason: Optional[str] = Field(None, description="撤销原因") + Returns: + 是否成功 + """ + if not self.is_active: + return False + + self.status = OrderStatus.CANCELLED.value + self.cancelled_at = datetime.now() + self.message = message + self.updated_at = datetime.now() + return True + + def reject(self, message: str | None = None) -> None: + """ + 拒绝订单 + + Args: + message: 拒绝原因 + """ + self.status = OrderStatus.REJECTED.value + self.message = message + self.updated_at = datetime.now() + + def submit(self, external_id: str | None = None) -> None: + """ + 提交订单 + + Args: + external_id: 外部订单ID + """ + self.status = OrderStatus.SUBMITTED.value + self.external_id = external_id + self.submitted_at = datetime.now() + self.updated_at = datetime.now() diff --git a/src/core/models/pairing.py b/src/core/models/pairing.py new file mode 100644 index 0000000..dfaadcc --- /dev/null +++ b/src/core/models/pairing.py @@ -0,0 +1,167 @@ +""" +股票-策略配对 ORM 模型 + +包含: +- PairingStatus: 配对状态枚举 +- Pairing: 股票-策略配对表 +""" + +from datetime import datetime +from decimal import Decimal +from enum import Enum + +from sqlalchemy import Index, JSON, Numeric, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base, TimestampMixin + + +class PairingStatus(str, Enum): + """配对状态""" + + ACTIVE = "active" # 运行中 + PAUSED = "paused" # 已暂停 + STOPPED = "stopped" # 已停止 + + +class Pairing(TimestampMixin, Base): + """ + 股票-策略配对 + + 一只股票可以配对多个策略,每个配对有独立的资金和持仓管理 + """ + + __tablename__ = "pairings" + + # 主键 + id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="配对ID") + + # 股票信息 + symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码") + symbol_name: Mapped[str | None] = mapped_column(String(50), comment="股票名称") + + # 策略信息 + strategy_id: Mapped[str] = mapped_column( + String(50), nullable=False, comment="策略ID" + ) + strategy_name: Mapped[str | None] = mapped_column(String(100), comment="策略名称") + + # 资金配置 + initial_capital: Mapped[Decimal] = mapped_column( + Numeric(16, 2), nullable=False, comment="初始资金" + ) + available_capital: Mapped[Decimal] = mapped_column( + Numeric(16, 2), nullable=False, comment="可用资金" + ) + frozen_capital: Mapped[Decimal] = mapped_column( + Numeric(16, 2), default=Decimal(0), comment="冻结资金" + ) + + # 状态 + status: Mapped[str] = mapped_column( + String(20), default=PairingStatus.STOPPED.value, comment="配对状态" + ) + + # 策略参数 (JSON) + params: Mapped[dict | None] = mapped_column(JSON, default=dict, comment="策略参数") + + # 统计信息 + total_trades: Mapped[int] = mapped_column(default=0, comment="总交易次数") + win_trades: Mapped[int] = mapped_column(default=0, comment="盈利次数") + loss_trades: Mapped[int] = mapped_column(default=0, comment="亏损次数") + total_pnl: Mapped[Decimal] = mapped_column( + Numeric(16, 2), default=Decimal(0), comment="累计盈亏" + ) + max_drawdown: Mapped[Decimal] = mapped_column( + Numeric(10, 4), default=Decimal(0), comment="最大回撤率" + ) + + # 备注 + remark: Mapped[str | None] = mapped_column(Text, comment="备注") + + __table_args__ = ( + Index("ix_pairings_symbol", "symbol"), + Index("ix_pairings_strategy_id", "strategy_id"), + Index("ix_pairings_status", "status"), + Index("ix_pairings_symbol_strategy", "symbol", "strategy_id"), + ) + + @property + def current_capital(self) -> Decimal: + """当前总资金 = 可用 + 冻结""" + return self.available_capital + self.frozen_capital + + @property + def win_rate(self) -> float | None: + """胜率""" + if self.total_trades == 0: + return None + return self.win_trades / self.total_trades + + @property + def return_rate(self) -> float: + """收益率 (%)""" + if self.initial_capital == 0: + return 0.0 + return float( + (self.current_capital - self.initial_capital) / self.initial_capital * 100 + ) + + def is_active(self) -> bool: + """是否运行中""" + return self.status == PairingStatus.ACTIVE.value + + def freeze_capital(self, amount: Decimal) -> bool: + """ + 冻结资金 + + Args: + amount: 冻结金额 + + Returns: + 是否成功 + """ + if amount > self.available_capital: + return False + self.available_capital -= amount + self.frozen_capital += amount + self.updated_at = datetime.now() + return True + + def unfreeze_capital(self, amount: Decimal) -> bool: + """ + 解冻资金 + + Args: + amount: 解冻金额 + + Returns: + 是否成功 + """ + if amount > self.frozen_capital: + return False + self.frozen_capital -= amount + self.available_capital += amount + self.updated_at = datetime.now() + return True + + def add_capital(self, amount: Decimal) -> None: + """增加可用资金""" + self.available_capital += amount + self.updated_at = datetime.now() + + def deduct_capital(self, amount: Decimal) -> bool: + """ + 扣减可用资金 + + Args: + amount: 扣减金额 + + Returns: + 是否成功 + """ + if amount > self.available_capital: + return False + self.available_capital -= amount + self.updated_at = datetime.now() + return True diff --git a/src/core/models/position.py b/src/core/models/position.py index faab241..4f6228a 100644 --- a/src/core/models/position.py +++ b/src/core/models/position.py @@ -1,92 +1,208 @@ """ -持仓数据模型 +持仓 ORM 模型 包含: -- Position: 持仓 -- PositionUpdate: 更新持仓请求 +- Position: 持仓表 """ -from datetime import datetime as dt +from datetime import datetime from decimal import Decimal -from typing import Optional -from pydantic import BaseModel, Field +from sqlalchemy import ForeignKey, Index, Numeric, String +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base, TimestampMixin -class Position(BaseModel): +class Position(TimestampMixin, Base): """ - 持仓数据 + 持仓表 - 注意: 持仓是按 pairing_id 独立管理的 - 同一股票在不同配对下有独立的持仓记录 + 记录每个配对的持仓情况 + 注意: 持仓是按 pairing_id 独立管理的,同一股票在不同配对下有独立的持仓记录 """ - # 标识 - id: str = Field(..., description="持仓ID") - pairing_id: str = Field(..., description="配对ID") - strategy_id: str = Field(..., description="策略ID") - symbol: str = Field(..., description="股票代码") + __tablename__ = "positions" + + # 主键 + id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="持仓ID") + + # 关联 + pairing_id: Mapped[str] = mapped_column( + String(32), + ForeignKey("pairings.id", ondelete="CASCADE"), + nullable=False, + comment="配对ID", + ) + + # 股票信息 + symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码") + symbol_name: Mapped[str | None] = mapped_column(String(50), comment="股票名称") # 持仓数量 - quantity: int = Field(default=0, description="持仓数量") - available: int = Field(default=0, description="可用数量 (T+1)") - frozen: int = Field(default=0, description="冻结数量") + quantity: Mapped[int] = mapped_column(default=0, comment="持仓数量") + available: Mapped[int] = mapped_column(default=0, comment="可用数量 (T+1)") + frozen: Mapped[int] = mapped_column(default=0, comment="冻结数量") - # 成本与盈亏 - avg_cost: Decimal = Field(default=Decimal(0), description="持仓成本") - total_cost: Decimal = Field(default=Decimal(0), description="总成本") - market_value: Optional[Decimal] = Field(None, description="市值") - unrealized_pnl: Optional[Decimal] = Field(None, description="浮动盈亏") - realized_pnl: Decimal = Field(default=Decimal(0), description="已实现盈亏") + # 成本信息 + avg_cost: Mapped[Decimal] = mapped_column( + Numeric(10, 4), default=Decimal(0), comment="持仓成本价" + ) + total_cost: Mapped[Decimal] = mapped_column( + Numeric(16, 2), default=Decimal(0), comment="总成本" + ) - # 时间 - created_at: dt = Field(default_factory=dt.now, description="创建时间") - updated_at: dt = Field(default_factory=dt.now, description="更新时间") + # 盈亏 (需要实时计算更新) + last_price: Mapped[Decimal | None] = mapped_column( + Numeric(10, 3), comment="最新价格" + ) + market_value: Mapped[Decimal | None] = mapped_column(Numeric(16, 2), comment="市值") + unrealized_pnl: Mapped[Decimal | None] = mapped_column( + Numeric(16, 2), comment="浮动盈亏" + ) + realized_pnl: Mapped[Decimal] = mapped_column( + Numeric(16, 2), default=Decimal(0), comment="已实现盈亏" + ) + + __table_args__ = ( + Index("ix_positions_pairing_id", "pairing_id"), + Index("ix_positions_symbol", "symbol"), + Index("ix_positions_pairing_symbol", "pairing_id", "symbol", unique=True), + ) @property - def pnl_ratio(self) -> Optional[Decimal]: + def pnl_ratio(self) -> float | None: """盈亏比例 (%)""" - if self.total_cost == 0: + if self.total_cost == 0 or self.unrealized_pnl is None: return None - if self.unrealized_pnl is None: - return None - return self.unrealized_pnl / self.total_cost * 100 + return float(self.unrealized_pnl / self.total_cost * 100) - def calculate_market_value(self, current_price: Decimal) -> Decimal: - """计算市值""" - self.market_value = current_price * self.quantity - return self.market_value + @property + def total_pnl(self) -> Decimal: + """总盈亏 = 浮动盈亏 + 已实现盈亏""" + return (self.unrealized_pnl or Decimal(0)) + self.realized_pnl - def calculate_unrealized_pnl(self, current_price: Decimal) -> Decimal: - """计算浮动盈亏""" - self.unrealized_pnl = current_price * self.quantity - self.total_cost - return self.unrealized_pnl + def update_price(self, price: Decimal) -> None: + """ + 更新最新价格,计算市值和浮动盈亏 - class Config: - json_encoders = { - Decimal: lambda v: float(v), - dt: lambda v: v.isoformat(), - } + Args: + price: 最新价格 + """ + self.last_price = price + self.market_value = price * self.quantity + # 计算浮动盈亏 + market_value = self.market_value + total_cost = self.total_cost + if market_value is not None and total_cost is not None: + self.unrealized_pnl = market_value - total_cost + self.updated_at = datetime.now() + def buy( + self, quantity: int, price: Decimal, commission: Decimal = Decimal(0) + ) -> None: + """ + 买入处理 -class PositionUpdate(BaseModel): - """更新持仓请求""" + Args: + quantity: 买入数量 + price: 买入价格 + commission: 手续费 + """ + if quantity <= 0: + return - quantity: Optional[int] = Field(None, description="持仓数量") - available: Optional[int] = Field(None, description="可用数量") - frozen: Optional[int] = Field(None, description="冻结数量") - avg_cost: Optional[Decimal] = Field(None, description="持仓成本") - total_cost: Optional[Decimal] = Field(None, description="总成本") - realized_pnl: Optional[Decimal] = Field(None, description="已实现盈亏") + # 计算新的成本 + buy_cost = price * quantity + commission + new_total_cost = self.total_cost + buy_cost + new_quantity = self.quantity + quantity + # 更新持仓 + self.quantity = new_quantity + self.total_cost = new_total_cost + self.avg_cost = ( + new_total_cost / new_quantity if new_quantity > 0 else Decimal(0) + ) + # 注意: T+1 规则,新买入的不计入可用 + self.updated_at = datetime.now() -class PositionSummary(BaseModel): - """持仓汇总""" + def sell( + self, quantity: int, price: Decimal, commission: Decimal = Decimal(0) + ) -> Decimal: + """ + 卖出处理 - pairing_id: str = Field(..., description="配对ID") - strategy_id: str = Field(..., description="策略ID") - total_market_value: Decimal = Field(default=Decimal(0), description="总市值") - total_cost: Decimal = Field(default=Decimal(0), description="总成本") - total_unrealized_pnl: Decimal = Field(default=Decimal(0), description="总浮动盈亏") - total_realized_pnl: Decimal = Field(default=Decimal(0), description="总已实现盈亏") - position_count: int = Field(default=0, description="持仓品种数") + Args: + quantity: 卖出数量 + price: 卖出价格 + commission: 手续费 + + Returns: + 本次实现盈亏 + """ + if quantity <= 0 or quantity > self.available: + raise ValueError(f"卖出数量无效: 请求 {quantity}, 可用 {self.available}") + + # 计算盈亏 + sell_amount = price * quantity - commission + cost = self.avg_cost * quantity + realized = sell_amount - cost + + # 更新持仓 + self.quantity -= quantity + self.available -= quantity + self.total_cost -= cost + self.realized_pnl += realized + + if self.quantity == 0: + self.avg_cost = Decimal(0) + self.total_cost = Decimal(0) + + self.updated_at = datetime.now() + return realized + + def freeze(self, quantity: int) -> bool: + """ + 冻结持仓 + + Args: + quantity: 冻结数量 + + Returns: + 是否成功 + """ + if quantity > self.available: + return False + self.available -= quantity + self.frozen += quantity + self.updated_at = datetime.now() + return True + + def unfreeze(self, quantity: int) -> bool: + """ + 解冻持仓 + + Args: + quantity: 解冻数量 + + Returns: + 是否成功 + """ + if quantity > self.frozen: + return False + self.frozen -= quantity + self.available += quantity + self.updated_at = datetime.now() + return True + + def settle_daily(self) -> None: + """ + 日终结算 (T+1 可用处理) + + 将今日买入的股票变为可用 + """ + # 今日买入 = 总数量 - 可用 - 冻结 + today_bought = self.quantity - self.available - self.frozen + if today_bought > 0: + self.available += today_bought + self.updated_at = datetime.now() diff --git a/src/core/models/signal.py b/src/core/models/signal.py index d55716b..bf70616 100644 --- a/src/core/models/signal.py +++ b/src/core/models/signal.py @@ -1,57 +1,166 @@ """ -交易信号模型 +交易信号 ORM 模型 + +包含: +- SignalSide: 信号方向枚举 +- SignalStatus: 信号状态枚举 +- Signal: 信号表 """ +from datetime import datetime +from decimal import Decimal from enum import Enum -from datetime import datetime as dt -from typing import Optional -from pydantic import BaseModel, Field +from sqlalchemy import DateTime, ForeignKey, Index, Numeric, String, Text +from sqlalchemy.orm import Mapped, mapped_column + +from .base import Base, TimestampMixin class SignalSide(str, Enum): """信号方向""" - BUY = "buy" - SELL = "sell" + BUY = "buy" # 买入 + SELL = "sell" # 卖出 class SignalStatus(str, Enum): """信号状态""" PENDING = "pending" # 待处理 + EXECUTING = "executing" # 执行中 EXECUTED = "executed" # 已执行 CANCELLED = "cancelled" # 已取消 FAILED = "failed" # 执行失败 + EXPIRED = "expired" # 已过期 -class Signal(BaseModel): - """交易信号""" +class Signal(TimestampMixin, Base): + """ + 交易信号表 - id: str = Field(..., description="信号ID") - pairing_id: str = Field(..., description="配对ID") - symbol: str = Field(..., description="股票代码") - strategy_id: str = Field(..., description="策略ID") + 策略产生的交易信号,等待执行 + """ - side: SignalSide = Field(..., description="方向") - price: float = Field(..., gt=0, description="价格") - quantity: int = Field(..., gt=0, description="数量") + __tablename__ = "signals" - reason: str = Field(default="", description="信号原因") - status: SignalStatus = Field(default=SignalStatus.PENDING, description="状态") + # 主键 + id: Mapped[str] = mapped_column(String(32), primary_key=True, comment="信号ID") - order_id: Optional[str] = Field(None, description="关联订单ID") + # 关联 + pairing_id: Mapped[str] = mapped_column( + String(32), + ForeignKey("pairings.id", ondelete="CASCADE"), + nullable=False, + comment="配对ID", + ) + order_id: Mapped[str | None] = mapped_column(String(32), comment="关联订单ID") - created_at: Optional[dt] = Field(None, description="创建时间") - executed_at: Optional[dt] = Field(None, description="执行时间") + # 信号内容 + symbol: Mapped[str] = mapped_column(String(20), nullable=False, comment="股票代码") + strategy_id: Mapped[str] = mapped_column( + String(50), nullable=False, comment="策略ID" + ) + side: Mapped[str] = mapped_column(String(10), nullable=False, comment="信号方向") + price: Mapped[Decimal] = mapped_column( + Numeric(10, 3), nullable=False, comment="建议价格" + ) + quantity: Mapped[int] = mapped_column(nullable=False, comment="建议数量") + # 信号来源和原因 + source: Mapped[str | None] = mapped_column(String(50), comment="信号来源") + reason: Mapped[str | None] = mapped_column(Text, comment="信号原因") -class SignalCreate(BaseModel): - """创建信号请求""" + # 状态 + status: Mapped[str] = mapped_column( + String(20), default=SignalStatus.PENDING.value, comment="信号状态" + ) + message: Mapped[str | None] = mapped_column(Text, comment="状态消息") - pairing_id: str = Field(..., description="配对ID") - symbol: str = Field(..., description="股票代码") - side: SignalSide = Field(..., description="方向") - price: float = Field(..., gt=0, description="价格") - quantity: int = Field(..., gt=0, description="数量") - reason: Optional[str] = Field(None, description="原因") + # 时间 + executed_at: Mapped[datetime | None] = mapped_column(DateTime, comment="执行时间") + expired_at: Mapped[datetime | None] = mapped_column(DateTime, comment="过期时间") + + __table_args__ = ( + Index("ix_signals_pairing_id", "pairing_id"), + Index("ix_signals_symbol", "symbol"), + Index("ix_signals_status", "status"), + Index("ix_signals_created_at", "created_at"), + ) + + @property + def is_pending(self) -> bool: + """是否待处理""" + return self.status == SignalStatus.PENDING.value + + @property + def is_finished(self) -> bool: + """是否已结束""" + return self.status in ( + SignalStatus.EXECUTED.value, + SignalStatus.CANCELLED.value, + SignalStatus.FAILED.value, + SignalStatus.EXPIRED.value, + ) + + @property + def signal_amount(self) -> Decimal: + """信号金额""" + return self.price * self.quantity + + def execute(self, order_id: str) -> None: + """ + 标记为已执行 + + Args: + order_id: 关联的订单ID + """ + self.status = SignalStatus.EXECUTED.value + self.order_id = order_id + self.executed_at = datetime.now() + self.updated_at = datetime.now() + + def cancel(self, message: str | None = None) -> None: + """ + 取消信号 + + Args: + message: 取消原因 + """ + self.status = SignalStatus.CANCELLED.value + self.message = message + self.updated_at = datetime.now() + + def fail(self, message: str | None = None) -> None: + """ + 标记为失败 + + Args: + message: 失败原因 + """ + self.status = SignalStatus.FAILED.value + self.message = message + self.updated_at = datetime.now() + + def expire(self) -> None: + """标记为过期""" + self.status = SignalStatus.EXPIRED.value + self.updated_at = datetime.now() + + def start_executing(self) -> None: + """标记为执行中""" + self.status = SignalStatus.EXECUTING.value + self.updated_at = datetime.now() + + def check_expired(self) -> bool: + """ + 检查是否过期 + + Returns: + 是否过期 + """ + if self.expired_at and datetime.now() > self.expired_at: + if self.is_pending: + self.expire() + return True + return False diff --git a/src/core/models/symbol_strategy.py b/src/core/models/symbol_strategy.py deleted file mode 100644 index 36ca5bc..0000000 --- a/src/core/models/symbol_strategy.py +++ /dev/null @@ -1,113 +0,0 @@ -""" -股票-策略配对模型 - -包含: -- SymbolStrategy: 配对关系 -- PairingCreate: 创建配对请求 -""" - -from datetime import datetime as dt -from decimal import Decimal -from enum import Enum -from typing import Optional - -from pydantic import BaseModel, Field - - -class PairingStatus(str, Enum): - """配对状态""" - - ACTIVE = "ACTIVE" # 活跃 - PAUSED = "PAUSED" # 暂停 - STOPPED = "STOPPED" # 停止 - - -class SymbolStrategy(BaseModel): - """ - 股票-策略配对 - - 一只股票可以配对多个策略 - 每个配对有独立的持仓和资金管理 - """ - - # 标识 - id: str = Field(..., description="配对ID") - symbol: str = Field(..., description="股票代码") - symbol_name: Optional[str] = Field(None, description="股票名称") - strategy_id: str = Field(..., description="策略ID") - strategy_name: Optional[str] = Field(None, description="策略名称") - - # 资金配置 - initial_capital: Decimal = Field(..., description="初始资金") - current_capital: Decimal = Field(..., description="当前资金") - available_capital: Decimal = Field(..., description="可用资金") - frozen_capital: Decimal = Field(default=Decimal(0), description="冻结资金") - - # 状态 - status: PairingStatus = Field(default=PairingStatus.ACTIVE, description="配对状态") - - # 策略参数 - params: dict = Field(default_factory=dict, description="策略参数") - - # 统计 - total_trades: int = Field(default=0, description="总交易次数") - win_trades: int = Field(default=0, description="盈利次数") - loss_trades: int = Field(default=0, description="亏损次数") - total_pnl: Decimal = Field(default=Decimal(0), description="总盈亏") - max_drawdown: Decimal = Field(default=Decimal(0), description="最大回撤") - - # 时间 - created_at: dt = Field(default_factory=dt.now, description="创建时间") - updated_at: dt = Field(default_factory=dt.now, description="更新时间") - - @property - def win_rate(self) -> Optional[float]: - """胜率""" - if self.total_trades == 0: - return None - return self.win_trades / self.total_trades - - @property - def return_rate(self) -> Decimal: - """收益率 (%)""" - if self.initial_capital == 0: - return Decimal(0) - return ( - (self.current_capital - self.initial_capital) / self.initial_capital * 100 - ) - - class Config: - json_encoders = { - Decimal: lambda v: float(v), - dt: lambda v: v.isoformat(), - } - - -class PairingCreate(BaseModel): - """创建配对请求""" - - symbol: str = Field(..., description="股票代码") - symbol_name: Optional[str] = Field(None, description="股票名称") - strategy_id: str = Field(..., description="策略ID") - strategy_name: Optional[str] = Field(None, description="策略名称") - initial_capital: Decimal = Field(..., gt=0, description="初始资金") - params: dict = Field(default_factory=dict, description="策略参数") - - -class PairingUpdate(BaseModel): - """更新配对请求""" - - status: Optional[PairingStatus] = Field(None, description="配对状态") - params: Optional[dict] = Field(None, description="策略参数") - current_capital: Optional[Decimal] = Field(None, description="当前资金") - available_capital: Optional[Decimal] = Field(None, description="可用资金") - - -class PairingQuery(BaseModel): - """查询配对请求""" - - symbol: Optional[str] = Field(None, description="股票代码") - strategy_id: Optional[str] = Field(None, description="策略ID") - status: Optional[PairingStatus] = Field(None, description="配对状态") - page: int = Field(default=1, ge=1, description="页码") - page_size: int = Field(default=20, ge=1, le=100, description="每页数量") diff --git a/src/core/schemas/__init__.py b/src/core/schemas/__init__.py new file mode 100644 index 0000000..7000ff8 --- /dev/null +++ b/src/core/schemas/__init__.py @@ -0,0 +1,39 @@ +""" +QTrade API Schemas + +Pydantic 模型,用于 API 请求/响应的数据验证和序列化 + +目录结构: +- kline.py: K线数据 Schema +- pairing.py: 配对 Schema +- order.py: 订单 Schema +- position.py: 持仓 Schema +- signal.py: 信号 Schema +""" + +from .kline import KlineCreate, KlineResponse, KlineQuery +from .pairing import PairingCreate, PairingResponse, PairingUpdate +from .order import OrderCreate, OrderResponse, OrderUpdate +from .position import PositionResponse, PositionSummary +from .signal import SignalCreate, SignalResponse + +__all__ = [ + # K线 + "KlineCreate", + "KlineResponse", + "KlineQuery", + # 配对 + "PairingCreate", + "PairingResponse", + "PairingUpdate", + # 订单 + "OrderCreate", + "OrderResponse", + "OrderUpdate", + # 持仓 + "PositionResponse", + "PositionSummary", + # 信号 + "SignalCreate", + "SignalResponse", +] diff --git a/src/core/schemas/kline.py b/src/core/schemas/kline.py new file mode 100644 index 0000000..a067875 --- /dev/null +++ b/src/core/schemas/kline.py @@ -0,0 +1,53 @@ +""" +K线数据 Schema + +用于 API 请求/响应 +""" + +from datetime import datetime as dt +from typing import Literal, Optional + +from pydantic import BaseModel, Field + + +class KlineCreate(BaseModel): + """创建K线请求""" + + symbol: str = Field(..., description="股票代码") + time: dt = Field(..., description="K线时间") + open: float = Field(..., gt=0, description="开盘价") + high: float = Field(..., gt=0, description="最高价") + low: float = Field(..., gt=0, description="最低价") + close: float = Field(..., gt=0, description="收盘价") + volume: int = Field(default=0, ge=0, description="成交量") + amount: float = Field(default=0, ge=0, description="成交额") + + +class KlineResponse(BaseModel): + """K线响应""" + + id: int = Field(..., description="K线ID") + symbol: str = Field(..., description="股票代码") + time: dt = Field(..., description="K线时间") + open: float = Field(..., description="开盘价") + high: float = Field(..., description="最高价") + low: float = Field(..., description="最低价") + close: float = Field(..., description="收盘价") + volume: int = Field(..., description="成交量") + amount: float = Field(..., description="成交额") + period: str = Field(..., description="K线周期") + + class Config: + from_attributes = True + + +class KlineQuery(BaseModel): + """K线查询请求""" + + symbol: str = Field(..., description="股票代码") + period: Literal["1m", "5m", "15m", "30m", "60m", "1d"] = Field( + default="1d", description="K线周期" + ) + start_time: Optional[dt] = Field(None, description="开始时间") + end_time: Optional[dt] = Field(None, description="结束时间") + limit: int = Field(default=100, ge=1, le=1000, description="返回数量") diff --git a/src/core/schemas/order.py b/src/core/schemas/order.py new file mode 100644 index 0000000..e5f73ad --- /dev/null +++ b/src/core/schemas/order.py @@ -0,0 +1,73 @@ +""" +订单 Schema + +用于 API 请求/响应 +""" + +from datetime import datetime +from typing import Literal, Optional + +from pydantic import BaseModel, Field + + +class OrderCreate(BaseModel): + """创建订单请求""" + + pairing_id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + side: Literal["buy", "sell"] = Field(..., description="订单方向") + order_type: Literal["limit", "market"] = Field( + default="limit", description="订单类型" + ) + price: float = Field(..., gt=0, description="委托价格") + quantity: int = Field(..., gt=0, description="委托数量") + signal_id: Optional[str] = Field(None, description="关联信号ID") + + +class OrderUpdate(BaseModel): + """更新订单请求""" + + status: Optional[str] = Field(None, description="订单状态") + filled_quantity: Optional[int] = Field(None, description="成交数量") + filled_amount: Optional[float] = Field(None, description="成交金额") + avg_price: Optional[float] = Field(None, description="成交均价") + message: Optional[str] = Field(None, description="状态消息") + + +class OrderResponse(BaseModel): + """订单响应""" + + id: str = Field(..., description="订单ID") + external_id: Optional[str] = Field(None, description="外部订单ID") + pairing_id: str = Field(..., description="配对ID") + signal_id: Optional[str] = Field(None, description="信号ID") + + # 订单内容 + symbol: str = Field(..., description="股票代码") + side: str = Field(..., description="订单方向") + order_type: str = Field(..., description="订单类型") + price: float = Field(..., description="委托价格") + quantity: int = Field(..., description="委托数量") + + # 成交信息 + filled_quantity: int = Field(default=0, description="成交数量") + filled_amount: float = Field(default=0, description="成交金额") + avg_price: Optional[float] = Field(None, description="成交均价") + unfilled_quantity: int = Field(..., description="未成交数量") + commission: float = Field(default=0, description="手续费") + + # 状态 + status: str = Field(..., description="订单状态") + is_active: bool = Field(..., description="是否活跃") + is_finished: bool = Field(..., description="是否已结束") + message: Optional[str] = Field(None, description="状态消息") + + # 时间 + created_at: datetime = Field(..., description="创建时间") + updated_at: datetime = Field(..., description="更新时间") + submitted_at: Optional[datetime] = Field(None, description="提交时间") + filled_at: Optional[datetime] = Field(None, description="成交时间") + cancelled_at: Optional[datetime] = Field(None, description="撤销时间") + + class Config: + from_attributes = True diff --git a/src/core/schemas/pairing.py b/src/core/schemas/pairing.py new file mode 100644 index 0000000..c11d70b --- /dev/null +++ b/src/core/schemas/pairing.py @@ -0,0 +1,68 @@ +""" +股票-策略配对 Schema + +用于 API 请求/响应 +""" + +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field + + +class PairingCreate(BaseModel): + """创建配对请求""" + + symbol: str = Field(..., description="股票代码") + symbol_name: Optional[str] = Field(None, description="股票名称") + strategy_id: str = Field(..., description="策略ID") + strategy_name: Optional[str] = Field(None, description="策略名称") + initial_capital: float = Field(..., gt=0, description="初始资金") + params: Optional[dict] = Field(default_factory=dict, description="策略参数") + remark: Optional[str] = Field(None, description="备注") + + +class PairingUpdate(BaseModel): + """更新配对请求""" + + status: Optional[str] = Field(None, description="状态") + params: Optional[dict] = Field(None, description="策略参数") + remark: Optional[str] = Field(None, description="备注") + + +class PairingResponse(BaseModel): + """配对响应""" + + id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + symbol_name: Optional[str] = Field(None, description="股票名称") + strategy_id: str = Field(..., description="策略ID") + strategy_name: Optional[str] = Field(None, description="策略名称") + + # 资金 + initial_capital: float = Field(..., description="初始资金") + available_capital: float = Field(..., description="可用资金") + frozen_capital: float = Field(..., description="冻结资金") + current_capital: float = Field(..., description="当前总资金") + + # 状态 + status: str = Field(..., description="配对状态") + + # 策略参数 + params: Optional[dict] = Field(None, description="策略参数") + + # 统计 + total_trades: int = Field(default=0, description="总交易次数") + win_trades: int = Field(default=0, description="盈利次数") + loss_trades: int = Field(default=0, description="亏损次数") + win_rate: Optional[float] = Field(None, description="胜率") + total_pnl: float = Field(default=0, description="累计盈亏") + return_rate: float = Field(default=0, description="收益率(%)") + max_drawdown: float = Field(default=0, description="最大回撤率") + + # 时间 + created_at: datetime = Field(..., description="创建时间") + updated_at: datetime = Field(..., description="更新时间") + + class Config: + from_attributes = True diff --git a/src/core/schemas/position.py b/src/core/schemas/position.py new file mode 100644 index 0000000..1220345 --- /dev/null +++ b/src/core/schemas/position.py @@ -0,0 +1,53 @@ +""" +持仓 Schema + +用于 API 请求/响应 +""" + +from datetime import datetime +from typing import Optional + +from pydantic import BaseModel, Field + + +class PositionResponse(BaseModel): + """持仓响应""" + + id: str = Field(..., description="持仓ID") + pairing_id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + symbol_name: Optional[str] = Field(None, description="股票名称") + + # 数量 + quantity: int = Field(default=0, description="持仓数量") + available: int = Field(default=0, description="可用数量") + frozen: int = Field(default=0, description="冻结数量") + + # 成本 + avg_cost: float = Field(default=0, description="持仓成本价") + total_cost: float = Field(default=0, description="总成本") + + # 盈亏 + last_price: Optional[float] = Field(None, description="最新价格") + market_value: Optional[float] = Field(None, description="市值") + unrealized_pnl: Optional[float] = Field(None, description="浮动盈亏") + realized_pnl: float = Field(default=0, description="已实现盈亏") + pnl_ratio: Optional[float] = Field(None, description="盈亏比例(%)") + + # 时间 + created_at: datetime = Field(..., description="创建时间") + updated_at: datetime = Field(..., description="更新时间") + + class Config: + from_attributes = True + + +class PositionSummary(BaseModel): + """持仓汇总""" + + pairing_id: str = Field(..., description="配对ID") + total_market_value: float = Field(default=0, description="总市值") + total_cost: float = Field(default=0, description="总成本") + total_unrealized_pnl: float = Field(default=0, description="总浮动盈亏") + total_realized_pnl: float = Field(default=0, description="总已实现盈亏") + position_count: int = Field(default=0, description="持仓品种数") diff --git a/src/core/schemas/signal.py b/src/core/schemas/signal.py new file mode 100644 index 0000000..16deb8a --- /dev/null +++ b/src/core/schemas/signal.py @@ -0,0 +1,59 @@ +""" +交易信号 Schema + +用于 API 请求/响应 +""" + +from datetime import datetime +from typing import Literal, Optional + +from pydantic import BaseModel, Field + + +class SignalCreate(BaseModel): + """创建信号请求""" + + pairing_id: str = Field(..., description="配对ID") + symbol: str = Field(..., description="股票代码") + strategy_id: str = Field(..., description="策略ID") + side: Literal["buy", "sell"] = Field(..., description="信号方向") + price: float = Field(..., gt=0, description="建议价格") + quantity: int = Field(..., gt=0, description="建议数量") + source: Optional[str] = Field(None, description="信号来源") + reason: Optional[str] = Field(None, description="信号原因") + expired_at: Optional[datetime] = Field(None, description="过期时间") + + +class SignalResponse(BaseModel): + """信号响应""" + + id: str = Field(..., description="信号ID") + pairing_id: str = Field(..., description="配对ID") + order_id: Optional[str] = Field(None, description="关联订单ID") + + # 信号内容 + symbol: str = Field(..., description="股票代码") + strategy_id: str = Field(..., description="策略ID") + side: str = Field(..., description="信号方向") + price: float = Field(..., description="建议价格") + quantity: int = Field(..., description="建议数量") + signal_amount: float = Field(..., description="信号金额") + + # 来源 + source: Optional[str] = Field(None, description="信号来源") + reason: Optional[str] = Field(None, description="信号原因") + + # 状态 + status: str = Field(..., description="信号状态") + is_pending: bool = Field(..., description="是否待处理") + is_finished: bool = Field(..., description="是否已结束") + message: Optional[str] = Field(None, description="状态消息") + + # 时间 + created_at: datetime = Field(..., description="创建时间") + updated_at: datetime = Field(..., description="更新时间") + executed_at: Optional[datetime] = Field(None, description="执行时间") + expired_at: Optional[datetime] = Field(None, description="过期时间") + + class Config: + from_attributes = True diff --git a/src/core/service_manager.py b/src/core/service_manager.py new file mode 100644 index 0000000..1e95f01 --- /dev/null +++ b/src/core/service_manager.py @@ -0,0 +1,321 @@ +""" +服务管理器 + +统一管理所有服务的启动、停止和配置 +""" + +import asyncio +from enum import Enum +from typing import Any, Callable, Optional + +from src.core.logger import get_logger + +logger = get_logger("service_manager") + + +class ServiceStatus(str, Enum): + """服务状态""" + + STOPPED = "stopped" + STARTING = "starting" + RUNNING = "running" + STOPPING = "stopping" + ERROR = "error" + + +class Service: + """服务基类""" + + def __init__(self, name: str, **config): + self.name = name + self.config = config + self.status = ServiceStatus.STOPPED + self.error: Optional[str] = None + + async def start(self): + """启动服务 (子类实现)""" + raise NotImplementedError + + async def stop(self): + """停止服务 (子类实现)""" + raise NotImplementedError + + def configure(self, **config): + """更新配置""" + self.config.update(config) + + +class ServiceManager: + """ + 服务管理器 + + 用法: + manager = ServiceManager() + + # 注册服务 + manager.register("redis", RedisService, host="127.0.0.1", port=6379) + manager.register("database", DatabaseService) + + # 配置服务 + manager.configure("redis", password="xxx") + + # 启动/停止 + await manager.start("redis") + await manager.start_all() + await manager.stop("redis") + await manager.stop_all() + """ + + def __init__(self): + self._services: dict[str, Service] = {} + self._start_order: list[str] = [] # 启动顺序 + + def register( + self, + name: str, + service_class: type[Service], + **config, + ) -> "ServiceManager": + """ + 注册服务 + + Args: + name: 服务名称 + service_class: 服务类 + **config: 服务配置 + + Returns: + self (支持链式调用) + """ + if name in self._services: + logger.warning(f"服务 {name} 已存在,将被覆盖") + + service = service_class(name, **config) + self._services[name] = service + self._start_order.append(name) + + logger.debug(f"注册服务: {name}") + return self + + def configure(self, name: str, **config) -> "ServiceManager": + """ + 配置服务 + + Args: + name: 服务名称 + **config: 配置项 + + Returns: + self (支持链式调用) + """ + if name not in self._services: + raise ValueError(f"服务 {name} 未注册") + + self._services[name].configure(**config) + logger.debug(f"配置服务 {name}: {config}") + return self + + def get(self, name: str) -> Optional[Service]: + """获取服务实例""" + return self._services.get(name) + + async def start(self, name: str) -> bool: + """ + 启动单个服务 + + Args: + name: 服务名称 + + Returns: + 是否成功 + """ + if name not in self._services: + logger.error(f"服务 {name} 未注册") + return False + + service = self._services[name] + + if service.status == ServiceStatus.RUNNING: + logger.warning(f"服务 {name} 已在运行") + return True + + try: + service.status = ServiceStatus.STARTING + logger.info(f"启动服务: {name}") + + await service.start() + + service.status = ServiceStatus.RUNNING + service.error = None + logger.info(f"✓ 服务 {name} 已启动") + return True + + except Exception as e: + service.status = ServiceStatus.ERROR + service.error = str(e) + logger.error(f"✗ 服务 {name} 启动失败: {e}") + return False + + async def stop(self, name: str) -> bool: + """ + 停止单个服务 + + Args: + name: 服务名称 + + Returns: + 是否成功 + """ + if name not in self._services: + logger.error(f"服务 {name} 未注册") + return False + + service = self._services[name] + + if service.status == ServiceStatus.STOPPED: + return True + + try: + service.status = ServiceStatus.STOPPING + logger.info(f"停止服务: {name}") + + await service.stop() + + service.status = ServiceStatus.STOPPED + logger.info(f"✓ 服务 {name} 已停止") + return True + + except Exception as e: + service.status = ServiceStatus.ERROR + service.error = str(e) + logger.error(f"✗ 服务 {name} 停止失败: {e}") + return False + + async def start_all(self) -> dict[str, bool]: + """ + 按顺序启动所有服务 + + Returns: + {服务名: 是否成功} + """ + results = {} + for name in self._start_order: + results[name] = await self.start(name) + return results + + async def stop_all(self) -> dict[str, bool]: + """ + 按逆序停止所有服务 + + Returns: + {服务名: 是否成功} + """ + results = {} + for name in reversed(self._start_order): + results[name] = await self.stop(name) + return results + + def status(self, name: str) -> Optional[ServiceStatus]: + """获取服务状态""" + service = self._services.get(name) + return service.status if service else None + + def list_services(self) -> list[dict]: + """ + 列出所有服务状态 + + Returns: + [{name, status, error}, ...] + """ + return [ + { + "name": name, + "status": service.status.value, + "error": service.error, + } + for name, service in self._services.items() + ] + + def print_status(self): + """打印服务状态表""" + print("\n服务状态:") + print("-" * 40) + for name, service in self._services.items(): + icon = { + ServiceStatus.RUNNING: "✓", + ServiceStatus.STOPPED: "○", + ServiceStatus.ERROR: "✗", + ServiceStatus.STARTING: "◐", + ServiceStatus.STOPPING: "◑", + }.get(service.status, "?") + print(f" {icon} {name}: {service.status.value}") + if service.error: + print(f" 错误: {service.error}") + print("-" * 40) + + +# ============== 内置服务实现 ============== + + +class RedisService(Service): + """Redis 服务""" + + def __init__(self, name: str, **config): + super().__init__(name, **config) + self._client = None + + async def start(self): + from src.core.redis_client import redis_client + + self._client = redis_client + await redis_client.connect() + + async def stop(self): + if self._client: + await self._client.disconnect() + self._client = None + + +class DatabaseService(Service): + """数据库服务""" + + def __init__(self, name: str, **config): + super().__init__(name, **config) + self._db = None + + async def start(self): + from src.core.database import db + + self._db = db + await db.connect() + + async def stop(self): + if self._db: + await self._db.disconnect() + self._db = None + + +class QMTService(Service): + """QMT 数据服务""" + + def __init__(self, name: str, **config): + super().__init__(name, **config) + self._downloader = None + + async def start(self): + from src.qmt_adapter.services.data_downloader import data_downloader + + self._downloader = data_downloader + await data_downloader.init() + + async def stop(self): + # QMT 数据下载器目前没有显式的关闭方法 + self._downloader = None + + @property + def downloader(self): + return self._downloader + + +# 全局服务管理器实例 +service_manager = ServiceManager() diff --git a/src/core_service/routes/order.py b/src/core_service/routes/order.py index f9fde64..0b069ec 100644 --- a/src/core_service/routes/order.py +++ b/src/core_service/routes/order.py @@ -9,7 +9,8 @@ from typing import Any, Optional from fastapi import APIRouter, Query, HTTPException from src.core.logger import get_logger -from src.core.models.order import OrderCreate, OrderStatus +from src.core.models import OrderStatus +from src.core.schemas.order import OrderCreate from ..services.order_service import order_service logger = get_logger("core_service.order") diff --git a/src/core_service/routes/pairing.py b/src/core_service/routes/pairing.py index f2f3293..1f5bcd4 100644 --- a/src/core_service/routes/pairing.py +++ b/src/core_service/routes/pairing.py @@ -10,7 +10,8 @@ from fastapi import APIRouter, Query, HTTPException from pydantic import BaseModel from src.core.logger import get_logger -from src.core.models.symbol_strategy import PairingCreate, PairingStatus +from src.core.models import PairingStatus +from src.core.schemas.pairing import PairingCreate from ..services.pairing_service import pairing_service logger = get_logger("core_service.pairing") diff --git a/src/core_service/services/balance_service.py b/src/core_service/services/balance_service.py index 8db270d..ce5c335 100644 --- a/src/core_service/services/balance_service.py +++ b/src/core_service/services/balance_service.py @@ -6,11 +6,13 @@ from typing import Any, Optional from datetime import datetime as dt +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select, func from src.core.database import db from src.core.logger import get_logger +from src.core.models import Pairing, Position, BalanceLog, BalanceLogType logger = get_logger("core_service.balance_service") @@ -29,36 +31,29 @@ class BalanceService: 资金信息 """ async with db.session() as session: - result = await session.execute( - text(""" - SELECT id, symbol, strategy_id, initial_capital, available_capital, - status, created_at, updated_at - FROM symbol_strategy_pairings - WHERE id = :id - """), - {"id": pairing_id}, - ) - row = result.fetchone() + stmt = select(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() - if not row: + if not pairing: return None - initial_capital = float(row[3]) if row[3] else 0 - available_capital = float(row[4]) if row[4] else 0 + initial_capital = ( + float(pairing.initial_capital) if pairing.initial_capital else 0 + ) + available_capital = ( + float(pairing.available_capital) if pairing.available_capital else 0 + ) # 计算持仓市值 - position_result = await session.execute( - text(""" - SELECT SUM(quantity * cost_price) as position_value - FROM positions - WHERE pairing_id = :pairing_id AND quantity > 0 - """), - {"pairing_id": pairing_id}, - ) - position_row = position_result.fetchone() - position_value = ( - float(position_row[0]) if position_row and position_row[0] else 0 + position_stmt = select( + func.sum(Position.quantity * Position.avg_cost) + ).where( + Position.pairing_id == pairing_id, + Position.quantity > 0, ) + position_result = await session.execute(position_stmt) + position_value = float(position_result.scalar() or 0) # 总资产 = 可用资金 + 持仓市值 total_assets = available_capital + position_value @@ -68,18 +63,22 @@ class BalanceService: pnl_ratio = pnl / initial_capital if initial_capital > 0 else 0 return { - "pairing_id": row[0], - "symbol": row[1], - "strategy_id": row[2], + "pairing_id": pairing.id, + "symbol": pairing.symbol, + "strategy_id": pairing.strategy_id, "initial_capital": initial_capital, "available_capital": available_capital, "position_value": position_value, "total_assets": total_assets, "pnl": pnl, "pnl_ratio": pnl_ratio, - "status": row[5], - "created_at": row[6].isoformat() if row[6] else None, - "updated_at": row[7].isoformat() if row[7] else None, + "status": pairing.status.value if pairing.status else None, + "created_at": pairing.created_at.isoformat() + if pairing.created_at + else None, + "updated_at": pairing.updated_at.isoformat() + if pairing.updated_at + else None, } async def list_balances( @@ -87,61 +86,48 @@ class BalanceService: strategy_id: Optional[str] = None, ) -> dict[str, Any]: """查询资金列表""" - conditions = ["1=1"] - params: dict[str, Any] = {} - - if strategy_id: - conditions.append("strategy_id = :strategy_id") - params["strategy_id"] = strategy_id - - where_clause = " AND ".join(conditions) - async with db.session() as session: - result = await session.execute( - text(f""" - SELECT id, symbol, strategy_id, initial_capital, available_capital, status - FROM symbol_strategy_pairings - WHERE {where_clause} - ORDER BY created_at DESC - """), - params, - ) - rows = result.fetchall() + stmt = select(Pairing) + if strategy_id: + stmt = stmt.where(Pairing.strategy_id == strategy_id) + stmt = stmt.order_by(Pairing.created_at.desc()) + + result = await session.execute(stmt) + pairings = result.scalars().all() items = [] - for row in rows: - pairing_id = row[0] - initial_capital = float(row[3]) if row[3] else 0 - available_capital = float(row[4]) if row[4] else 0 + for pairing in pairings: + initial_capital = ( + float(pairing.initial_capital) if pairing.initial_capital else 0 + ) + available_capital = ( + float(pairing.available_capital) if pairing.available_capital else 0 + ) # 计算持仓市值 - position_result = await session.execute( - text(""" - SELECT SUM(quantity * cost_price) as position_value - FROM positions - WHERE pairing_id = :pairing_id AND quantity > 0 - """), - {"pairing_id": pairing_id}, - ) - position_row = position_result.fetchone() - position_value = ( - float(position_row[0]) if position_row and position_row[0] else 0 + position_stmt = select( + func.sum(Position.quantity * Position.avg_cost) + ).where( + Position.pairing_id == pairing.id, + Position.quantity > 0, ) + position_result = await session.execute(position_stmt) + position_value = float(position_result.scalar() or 0) total_assets = available_capital + position_value pnl = total_assets - initial_capital items.append( { - "pairing_id": pairing_id, - "symbol": row[1], - "strategy_id": row[2], + "pairing_id": pairing.id, + "symbol": pairing.symbol, + "strategy_id": pairing.strategy_id, "initial_capital": initial_capital, "available_capital": available_capital, "position_value": position_value, "total_assets": total_assets, "pnl": pnl, - "status": row[5], + "status": pairing.status.value if pairing.status else None, } ) @@ -154,39 +140,30 @@ class BalanceService: """获取资金汇总""" async with db.session() as session: # 汇总所有配对资金 - result = await session.execute( - text(""" - SELECT - COUNT(*) as pairing_count, - SUM(initial_capital) as total_initial, - SUM(available_capital) as total_available - FROM symbol_strategy_pairings - """) + stmt = select( + func.count(Pairing.id).label("pairing_count"), + func.sum(Pairing.initial_capital).label("total_initial"), + func.sum(Pairing.available_capital).label("total_available"), ) - row = result.fetchone() + result = await session.execute(stmt) + row = result.one() - total_initial = float(row[1]) if row and row[1] else 0 - total_available = float(row[2]) if row and row[2] else 0 + total_initial = float(row.total_initial) if row.total_initial else 0 + total_available = float(row.total_available) if row.total_available else 0 # 计算所有持仓市值 - position_result = await session.execute( - text(""" - SELECT SUM(quantity * cost_price) as total_position_value - FROM positions - WHERE quantity > 0 - """) - ) - position_row = position_result.fetchone() - total_position_value = ( - float(position_row[0]) if position_row and position_row[0] else 0 - ) + position_stmt = select( + func.sum(Position.quantity * Position.avg_cost) + ).where(Position.quantity > 0) + position_result = await session.execute(position_stmt) + total_position_value = float(position_result.scalar() or 0) total_assets = total_available + total_position_value total_pnl = total_assets - total_initial total_pnl_ratio = total_pnl / total_initial if total_initial > 0 else 0 return { - "pairing_count": row[0] if row else 0, + "pairing_count": row.pairing_count or 0, "total_initial_capital": total_initial, "total_available_capital": total_available, "total_position_value": total_position_value, @@ -213,55 +190,38 @@ class BalanceService: 调整后的资金信息 """ now = dt.now() + amount_decimal = Decimal(str(amount)) async with db.session() as session: # 检查配对是否存在 - result = await session.execute( - text( - "SELECT id, initial_capital, available_capital FROM symbol_strategy_pairings WHERE id = :id" - ), - {"id": pairing_id}, - ) - row = result.fetchone() + stmt = select(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() - if not row: + if not pairing: return None - new_initial = float(row[1] or 0) + amount - new_available = float(row[2] or 0) + amount + new_initial = (pairing.initial_capital or Decimal(0)) + amount_decimal + new_available = (pairing.available_capital or Decimal(0)) + amount_decimal if new_initial < 0 or new_available < 0: raise ValueError("资金不足,无法调整") # 更新资金 - await session.execute( - text(""" - UPDATE symbol_strategy_pairings - SET initial_capital = :initial, available_capital = :available, updated_at = :updated_at - WHERE id = :id - """), - { - "id": pairing_id, - "initial": new_initial, - "available": new_available, - "updated_at": now, - }, - ) + pairing.initial_capital = new_initial + pairing.available_capital = new_available + pairing.updated_at = now # 记录调整日志 - await session.execute( - text(""" - INSERT INTO balance_logs (pairing_id, amount, reason, created_at) - VALUES (:pairing_id, :amount, :reason, :created_at) - """), - { - "pairing_id": pairing_id, - "amount": amount, - "reason": reason, - "created_at": now, - }, + log = BalanceLog( + pairing_id=pairing_id, + log_type=BalanceLogType.ADJUST, + amount=amount_decimal, + balance_after=new_available, + description=reason, + created_at=now, ) - + session.add(log) await session.commit() logger.info(f"资金调整: {pairing_id}, {amount}, {reason}") diff --git a/src/core_service/services/order_service.py b/src/core_service/services/order_service.py index 38d202c..95a199c 100644 --- a/src/core_service/services/order_service.py +++ b/src/core_service/services/order_service.py @@ -9,13 +9,16 @@ import uuid import asyncio from typing import Any, Optional from datetime import datetime as dt, date +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select, func, update, case, and_ +from sqlalchemy.ext.asyncio import AsyncSession from src.core.database import db from src.core.redis_client import redis_client from src.core.logger import get_logger -from src.core.models.order import OrderCreate, OrderStatus, OrderSide +from src.core.models import Order, OrderStatus, OrderSide, OrderType, Pairing, Position +from src.core.schemas.order import OrderCreate logger = get_logger("core_service.order_service") @@ -61,65 +64,45 @@ class OrderService: async with db.session() as session: # 检查配对是否存在且运行中 - result = await session.execute( - text(""" - SELECT id, status, available_capital - FROM symbol_strategy_pairings - WHERE id = :pairing_id - """), - {"pairing_id": order.pairing_id}, - ) - pairing = result.fetchone() + stmt = select(Pairing).where(Pairing.id == order.pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() if not pairing: raise ValueError(f"配对不存在: {order.pairing_id}") - if pairing[1] != "ACTIVE": + from src.core.models import PairingStatus + + if pairing.status != PairingStatus.ACTIVE: raise ValueError(f"配对未运行: {order.pairing_id}") # 买入时检查资金 if order.side == OrderSide.BUY: - required = order.price * order.quantity - if float(pairing[2] or 0) < required: - raise ValueError(f"资金不足: 需要 {required}, 可用 {pairing[2]}") + required = Decimal(str(order.price)) * order.quantity + if (pairing.available_capital or Decimal(0)) < required: + raise ValueError( + f"资金不足: 需要 {required}, 可用 {pairing.available_capital}" + ) - # 创建订单 - await session.execute( - text(""" - INSERT INTO orders - (id, pairing_id, symbol, side, order_type, price, quantity, - filled_quantity, status, created_at, updated_at) - VALUES (:id, :pairing_id, :symbol, :side, :order_type, :price, - :quantity, :filled_quantity, :status, :created_at, :updated_at) - """), - { - "id": order_id, - "pairing_id": order.pairing_id, - "symbol": order.symbol, - "side": order.side.value, - "order_type": order.order_type.value, - "price": order.price, - "quantity": order.quantity, - "filled_quantity": 0, - "status": OrderStatus.PENDING.value, - "created_at": now, - "updated_at": now, - }, + # 创建订单对象 + new_order = Order( + id=order_id, + pairing_id=order.pairing_id, + symbol=order.symbol, + side=order.side, + order_type=order.order_type, + price=Decimal(str(order.price)), + quantity=order.quantity, + filled_quantity=0, + status=OrderStatus.PENDING, + created_at=now, + updated_at=now, ) + session.add(new_order) await session.commit() + await session.refresh(new_order) - order_data = { - "order_id": order_id, - "pairing_id": order.pairing_id, - "symbol": order.symbol, - "side": order.side.value, - "order_type": order.order_type.value, - "price": order.price, - "quantity": order.quantity, - "filled_quantity": 0, - "status": OrderStatus.PENDING.value, - "created_at": now.isoformat(), - } + order_data = new_order.to_dict() # 发布订单创建事件(QMT 适配器监听) import json @@ -138,32 +121,20 @@ class OrderService: async with db.session() as session: # 检查订单状态 - result = await session.execute( - text("SELECT id, status FROM orders WHERE id = :id"), - {"id": order_id}, - ) - row = result.fetchone() + stmt = select(Order).where(Order.id == order_id) + result = await session.execute(stmt) + order = result.scalar_one_or_none() - if not row: + if not order: return None - if row[1] not in [OrderStatus.PENDING.value, OrderStatus.PARTIAL.value]: - raise ValueError(f"订单状态不允许撤销: {row[1]}") + if order.status not in [OrderStatus.PENDING, OrderStatus.PARTIAL]: + raise ValueError(f"订单状态不允许撤销: {order.status.value}") # 更新状态 - await session.execute( - text(""" - UPDATE orders - SET status = :status, cancel_reason = :reason, updated_at = :updated_at - WHERE id = :id - """), - { - "id": order_id, - "status": OrderStatus.CANCELLED.value, - "reason": reason, - "updated_at": now, - }, - ) + order.status = OrderStatus.CANCELLED + order.cancel_reason = reason + order.updated_at = now await session.commit() # 发布撤单事件 @@ -174,36 +145,14 @@ class OrderService: async def get_order(self, order_id: str) -> Optional[dict[str, Any]]: """获取订单详情""" async with db.session() as session: - result = await session.execute( - text(""" - SELECT id, pairing_id, symbol, side, order_type, price, quantity, - filled_quantity, filled_price, status, cancel_reason, - created_at, updated_at - FROM orders - WHERE id = :id - """), - {"id": order_id}, - ) - row = result.fetchone() + stmt = select(Order).where(Order.id == order_id) + result = await session.execute(stmt) + order = result.scalar_one_or_none() - if not row: + if not order: return None - return { - "order_id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "side": row[3], - "order_type": row[4], - "price": float(row[5]) if row[5] else 0, - "quantity": row[6], - "filled_quantity": row[7], - "filled_price": float(row[8]) if row[8] else None, - "status": row[9], - "cancel_reason": row[10], - "created_at": row[11].isoformat() if row[11] else None, - "updated_at": row[12].isoformat() if row[12] else None, - } + return order.to_dict() async def list_orders( self, @@ -214,65 +163,35 @@ class OrderService: page_size: int = 20, ) -> dict[str, Any]: """查询订单列表""" - conditions = ["1=1"] - params: dict[str, Any] = {} - - if pairing_id: - conditions.append("pairing_id = :pairing_id") - params["pairing_id"] = pairing_id - - if symbol: - conditions.append("symbol = :symbol") - params["symbol"] = symbol - - if status: - conditions.append("status = :status") - params["status"] = status.value - - where_clause = " AND ".join(conditions) - offset = (page - 1) * page_size - async with db.session() as session: + # 构建查询 + stmt = select(Order) + count_stmt = select(func.count(Order.id)) + + if pairing_id: + stmt = stmt.where(Order.pairing_id == pairing_id) + count_stmt = count_stmt.where(Order.pairing_id == pairing_id) + if symbol: + stmt = stmt.where(Order.symbol == symbol) + count_stmt = count_stmt.where(Order.symbol == symbol) + if status: + stmt = stmt.where(Order.status == status) + count_stmt = count_stmt.where(Order.status == status) + # 查询总数 - count_result = await session.execute( - text(f"SELECT COUNT(*) FROM orders WHERE {where_clause}"), - params, - ) - total = count_result.scalar() or 0 + total_result = await session.execute(count_stmt) + total = total_result.scalar() or 0 - # 查询列表 - result = await session.execute( - text(f""" - SELECT id, pairing_id, symbol, side, order_type, price, quantity, - filled_quantity, status, created_at - FROM orders - WHERE {where_clause} - ORDER BY created_at DESC - LIMIT :limit OFFSET :offset - """), - {**params, "limit": page_size, "offset": offset}, + # 分页查询 + offset = (page - 1) * page_size + stmt = ( + stmt.order_by(Order.created_at.desc()).offset(offset).limit(page_size) ) - rows = result.fetchall() - - items = [] - for row in rows: - items.append( - { - "order_id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "side": row[3], - "order_type": row[4], - "price": float(row[5]) if row[5] else 0, - "quantity": row[6], - "filled_quantity": row[7], - "status": row[8], - "created_at": row[9].isoformat() if row[9] else None, - } - ) + result = await session.execute(stmt) + orders = result.scalars().all() return { - "items": items, + "items": [o.to_dict() for o in orders], "total": total, "page": page, "page_size": page_size, @@ -363,50 +282,35 @@ class OrderService: async with db.session() as session: # 获取订单信息 - result = await session.execute( - text(""" - SELECT id, pairing_id, symbol, side, quantity, filled_quantity - FROM orders - WHERE id = :id - """), - {"id": order_id}, - ) - order = result.fetchone() + stmt = select(Order).where(Order.id == order_id) + result = await session.execute(stmt) + order = result.scalar_one_or_none() if not order: logger.warning(f"订单不存在: {order_id}") return # 更新已成交数量 - new_filled = (order[5] or 0) + filled_qty + new_filled = (order.filled_quantity or 0) + filled_qty new_status = ( - OrderStatus.FILLED.value - if new_filled >= order[4] - else OrderStatus.PARTIAL.value + OrderStatus.FILLED + if new_filled >= order.quantity + else OrderStatus.PARTIAL ) - await session.execute( - text(""" - UPDATE orders - SET filled_quantity = :filled_qty, filled_price = :filled_price, - status = :status, updated_at = :updated_at - WHERE id = :id - """), - { - "id": order_id, - "filled_qty": new_filled, - "filled_price": filled_price, - "status": new_status, - "updated_at": now, - }, - ) + order.filled_quantity = new_filled + order.filled_price = Decimal(str(filled_price)) + order.status = new_status + order.updated_at = now # 更新持仓 await self._update_position( session=session, - pairing_id=order[1], - symbol=order[2], - side=order[3], + pairing_id=order.pairing_id, + symbol=order.symbol, + side=order.side.value + if isinstance(order.side, OrderSide) + else order.side, quantity=filled_qty, price=filled_price, ) @@ -426,102 +330,71 @@ class OrderService: ) -> None: """更新持仓""" # 获取当前持仓 - result = await session.execute( - text(""" - SELECT id, quantity, cost_price - FROM positions - WHERE pairing_id = :pairing_id AND symbol = :symbol - """), - {"pairing_id": pairing_id, "symbol": symbol}, + stmt = select(Position).where( + Position.pairing_id == pairing_id, + Position.symbol == symbol, ) - position = result.fetchone() + result = await session.execute(stmt) + position = result.scalar_one_or_none() now = dt.now() + price_decimal = Decimal(str(price)) if side == "buy": if position: # 更新持仓 - old_qty = position[1] or 0 - old_cost = float(position[2] or 0) + old_qty = position.quantity or 0 + old_cost = position.avg_cost or Decimal(0) new_qty = old_qty + quantity # 加权平均成本 new_cost = ( - (old_qty * old_cost + quantity * price) / new_qty + (old_qty * old_cost + quantity * price_decimal) / new_qty if new_qty > 0 - else 0 + else Decimal(0) ) - await session.execute( - text(""" - UPDATE positions - SET quantity = :quantity, cost_price = :cost_price, updated_at = :updated_at - WHERE id = :id - """), - { - "id": position[0], - "quantity": new_qty, - "cost_price": new_cost, - "updated_at": now, - }, - ) + position.quantity = new_qty + position.avg_cost = new_cost + position.total_cost = new_cost * new_qty + position.updated_at = now else: # 创建持仓 position_id = str(uuid.uuid4())[:8] - await session.execute( - text(""" - INSERT INTO positions - (id, pairing_id, symbol, quantity, available, frozen, cost_price, created_at, updated_at) - VALUES (:id, :pairing_id, :symbol, :quantity, :available, :frozen, :cost_price, :created_at, :updated_at) - """), - { - "id": position_id, - "pairing_id": pairing_id, - "symbol": symbol, - "quantity": quantity, - "available": quantity, - "frozen": 0, - "cost_price": price, - "created_at": now, - "updated_at": now, - }, + new_position = Position( + id=position_id, + pairing_id=pairing_id, + symbol=symbol, + quantity=quantity, + available=quantity, + frozen=0, + avg_cost=price_decimal, + total_cost=price_decimal * quantity, + created_at=now, + updated_at=now, ) + session.add(new_position) else: # sell if position: - new_qty = max(0, (position[1] or 0) - quantity) - await session.execute( - text(""" - UPDATE positions - SET quantity = :quantity, available = :available, updated_at = :updated_at - WHERE id = :id - """), - { - "id": position[0], - "quantity": new_qty, - "available": new_qty, - "updated_at": now, - }, - ) + new_qty = max(0, (position.quantity or 0) - quantity) + position.quantity = new_qty + position.available = new_qty + position.updated_at = now # 更新配对资金 - amount = quantity * price - if side == "buy": - await session.execute( - text(""" - UPDATE symbol_strategy_pairings - SET available_capital = available_capital - :amount - WHERE id = :pairing_id - """), - {"pairing_id": pairing_id, "amount": amount}, - ) - else: - await session.execute( - text(""" - UPDATE symbol_strategy_pairings - SET available_capital = available_capital + :amount - WHERE id = :pairing_id - """), - {"pairing_id": pairing_id, "amount": amount}, - ) + stmt = select(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() + + if pairing: + amount = Decimal(str(quantity * price)) + if side == "buy": + pairing.available_capital = ( + pairing.available_capital or Decimal(0) + ) - amount + else: + pairing.available_capital = ( + pairing.available_capital or Decimal(0) + ) + amount # 单例 diff --git a/src/core_service/services/pairing_service.py b/src/core_service/services/pairing_service.py index fdbb5a9..55d4393 100644 --- a/src/core_service/services/pairing_service.py +++ b/src/core_service/services/pairing_service.py @@ -7,13 +7,15 @@ import uuid from typing import Any, Optional from datetime import datetime as dt +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select, func, delete, update from src.core.database import db from src.core.redis_client import redis_client from src.core.logger import get_logger -from src.core.models.symbol_strategy import PairingCreate, PairingStatus +from src.core.models import Pairing, PairingStatus +from src.core.schemas.pairing import PairingCreate logger = get_logger("core_service.pairing_service") @@ -37,67 +39,41 @@ class PairingService: pairing_id = str(uuid.uuid4())[:8] now = dt.now() - # 检查是否已存在相同配对 async with db.session() as session: - result = await session.execute( - text(""" - SELECT id FROM symbol_strategy_pairings - WHERE symbol = :symbol AND strategy_id = :strategy_id - AND status != 'stopped' - """), - {"symbol": pairing.symbol, "strategy_id": pairing.strategy_id}, + # 检查是否已存在相同配对 + stmt = select(Pairing).where( + Pairing.symbol == pairing.symbol, + Pairing.strategy_id == pairing.strategy_id, + Pairing.status != PairingStatus.STOPPED, ) - existing = result.fetchone() + result = await session.execute(stmt) + existing = result.scalar_one_or_none() if existing: raise ValueError( f"已存在相同配对: {pairing.symbol} - {pairing.strategy_id}" ) - # 创建配对 - await session.execute( - text(""" - INSERT INTO symbol_strategy_pairings - (id, symbol, strategy_id, status, initial_capital, available_capital, - params, created_at, updated_at) - VALUES (:id, :symbol, :strategy_id, :status, :initial_capital, - :available_capital, :params, :created_at, :updated_at) - """), - { - "id": pairing_id, - "symbol": pairing.symbol, - "strategy_id": pairing.strategy_id, - "status": PairingStatus.STOPPED.value, - "initial_capital": pairing.initial_capital, - "available_capital": pairing.initial_capital, - "params": pairing.params or "{}", - "created_at": now, - "updated_at": now, - }, + # 创建配对对象 + new_pairing = Pairing( + id=pairing_id, + symbol=pairing.symbol, + strategy_id=pairing.strategy_id, + status=PairingStatus.STOPPED, + initial_capital=Decimal(str(pairing.initial_capital)), + available_capital=Decimal(str(pairing.initial_capital)), + params=pairing.params or "{}", + created_at=now, + updated_at=now, ) + session.add(new_pairing) await session.commit() + await session.refresh(new_pairing) # 缓存到 Redis - await self._cache_pairing( - pairing_id, - { - "id": pairing_id, - "symbol": pairing.symbol, - "strategy_id": pairing.strategy_id, - "status": PairingStatus.STOPPED.value, - "initial_capital": pairing.initial_capital, - "available_capital": pairing.initial_capital, - }, - ) + await self._cache_pairing(pairing_id, new_pairing.to_dict()) - return { - "id": pairing_id, - "symbol": pairing.symbol, - "strategy_id": pairing.strategy_id, - "status": PairingStatus.STOPPED.value, - "initial_capital": pairing.initial_capital, - "created_at": now.isoformat(), - } + return new_pairing.to_dict() async def get(self, pairing_id: str) -> Optional[dict[str, Any]]: """获取配对详情""" @@ -108,31 +84,14 @@ class PairingService: # 从数据库获取 async with db.session() as session: - result = await session.execute( - text(""" - SELECT id, symbol, strategy_id, status, initial_capital, - available_capital, params, created_at, updated_at - FROM symbol_strategy_pairings - WHERE id = :id - """), - {"id": pairing_id}, - ) - row = result.fetchone() + stmt = select(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() - if not row: + if not pairing: return None - data = { - "id": row[0], - "symbol": row[1], - "strategy_id": row[2], - "status": row[3], - "initial_capital": float(row[4]) if row[4] else 0, - "available_capital": float(row[5]) if row[5] else 0, - "params": row[6], - "created_at": row[7].isoformat() if row[7] else None, - "updated_at": row[8].isoformat() if row[8] else None, - } + data = pairing.to_dict() # 缓存 await self._cache_pairing(pairing_id, data) @@ -148,65 +107,35 @@ class PairingService: page_size: int = 20, ) -> dict[str, Any]: """查询配对列表""" - conditions = ["1=1"] - params: dict[str, Any] = {} - - if symbol: - conditions.append("symbol = :symbol") - params["symbol"] = symbol - - if strategy_id: - conditions.append("strategy_id = :strategy_id") - params["strategy_id"] = strategy_id - - if status: - conditions.append("status = :status") - params["status"] = status.value - - where_clause = " AND ".join(conditions) - offset = (page - 1) * page_size - async with db.session() as session: + # 构建查询条件 + stmt = select(Pairing) + count_stmt = select(func.count(Pairing.id)) + + if symbol: + stmt = stmt.where(Pairing.symbol == symbol) + count_stmt = count_stmt.where(Pairing.symbol == symbol) + if strategy_id: + stmt = stmt.where(Pairing.strategy_id == strategy_id) + count_stmt = count_stmt.where(Pairing.strategy_id == strategy_id) + if status: + stmt = stmt.where(Pairing.status == status) + count_stmt = count_stmt.where(Pairing.status == status) + # 查询总数 - count_result = await session.execute( - text( - f"SELECT COUNT(*) FROM symbol_strategy_pairings WHERE {where_clause}" - ), - params, - ) - total = count_result.scalar() or 0 + total_result = await session.execute(count_stmt) + total = total_result.scalar() or 0 - # 查询列表 - result = await session.execute( - text(f""" - SELECT id, symbol, strategy_id, status, initial_capital, - available_capital, created_at, updated_at - FROM symbol_strategy_pairings - WHERE {where_clause} - ORDER BY created_at DESC - LIMIT :limit OFFSET :offset - """), - {**params, "limit": page_size, "offset": offset}, + # 分页查询 + offset = (page - 1) * page_size + stmt = ( + stmt.order_by(Pairing.created_at.desc()).offset(offset).limit(page_size) ) - rows = result.fetchall() - - items = [] - for row in rows: - items.append( - { - "id": row[0], - "symbol": row[1], - "strategy_id": row[2], - "status": row[3], - "initial_capital": float(row[4]) if row[4] else 0, - "available_capital": float(row[5]) if row[5] else 0, - "created_at": row[6].isoformat() if row[6] else None, - "updated_at": row[7].isoformat() if row[7] else None, - } - ) + result = await session.execute(stmt) + pairings = result.scalars().all() return { - "items": items, + "items": [p.to_dict() for p in pairings], "total": total, "page": page, "page_size": page_size, @@ -221,24 +150,18 @@ class PairingService: now = dt.now() async with db.session() as session: - # 检查是否存在 - result = await session.execute( - text("SELECT id FROM symbol_strategy_pairings WHERE id = :id"), - {"id": pairing_id}, - ) - if not result.fetchone(): + # 查询并更新 + stmt = select(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) + pairing = result.scalar_one_or_none() + + if not pairing: return None - # 更新状态 - await session.execute( - text(""" - UPDATE symbol_strategy_pairings - SET status = :status, updated_at = :updated_at - WHERE id = :id - """), - {"id": pairing_id, "status": status.value, "updated_at": now}, - ) + pairing.status = status + pairing.updated_at = now await session.commit() + await session.refresh(pairing) # 更新缓存 await self._invalidate_pairing_cache(pairing_id) @@ -253,10 +176,8 @@ class PairingService: async def delete(self, pairing_id: str) -> bool: """删除配对""" async with db.session() as session: - result = await session.execute( - text("DELETE FROM symbol_strategy_pairings WHERE id = :id"), - {"id": pairing_id}, - ) + stmt = delete(Pairing).where(Pairing.id == pairing_id) + result = await session.execute(stmt) await session.commit() if result.rowcount == 0: # type: ignore @@ -270,29 +191,11 @@ class PairingService: async def get_active_pairings(self) -> list[dict[str, Any]]: """获取所有运行中的配对""" async with db.session() as session: - result = await session.execute( - text(""" - SELECT id, symbol, strategy_id, status, initial_capital, - available_capital, params - FROM symbol_strategy_pairings - WHERE status = :status - """), - {"status": PairingStatus.ACTIVE.value}, - ) - rows = result.fetchall() + stmt = select(Pairing).where(Pairing.status == PairingStatus.ACTIVE) + result = await session.execute(stmt) + pairings = result.scalars().all() - return [ - { - "id": row[0], - "symbol": row[1], - "strategy_id": row[2], - "status": row[3], - "initial_capital": float(row[4]) if row[4] else 0, - "available_capital": float(row[5]) if row[5] else 0, - "params": row[6], - } - for row in rows - ] + return [p.to_dict() for p in pairings] async def _cache_pairing(self, pairing_id: str, data: dict[str, Any]) -> None: """缓存配对信息""" diff --git a/src/core_service/services/position_service.py b/src/core_service/services/position_service.py index 7fd44df..db08319 100644 --- a/src/core_service/services/position_service.py +++ b/src/core_service/services/position_service.py @@ -5,12 +5,14 @@ """ from typing import Any, Optional +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select, func from src.core.database import db from src.core.redis_client import redis_client from src.core.logger import get_logger +from src.core.models import Position, Pairing logger = get_logger("core_service.position_service") @@ -32,46 +34,34 @@ class PositionService: 持仓信息 """ async with db.session() as session: - result = await session.execute( - text(""" - SELECT p.id, p.pairing_id, p.symbol, p.quantity, p.available, - p.frozen, p.cost_price, p.created_at, p.updated_at - FROM positions p - WHERE p.pairing_id = :pairing_id - """), - {"pairing_id": pairing_id}, - ) - row = result.fetchone() + stmt = select(Position).where(Position.pairing_id == pairing_id) + result = await session.execute(stmt) + position = result.scalar_one_or_none() - if not row: + if not position: return None - quantity = row[3] or 0 - cost_price = float(row[6]) if row[6] else 0 + quantity = position.quantity or 0 + cost_price = float(position.avg_cost) if position.avg_cost else 0 # 获取最新价格计算市值和盈亏 - latest_price = await self._get_latest_price(row[2]) + latest_price = await self._get_latest_price(position.symbol) market_value = quantity * latest_price pnl = (latest_price - cost_price) * quantity if cost_price > 0 else 0 pnl_ratio = ( (latest_price - cost_price) / cost_price if cost_price > 0 else 0 ) - return { - "id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "quantity": quantity, - "available": row[4] or 0, - "frozen": row[5] or 0, - "cost_price": cost_price, - "latest_price": latest_price, - "market_value": market_value, - "pnl": pnl, - "pnl_ratio": pnl_ratio, - "created_at": row[7].isoformat() if row[7] else None, - "updated_at": row[8].isoformat() if row[8] else None, - } + data = position.to_dict() + data.update( + { + "latest_price": latest_price, + "market_value": market_value, + "pnl": pnl, + "pnl_ratio": pnl_ratio, + } + ) + return data async def list_positions( self, @@ -80,63 +70,47 @@ class PositionService: has_position: Optional[bool] = None, ) -> dict[str, Any]: """查询持仓列表""" - conditions = ["1=1"] - params: dict[str, Any] = {} - - if strategy_id: - conditions.append("sp.strategy_id = :strategy_id") - params["strategy_id"] = strategy_id - - if symbol: - conditions.append("p.symbol = :symbol") - params["symbol"] = symbol - - if has_position is True: - conditions.append("p.quantity > 0") - elif has_position is False: - conditions.append("(p.quantity = 0 OR p.quantity IS NULL)") - - where_clause = " AND ".join(conditions) - async with db.session() as session: - result = await session.execute( - text(f""" - SELECT p.id, p.pairing_id, p.symbol, p.quantity, p.available, - p.frozen, p.cost_price, sp.strategy_id - FROM positions p - JOIN symbol_strategy_pairings sp ON p.pairing_id = sp.id - WHERE {where_clause} - ORDER BY p.updated_at DESC - """), - params, + # 联表查询 + stmt = select(Position, Pairing.strategy_id).join( + Pairing, Position.pairing_id == Pairing.id ) - rows = result.fetchall() + + if strategy_id: + stmt = stmt.where(Pairing.strategy_id == strategy_id) + if symbol: + stmt = stmt.where(Position.symbol == symbol) + if has_position is True: + stmt = stmt.where(Position.quantity > 0) + elif has_position is False: + stmt = stmt.where( + (Position.quantity == 0) | (Position.quantity.is_(None)) + ) + + stmt = stmt.order_by(Position.updated_at.desc()) + result = await session.execute(stmt) + rows = result.all() items = [] - for row in rows: - quantity = row[3] or 0 - cost_price = float(row[6]) if row[6] else 0 + for position, strat_id in rows: + quantity = position.quantity or 0 + cost_price = float(position.avg_cost) if position.avg_cost else 0 # 获取最新价格 - latest_price = await self._get_latest_price(row[2]) + latest_price = await self._get_latest_price(position.symbol) market_value = quantity * latest_price pnl = (latest_price - cost_price) * quantity if cost_price > 0 else 0 - items.append( + data = position.to_dict() + data.update( { - "id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "quantity": quantity, - "available": row[4] or 0, - "frozen": row[5] or 0, - "cost_price": cost_price, "latest_price": latest_price, "market_value": market_value, "pnl": pnl, - "strategy_id": row[7], + "strategy_id": strat_id, } ) + items.append(data) return { "items": items, @@ -146,35 +120,27 @@ class PositionService: async def get_summary(self) -> dict[str, Any]: """获取持仓汇总""" async with db.session() as session: - result = await session.execute( - text(""" - SELECT - COUNT(DISTINCT p.pairing_id) as pairing_count, - COUNT(DISTINCT p.symbol) as symbol_count, - SUM(p.quantity) as total_quantity - FROM positions p - WHERE p.quantity > 0 - """) - ) - row = result.fetchone() + # 统计有持仓的数量 + stmt = select( + func.count(func.distinct(Position.pairing_id)).label("pairing_count"), + func.count(func.distinct(Position.symbol)).label("symbol_count"), + func.sum(Position.quantity).label("total_quantity"), + ).where(Position.quantity > 0) + result = await session.execute(stmt) + row = result.one() - # 计算总市值 - positions_result = await session.execute( - text(""" - SELECT symbol, quantity, cost_price - FROM positions - WHERE quantity > 0 - """) - ) - positions = positions_result.fetchall() + # 查询所有有持仓的记录 + positions_stmt = select(Position).where(Position.quantity > 0) + positions_result = await session.execute(positions_stmt) + positions = positions_result.scalars().all() total_market_value = 0.0 total_cost = 0.0 for pos in positions: - quantity = pos[1] or 0 - cost_price = float(pos[2]) if pos[2] else 0 - latest_price = await self._get_latest_price(pos[0]) + quantity = pos.quantity or 0 + cost_price = float(pos.avg_cost) if pos.avg_cost else 0 + latest_price = await self._get_latest_price(pos.symbol) total_market_value += quantity * latest_price total_cost += quantity * cost_price @@ -183,9 +149,9 @@ class PositionService: total_pnl_ratio = total_pnl / total_cost if total_cost > 0 else 0 return { - "pairing_count": row[0] if row else 0, - "symbol_count": row[1] if row else 0, - "total_quantity": row[2] if row else 0, + "pairing_count": row.pairing_count or 0, + "symbol_count": row.symbol_count or 0, + "total_quantity": row.total_quantity or 0, "total_market_value": total_market_value, "total_cost": total_cost, "total_pnl": total_pnl, diff --git a/src/data_service/services/kline_service.py b/src/data_service/services/kline_service.py index f504b72..61f6116 100644 --- a/src/data_service/services/kline_service.py +++ b/src/data_service/services/kline_service.py @@ -10,25 +10,36 @@ K线存储与查询服务 import asyncio from typing import Any, Optional from datetime import datetime as dt, timedelta +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select +from sqlalchemy.dialects.mysql import insert as mysql_insert from src.core.logger import get_logger from src.core.database import db from src.core.redis_client import redis_client, RedisChannels +from src.core.models import ( + Kline1m, + Kline5m, + Kline15m, + Kline30m, + Kline60m, + Kline1d, + get_kline_model, + KLINE_MODELS, +) logger = get_logger("data_service.kline_service") # K线周期配置 KLINE_PERIODS = { - "1m": {"table": "klines_1m", "interval": timedelta(minutes=1)}, - "5m": {"table": "klines_5m", "interval": timedelta(minutes=5)}, - "15m": {"table": "klines_15m", "interval": timedelta(minutes=15)}, - "30m": {"table": "klines_30m", "interval": timedelta(minutes=30)}, - "60m": {"table": "klines_60m", "interval": timedelta(minutes=60)}, - "1d": {"table": "klines_1d", "interval": timedelta(days=1)}, - "1w": {"table": "klines_1w", "interval": timedelta(weeks=1)}, + "1m": {"model": Kline1m, "interval": timedelta(minutes=1)}, + "5m": {"model": Kline5m, "interval": timedelta(minutes=5)}, + "15m": {"model": Kline15m, "interval": timedelta(minutes=15)}, + "30m": {"model": Kline30m, "interval": timedelta(minutes=30)}, + "60m": {"model": Kline60m, "interval": timedelta(minutes=60)}, + "1d": {"model": Kline1d, "interval": timedelta(days=1)}, } @@ -162,39 +173,31 @@ class KlineService: logger.warning(f"未知K线周期: {period}") return - table_name = config["table"] - - # 使用 INSERT ... ON DUPLICATE KEY UPDATE - query = text(f""" - INSERT INTO {table_name} - (symbol, open, high, low, close, volume, amount, timestamp) - VALUES - (:symbol, :open, :high, :low, :close, :volume, :amount, :timestamp) - ON DUPLICATE KEY UPDATE - open = VALUES(open), - high = VALUES(high), - low = VALUES(low), - close = VALUES(close), - volume = VALUES(volume), - amount = VALUES(amount) - """) + model = config["model"] try: async with db.session() as session: for kline in klines: - await session.execute( - query, - { - "symbol": kline.get("symbol"), - "open": kline.get("open", 0), - "high": kline.get("high", 0), - "low": kline.get("low", 0), - "close": kline.get("close", 0), - "volume": kline.get("volume", 0), - "amount": kline.get("amount", 0), - "timestamp": kline.get("timestamp"), - }, + # 使用 MySQL 的 INSERT ... ON DUPLICATE KEY UPDATE + stmt = mysql_insert(model).values( + symbol=kline.get("symbol"), + time=kline.get("timestamp"), + open=Decimal(str(kline.get("open", 0))), + high=Decimal(str(kline.get("high", 0))), + low=Decimal(str(kline.get("low", 0))), + close=Decimal(str(kline.get("close", 0))), + volume=kline.get("volume", 0), + amount=Decimal(str(kline.get("amount", 0))), ) + stmt = stmt.on_duplicate_key_update( + open=stmt.inserted.open, + high=stmt.inserted.high, + low=stmt.inserted.low, + close=stmt.inserted.close, + volume=stmt.inserted.volume, + amount=stmt.inserted.amount, + ) + await session.execute(stmt) await session.commit() except Exception as e: logger.error(f"保存K线失败: {e}") @@ -224,47 +227,25 @@ class KlineService: if not config: return [] - table_name = config["table"] - - conditions = ["symbol = :symbol"] - params: dict[str, Any] = {"symbol": symbol, "limit": limit} - - if start_time: - conditions.append("timestamp >= :start_time") - params["start_time"] = start_time - - if end_time: - conditions.append("timestamp <= :end_time") - params["end_time"] = end_time - - where_clause = " AND ".join(conditions) - - query = text(f""" - SELECT symbol, open, high, low, close, volume, amount, timestamp - FROM {table_name} - WHERE {where_clause} - ORDER BY timestamp DESC - LIMIT :limit - """) + model = config["model"] try: async with db.session() as session: - result = await session.execute(query, params) - rows = result.fetchall() + # 构建查询 + stmt = select(model).where(model.symbol == symbol) - return [ - { - "symbol": row[0], - "open": float(row[1]) if row[1] else 0, - "high": float(row[2]) if row[2] else 0, - "low": float(row[3]) if row[3] else 0, - "close": float(row[4]) if row[4] else 0, - "volume": int(row[5]) if row[5] else 0, - "amount": float(row[6]) if row[6] else 0, - "timestamp": row[7].isoformat() if row[7] else None, - } - for row in reversed(rows) - ] + if start_time: + stmt = stmt.where(model.time >= start_time) + if end_time: + stmt = stmt.where(model.time <= end_time) + + stmt = stmt.order_by(model.time.desc()).limit(limit) + + result = await session.execute(stmt) + rows = result.scalars().all() + + # 返回时间正序 + return [kline.to_dict() for kline in reversed(rows)] except Exception as e: logger.error(f"查询K线失败: {e}") return [] diff --git a/src/gateway/routes/account.py b/src/gateway/routes/account.py index 3053e7d..d1593ac 100644 --- a/src/gateway/routes/account.py +++ b/src/gateway/routes/account.py @@ -9,7 +9,8 @@ from typing import Any, Optional from fastapi import APIRouter, Query from src.core.logger import get_logger -from src.core.models.symbol_strategy import PairingCreate, PairingStatus +from src.core.models import PairingStatus +from src.core.schemas.pairing import PairingCreate router = APIRouter() logger = get_logger("gateway.account") diff --git a/src/gateway/routes/trading.py b/src/gateway/routes/trading.py index 8d1ed3d..2447d7a 100644 --- a/src/gateway/routes/trading.py +++ b/src/gateway/routes/trading.py @@ -9,7 +9,8 @@ from typing import Any, Optional from fastapi import APIRouter, Query from src.core.logger import get_logger -from src.core.models.order import OrderCreate, OrderStatus +from src.core.models import OrderStatus +from src.core.schemas.order import OrderCreate router = APIRouter() logger = get_logger("gateway.trading") diff --git a/src/main.py b/src/main.py index 28a2b7e..95a4294 100644 --- a/src/main.py +++ b/src/main.py @@ -1,217 +1,49 @@ """ -QTrade 服务启动入口 - -支持启动单个服务或所有服务 -用法: - python -m src.main # 启动所有服务 - python -m src.main gateway # 只启动 Gateway - python -m src.main core_service # 只启动 Core Service - python -m src.main data_service # 只启动 Data Service - python -m src.main strategy_engine # 只启动 Strategy Engine +QTrade 主入口 """ -import argparse import asyncio import sys +from pathlib import Path -import uvicorn +project_root = Path(__file__).resolve().parent.parent +sys.path.insert(0, str(project_root)) from src.core.config import settings from src.core.logger import get_logger -from src.core.database import db -from src.core.redis_client import redis_client +from src.core.service_manager import ( + service_manager, + RedisService, + DatabaseService, +) logger = get_logger("main") -# 服务配置映射 -SERVICE_CONFIG = { - "gateway": { - "module": "src.gateway.app:app", - "host": settings.services.gateway.host, - "port": settings.services.gateway.port, - }, - "core_service": { - "module": "src.core_service.app:app", - "host": settings.services.core_service.host, - "port": settings.services.core_service.port, - }, - "data_service": { - "module": "src.data_service.app:app", - "host": settings.services.data_service.host, - "port": settings.services.data_service.port, - }, - "strategy_engine": { - "module": "src.strategy_engine.app:app", - "host": settings.services.strategy_engine.host, - "port": settings.services.strategy_engine.port, - }, - "qmt_adapter": { - "module": "src.qmt_adapter.app:app", - "host": settings.services.qmt_adapter.host, - "port": settings.services.qmt_adapter.port, - }, -} +def setup_services(): + """注册服务""" + service_manager.register("redis", RedisService) + service_manager.register("database", DatabaseService) -async def init_infrastructure() -> None: - """初始化基础设施(Redis、数据库)""" - logger.info("正在初始化基础设施...") +async def main(): + """主函数""" + logger.info(f"QTrade {settings.app.version} 启动") - try: - # 连接 Redis - await redis_client.connect() - logger.info("✓ Redis 连接成功") - except Exception as e: - logger.warning(f"✗ Redis 连接失败: {e}") + setup_services() + await service_manager.start_all() + service_manager.print_status() - try: - # 连接数据库 - await db.connect() - logger.info("✓ 数据库连接成功") - except Exception as e: - logger.warning(f"✗ 数据库连接失败: {e}") + # 等待退出 + print("\n按回车键退出...") + await asyncio.get_event_loop().run_in_executor(None, input) - logger.info("基础设施初始化完成") - - -async def shutdown_infrastructure() -> None: - """关闭基础设施连接""" - logger.info("正在关闭基础设施...") - - try: - await redis_client.disconnect() - except Exception: - pass - - try: - await db.disconnect() - except Exception: - pass - - logger.info("基础设施已关闭") - - -def run_service(service_name: str) -> None: - """ - 运行单个服务 - - Args: - service_name: 服务名称 - """ - if service_name not in SERVICE_CONFIG: - logger.error(f"未知服务: {service_name}") - logger.info(f"可用服务: {', '.join(SERVICE_CONFIG.keys())}") - sys.exit(1) - - config = SERVICE_CONFIG[service_name] - - logger.info(f"启动服务: {service_name}") - logger.info(f" 地址: http://{config['host']}:{config['port']}") - - uvicorn.run( - config["module"], - host=config["host"], - port=config["port"], - reload=False, # Windows 下 reload 可能有问题,暂时关闭 - log_level="info" if settings.app.debug else "warning", - ) - - -async def run_all_services() -> None: - """ - 运行所有服务(开发模式) - - 注意: 生产环境建议使用 Supervisor 分别管理各服务 - """ - logger.info("=" * 50) - logger.info("QTrade 量化交易系统") - logger.info(f"版本: {settings.app.version}") - logger.info(f"环境: {settings.app.env}") - logger.info("=" * 50) - - # 初始化基础设施 - await init_infrastructure() - - # 创建服务配置列表 - servers = [] - for name, config in SERVICE_CONFIG.items(): - server_config = uvicorn.Config( - config["module"], - host=config["host"], - port=config["port"], - log_level="info", - ) - server = uvicorn.Server(server_config) - servers.append((name, server)) - logger.info(f" {name}: http://{config['host']}:{config['port']}") - - logger.info("-" * 50) - logger.info("按 Ctrl+C 停止所有服务") - - # 启动所有服务 - try: - await asyncio.gather(*[server.serve() for _, server in servers]) - except asyncio.CancelledError: - pass - finally: - await shutdown_infrastructure() - - -def main() -> None: - """主入口""" - parser = argparse.ArgumentParser( - description="QTrade 服务启动器", - formatter_class=argparse.RawDescriptionHelpFormatter, - epilog=""" -服务列表: - gateway API 网关 (端口 8001) - core_service 核心业务服务 (端口 8010) - data_service 数据服务 (端口 8020) - strategy_engine 策略引擎 (端口 8030) - -示例: - python -m src.main 启动所有服务 - python -m src.main gateway 只启动 Gateway - python -m src.main core_service 只启动 Core Service - """, - ) - - parser.add_argument( - "service", - nargs="?", - choices=list(SERVICE_CONFIG.keys()), - help="要启动的服务名称,不指定则启动所有服务", - ) - - parser.add_argument( - "--host", - type=str, - help="覆盖服务监听地址", - ) - - parser.add_argument( - "--port", - type=int, - help="覆盖服务监听端口", - ) - - args = parser.parse_args() - - if args.service: - # 启动单个服务 - if args.host: - SERVICE_CONFIG[args.service]["host"] = args.host - if args.port: - SERVICE_CONFIG[args.service]["port"] = args.port - run_service(args.service) - else: - # 启动所有服务 - try: - asyncio.run(run_all_services()) - except KeyboardInterrupt: - logger.info("收到退出信号,正在关闭...") + await service_manager.stop_all() + logger.info("已退出") if __name__ == "__main__": - main() + try: + asyncio.run(main()) + except KeyboardInterrupt: + print("\n用户中断") diff --git a/src/qmt_adapter/services/__init__.py b/src/qmt_adapter/services/__init__.py index 97f666a..e2f1db9 100644 --- a/src/qmt_adapter/services/__init__.py +++ b/src/qmt_adapter/services/__init__.py @@ -1,3 +1,23 @@ """ QMT Adapter 服务模块 + +包含: +- qmt_client: QMT 客户端封装 +- data_downloader: 数据下载服务 +- order_executor: 订单执行器 +- quote_pusher: 行情推送器 """ + +from .qmt_client import QMTClient, qmt_client +from .data_downloader import DataDownloader, data_downloader +from .order_executor import OrderExecutor +from .quote_pusher import QuotePusher + +__all__ = [ + "QMTClient", + "qmt_client", + "DataDownloader", + "data_downloader", + "OrderExecutor", + "QuotePusher", +] diff --git a/src/qmt_adapter/services/data_downloader.py b/src/qmt_adapter/services/data_downloader.py new file mode 100644 index 0000000..4230f30 --- /dev/null +++ b/src/qmt_adapter/services/data_downloader.py @@ -0,0 +1,332 @@ +""" +XtQuant 数据下载服务 + +基于 xtquant SDK 下载股票历史K线数据 +参考: learning_matirals/XTDataSynchronizer.py +""" + +import json +from datetime import datetime, timedelta +from decimal import Decimal +from typing import Any, Optional + +from src.core.logger import get_logger +from src.core.config import settings + +logger = get_logger("qmt_adapter.data_downloader") + + +# K线周期配置 +PERIOD_CONFIG = { + "1m": {"xt_period": "1m", "interval_minutes": 1}, + "5m": {"xt_period": "5m", "interval_minutes": 5}, + "15m": {"xt_period": "15m", "interval_minutes": 15}, + "30m": {"xt_period": "30m", "interval_minutes": 30}, + "60m": {"xt_period": "60m", "interval_minutes": 60}, + "1d": {"xt_period": "1d", "interval_minutes": 1440}, +} + + +class DataDownloadError(Exception): + """数据下载异常""" + + pass + + +class DataDownloader: + """ + XtQuant 数据下载器 + + 功能: + - 下载历史K线数据 + - 支持多周期 (1m, 5m, 15m, 30m, 60m, 1d) + - 数据格式转换 + """ + + def __init__(self): + self._initialized = False + self._xtdata = None + self._xtdc = None + + # 默认字段列表 + self._fields = ["open", "high", "low", "close", "volume", "amount"] + + async def init(self) -> bool: + """ + 初始化 XtQuant 数据中心 + + Returns: + 是否初始化成功 + """ + if self._initialized: + return True + + logger.info("初始化 XtQuant 数据下载器...") + + try: + # 导入 XtQuant + from xtquant import xtdata + from xtquant import xtdatacenter as xtdc + + self._xtdata = xtdata + self._xtdc = xtdc + logger.info("XtQuant SDK 已加载") + + # 设置数据中心 Token (必须在 init() 之前设置) + token = getattr(settings.qmt, "data_token", None) + if token: + self._xtdc.set_token(token) + logger.info("已设置数据中心 Token") + else: + logger.warning("未设置数据中心 Token,可能需要运行 Mini QMT 客户端") + + # 初始化数据中心 + self._xtdc.init() + logger.info("XtQuant 数据中心已初始化") + + # 设置优化地址 (可选,必须在 init() 之后设置) + optimize_addresses = getattr(settings.qmt, "optimize_addresses", None) + if optimize_addresses: + self._xtdc.set_allow_optmize_address(optimize_addresses) + logger.info(f"已设置优化地址: {optimize_addresses}") + + # 下载基础数据 + logger.info("下载板块数据...") + self._xtdata.download_sector_data() + + logger.info("下载历史合约数据...") + self._xtdata.download_history_contracts() + + self._initialized = True + logger.info("XtQuant 数据下载器初始化完成") + return True + + except ImportError as e: + logger.error(f"XtQuant SDK 未安装: {e}") + raise DataDownloadError(f"XtQuant SDK 未安装: {e}") + except Exception as e: + logger.error(f"XtQuant 数据下载器初始化失败: {e}") + raise DataDownloadError(f"XtQuant 数据下载器初始化失败: {e}") + + async def download_history( + self, + stocks: list[str], + period: str = "1d", + start_date: Optional[str] = None, + end_date: Optional[str] = None, + days: int = 120, + ) -> dict[str, list[dict]]: + """ + 下载历史K线数据 + + Args: + stocks: 股票代码列表, 如 ["159915.SZ", "601288.SH"] + period: K线周期 (1m, 5m, 15m, 30m, 60m, 1d) + start_date: 开始日期 (格式: YYYYMMDD), 不传则根据 days 计算 + end_date: 结束日期 (格式: YYYYMMDD), 不传则为当天 + days: 下载天数 (start_date 未指定时使用) + + Returns: + {股票代码: [K线数据列表]} + """ + if not self._initialized: + await self.init() + + # 计算日期范围 + if not end_date: + end_date = (datetime.now() + timedelta(days=1)).strftime("%Y%m%d") + if not start_date: + start_date = (datetime.now() - timedelta(days=days)).strftime("%Y%m%d") + + logger.info( + f"下载历史数据: {stocks}, 周期: {period}, 日期: {start_date} - {end_date}" + ) + + # 使用 XtQuant 下载 + result: dict[str, list[dict]] = {} + + try: + # 获取 xtquant 周期 + xt_period = PERIOD_CONFIG.get(period, {}).get("xt_period", "1d") + + # 先下载数据到本地 + for stock in stocks: + logger.info(f"下载 {stock} 的 {period} K线数据...") + self._xtdata.download_history_data( + stock, xt_period, start_date, end_date + ) + + # 获取数据 + prices = self._xtdata.get_market_data_ex( + field_list=self._fields, + stock_list=stocks, + period=xt_period, + start_time=start_date, + end_time=end_date, + count=-1, + dividend_type="front", # 前复权 + fill_data=True, + ) + + # 转换格式 + for stock in stocks: + if stock in prices: + klines = self._convert_klines(stock, period, prices[stock]) + result[stock] = klines + logger.info(f"{stock}: 获取 {len(klines)} 条K线") + else: + result[stock] = [] + logger.warning(f"{stock}: 无数据") + + except Exception as e: + logger.error(f"下载历史数据失败: {e}") + raise DataDownloadError(f"下载历史数据失败: {e}") + + return result + + async def download_realtime(self, stocks: list[str]) -> dict[str, dict]: + """ + 获取实时行情数据 + + Args: + stocks: 股票代码列表 + + Returns: + {股票代码: Tick数据} + """ + if not self._initialized: + await self.init() + + result: dict[str, dict] = {} + + try: + ticks = self._xtdata.get_full_tick(stocks) + + for stock in stocks: + if stock in ticks: + data = ticks[stock] + result[stock] = { + "symbol": stock, + "time": datetime.now().isoformat(), + "last_price": data.get("lastPrice", 0), + "open": data.get("open", 0), + "high": data.get("high", 0), + "low": data.get("low", 0), + "close": data.get("lastPrice", 0), + "volume": data.get("volume", 0), + "amount": data.get("amount", 0), + "bid_prices": data.get("bidPrice", [0] * 5), + "bid_volumes": data.get("bidVol", [0] * 5), + "ask_prices": data.get("askPrice", [0] * 5), + "ask_volumes": data.get("askVol", [0] * 5), + } + else: + logger.warning(f"{stock}: 无实时数据") + + except Exception as e: + logger.error(f"获取实时行情失败: {e}") + raise DataDownloadError(f"获取实时行情失败: {e}") + + return result + + async def get_stock_info(self, stock: str) -> Optional[dict]: + """ + 获取股票基本信息 + + Args: + stock: 股票代码 + + Returns: + 股票信息 + """ + if not self._initialized: + await self.init() + + try: + detail = self._xtdata.get_instrument_detail(stock) + if detail: + return { + "symbol": f"{detail['InstrumentID']}.{detail['ExchangeID']}", + "name": detail.get("InstrumentName", "").replace("\r\n", ""), + "exchange": detail.get("ExchangeID", ""), + "instrument_id": detail.get("InstrumentID", ""), + } + else: + logger.warning(f"{stock}: 未找到股票信息") + return None + except Exception as e: + logger.error(f"获取股票信息失败: {e}") + raise DataDownloadError(f"获取股票信息失败: {e}") + + async def get_trading_calendar( + self, + exchange: str = "SH", + start_date: Optional[str] = None, + end_date: Optional[str] = None, + ) -> list[str]: + """ + 获取交易日历 + + Args: + exchange: 交易所 (SH/SZ) + start_date: 开始日期 + end_date: 结束日期 + + Returns: + 交易日列表 + """ + if not self._initialized: + await self.init() + + if not start_date: + start_date = (datetime.now() - timedelta(days=30)).strftime("%Y%m%d") + if not end_date: + end_date = datetime.now().strftime("%Y%m%d") + + try: + calendars = self._xtdata.get_trading_calendar( + exchange, start_date, end_date + ) + return [str(d) for d in calendars] + except Exception as e: + logger.error(f"获取交易日历失败: {e}") + raise DataDownloadError(f"获取交易日历失败: {e}") + + def _convert_klines(self, stock: str, period: str, df) -> list[dict]: + """ + 将 xtquant DataFrame 转换为 K线字典列表 + + Args: + stock: 股票代码 + period: 周期 + df: xtquant 返回的 DataFrame + + Returns: + K线数据列表 + """ + klines = [] + + for index, row in df.iterrows(): + # 跳过空数据 + if row["open"] == 0 or row["close"] == 0: + continue + + klines.append( + { + "symbol": stock, + "time": str(index), + "period": period, + "open": float(row["open"]), + "high": float(row["high"]), + "low": float(row["low"]), + "close": float(row["close"]), + "volume": int(row["volume"]), + "amount": float(row["amount"]), + } + ) + + return klines + + +# 单例 +data_downloader = DataDownloader() diff --git a/src/strategy_engine/routes/signal.py b/src/strategy_engine/routes/signal.py index 1cd3acb..d20f48a 100644 --- a/src/strategy_engine/routes/signal.py +++ b/src/strategy_engine/routes/signal.py @@ -10,7 +10,7 @@ from fastapi import APIRouter, Query, HTTPException from pydantic import BaseModel, Field from src.core.logger import get_logger -from src.core.models.signal import SignalSide +from src.core.models import SignalSide logger = get_logger("strategy_engine.signal") router = APIRouter() diff --git a/src/strategy_engine/services/base_strategy.py b/src/strategy_engine/services/base_strategy.py index c4fc97c..986d028 100644 --- a/src/strategy_engine/services/base_strategy.py +++ b/src/strategy_engine/services/base_strategy.py @@ -10,7 +10,7 @@ from datetime import datetime as dt from pydantic import BaseModel, Field -from src.core.models.signal import SignalSide +from src.core.models import SignalSide class StrategyContext(BaseModel): diff --git a/src/strategy_engine/services/signal_manager.py b/src/strategy_engine/services/signal_manager.py index 23f9eea..b4165dc 100644 --- a/src/strategy_engine/services/signal_manager.py +++ b/src/strategy_engine/services/signal_manager.py @@ -8,13 +8,14 @@ import uuid import json from typing import Any, Optional from datetime import datetime as dt, date +from decimal import Decimal -from sqlalchemy import text +from sqlalchemy import select, func from src.core.database import db from src.core.redis_client import redis_client from src.core.logger import get_logger -from src.core.models.signal import SignalSide +from src.core.models import Signal, SignalSide, SignalStatus logger = get_logger("strategy_engine.signal_manager") @@ -59,37 +60,23 @@ class SignalManager: # 记录到数据库 async with db.session() as session: - await session.execute( - text(""" - INSERT INTO signals - (id, pairing_id, symbol, strategy_id, side, price, quantity, reason, created_at) - VALUES (:id, :pairing_id, :symbol, :strategy_id, :side, :price, :quantity, :reason, :created_at) - """), - { - "id": signal_id, - "pairing_id": pairing_id, - "symbol": symbol, - "strategy_id": strategy_id, - "side": side.value, - "price": price, - "quantity": quantity, - "reason": reason, - "created_at": now, - }, + new_signal = Signal( + id=signal_id, + pairing_id=pairing_id, + symbol=symbol, + strategy_id=strategy_id, + side=side, + price=Decimal(str(price)), + quantity=quantity, + reason=reason, + status=SignalStatus.PENDING, + created_at=now, ) + session.add(new_signal) await session.commit() + await session.refresh(new_signal) - signal_data = { - "signal_id": signal_id, - "pairing_id": pairing_id, - "symbol": symbol, - "strategy_id": strategy_id, - "side": side.value, - "price": price, - "quantity": quantity, - "reason": reason, - "created_at": now.isoformat(), - } + signal_data = new_signal.to_dict() # 发布信号到 Redis(Core Service 监听并创建订单) await redis_client.publish("signal:created", json.dumps(signal_data)) @@ -108,59 +95,32 @@ class SignalManager: page_size: int = 20, ) -> dict[str, Any]: """查询信号历史""" - conditions = ["1=1"] - params: dict[str, Any] = {} - - if pairing_id: - conditions.append("pairing_id = :pairing_id") - params["pairing_id"] = pairing_id - - if symbol: - conditions.append("symbol = :symbol") - params["symbol"] = symbol - - where_clause = " AND ".join(conditions) - offset = (page - 1) * page_size - async with db.session() as session: + # 构建查询 + stmt = select(Signal) + count_stmt = select(func.count(Signal.id)) + + if pairing_id: + stmt = stmt.where(Signal.pairing_id == pairing_id) + count_stmt = count_stmt.where(Signal.pairing_id == pairing_id) + if symbol: + stmt = stmt.where(Signal.symbol == symbol) + count_stmt = count_stmt.where(Signal.symbol == symbol) + # 查询总数 - count_result = await session.execute( - text(f"SELECT COUNT(*) FROM signals WHERE {where_clause}"), - params, - ) - total = count_result.scalar() or 0 + total_result = await session.execute(count_stmt) + total = total_result.scalar() or 0 - # 查询列表 - result = await session.execute( - text(f""" - SELECT id, pairing_id, symbol, strategy_id, side, price, quantity, reason, created_at - FROM signals - WHERE {where_clause} - ORDER BY created_at DESC - LIMIT :limit OFFSET :offset - """), - {**params, "limit": page_size, "offset": offset}, + # 分页查询 + offset = (page - 1) * page_size + stmt = ( + stmt.order_by(Signal.created_at.desc()).offset(offset).limit(page_size) ) - rows = result.fetchall() - - items = [] - for row in rows: - items.append( - { - "signal_id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "strategy_id": row[3], - "side": row[4], - "price": float(row[5]) if row[5] else 0, - "quantity": row[6], - "reason": row[7], - "created_at": row[8].isoformat() if row[8] else None, - } - ) + result = await session.execute(stmt) + signals = result.scalars().all() return { - "items": items, + "items": [s.to_dict() for s in signals], "total": total, "page": page, "page_size": page_size, @@ -173,41 +133,17 @@ class SignalManager: """获取今日信号""" today = date.today() - conditions = ["DATE(created_at) = :today"] - params: dict[str, Any] = {"today": today} - - if pairing_id: - conditions.append("pairing_id = :pairing_id") - params["pairing_id"] = pairing_id - - where_clause = " AND ".join(conditions) - async with db.session() as session: - result = await session.execute( - text(f""" - SELECT id, pairing_id, symbol, strategy_id, side, price, quantity, reason, created_at - FROM signals - WHERE {where_clause} - ORDER BY created_at DESC - """), - params, - ) - rows = result.fetchall() + stmt = select(Signal).where(func.date(Signal.created_at) == today) - return [ - { - "signal_id": row[0], - "pairing_id": row[1], - "symbol": row[2], - "strategy_id": row[3], - "side": row[4], - "price": float(row[5]) if row[5] else 0, - "quantity": row[6], - "reason": row[7], - "created_at": row[8].isoformat() if row[8] else None, - } - for row in rows - ] + if pairing_id: + stmt = stmt.where(Signal.pairing_id == pairing_id) + + stmt = stmt.order_by(Signal.created_at.desc()) + result = await session.execute(stmt) + signals = result.scalars().all() + + return [s.to_dict() for s in signals] # 单例 diff --git a/src/strategy_engine/services/strategy_executor.py b/src/strategy_engine/services/strategy_executor.py index 5631f9c..e1491c7 100644 --- a/src/strategy_engine/services/strategy_executor.py +++ b/src/strategy_engine/services/strategy_executor.py @@ -14,7 +14,7 @@ from sqlalchemy import text from src.core.database import db from src.core.redis_client import redis_client from src.core.logger import get_logger -from src.core.models.symbol_strategy import PairingStatus +from src.core.models import PairingStatus from .base_strategy import BaseStrategy, StrategyContext, TickData from .strategy_registry import strategy_registry