关于 algo-risk-test
algo-risk-test 是一项用于在 OpenAlgo 沙盒中验证交易策略风险管理逻辑的测试技能,适合策略开发与测试。它检查止损、止盈、移动止损、时间退出及组合上限,并避免将测试订单发送给真实经纪商。
主要功能
- 01从策略文件读取风险与指标参数
- 02生成同目录的 risk_test.py
- 03验证止损、止盈和移动止损
- 04检查时间退出与退出订单
- 05测试组合上限及进程终止
适用场景
- 01在沙盒中检查策略退出逻辑
- 02确认 WebSocket 行情与退出路径
- 03验证组合亏损上限触发
安装
复制下面的命令,在终端中运行。
$
npx skills add https:/ / github.com/ marketcalls/ openalgo-execution-skills --skill algo-risk-test安装后在 Claude Code 中输入/algo-risk-test确认已加载。
详细介绍
在不冒真实资金风险的情况下,对风险管理器和投资组合上限进行冒烟测试。
参数
$0 = 策略文件的路径(例如 strategies/ema_crossover_SBIN/strategy.py)。
如果未提供,请列出可用策略并询问用户。
预检
告知用户:
- 在 UI 中开启 OpenAlgo 的分析器开关:访问
http://127.0.0.1:5000/analyzer并点击“Sandbox Mode”。这会将所有订单路由到沙盒引擎,不会连接经纪商。 - 确认
client.analyzerstatus()返回analyze_mode: True:from openalgo import api c = api(api_key="...", host="http://127.0.0.1:5000") print(c.analyzerstatus()) # -> {data: {analyze_mode: True, mode: "analyze", ...}} - 策略将以
--mode live运行,但订单是模拟的。
说明
-
读取策略文件,提取:
SYMBOL、EXCHANGERISK(sl_pct、tp_pct、trail_pct、time_exit_min)- 指标参数
-
在同一文件夹中生成同级文件
risk_test.py。模式:
"""
Risk verification harness for <strategy_name>.
Runs the strategy in --mode live (with OpenAlgo sandbox toggled ON).
Once a position opens, this script injects synthetic price moves via
client.placeorder() (sandbox absorbs them) to push LTP through SL, TP,
and trail thresholds, verifying the risk manager fires.
Usage:
# In one terminal:
python strategy.py --mode live
# In another:
python risk_test.py
"""
import logging, os, sys, time
from pathlib import Path
from dotenv import find_dotenv, load_dotenv
_HERE = Path(__file__).resolve().parent
for p in [_HERE, *_HERE.parents]:
c = p / ".claude" / "skills" / "algo-expert" / "rules" / "assets" / "core"
if c.exists():
sys.path.insert(0, str(c.parent)); break
from openalgo import api # noqa: E402
logging.basicConfig(level="INFO", format="%(asctime)s [%(levelname)s] %(message)s",
stream=sys.stdout)
log = logging.getLogger("risk_test")
load_dotenv(find_dotenv(usecwd=True))
# --- Read these from strategy.py ---
SYMBOL = "SBIN"
EXCHANGE = "NSE"
SL_PCT = 0.01
TP_PCT = 0.02
TRAIL_PCT = 0.008
API_KEY = os.getenv("OPENALGO_API_KEY", "")
API_HOST = os.getenv("HOST_SERVER") or os.getenv("OPENALGO_HOST", "http://127.0.0.1:5000")
client = api(api_key=API_KEY, host=API_HOST)
def assert_sandbox():
s = client.analyzerstatus()
if not s.get("data", {}).get("analyze_mode"):
log.error("OpenAlgo is NOT in sandbox mode. Toggle it on at /analyzer first.")
sys.exit(1)
def get_open_position():
pb = client.positionbook()
for r in pb.get("data", []):
if r.get("symbol") == SYMBOL and int(float(r.get("quantity", 0) or 0)) != 0:
return r
return None
def main():
assert_sandbox()
log.info("Sandbox confirmed. Waiting for strategy to open a position...")
while True:
pos = get_open_position()
if pos:
log.info("Position detected: %s", pos)
break
time.sleep(5)
entry = float(pos["average_price"])
qty = abs(int(float(pos["quantity"])))
log.info("Entry %.2f qty=%d", entry, qty)
# --- Test 1: trigger the SL by placing a counter-order at SL price ---
sl_target = entry * (1 - SL_PCT) * 0.99 # push 1% past trigger
log.info("Test SL: pushing LTP to %.2f", sl_target)
# In sandbox, the trade above is simulated. The risk manager should detect
# the LTP move (via WS) and fire placesmartorder(position_size=0) to flatten.
# Real ticks come from broker, but in sandbox they come from your placeorder
# calls and OpenAlgo's simulator. Verify by polling positionbook.
time.sleep(10)
pos_after = get_open_position()
if pos_after is None:
log.info("PASS: SL triggered, position flattened.")
else:
log.error("FAIL: position still open after SL move.")
# --- Test 2: similarly for TP and TRAIL ---
# ... (extend as needed)
if __name__ == "__main__":
main()
-
告知用户如何运行:
# Terminal 1: run the strategy in live mode (OpenAlgo sandbox active) python strategies/ema_crossover_SBIN/strategy.py --mode live # Terminal 2: run the risk verifier python strategies/ema_crossover_SBIN/risk_test.py -
请注意,OpenAlgo 的沙盒不接受任意“set LTP”命令。要实际验证风险管理器,通常需要:
- 在交易时段运行策略(沙盒使用真实 LTP)
- 等待信号触发,然后让测试时机与真实的不利价格变动相吻合
或者:临时将 SL_PCT 降至 0.0001(1 bp),这样任何一个跳动都会触发 SL——以此确认 WS 数据流和退出路径正常。
手动检查
如果无法进行自动合成注入(受沙盒限制),用户应:
- 在交易时段于沙盒中运行策略
- 确认 WS 已连接且有 tick 流入(临时设置
verbose=True) - 确认真实的不利价格变动会触发
placesmartorder(position_size=0)(检查tradebook()中的平仓交易) - 确认
core/risk_manager.py的_check_exits()日志行出现,且包含reason=SL_PCT/TP_PCT/TRAIL
验证项目
| 检查项 | 方法 |
|---|---|
| WS 已连接,LTP 已到达 | 日志显示 subscribe_ltp 成功,且触发 tick 回调 |
| SL 触发退出 | 日志:EXIT trigger ... reason=SL_PCT (...) |
| TP 触发退出 | 日志:EXIT trigger ... reason=TP_PCT (...) |
| 跟踪止损锁定利润 | 日志:EXIT trigger ... reason=TRAIL (...) |
| 时间退出触发 | 日志:EXIT trigger ... reason=TIME_EXIT (...) |
退出操作调用 placesmartorder(position_size=0) | 日志:Exit order placed: ... |
| 记录退出成交价以计算滑点 | 运行结束报告显示非零成交量 |
| 投资组合上限触发 | 运行 /algo-portfolio,强制某个策略生成低于上限的虚假 P&L,并验证 SIGTERM 传播 |
避免
analyze_mode: False时不要运行风险测试——这会触发真实经纪商订单- 不要使用图标或表情符号
评论
支持 Markdown