From ba62c6b0b8f593cf230411189c6b90a4b30ffed3 Mon Sep 17 00:00:00 2001 From: zhiyong Date: Wed, 30 Apr 2025 13:02:48 +0800 Subject: [PATCH] add example --- src/example_trade.py | 50 +++++++++++++++++++++++++++++++++----------- 1 file changed, 38 insertions(+), 12 deletions(-) diff --git a/src/example_trade.py b/src/example_trade.py index 92c4573..8f02945 100644 --- a/src/example_trade.py +++ b/src/example_trade.py @@ -2,52 +2,78 @@ import requests # 服务器地址 URL = "http://trader.biggerfish.tech:9527/yu" +# 策略名称常量 +STRATEGY = "追梦投资港股ETF" -def buy(code: str, price: float, amount: int) -> dict: +def buy(code: str, price: float, amount: int, strategy_name: str) -> dict: """买入股票 Args: code: 股票代码,例如 "601988.SH" price: 买入价格 amount: 买入数量 - - Returns: - dict: 交易结果 + strategy_name: 策略名称 """ data = { "code": code, "price": str(price), - "amount": str(amount) + "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) -> dict: +def sell(code: str, price: float, amount: int, strategy_name: str) -> dict: """卖出股票 Args: code: 股票代码,例如 "601988.SH" price: 卖出价格 amount: 卖出数量 - - Returns: - dict: 交易结果 + strategy_name: 策略名称 """ data = { "code": code, "price": str(price), - "amount": str(amount) + "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() + if __name__ == "__main__": + # 示例:查询默认策略的持仓信息 + positions = get_positions(STRATEGY) + print("当前持仓:", positions) + # 模拟输出: + + # 示例:买入中国银行1000股,价格3.45 - result = buy("601988.SH", 3.45, 1000) + result = buy("601988.SH", 3.45, 1000, STRATEGY) print("买入结果:", result) + # 模拟输出: + # 示例:卖出中国银行1000股,价格3.48 - result = sell("601988.SH", 3.48, 1000) + result = sell("601988.SH", 3.48, 1000, STRATEGY) print("卖出结果:", result) + # 模拟输出: + + + # 示例:再次查询持仓变化 + positions = get_positions(STRATEGY) + print("交易后持仓:", positions) + # 模拟输出: + \ No newline at end of file