claude-force: Skill for Claude Code

.claude/skills/state-management-patterns/SKILL.md

state-management-patterns is a skill for Claude Code from khanh-vu/claude-force. It costs 0 tokens per session (2,993 once invoked), scanned A, original, MIT.

A set of patterns for keeping cryptocurrency trading positions consistent across an exchange, a database, and in-memory application data. Position reconciliation means comparing these sources and resolving differences.

In plain words
What is it for?
Use it to reconcile positions, track prices and profit or loss, and maintain a reliable position state across trading-system components.
Why use it?
Trading systems can make incorrect decisions when their copies of position data drift apart or when an order is processed twice.

Skill for Claude Code

Written for Claude Code: installed under .claude/. Also seen: positional $N argument.

This is khanh-vu/claude-force's own configuration. It tells Claude Code how to work on claude-force itself, so it is not a mod to install elsewhere. Copy it as a starting point and replace the rules that are about this project. Everything claude-force configures →

Reuse

Borrowing it

Nothing to install: this file belongs to khanh-vu/claude-force. Take a copy, put it at the same path in your own repository, and replace the rules that are about this project with yours.

Copy the file
curl -O https://raw.githubusercontent.com/khanh-vu/claude-force/main/.claude/skills/state-management-patterns/SKILL.md
Clone the repo
git clone --depth 1 https://github.com/khanh-vu/claude-force

Made for: Claude Code.

Wrote this? Show the measurements

A badge with what this costs and how it scanned, read live from this page, so it follows the numbers instead of freezing them. Markdown for a README, HTML for a documentation site or a project page.

agentmods badge for state-management-patterns

README.md
[![agentmods](https://agentmods.dev/badge/skills/khanh-vu/claude-force/state-management-patterns.svg)](https://agentmods.dev/skills/khanh-vu/claude-force/state-management-patterns)
Your own site
<a href="https://agentmods.dev/skills/khanh-vu/claude-force/state-management-patterns"><img src="https://agentmods.dev/badge/skills/khanh-vu/claude-force/state-management-patterns.svg" alt="Measured on agentmods" height="20"></a>
Per session 0 Skills are progressive disclosure: only the name and description are preloaded; the body loads when the skill is used.
When invoked 2,993 The whole file, excluding the scripts and references it only reads on demand.
Security scan A 0 findings. A grade says what 26 rules found in the file — not that it is safe.
Origin original No closer match found in the catalogue.
Token cost

What it costs to keep this loaded

Counted locally with the o200k_base tokenizer, which is exact for GPT models; Claude uses its own tokenizer and its counts differ. Treat this as one consistent yardstick across the catalogue rather than a bill. Prices are per million input tokens.

ModelPer sessionOnce invoked
Fable 5.1 $0.00000 $0.02993
Opus 5 $0.00000 $0.01496
Sonnet 5 $0.00000 $0.00599
Haiku 4.5 $0.00000 $0.00299

Measured 8d ago against content hash b25506d61b3a, method: parsed. Prices are Anthropic first-party input rates as of 2026-09-08, from the pricing page.

Security

Grade A, and why

state-management-patterns scanned grade A with 0 findings against 26 rules in 11 categories — prompt injection, anti-refusal, data exfiltration, privilege escalation, supply chain, agent snooping, system-prompt leakage, SSRF and excessive agency — measured 8d ago.

A static scan of the body, not an audit. Every finding is printed with the line that produced it so you can judge whether it matters here. A mod is markdown that instructs an agent; that is exactly why what it instructs is worth reading.

Nothing flagged

None of the 26 patterns this scan looks for appear in this file: no shell pipes, no recursive deletes, no credential paths, no hidden text, no instruction-override or anti-refusal phrasing, no agent-config snooping. That is not a guarantee, it is the absence of the things that are checkable.

.claude/skills/state-management-patterns/SKILL.md · 465 lines

How it starts

The opening of the file, as written. The whole thing — 465 lines — stays where its author put it; the contents beside it link to each section on GitHub.

State Management Patterns

Robust state management for distributed cryptocurrency trading systems.

Position Reconciliation

from dataclasses import dataclass
from decimal import Decimal
from typing import Dict, List, Optional
from datetime import datetime

@dataclass
class Position:
    symbol: str
    amount: Decimal
    entry_price: Decimal
    current_price: Decimal
    unrealized_pnl: Decimal
    realized_pnl: Decimal
    leverage: Decimal
    liquidation_price: Optional[Decimal]
    last_updated: datetime

class PositionReconciliation:
    """
    Reconcile positions between exchange, database, and in-memory state
    Critical for preventing duplicate orders and state drift
    """

    def __init__(self, exchange_connector, database, cache):
        self.exchange = exchange_connector
        self.db = database
        self.cache = cache

    async def reconcile_positions(self) -> Dict[str, Position]:
        """
        Full position reconciliation across all data sources
        Returns: Reconciled positions (source of truth)
        """
        logger.info("Starting position reconciliation...")

        # Fetch positions from all sources
        exchange_positions = await self._fetch_exchange_positions()
        db_positions = await self.db.get_positions()
        cache_positions = await self.cache.get_positions()

        # Build position map keyed by symbol
        reconciled = {}

        # Use exchange as source of truth
        for symbol, exchange_pos in exchange_positions.items():
            db_pos = db_positions.get(symbol)
            cache_pos = cache_positions.get(symbol)

            # Detect discrepancies
            discrepancies = []

            if db_pos and abs(db_pos.amount - exchange_pos.amount) > Decimal('0.0001'):
                discrepancies.append(
                    f"DB amount mismatch: {db_pos.amount} vs exchange {exchange_pos.amount}"
                )

            if cache_pos and abs(cache_pos.amount - exchange_pos.amount) > Decimal('0.0001'):
                discrepancies.append(
                    f"Cache amount mismatch: {cache_pos.amount} vs exchange {exchange_pos.amount}"
                )

            # Update DB and cache to match exchange
            if discrepancies:
                logger.warning(
                    f"Position discrepancy for {symbol}: {', '.join(discrepancies)}"
                )

                await self.db.update_position(exchange_pos)
                await self.cache.set_position(symbol, exchange_pos)

            reconciled[symbol] = exchange_pos

        # Check for positions in DB/cache but not on exchange (stale data)
        all_symbols = set(exchange_positions.keys()) | set(db_positions.keys()) | set(cache_positions.keys())

        for symbol in all_symbols:
            if symbol not in exchange_positions:
                if symbol in db_positions or symbol in cache_positions:
                    logger.warning(f"Found stale position for {symbol} - removing from DB/cache")
                    await self.db.delete_position(symbol)
                    await self.cache.delete_position(symbol)

        logger.info(f"Position reconciliation complete: {len(reconciled)} positions")

        return reconciled

    async def _fetch_exchange_positions(self) -> Dict[str, Position]:
        """Fetch positions from exchange and convert to Position objects"""
        raw_positions = await self.exchange.fetch_positions()

        positions = {}
        for pos in raw_positions:
            if pos['contracts'] == 0:
                continue  # Skip closed positions

            position = Position(
                symbol=pos['symbol'],
                amount=Decimal(str(pos['contracts'])),
                entry_price=Decimal(str(pos['entryPrice'])),
                current_price=Decimal(str(pos['markPrice'])),
                unrealized_pnl=Decimal(str(pos['unrealizedPnl'])),
                realized_pnl=Decimal(str(pos.get('realizedPnl', 0))),
                leverage=Decimal(str(pos.get('leverage', 1))),
                liquidation_price=Decimal(str(pos['liquidationPrice'])) if pos.get('liquidationPrice') else None,
                last_updated=datetime.utcnow()
            )

            positions[pos['symbol']] = position

        return positions

Read the full file on GitHub · 465 lines

Changes

What this file has done since we first saw it

Hashed on every crawl. A supply-chain change to an agent config is a question of when, not whether, so the history is kept rather than the latest state alone.

  1. 8d ago First seen · 465 lines · 0 tokens per session scan A b25506d61b3a

Subscribe to this mod's changes

state-management-patterns is a skill published in the GitHub repository khanh-vu/claude-force (5 stars, last pushed 9mo ago), licensed MIT. It costs nothing until one of its globs matches a file; then it loads 2,993 tokens. A static security scan graded it A with 0 findings. No closer match exists in the catalogue, so it is treated as the original; first seen 2026-08-31.

Related

Other skills, from other repositories