Skip to content

reddygopalkrishna/trading-skills / skills/trading-entry

trading-entry

Verified

Entry timer for intraday setups in any market - watches bar by bar and says the moment a setup triggers, waiting (and how far), still forming, expired or market closed. Opening-range breakout (first 15 minutes by default) or a break of any level you give, long or short, on 1, 2, 5 or 15-minute bars, with an optional volume check and a no-entries-near-the-close cutoff. Reads each exchange's session from the data (NSE 09:15, NYSE 09:30, LSE 08:00...), replays past sessions for practice, and hands the trigger to trading-plan with stop ideas. Never places an order. Use when the user says "tell me when to get in", "watch RELIANCE", "has it broken out", "did it break the opening range", "time my entry", "ORB", "check my watchlist for breakouts", or after a scan finds a setup.

FileKindSize
SKILL.mdskill md3.9 KB
assets/watchlists/crypto-majors.txtmarkdown112 B
assets/watchlists/global-index-etfs.txtmarkdown106 B
assets/watchlists/global-large-caps.txtmarkdown306 B
assets/watchlists/india-large-caps.txtmarkdown291 B
assets/watchlists/us-mega-caps.txtmarkdown173 B
assets/watchlists/world-indices.txtmarkdown104 B
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/entry.pyscript8.1 KB

scripts/_vendor/tradekit/brokers/dhan.py

View on GitHub
"""DhanHQ v2 adapter (REST, standard library only).

Credentials (environment variables win over secrets.json):
    DHAN_CLIENT_ID / dhan_client_id
    DHAN_ACCESS_TOKEN / dhan_access_token     valid 24 hours; create it in web.dhan.co > Access DhanHQ APIs

Symbols are EXCHANGESEGMENT:SECURITYID, e.g. NSE_EQ:11536 (Dhan identifies instruments by numeric
securityId; look it up in Dhan's scrip master CSV, https://images.dhan.co/api-data/api-scrip-master.csv).
Products: CNC, INTRADAY (alias MIS), MARGIN (alias NRML), MTF.
Cost: Trading APIs are free for all Dhan users (Data APIs are paid and are not used here).
Rules: a registered static IP is mandatory for placing, modifying and cancelling orders.
Dhan's published example responses are not fully consistent (e.g. fund field spelled "availabelBalance");
this adapter accepts both spellings.
"""

from __future__ import annotations

from typing import Dict, List, Optional

from .. import config
from . import _rest
from .base import Broker, BrokerError, normalize_order

BASE = "https://api.dhan.co/v2"
_TYPE = {"market": "MARKET", "limit": "LIMIT", "stop": "STOP_LOSS_MARKET", "stop_limit": "STOP_LOSS"}
_PRODUCT = {"CNC": "CNC", "MIS": "INTRADAY", "INTRADAY": "INTRADAY", "NRML": "MARGIN", "MARGIN": "MARGIN", "MTF": "MTF"}
_OPEN = ("TRANSIT", "PENDING", "PART_TRADED")


def split_symbol(symbol: str):
    seg, _, sid = symbol.strip().partition(":")
    if not sid or not sid.isdigit():
        raise BrokerError("Dhan symbols look like NSE_EQ:11536 (EXCHANGESEGMENT:securityId from the scrip master)")
    return seg.upper(), sid


class DhanClient:
    def __init__(self, client_id: Optional[str] = None, access_token: Optional[str] = None):
        self.client_id = client_id or config.secret("dhan_client_id", "DHAN_CLIENT_ID")
        self.access_token = access_token or config.secret("dhan_access_token", "DHAN_ACCESS_TOKEN")

    def _req(self, method, path, body=None):
        _rest.need("Dhan", client_id=self.client_id, access_token=self.access_token)
        return _rest.call("Dhan", method, BASE + path, {"access-token": self.access_token, "Content-Type": "application/json",
                                                         "Accept": "application/json"}, body=body)

    def profile(self):
        return self._req("GET", "/profile")

    def fundlimit(self):
        return self._req("GET", "/fundlimit")

    def positions(self):
        return self._req("GET", "/positions")

    def holdings(self):
        return self._req("GET", "/holdings")

    def orders(self):
        return self._req("GET", "/orders")

    def place_order(self, body):
        return self._req("POST", "/orders", body=body)

    def cancel_order(self, order_id):
        return self._req("DELETE", f"/orders/{order_id}")


class DhanBroker(Broker):
    name = "dhan"
    live = True

    def __init__(self, client: Optional[DhanClient] = None):
        self.client = client or DhanClient()
        self.cfg = config.load()

    def account(self) -> Dict:
        f = self.client.fundlimit()
        cash = _rest.f(_rest.first(f, ("availabelBalance", "availableBalance"), 0))
        return {"broker": "dhan", "live": True, "currency": self.cfg["account"].get("currency"),
                "cash": round(cash, 2), "equity": round(cash + _rest.f(f.get("utilizedAmount")), 2)}

    def positions(self) -> List[Dict]:
        out = []
        try:
            held = self.client.holdings()
            for h in held if isinstance(held, list) else []:
                q = _rest.f(h.get("totalQty"))
                if q:
                    avg = _rest.f(h.get("avgCostPrice"))
                    out.append({"symbol": f"{h.get('exchange', 'NSE')}_EQ:{h.get('securityId')}", "qty": q, "avg_price": avg,
                                "last_price": avg, "market_value": round(q * avg, 2), "unrealized_pnl": 0.0,
                                "product": "CNC", "name": h.get("tradingSymbol")})
        except BrokerError:
            pass  # a fresh account with no holdings can answer with an error body
        pos = self.client.positions()
        for p in pos if isinstance(pos, list) else []:
            q = _rest.f(p.get("netQty"))
            if q == 0:
                continue
            avg = _rest.f(p.get("costPrice"))
            out.append({"symbol": f"{p.get('exchangeSegment')}:{p.get('securityId')}", "qty": q, "avg_price": avg,
                        "last_price": avg, "market_value": round(q * avg, 2),
                        "unrealized_pnl": round(_rest.f(p.get("unrealizedProfit")), 2),
                        "product": p.get("productType"), "name": p.get("tradingSymbol")})
        return out  # Dhan returns no last price; value is at cost

    def orders(self, open_only: bool = False) -> List[Dict]:
        out = []
        book = self.client.orders()
        for o in book if isinstance(book, list) else []:
            st = str(o.get("orderStatus", "")).upper()
            if open_only and st not in _OPEN:
                continue
            out.append({"order_id": o.get("orderId"), "symbol": f"{o.get('exchangeSegment')}:{o.get('securityId')}",
                        "side": str(o.get("transactionType", "")).lower(), "qty": o.get("quantity"),
                        "type": o.get("orderType"), "limit_price": o.get("price"), "stop_price": o.get("triggerPrice"),
                        "status": st.lower(), "filled_qty": o.get("filledQty"), "avg_fill_price": o.get("averageTradedPrice"),
                        "product": o.get("productType"), "created": o.get("createTime"), "message": o.get("omsErrorDescription")})
        return out

    def to_params(self, order: Dict) -> Dict:
        o = normalize_order(order)
        seg, sid = split_symbol(o["symbol"])
        _rest.need("Dhan", client_id=self.client.client_id)
        tag = "".join(c for c in str(order.get("tag") or "tskills") if c.isalnum() or c in "_- ")[:30]
        return {"dhanClientId": self.client.client_id, "correlationId": tag, "transactionType": o["side"].upper(),
                "exchangeSegment": seg, "productType": _rest.product_for(order, _PRODUCT, "Dhan"),
                "orderType": _TYPE[o["type"]], "validity": "DAY", "securityId": sid,
                "quantity": _rest.whole_qty(o, "Dhan"), "price": o["limit_price"] or 0,
                "triggerPrice": o["stop_price"] or 0}

    def place(self, order: Dict) -> Dict:
        params = self.to_params(order)
        j = self.client.place_order(params)
        if not j.get("orderId"):
            raise BrokerError(f"Dhan did not return an orderId: {str(j)[:200]}")
        return {"order_id": j["orderId"], "status": "submitted", "broker_status": j.get("orderStatus"),
                "broker": "dhan", "params": params}

    def cancel(self, order_id: str) -> Dict:
        j = self.client.cancel_order(order_id) or {}
        return {"order_id": j.get("orderId", order_id), "status": "cancel_requested"}
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