Skip to content

reddygopalkrishna/trading-skills / skills/trading-risk

trading-risk

Verified

Mandatory risk checkpoint before any order - verifies stop placement, risk per trade, reward:risk, position size, total portfolio heat, max positions, duplicate exposure, daily loss limit, losing-streak pause, drawdown circuit breaker and the kill switch, then issues a short-lived approval that trading-broker requires. Also shows a live risk dashboard. Use when about to place, submit or confirm any trade, when the user asks "can I take this trade", "am I over-risked", "how much risk do I have on", or whenever trading-broker asks for an approval.

FileKindSize
SKILL.mdskill md2.8 KB
scripts/_vendor/tradekit/__init__.pyscript516 B
scripts/_vendor/tradekit/alerts.pyscript7.5 KB
scripts/_vendor/tradekit/analysis.pyscript10.3 KB
scripts/_vendor/tradekit/backtest.pyscript17.8 KB
scripts/_vendor/tradekit/brokers/__init__.pyscript1022 B
scripts/_vendor/tradekit/brokers/_rest.pyscript2.7 KB
scripts/_vendor/tradekit/brokers/base.pyscript3.5 KB
scripts/_vendor/tradekit/brokers/dhan.pyscript6.8 KB
scripts/_vendor/tradekit/brokers/fyers.pyscript7.1 KB
scripts/_vendor/tradekit/brokers/groww.pyscript7.7 KB
scripts/_vendor/tradekit/brokers/kite.pyscript14.5 KB
scripts/_vendor/tradekit/brokers/paper.pyscript12.7 KB
scripts/_vendor/tradekit/brokers/upstox.pyscript7.8 KB
scripts/_vendor/tradekit/cli.pyscript2.4 KB
scripts/_vendor/tradekit/config.pyscript6.0 KB
scripts/_vendor/tradekit/data.pyscript18.5 KB
scripts/_vendor/tradekit/disclosures.pyscript17.4 KB
scripts/_vendor/tradekit/expr.pyscript19.0 KB
scripts/_vendor/tradekit/feeds.pyscript9.4 KB
scripts/_vendor/tradekit/frame.pyscript8.9 KB
scripts/_vendor/tradekit/fundamentals.pyscript6.1 KB
scripts/_vendor/tradekit/gate.pyscript8.1 KB
scripts/_vendor/tradekit/http.pyscript4.3 KB
scripts/_vendor/tradekit/indicators.pyscript13.1 KB
scripts/_vendor/tradekit/journal.pyscript11.1 KB
scripts/_vendor/tradekit/metrics.pyscript6.2 KB
scripts/_vendor/tradekit/montecarlo.pyscript7.8 KB
scripts/_vendor/tradekit/options.pyscript24.4 KB
scripts/_vendor/tradekit/patterns.pyscript12.9 KB
scripts/_vendor/tradekit/report.pyscript8.4 KB
scripts/_vendor/tradekit/risk.pyscript4.7 KB
scripts/_vendor/tradekit/sec.pyscript12.0 KB
scripts/_vendor/tradekit/session.pyscript9.4 KB
scripts/gate.pyscript7.4 KB

scripts/_vendor/tradekit/brokers/_rest.py

View on GitHub
"""Shared plumbing for the JSON REST broker adapters (Fyers, Upstox, Dhan, Groww).

Secrets are only ever put in request headers. They are never written into error
messages: errors carry the HTTP status and the broker's own response body.
"""

from __future__ import annotations

import json
from typing import Any, Dict, Iterable, Optional

from .. import config, http
from .base import BrokerError


def call(label: str, method: str, url: str, headers: Dict[str, str], params: Optional[Dict] = None,
         body: Optional[Any] = None, form: Optional[Dict] = None) -> Any:
    """One HTTP call. Returns parsed JSON. Raises BrokerError with the broker's message on failure."""
    try:
        raw = http.request(method, url, params=params, data=form, json_body=body, headers=headers)
    except http.HTTPError as e:
        raise BrokerError(f"{label} {method} {_path(url)} failed [{e.status}] {_brief(e.body)}") from None
    except RuntimeError as e:
        raise BrokerError(f"{label} {method} {_path(url)}: {e}") from None
    if not raw:
        return {}
    try:
        return json.loads(raw.decode("utf-8"))
    except (UnicodeDecodeError, json.JSONDecodeError):
        raise BrokerError(f"{label} {method} {_path(url)}: response was not JSON") from None


def _path(url: str) -> str:
    return "/" + url.split("://", 1)[-1].split("/", 1)[-1] if "/" in url.split("://", 1)[-1] else url


def _brief(text: str, n: int = 300) -> str:
    return (text or "").replace("\n", " ")[:n]


def need(label: str, **creds) -> None:
    """Raise a clear error naming (not showing) missing credentials."""
    missing = [k for k, v in creds.items() if not v]
    if missing:
        raise BrokerError(f"{label}: missing {', '.join(missing)}. Run the {label.lower()}-login step in "
                          "trading-setup (or set the matching environment variables).")


def product_for(order: Dict, table: Dict[str, str], broker_label: str, default: str = "CNC") -> str:
    cfg = config.load()["broker"]
    raw = str(order.get("product") or cfg.get("default_product") or default).upper()
    if raw in table:
        return table[raw]
    if raw in table.values():
        return raw
    raise BrokerError(f"{broker_label}: product {raw!r} not supported (use {', '.join(sorted(set(table) | set(table.values())))})")


def whole_qty(order: Dict, label: str) -> int:
    if not float(order["qty"]).is_integer():
        raise BrokerError(f"{label} quantities must be whole numbers")
    return int(order["qty"])


def f(x, default: float = 0.0) -> float:
    try:
        return float(x)
    except (TypeError, ValueError):
        return default


def first(d: Dict, keys: Iterable[str], default=None):
    for k in keys:
        if d.get(k) not in (None, ""):
            return d[k]
    return default
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 198kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall