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/base.py

View on GitHub
"""Broker interface and order validation shared by every adapter."""

from __future__ import annotations

from typing import Dict, List, Optional

ORDER_TYPES = ("market", "limit", "stop", "stop_limit")
SIDES = ("buy", "sell")


class BrokerError(RuntimeError):
    pass


def normalize_order(order: Dict) -> Dict:
    """Validate and normalize an order dict. Raises BrokerError with a clear message."""
    o = dict(order)
    o["symbol"] = str(o.get("symbol") or "").strip()
    if not o["symbol"]:
        raise BrokerError("order needs a symbol")
    o["side"] = str(o.get("side") or "").lower()
    if o["side"] in ("long", "b"):
        o["side"] = "buy"
    if o["side"] in ("short", "s"):
        o["side"] = "sell"
    if o["side"] not in SIDES:
        raise BrokerError("side must be buy or sell")
    try:
        o["qty"] = float(o.get("qty"))
    except (TypeError, ValueError):
        raise BrokerError("qty must be a number") from None
    if o["qty"] <= 0:
        raise BrokerError("qty must be > 0")
    if o["qty"].is_integer():
        o["qty"] = int(o["qty"])
    o["type"] = str(o.get("type") or "limit").lower().replace("-", "_")
    if o["type"] in ("mkt",):
        o["type"] = "market"
    if o["type"] in ("lmt",):
        o["type"] = "limit"
    if o["type"] not in ORDER_TYPES:
        raise BrokerError(f"type must be one of {', '.join(ORDER_TYPES)}")
    for k in ("limit_price", "stop_price", "stop_loss", "take_profit"):
        if o.get(k) in ("", None):
            o[k] = None
        else:
            try:
                o[k] = float(o[k])
            except (TypeError, ValueError):
                raise BrokerError(f"{k} must be a number") from None
            if o[k] <= 0:
                raise BrokerError(f"{k} must be > 0")
    if o["type"] in ("limit", "stop_limit") and o["limit_price"] is None:
        raise BrokerError(f"{o['type']} order needs limit_price")
    if o["type"] in ("stop", "stop_limit") and o["stop_price"] is None:
        raise BrokerError(f"{o['type']} order needs stop_price")
    ref = o["limit_price"] or o["stop_price"]
    if ref and o.get("stop_loss"):
        if o["side"] == "buy" and o["stop_loss"] >= ref:
            raise BrokerError("stop_loss must be below the entry price for a buy")
        if o["side"] == "sell" and o["stop_loss"] <= ref:
            raise BrokerError("stop_loss must be above the entry price for a sell")
    if ref and o.get("take_profit"):
        if o["side"] == "buy" and o["take_profit"] <= ref:
            raise BrokerError("take_profit must be above the entry price for a buy")
        if o["side"] == "sell" and o["take_profit"] >= ref:
            raise BrokerError("take_profit must be below the entry price for a sell")
    return o


class Broker:
    name = "base"
    live = False

    def account(self) -> Dict:
        """{'equity', 'cash', 'currency', 'broker', 'live'}"""
        raise NotImplementedError

    def positions(self) -> List[Dict]:
        """[{'symbol', 'qty' (signed), 'avg_price', 'last_price', 'market_value', 'unrealized_pnl'}]"""
        raise NotImplementedError

    def orders(self, open_only: bool = False) -> List[Dict]:
        raise NotImplementedError

    def place(self, order: Dict) -> Dict:
        """Returns {'order_id', 'status', ...}"""
        raise NotImplementedError

    def cancel(self, order_id: str) -> Dict:
        raise NotImplementedError

    def get_order(self, order_id: str) -> Optional[Dict]:
        return next((o for o in self.orders() if str(o.get("order_id")) == str(order_id)), None)
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