
algo-risk-test
Verify a strategy's SL / TP / trailing stop / portfolio caps fire correctly. Uses OpenAlgo sandbox + synthetic price moves. Run this before going live.
- Installs
- 43
- Last 24h
- —
- Trending rank
- —
- Security
- Not audited
Install
Works with every agent the skills CLI supports.
npx skills add https://github.com/marketcalls/openalgo-execution-skills --skill algo-risk-test- 01
Install
Run the command in your project. The CLI asks which agents to install for.
- 02
Describe the task
Ask your agent for something this skill covers. It loads algo-risk-test automatically when relevant.
- 03
Review the result
The agent follows the SKILL.md steps, scripts and references bundled with the skill.
SKILL.md
The instructions your agent reads when the skill is triggered.
Smoke-test the risk manager and portfolio caps without risking real capital.
Arguments
$0 = path to a strategy file (e.g. strategies/ema_crossover_SBIN/strategy.py).
If not given, list available strategies and ask.
Pre-flight
Tell the user:
- Flip OpenAlgo's analyzer toggle ON in the UI: visit
http://127.0.0.1:5000/analyzerand click "Sandbox Mode". This routes all orders to the sandbox engine, no broker. - Confirm
client.analyzerstatus()returnsanalyze_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", ...}} - The strategy will run in
--mode livebut orders are simulated.
Instructions
-
Read the strategy file to extract:
SYMBOL,EXCHANGERISK(sl_pct, tp_pct, trail_pct, time_exit_min)- Indicator parameters
-
Generate a sibling
risk_test.pyin the same folder. Pattern:
"""
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()
-
Tell the user how to run:
# 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 -
Note that OpenAlgo's sandbox doesn't accept arbitrary "set LTP" commands. Real verification of the risk manager often needs:
- Letting the strategy run during market hours (sandbox uses real LTP)
- Watching for the signal to fire and then timing the test to coincide with a real adverse price move
Or: temporarily lower SL_PCT to 0.0001 (1 bp) so any tick triggers the SL - confirms the WS feed and exit path work.
Manual checks
If automated synthetic injection isn't possible (sandbox limitations), the user should:
- Run the strategy in sandbox during market hours
- Confirm WS connects and ticks flow (set
verbose=Truetemporarily) - Confirm a real adverse move fires
placesmartorder(position_size=0)(checktradebook()for the closing trade) - Confirm
core/risk_manager.py's_check_exits()log line appears withreason=SL_PCT/TP_PCT/TRAIL
What to verify
| Check | How |
|---|---|
| WS connects, LTP arrives | log shows subscribe_ltp success and tick callbacks fire |
| SL triggers exit | log: EXIT trigger ... reason=SL_PCT (...) |
| TP triggers exit | log: EXIT trigger ... reason=TP_PCT (...) |
| Trailing stop locks profit | log: EXIT trigger ... reason=TRAIL (...) |
| Time exit fires | log: EXIT trigger ... reason=TIME_EXIT (...) |
Exit places placesmartorder(position_size=0) | log: Exit order placed: ... |
| Exit fill price recorded for slippage | end-of-run report shows non-zero fills |
| Portfolio cap fires | run /algo-portfolio, force a strategy to fake P&L below cap, verify SIGTERM propagation |
Avoid
- Do not run risk tests with
analyze_mode: False- real broker orders WILL fire - Do not use icons/emojis
FAQ
What does the algo-risk-test skill do?
Verify a strategy's SL / TP / trailing stop / portfolio caps fire correctly. Uses OpenAlgo sandbox + synthetic price moves. Run this before going live.
How do I install algo-risk-test?
Run npx skills add https://github.com/marketcalls/openalgo-execution-skills --skill algo-risk-test in your project. The skills CLI detects the agents you use and copies the skill into the right folder. For Claude Code you can also place the skill folder at ~/.claude/skills/algo-risk-test/ (personal) or .claude/skills/algo-risk-test/ (project).
Which AI agents can use algo-risk-test?
Any agent that supports the open Agent Skills format (a folder with a SKILL.md file), including Claude Code, Codex, Cursor, GitHub Copilot, Gemini CLI, Windsurf, Cline, OpenCode and more.
Is algo-risk-test safe to install?
No partner security audit is available yet. Skills can run commands and scripts, so read the SKILL.md and any bundled files before installing.
Who maintains algo-risk-test?
It is published by marketcalls in marketcalls/openalgo-execution-skills. It has 43 recorded installs.
More from marketcalls/openalgo-execution-skills
algo-strategy
marketcalls/openalgo-execution-skills
Open the skill to read its SKILL.md instructions.
algo-options
marketcalls/openalgo-execution-skills
Open the skill to read its SKILL.md instructions.
algo-expert
marketcalls/openalgo-execution-skills
Open the skill to read its SKILL.md instructions.
algo-host
marketcalls/openalgo-execution-skills
Open the skill to read its SKILL.md instructions.
algo-portfolio
marketcalls/openalgo-execution-skills
Open the skill to read its SKILL.md instructions.
algo-setup
marketcalls/openalgo-execution-skills
Set up the Python environment for OpenAlgo execution skills - venv, openalgo[indicators], vectorbt, talib, scikit-learn, xgboost. Scaffolds strategies/ folder and .env.
Popular testing & qa skills
tdd
mattpocock/skills
Test-driven development. Use when the user wants to build features or fix bugs test-first, mentions "red-green-refactor", or wants integration tests.
grilling
mattpocock/skills
Grill the user relentlessly about a plan, decision, or idea. Use when the user wants to stress-test their thinking, or uses any 'grill' trigger phrases.
migrate-to-shoehorn
mattpocock/skills
Migrate test files from as type assertions to @total-typescript/shoehorn. Use when user mentions shoehorn, wants to replace as in tests, or needs partial test data.
run-train
lllllllama/rigorpilot-skills
Rigor Train skill for deep learning research repositories. Use when a documented or selected training command should be run conservatively for startup verification, short-run verification, full kickoff, or resume, with command, config, seed, log, checkpoint, status, and metric evidence written to standardized trainoutputs/. Do not use for environment setup, exploratory sweeps, speculative idea implementation, or end-to-end orchestration.
test-driven-development
obra/superpowers
Use when implementing any feature or bugfix, before writing implementation code
finishing-a-development-branch
obra/superpowers
Use when implementation is complete, all tests pass, and you need to decide how to integrate the work