迅投 示例
时间: 2025-06-06 10:22:04 浏览: 25
### 迅投(QMT)使用示例与配置教程
迅投 QMT 是一款专业的量化交易平台,支持多种交易场景和复杂策略的实现。以下是基于已有引用内容以及专业知识总结的一些常见使用示例和配置方法。
#### 1. 数据获取基础
通过 `XtQuant` 的 Python 接口可以轻松获取市场数据。以下是一个简单的例子展示如何连接并查询股票行情:
```python
from xtquant import xtdata
def get_stock_data(stock_code, start_time, end_time):
"""
获取指定时间段内的股票K线数据
:param stock_code: 股票代码 (e.g., '000001.SZ')
:param start_time: 开始时间 (e.g., '2023-01-01')
:param end_time: 结束时间 (e.g., '2023-12-31')
:return: DataFrame 类型的历史数据
"""
data = xtdata.get_market_data(
security=[stock_code],
period="day",
start_time=start_time,
end_time=end_time,
fields=["open", "high", "low", "close"]
)
return data
# 示例调用
df = get_stock_data('000001.SZ', '2023-01-01', '2023-12-31')
print(df.head())
```
以上代码展示了如何利用 `xtdata.get_market_data()` 方法来拉取某只股票的日 K 线数据[^1]。
---
#### 2. 实现双账户轮动策略
对于涉及多个账户的操作(如普通账户与信用账户),可以通过继承类的方式设计更灵活的策略逻辑。下面是一段简化版的双账户轮动策略实现:
```python
class DualAccountStrategy:
def __init__(self, common_acc, margin_acc):
self.common_acc = common_acc
self.margin_acc = margin_acc
def _get_position(self, account, stock_code):
""" 查询某个账户中的持仓数量 """
positions = xtdata.get_positions(account)
for pos in positions:
if pos['code'] == stock_code:
return pos['volume']
return 0
def _check_trend(self, stock_code):
""" 判断当前标的的趋势方向 """
close_prices = xtdata.get_market_data(security=[stock_code], period='min', fields=['close'])
last_price = close_prices.iloc[-1]['close']
prev_price = close_prices.iloc[-2]['close']
return last_price > prev_price
def execute_cross_strategy(self, stock_code):
""" 执行跨账户买卖操作 """
common_hold = self._get_position(self.common_acc, stock_code)
if self._check_trend(stock_code):
if common_hold < 1000:
# 如果普通账户持有量不足,则买入
xtdata.place_order(account=self.common_acc, code=stock_code, action='BUY', volume=500)
else:
# 否则切换至信用账户加仓
xtdata.place_order(account=self.margin_acc, code=stock_code, action='BUY', volume=300)
```
该部分实现了两个核心功能:一是动态调整不同账户间的仓位分配;二是依据价格变化趋势决定具体下单行为[^3]。
---
#### 3. 参数化数据库配置
如果需要存储历史记录或者管理复杂的网格交易参数,通常会引入 MySQL 数据库辅助完成任务。这里给出一个标准的数据库初始化脚本供参考:
```python
import pymysql
db_config = {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'your_password_here',
'db': 'gridtrade',
'charset': 'utf8'
}
def init_database():
connection = pymysql.connect(**db_config)
try:
with connection.cursor() as cursor:
sql_create_table = '''
CREATE TABLE IF NOT EXISTS trade_records (
id INT AUTO_INCREMENT PRIMARY KEY,
order_id VARCHAR(255),
symbol VARCHAR(20),
price DECIMAL(10, 2),
quantity INT,
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP
);
'''
cursor.execute(sql_create_table)
connection.commit()
finally:
connection.close()
if __name__ == "__main__":
init_database()
```
这段代码定义了一个名为 `trade_records` 的表结构,用于保存每次订单的关键信息[^4]。
---
#### 4. 风险控制机制
针对信用账户特有的风险属性,建议定期检查维持担保比例以规避爆仓风险。例如:
```python
def check_maintenance_margin(trader_instance, acc):
risk_info = trader_instance.query_credit_risk(acc)
maintain_ratio = float(risk_info.maintain_ratio.replace('%', '')) / 100
if maintain_ratio < 1.3:
raise Exception("Maintain ratio is too low! Please reduce leverage.")
print(f"Current Maintain Ratio: {maintain_ratio:.2f}")
```
上述函数会在维护保证金低于设定阈值时抛出警告提示。
---
###
阅读全文
相关推荐

















