real_trader/src/example_trade.py
2025-04-30 14:33:02 +08:00

102 lines
3.0 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import requests
# 服务器地址
URL = "http://trader.biggerfish.tech:9527/yu"
# 策略名称常量
STRATEGY = "追梦投资港股ETF"
def buy(code: str, price: float, amount: int, strategy_name: str) -> dict:
"""买入股票
Args:
code: 股票代码,例如 "601988.SH"
price: 买入价格
amount: 买入数量
strategy_name: 策略名称
"""
data = {
"code": code,
"price": str(price),
"amount": str(amount),
"strategy_name": strategy_name
}
response = requests.post(f"{URL}/buy", json=data)
return response.json()
def sell(code: str, price: float, amount: int, strategy_name: str) -> dict:
"""卖出股票
Args:
code: 股票代码,例如 "601988.SH"
price: 卖出价格
amount: 卖出数量
strategy_name: 策略名称
"""
data = {
"code": code,
"price": str(price),
"amount": str(amount),
"strategy_name": strategy_name
}
response = requests.post(f"{URL}/sell", json=data)
return response.json()
def get_positions(strategy_name: str) -> dict:
"""获取持仓信息
Args:
strategy_name: 策略名称
"""
params = {"strategy_name": strategy_name}
response = requests.get(f"{URL}/positions", params=params)
return response.json()
def clear_strategy(strategy_name: str) -> dict:
"""清除策略持仓数据
Args:
strategy_name: 策略名称
"""
response = requests.delete(f"{URL}/clear/{strategy_name}")
return response.json()
if __name__ == "__main__":
# 示例:查询默认策略的持仓信息
positions = get_positions(STRATEGY)
print("当前持仓:", positions)
# 模拟输出:
# {'data': [], 'success': True}
# 示例买入中国银行1000股价格3.45
result = buy("601988.SH", 3.45, 3000, STRATEGY)
print("买入结果:", result)
# 模拟输出:
#{'data': {'message': '模拟买入 - 代码: 601988.SH, 价格: 3.45, 数量: 3000', 'order_id': 'simulation'}, 'success': True}
# 示例卖出中国银行1000股价格3.48
result = sell("601988.SH", 3.48, 1000, STRATEGY)
print("卖出结果:", result)
# 模拟输出:
# {'data': {'message': '模拟卖出 - 代码: 601988.SH, 价格: 3.48, 数量: 1000', 'order_id': 'simulation'}, 'success': True}
# 示例:再次查询持仓变化
positions = get_positions(STRATEGY)
print("交易后持仓:", positions)
# 模拟输出:
# {'data': [{'601988.SH': {'closeable_amount': 2000, 'total_amount': 2000}}], 'success': True}
# 示例:清除策略持仓数据
result = clear_strategy(STRATEGY)
print("清除策略持仓结果:", result)
# 模拟输出:
# {'message': "成功清除策略 '追梦投资港股ETF' 的持仓数据", 'success': True}
# 示例:清除后查询持仓
positions = get_positions(STRATEGY)
print("清除后持仓:", positions)
# 模拟输出:
# {'data': [], 'success': True}