⏳ This skill is pending AI review.

Scores will appear once the review pipeline completes.

v2.0

money-atlas-intelligence-os

elmatadorz@elmatadorz⭐ 59 stars· last commit 3mo ago· 0 open issues

|

Choose how to use this skill

You do not need every option. Choose the path your AI client supports. The stable page stays the same; versioned files are immutable.

1. Native installer

This listing has no registered native installer command. Use the complete package or source fallback below, depending on what your client supports.

Do not guess an installer command or replace an existing version without reviewing the diff.

2. Complete package recommended

Download the ZIP when available. It includes SKILL.md plus the references, security notes and version metadata.

No complete ProSkills package is published for this listing yet.

3. Prompt-only

Copy the prompt above when the agent can read the stable page or when you want to adopt the workflow without installing a skill.

Need only the instruction file?

Download SKILL.md only if your client requires a single file. The complete ZIP is safer for a full installation because it preserves the references and release context.

No path installs or executes anything by itself. Your agent still needs access to the project files. Before updating, compare the installed version and review the diff.

—/10

// RATINGS

⭐GitHub Stars
⭐⭐ 59 on GitHubGitHub ↗

Growing

🟢ProSkills Score
—
📍

Not yet listed on ClawHub or SkillsMP

// README

Money Atlas Intelligence OS

Claude Skill (Agent) — Financial Market Strategic Intelligence

Version: 2.0
Author: Bunyawat Dechanon (ElmatadorZ)
Brand: Money Atlas / Alternative Slowbar
Type: Custom Skill (SKILL.md format)


What This Is

A skill that transforms financial market questions into structured, scenario-based intelligence.

Not a prediction engine.
Not a signal bot.
A thinking system — built to reason the way a disciplined analyst does.

When you ask about BTC, gold, macro, forex, or any asset — this skill activates a multi-layer reasoning pipeline that separates what's actually happening from what the market narrative wants you to believe.


Core Engine

Genesis Protocol — 3-Step Thinking Pipeline

Step 1: First Principle Codex Deconstruct the market from root causes — not price action alone.

  • What is actually happening?
  • Why is price/macro moving this way?
  • What is the structural driver?
  • Where is the asymmetric opportunity?
  • What happens next under each scenario?

Step 2: System Thinking — Micro → Macro

  • Micro: Asset-specific technicals, on-chain data, positioning
  • Meso: Sector rotation, correlated assets, sentiment
  • Macro: Fed, DXY, liquidity cycle, geopolitics
  • Meta: What narrative is the market constructing — and who benefits?

Step 3: AI Fluency 4D

  • Delegation — Pattern recognition across data
  • Description — Convert market noise → structured signal
  • Discernment — Question bias, timeframe, missing information
  • Diligence — Human makes the final decision. Always.

SMC Layer — Smart Money Cycle Map

Identifies where price is in the institutional cycle:

LayerPhaseWhat's Happening
L1AccumulationQuiet buying, engineered fake breakdowns
L2ExpansionBreakout, momentum building
L3Decision ZoneHigh-stakes inflection point
L4DistributionQuiet selling, engineered fake breakouts
L5Exit LiquidityRetail buys tops, institutions exit

Every analysis maps the current layer + next probable move + invalidation condition.


Output Modes

LIGHT MODE — Quick Insight

For single-asset questions and fast reads.

📍 MARKET STRUCTURE INSIGHT
[SMC layer + price context]

📍 KEY RISK
[What breaks the thesis]

📍 STRATEGIC TAKEAWAY
[1-2 sentence actionable insight]

FULL MODE — Deep Analysis

For investment decisions, macro analysis, strategy, or "should I" questions.

📍 SITUATION MAP
📍 FIRST PRINCIPLE BREAKDOWN
📍 SYSTEM MAP (Macro → Liquidity → Asset → Price)
📍 SMC LAYER MAP
📍 NARRATIVE INTELLIGENCE
📍 SCENARIOS
   🐂 Bull: [entry zone | target | condition]
   🐻 Bear: [trigger | target | condition]
   ⚖️ Base: [most probable path]
📍 DECISION FRAMEWORK
📍 RISK & FAILURE MODE
   CONFIDENCE: [X%] | KEY UNKNOWNS: [list]

Mode is auto-detected from question context.
User can override: type FULL or LIGHT at any time.


Trigger Topics

This skill activates when you ask about:

  • Crypto: BTC, ETH, altcoins, on-chain data
  • Commodities: Gold, silver, oil, soft commodities
  • Macro: Fed policy, interest rates, inflation, DXY, liquidity cycles
  • Equities: Stocks, indices, sector rotation
  • Forex: Currency pairs, emerging markets
  • Geopolitics: Events affecting market structure
  • Strategy: Portfolio allocation, risk management, entry/exit frameworks

What This Skill Does NOT Do

  • Give single-point price predictions without scenarios
  • Express certainty without evidence
  • Omit the risk or invalidation condition
  • Tell you what to do — it gives you a framework to decide

If output violates any of these → the system flags ⚠️ INSUFFICIENT EDGE and re-evaluates before responding.


Architecture

Input (market question)
│
├── Genesis Protocol
│   ├── First Principle Codex (root cause decomposition)
│   ├── System Thinking (micro → macro chain)
│   └── AI Fluency 4D (bias check + discernment)
│
├── SMC Layer Engine
│   ├── Market structure mapping
│   ├── Liquidity zone identification
│   └── Smart money vs. retail narrative separation
│
├── Scenario Engine
│   ├── Bull / Bear / Base case
│   ├── Entry-exit zones
│   └── Invalidation conditions
│
└── Output (LIGHT or FULL mode)

File Structure

money-atlas-intelligence-os/
├── SKILL.md                    ← Claude skill definition (main entry point)
├── skill_config.json           ← Skill metadata and trigger config
├── architecture.md             ← System architecture overview
├── system_prompt.txt           ← Session boot prompt
├── full_mode.txt               ← Full mode output spec
├── light_mode.txt              ← Light mode output spec
│
├── core/                       ← Genesis Protocol engine
│   ├── genesis_core.py
│   ├── ai_fluency_4d.py
│   ├── discernment_engine.py
│   └── decision_engine.py
│
├── agents/                     ← Specialist agent layer
│   ├── orchestrator.py
│   ├── analyst_agent.py
│   ├── macro_agent.py
│   ├── smc_agent.py
│   ├── risk_agent.py
│   ├── sentiment_agent.py
│   ├── skeptic_agent.py
│   └── strategist_agent.py
│
├── smc/                        ← Smart Money Concept engine
├── intelligence/               ← Alpha, macro, geopolitics engines
├── strategy/                   ← Scenario + asymmetric opportunity engine
├── execution/                  ← Signal, risk, trade logging
├── orchestrator/               ← Multi-agent coordination
├── cli/                        ← Command-line runners
│
├── tests/                      ← unit tests for the reasoning engines + skill contract
├── examples/                   ← worked input→output examples + runnable demo
│   └── worked/
└── tools/validate_skill.py     ← installability + integrity checker (run in CI)

How to Install (Claude Custom Skill)

  1. Clone or download this repository
  2. Place the money-atlas-intelligence-os/ folder in your Claude skills directory
  3. The skill activates automatically when Claude detects relevant financial market questions
  4. Or call it explicitly by referencing the skill name in your system prompt

The skill entry point is SKILL.md (the Anthropic standard filename). The reasoning is self-contained in that file and needs no tools to run — see metadata.compatibility in its frontmatter. The Python modules are an optional execution layer.


Verifying it before you trust it

Two things are checked on every push, and you can run both locally:

pip install pytest pyyaml

python tools/validate_skill.py   # frontmatter, license, and safety structure intact
python -m pytest -q              # unit tests over the reasoning engines + skill contract

The tests are not decorative. They pin the gates that would cost money if they drifted — a BUY signal only on high-confidence accumulation, risk raised on distribution, First Principle truths kept separate from inference — and the skill's own promises: every scenario carries an invalidation condition, and the skill abstains rather than invent a price when it has no data. See examples/worked/ for what the output looks like in each case, including the insufficient-data case where the correct answer is to decline.


Non-Negotiable Constraints

Every output must include:

  • Multiple scenarios — no single prediction
  • Explicit uncertainty — confidence level + key unknowns
  • Invalidation point — what breaks the entire analysis
  • Human decision primacy — the skill advises, the human decides

Violation of any constraint → output is invalid → re-evaluate.


Part of the Skynet Skill Ecosystem

This skill operates within the broader Skynet Elite Commander meta-intelligence system:

SkillDomain
skynet-elite-commanderMeta-cognition OS — routes all domains
money-atlas-intelligence-osFinancial markets, macro, trading
alternative-coffee-intelligenceCoffee science and

// HOW IT'S BUILT

// FILES

92 files shipped with this skill. Inline text is the catalog copy. The upstream link is the source repository.

  • SKILL.md5.9 KB7f3d2f2c2e02upstream ↗
    ---
    name: "money-atlas-intelligence-os"
    version: "2.0"
    author: "Money Atlas — Bunyawat Dechanon"
    license: "Apache-2.0"
    description: |
      Use this skill for ANY financial market, investment, or macro-economic analysis.
      ALWAYS trigger this skill — do not skip it — when the user asks about:
      BTC, bitcoin, crypto, gold, silver, oil, stocks, forex, bonds, interest rates,
      Fed policy, inflation, deflation, stagflation, market structure, trading setups,
      portfolio allocation, asset allocation, investment strategy, price analysis,
      market outlook, geopolitics affecting markets, or any question involving
      "should I buy/sell/hold [any asset]", "what will [asset] do", or
      "analyze [market/asset]". Apply Genesis Protocol (First Principle + System Thinking)
      combined with SMC Layer analysis to produce structured insights with explicit
      scenarios, entry/exit zones, and uncertainty. For non-market strategic thinking,
      use genesis-mind-strategic-intelligence instead.
    metadata:
      category: "finance"
      compatibility: "Any instruction-following model. Reasoning is model-independent — the
        SKILL.md is self-contained and needs no tools to run. The optional Python modules
        (analyzer, signals, smc, backtest) are stdlib-only and target Python 3.9+."
      requires_tools: false
      produces: "Structured market scenarios with explicit entry/exit zones, stated
        confidence, and an invalidation condition for every scenario."
      not_for: "Real-time price feeds, execution/order placement, or personalized
        investment advice. It is a reasoning framework, not a signal service or a broker."
    ---
    
    # MONEY ATLAS INTELLIGENCE OS v2
    ## Financial Market Strategic Intelligence
    
    Execute. Don't describe.
    
    ---
    
    ## ACTIVATION
    
    **LIGHT MODE** (default) — for quick insight, single asset questions
    **FULL MODE** — for investment decisions, macro analysis, strategy, any "should I" question
    
    Auto-detect. User can override: type "FULL" or "LIGHT"
    
    ---
    
    ## GENESIS PROTOCOL — Core Thinking Engine
    
    ### Step 1: First Principle Codex
    Problem:   What is actually happening in this market?
    Cause:     Why is price/macro moving this way?
    Mechanism: What is the structural driver?
    Leverage:  Where is the asymmetric opportunity?
    Outcome:   What happens next under each scenario?
    ### Step 2: System Thinking — Micro → Macro
    Micro:  Asset-specific technicals, on-chain, positioning
    Meso:   Sector rotation, correlated assets, sentiment
    Macro:  Fed, DXY, liquidity cycle, geopolitics
    Meta:   Narrative — what story is market telling?
    ### Step 3: AI Fluency 4D
    - **Delegation** — Use data pattern recognition
    - **Description** — Convert vague market noise → structured signal
    - **Discernment** — Question bias, timeframe, missing data
    - **Diligence** — Human = final decision. Always show risk.
    
    ---
    
    ## SMC LAYER — Market Structure Intelligence
    
    When market context detected, map to 5 layers:
    
    | Layer | Phase | What Smart Money does |
    |---|---|---|
    | L1 | Accumulation | Quiet buying, fake breakdowns |
    | L2 | Expansion | Breakout, momentum builds |
    | L3 | Decision Zone | **We are here or approaching** |
    | L4 | Distribution | Quiet selling, fake breakouts |
    | L5 | Exit Liquidity | Retail buys tops, Smart Money exits |
    
    **Always identify:** current layer + next probable move + invalidation
    
    ---
    
    ## OUTPUT — LIGHT MODE
    📍 MARKET STRUCTURE INSIGHT
    [Current SMC layer + price context]
    📍 KEY RISK
    [What breaks the thesis]
    📍 STRATEGIC TAKEAWAY
    [1-2 sentence actionable insight]
    ---
    
    ## OUTPUT — FULL MODE
    📍 SITUATION MAP
    [Real-time context — price, macro, narrative]
    📍 FIRST PRINCIPLE BREAKDOWN
    [What is actually driving price — not what media says]
    📍 SYSTEM MAP
    [Macro → Liquidity → Asset → Price chain]
    📍 SMC LAYER MAP
    [Current layer + structure + liquidity zones]
    📍 NARRATIVE INTELLIGENCE
    [What Smart Money wants retail to believe vs. reality]
    📍 SCENARIOS
    🐂 Bull: [entry zone | target | condition]
    🐻 Bear: [trigger | target | condition]
    ⚖️ Base: [most probable path]
    📍 DECISION FRAMEWORK
    [IF your timeframe is X → do Y]
    [IF your risk tolerance is X → do Y]
    📍 RISK & FAILURE MODE
    [What invalidates this entire analysis]
    CONFIDENCE: [X%] | KEY UNKNOWNS: [list]
    ---
    
    ## CONSTRAINTS — Non-negotiable
    
    - Never give single prediction — always scenarios
    - Always include uncertainty and confidence level
    - Avoid narrative bias — question the consensus
    - Highlight missing data explicitly
    - Human = final decision. Always.
    
    ---
    
    ## FAILURE SYSTEM
    
    Output invalid if:
    - No alternative scenario
    - No risk mentioned
    - Too certain without evidence
    - No invalidation point
    
    → Re-evaluate before outputting
    → If still weak: `⚠️ INSUFFICIENT EDGE`
    
    ### When information is insufficient
    
    The skill must degrade honestly rather than fabricate. It has no live price feed
    and no order execution — those are out of scope by design (see `not_for` in the
    metadata). So:
    
    - **No live data provided** → state the reasoning *framework* for the asset and name
      exactly which inputs would resolve it. Do not invent a current price, level, or
      figure. An invented number is worse than an admitted gap.
    - **A quantitative claim cannot be sourced** → mark it `[UNVERIFIED]` and keep it out
      of the entry/exit zones, which must rest only on stated inputs.
    - **The question is not a market question** → hand off to
      `genesis-mind-strategic-intelligence` rather than stretching this skill past its edge.
    - **Asked for a buy/sell/hold decision as personal advice** → give the structured
      scenarios and their invalidation conditions; the human makes the decision. This skill
      does not issue personalized investment advice.
    
    An abstention is a valid output. A confident answer built on data the skill does not
    have is not.
    
    ---
    
    ## REFERENCE FILES — Load when needed
    
    - Output mode details → read `full_mode.txt` / `light_mode.txt`
    - System architecture → read `architecture.md`
    - Session boot prompt → read `system_prompt.txt`
    
  • examples/README.md1.4 KB417ca0826babupstream ↗
    # Examples
    
    Two kinds of example live here:
    
    - **Worked examples** (`worked/*.md`) — a real question and the *shape* of the
      answer the skill produces. These show an agent, or a person evaluating the
      skill, what "good output" looks like before installing it.
    - **Runnable demo** (`full_system_demo.py`) — drives the optional Python engines
      end to end over sample OHLCV data.
    
    ## Worked examples
    
    | File | Question | What it demonstrates |
    |---|---|---|
    | [worked/01-btc-light-mode.md](worked/01-btc-light-mode.md) | "Quick read on BTC?" | LIGHT mode: one scenario, confidence, invalidation |
    | [worked/02-gold-full-mode.md](worked/02-gold-full-mode.md) | "Should I add gold here?" | FULL mode: First Principle → SMC → scenarios with entry/exit |
    | [worked/03-insufficient-data.md](worked/03-insufficient-data.md) | "Where's BTC headed?" (no data) | Honest degradation — the skill abstains instead of inventing a price |
    
    Every worked example ends with an **invalidation condition**, because an output
    without one is invalid by the skill's own FAILURE SYSTEM.
    
    ## Running the demo
    
    ```bash
    pip install -r ../requirements.txt   # if the engines need optional deps
    python full_system_demo.py
    ```
    
    The reasoning in `SKILL.md` needs none of this — it runs on the model alone. The
    Python engines are an optional execution layer for when you want to drive the
    same structure over real candles.
    
  • README.md9.9 KBf11dadfb4c99upstream ↗
    # Money Atlas Intelligence OS
    ### Claude Skill (Agent) — Financial Market Strategic Intelligence
    
    **Version:** 2.0  
    **Author:** Bunyawat Dechanon (ElmatadorZ)  
    **Brand:** Money Atlas / Alternative Slowbar  
    **Type:** Custom Skill (SKILL.md format)
    
    ---
    
    ## What This Is
    
    A skill that transforms financial market questions into structured, scenario-based intelligence.
    
    Not a prediction engine.  
    Not a signal bot.  
    A thinking system — built to reason the way a disciplined analyst does.
    
    When you ask about BTC, gold, macro, forex, or any asset — this skill activates a multi-layer reasoning pipeline that separates what's actually happening from what the market narrative wants you to believe.
    
    ---
    
    ## Core Engine
    
    ### Genesis Protocol — 3-Step Thinking Pipeline
    
    **Step 1: First Principle Codex**
    Deconstruct the market from root causes — not price action alone.
    - What is *actually* happening?
    - Why is price/macro moving this way?
    - What is the structural driver?
    - Where is the asymmetric opportunity?
    - What happens next under each scenario?
    
    **Step 2: System Thinking — Micro → Macro**
    - Micro: Asset-specific technicals, on-chain data, positioning
    - Meso: Sector rotation, correlated assets, sentiment
    - Macro: Fed, DXY, liquidity cycle, geopolitics
    - Meta: What narrative is the market constructing — and who benefits?
    
    **Step 3: AI Fluency 4D**
    - Delegation — Pattern recognition across data
    - Description — Convert market noise → structured signal
    - Discernment — Question bias, timeframe, missing information
    - Diligence — Human makes the final decision. Always.
    
    ---
    
    ### SMC Layer — Smart Money Cycle Map
    
    Identifies where price is in the institutional cycle:
    
    | Layer | Phase | What's Happening |
    |---|---|---|
    | L1 | Accumulation | Quiet buying, engineered fake breakdowns |
    | L2 | Expansion | Breakout, momentum building |
    | L3 | Decision Zone | High-stakes inflection point |
    | L4 | Distribution | Quiet selling, engineered fake breakouts |
    | L5 | Exit Liquidity | Retail buys tops, institutions exit |
    
    Every analysis maps the current layer + next probable move + invalidation condition.
    
    ---
    
    ## Output Modes
    
    ### LIGHT MODE — Quick Insight
    For single-asset questions and fast reads.
    
    ```
    📍 MARKET STRUCTURE INSIGHT
    [SMC layer + price context]
    
    📍 KEY RISK
    [What breaks the thesis]
    
    📍 STRATEGIC TAKEAWAY
    [1-2 sentence actionable insight]
    ```
    
    ### FULL MODE — Deep Analysis
    For investment decisions, macro analysis, strategy, or "should I" questions.
    
    ```
    📍 SITUATION MAP
    📍 FIRST PRINCIPLE BREAKDOWN
    📍 SYSTEM MAP (Macro → Liquidity → Asset → Price)
    📍 SMC LAYER MAP
    📍 NARRATIVE INTELLIGENCE
    📍 SCENARIOS
       🐂 Bull: [entry zone | target | condition]
       🐻 Bear: [trigger | target | condition]
       ⚖️ Base: [most probable path]
    📍 DECISION FRAMEWORK
    📍 RISK & FAILURE MODE
       CONFIDENCE: [X%] | KEY UNKNOWNS: [list]
    ```
    
    Mode is auto-detected from question context.  
    User can override: type `FULL` or `LIGHT` at any time.
    
    ---
    
    ## Trigger Topics
    
    This skill activates when you ask about:
    
    - **Crypto:** BTC, ETH, altcoins, on-chain data
    - **Commodities:** Gold, silver, oil, soft commodities
    - **Macro:** Fed policy, interest rates, inflation, DXY, liquidity cycles
    - **Equities:** Stocks, indices, sector rotation
    - **Forex:** Currency pairs, emerging markets
    - **Geopolitics:** Events affecting market structure
    - **Strategy:** Portfolio allocation, risk management, entry/exit frameworks
    
    ---
    
    ## What This Skill Does NOT Do
    
    - Give single-point price predictions without scenarios
    - Express certainty without evidence
    - Omit the risk or invalidation condition
    - Tell you what to do — it gives you a framework to decide
    
    If output violates any of these → the system flags `⚠️ INSUFFICIENT EDGE` and re-evaluates before responding.
    
    ---
    
    ## Architecture
    
    ```
    Input (market question)
    │
    ├── Genesis Protocol
    │   ├── First Principle Codex (root cause decomposition)
    │   ├── System Thinking (micro → macro chain)
    │   └── AI Fluency 4D (bias check + discernment)
    │
    ├── SMC Layer Engine
    │   ├── Market structure mapping
    │   ├── Liquidity zone identification
    │   └── Smart money vs. retail narrative separation
    │
    ├── Scenario Engine
    │   ├── Bull / Bear / Base case
    │   ├── Entry-exit zones
    │   └── Invalidation conditions
    │
    └── Output (LIGHT or FULL mode)
    ```
    
    ---
    
    ## File Structure
    
    ```
    money-atlas-intelligence-os/
    ├── SKILL.md                    ← Claude skill definition (main entry point)
    ├── skill_config.json           ← Skill metadata and trigger config
    ├── architecture.md             ← System architecture overview
    ├── system_prompt.txt           ← Session boot prompt
    ├── full_mode.txt               ← Full mode output spec
    ├── light_mode.txt              ← Light mode output spec
    │
    ├── core/                       ← Genesis Protocol engine
    │   ├── genesis_core.py
    │   ├── ai_fluency_4d.py
    │   ├── discernment_engine.py
    │   └── decision_engine.py
    │
    ├── agents/                     ← Specialist agent layer
    │   ├── orchestrator.py
    │   ├── analyst_agent.py
    │   ├── macro_agent.py
    │   ├── smc_agent.py
    │   ├── risk_agent.py
    │   ├── sentiment_agent.py
    │   ├── skeptic_agent.py
    │   └── strategist_agent.py
    │
    ├── smc/                        ← Smart Money Concept engine
    ├── intelligence/               ← Alpha, macro, geopolitics engines
    ├── strategy/                   ← Scenario + asymmetric opportunity engine
    ├── execution/                  ← Signal, risk, trade logging
    ├── orchestrator/               ← Multi-agent coordination
    ├── cli/                        ← Command-line runners
    │
    ├── tests/                      ← unit tests for the reasoning engines + skill contract
    ├── examples/                   ← worked input→output examples + runnable demo
    │   └── worked/
    └── tools/validate_skill.py     ← installability + integrity checker (run in CI)
    ```
    
    ---
    
    ## How to Install (Claude Custom Skill)
    
    1. Clone or download this repository
    2. Place the `money-atlas-intelligence-os/` folder in your Claude skills directory
    3. The skill activates automatically when Claude detects relevant financial market questions
    4. Or call it explicitly by referencing the skill name in your system prompt
    
    The skill entry point is **`SKILL.md`** (the Anthropic standard filename). The reasoning is
    self-contained in that file and needs no tools to run — see `metadata.compatibility` in its
    frontmatter. The Python modules are an optional execution layer.
    
    ---
    
    ## Verifying it before you trust it
    
    Two things are checked on every push, and you can run both locally:
    
    ```bash
    pip install pytest pyyaml
    
    python tools/validate_skill.py   # frontmatter, license, and safety structure intact
    python -m pytest -q              # unit tests over the reasoning engines + skill contract
    ```
    
    The tests are not decorative. They pin the gates that would cost money if they drifted — a BUY
    signal only on high-confidence accumulation, risk raised on distribution, First Principle truths
    kept separate from inference — and the skill's own promises: every scenario carries an invalidation
    condition, and the skill abstains rather than invent a price when it has no data. See
    [`examples/worked/`](examples/worked/) for what the output looks like in each case, including the
    [insufficient-data case](examples/worked/03-insufficient-data.md) where the correct answer is to
    decline.
    
    ---
    
    ## Non-Negotiable Constraints
    
    Every output must include:
    
    - **Multiple scenarios** — no single prediction
    - **Explicit uncertainty** — confidence level + key unknowns
    - **Invalidation point** — what breaks the entire analysis
    - **Human decision primacy** — the skill advises, the human decides
    
    Violation of any constraint → output is invalid → re-evaluate.
    
    ---
    
    ## Part of the Skynet Skill Ecosystem
    
    This skill operates within the broader **Skynet Elite Commander** meta-intelligence system:
    
    | Skill | Domain |
    |---|---|
    | `skynet-elite-commander` | Meta-cognition OS — routes all domains |
    | `money-atlas-intelligence-os` | Financial markets, macro, trading |
    | `alternative-coffee-intelligence` | Coffee science and roastery operations |
    | `genesis-mind-strategic-intelligence` | Strategic thinking, business, philosophy |
    | `first-principle-codex-os` | Anti-hallucination cognitive base layer |
    
    ---
    
    ## ⚠️ Not financial advice
    
    This system **analyses** markets. It does not advise. Its output is structured scenarios with
    explicit uncertainty — an analytical instrument, not a recommendation, and it can be wrong.
    You are solely responsible for your own decisions. Consult a licensed financial adviser before
    acting on any output, and never deploy it against capital you cannot afford to lose.
    See [NOTICE](NOTICE) and the warranty disclaimer in the [LICENSE](LICENSE).
    
    ---
    
    ## License
    
    **[Apache License 2.0](LICENSE)** — OSI-approved, with an express patent grant. Free to use,
    modify, and redistribute, including commercially at any revenue. Keep the licence and
    [NOTICE](NOTICE), and state any changed files.
    
    Attribution is requested (not required beyond NOTICE):
    **Built on Money Atlas Intelligence OS by Bunyawat Dechanon (ElmatadorZ)**
    
    Apache §6 grants no rights to the name: a derivative that removes the uncertainty disclosure,
    the scenario structure, or the refusal to present analysis as advice must be renamed.
    
    *(Earlier releases used the custom Open Cognitive License v1.0 with a 2% clause above $10M/year;
    it was replaced to remove adoption friction. Prior text is in the git history.)*
    
    ---
    
    ## Author
    
    **Bunyawat Dechanon**  
    Independent Builder & Architect  
    Brand: Alternative Slowbar / Money Atlas  
    Location: Thailand
    
    > *"The market is always telling a story. This skill helps you read who wrote it."*
    
  • .github/workflows/validate.yml2.6 KB5f786014d3f8upstream ↗
    name: Validate
    
    on:
      push:
        branches: [main]
      pull_request:
        branches: [main]
      workflow_dispatch:
    
    permissions:
      contents: read
    
    jobs:
      python:
        name: python compiles (py${{ matrix.python-version }})
        runs-on: ubuntu-latest
        strategy:
          fail-fast: false
          matrix:
            python-version: ["3.9", "3.11", "3.12"]
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with:
              python-version: ${{ matrix.python-version }}
          - name: Byte-compile every module
            run: python -m compileall -q . && echo "  OK  all modules compile"
    
      skill:
        name: skill integrity
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with:
              python-version: "3.12"
          - run: pip install --quiet pyyaml
          - name: Validate SKILL.md
            run: python tools/validate_skill.py
    
      tests:
        name: unit tests (py${{ matrix.python-version }})
        runs-on: ubuntu-latest
        strategy:
          fail-fast: false
          matrix:
            python-version: ["3.9", "3.11", "3.12"]
        steps:
          - uses: actions/checkout@v4
          - uses: actions/setup-python@v5
            with:
              python-version: ${{ matrix.python-version }}
          - run: pip install --quiet pytest pyyaml
          - name: Run the reasoning-engine and skill-contract tests
            run: python -m pytest -q
    
      hygiene:
        name: repo hygiene
        runs-on: ubuntu-latest
        steps:
          - uses: actions/checkout@v4
          - name: No secrets, no stray filenames
            run: |
              python - <<'PY'
              import pathlib, re, sys
              probs = []
              skip = {'.git', '__pycache__', '.pytest_cache'}
              allow = {'LICENSE', 'NOTICE', 'CODEOWNERS', 'Makefile', 'Dockerfile'}
              secret = re.compile(r"(api[_-]?key|secret|token|password)\s*[:=]\s*['\"][A-Za-z0-9_\-]{16,}", re.I)
              for p in pathlib.Path('.').rglob('*'):
                  if skip & set(p.parts) or not p.is_file(): continue
                  if any(c in p.name for c in '└├─│'): probs.append(f"tree glyph: {p}")
                  if not p.suffix and p.name not in allow and not p.name.startswith('.'):
                      probs.append(f"missing extension: {p}")
                  if p.suffix in {'.py', '.json', '.txt', '.md'}:
                      try: t = p.read_text(encoding='utf-8', errors='ignore')
                      except Exception: continue
                      if secret.search(t): probs.append(f"possible hardcoded credential: {p}")
              if probs:
                  print("\n".join(f"  {x}" for x in probs)); sys.exit(1)
              print("  OK  hygiene clean")
              PY
    
  • .gitignore351 Be484fa782d88upstream ↗
    # Python
    __pycache__/
    *.py[cod]
    *.egg-info/
    .venv/
    venv/
    env/
    
    # Secrets — never commit broker or data-provider credentials
    .env
    .env.*
    !.env.example
    *.key
    credentials.json
    
    # Runtime state / outputs
    memory.json.bak
    *.log
    output/
    logs/
    
    # Tooling
    .pytest_cache/
    .mypy_cache/
    .ruff_cache/
    .coverage
    
    # OS / editor
    .DS_Store
    Thumbs.db
    .idea/
    .vscode/
    
  • adapter.py358 Ba88a022ac1bdupstream ↗
    from smc.smc_layer_masterpiece import SMCLayerEngine
    
    class SMCAdapter:
    
        def __init__(self):
            self.engine = SMCLayerEngine()
    
        async def analyze(self, symbol, timeframe, candles):
            result = await self.engine.analyze(
                symbol=symbol,
                timeframe=timeframe,
                candles=candles
            )
            return result
    
  • agents/analyst_agent.py155 Bebade9d1fa13upstream ↗
    class AnalystAgent:
    
        def run(self, data):
            return {
                "insight": "Market structure analyzed",
                "confidence": 0.7
            }
    
  • agents/base_agent.py335 B49842866644cupstream ↗
    # agents/base_agent.py
    
    from dataclasses import dataclass
    from typing import Dict, Any
    
    @dataclass
    class AgentOutput:
        name: str
        data: Dict[str, Any]
        confidence: float
        reasoning: str
    
    
    class BaseAgent:
        name = "base"
    
        async def run(self, context: Dict[str, Any]) -> AgentOutput:
            raise NotImplementedError
    
  • agents/genesis_agent.py448 Ba86a1fb9ba79upstream ↗
    from .base_agent import BaseAgent, AgentOutput
    from core.genesis_core import GenesisCore
    
    
    class GenesisAgent(BaseAgent):
        name = "genesis"
    
        def __init__(self):
            self.core = GenesisCore()
    
        async def run(self, context):
    
            result = self.core.run(context)
    
            return AgentOutput(
                name=self.name,
                data=result,
                confidence=0.9,
                reasoning="Genesis Protocol executed"
            )
    
  • agents/macro_agent.py444 Befa713cfd683upstream ↗
    # agents/macro_agent.py
    
    from .base_agent import BaseAgent, AgentOutput
    
    class MacroAgent(BaseAgent):
        name = "macro"
    
        async def run(self, context):
            macro = context.get("macro_data", {})
    
            insight = "Liquidity tightening → risk assets under pressure"
    
            return AgentOutput(
                name=self.name,
                data={"macro_bias": "bearish"},
                confidence=0.7,
                reasoning=insight
            )
    
  • agents/orchestrator.py729 B9992602fefbbupstream ↗
    # agents/orchestrator.py
    
    import asyncio
    
    from .macro_agent import MacroAgent
    from .smc_agent import SMCAgent
    from .sentiment_agent import SentimentAgent
    from .risk_agent import RiskAgent
    from .portfolio_agent import PortfolioAgent
    
    
    class Orchestrator:
    
        def __init__(self):
            self.agents = [
                MacroAgent(),
                SMCAgent(),
                SentimentAgent(),
                RiskAgent(),
                GenesisAgent(),
                PortfolioAgent()
            ]
    
        async def run(self, context):
    
            results = {}
    
            for agent in self.agents:
                output = await agent.run(context)
                results[agent.name] = output.data
                context[agent.name] = output.data
    
            return results
    
  • agents/portfolio_agent.py598 B348c7fe24e7dupstream ↗
    # agents/portfolio_agent.py
    
    from .base_agent import BaseAgent, AgentOutput
    
    class PortfolioAgent(BaseAgent):
        name = "portfolio"
    
        async def run(self, context):
    
            macro = context["macro"]["macro_bias"]
            risk = context["risk"]["risk_level"]
    
            if macro == "bearish" and risk == "high":
                decision = "Reduce exposure"
            else:
                decision = "Hold / Accumulate"
    
            return AgentOutput(
                name=self.name,
                data={"decision": decision},
                confidence=0.8,
                reasoning=f"Macro={macro}, Risk={risk}"
            )
    
  • agents/risk_agent.py341 B7c1e6023e2eaupstream ↗
    # agents/risk_agent.py
    
    from .base_agent import BaseAgent, AgentOutput
    
    class RiskAgent(BaseAgent):
        name = "risk"
    
        async def run(self, context):
            return AgentOutput(
                name=self.name,
                data={"risk_level": "high"},
                confidence=0.75,
                reasoning="Volatility expansion likely"
            )
    
  • agents/sentiment_agent.py360 B96b1debfaf61upstream ↗
    # agents/sentiment_agent.py
    
    from .base_agent import BaseAgent, AgentOutput
    
    class SentimentAgent(BaseAgent):
        name = "sentiment"
    
        async def run(self, context):
            return AgentOutput(
                name=self.name,
                data={"sentiment": "greed"},
                confidence=0.6,
                reasoning="Market shows late-stage optimism"
            )
    
  • agents/skeptic_agent.py158 B301021a30de4upstream ↗
    class SkepticAgent:
    
        def run(self, analysis):
            return {
                "critique": "Potential bias detected",
                "confidence": 0.6
            }
    
  • agents/smc_agent.py449 Bd5f75e0f4803upstream ↗
    from .base_agent import BaseAgent, AgentOutput
    from smc.smc_wrapper import SMCWrapper
    
    
    class SMCAgent(BaseAgent):
        name = "smc"
    
        def __init__(self):
            self.wrapper = SMCWrapper()
    
        async def run(self, context):
    
            smc_data = await self.wrapper.analyze(context)
    
            return AgentOutput(
                name=self.name,
                data=smc_data,
                confidence=0.85,
                reasoning=smc_data["summary"]
            )
    
  • agents/strategist_agent.py166 Bdd4ba4dfb539upstream ↗
    class StrategistAgent:
    
        def run(self, analysis):
            return {
                "strategy": "Optimal allocation strategy",
                "confidence": 0.75
            }
    
  • analyzer/insight_engine.py557 B805c90321027upstream ↗
    class InsightEngine:
    
        def generate(self, smc_layers):
    
            insights = []
    
            for layer in smc_layers:
    
                if layer.state == "accumulating":
                    insights.append(
                        f"Layer {layer.layer}: มีสัญญาณสะสมของทุนใหญ่"
                    )
    
                elif layer.state == "distributing":
                    insights.append(
                        f"Layer {layer.layer}: มีแรงขายจากผู้ถือครอง"
                    )
    
            return insights
    
  • analyzer/risk_engine.py509 B548173a7aa76upstream ↗
    class RiskEngine:
    
        def evaluate(self, smc_layers):
    
            risks = []
    
            for layer in smc_layers:
    
                if layer.confidence < 0.5:
                    risks.append(
                        f"Layer {layer.layer}: ความไม่แน่นอนสูง"
                    )
    
                if layer.state == "distributing":
                    risks.append(
                        f"Layer {layer.layer}: เสี่ยงต่อการปรับฐาน"
                    )
    
            return risks
    
  • architecture.md287 B4469b8872df5upstream ↗
    # Architecture Overview
    
    ## Layer 1: Genesis Protocol
    - Thinking engine
    - System reasoning
    
    ## Layer 2: SMC Engine
    - Price structure
    - Cost basis inference
    
    ## Layer 3: Narrative Engine
    - Smart money interpretation
    - Liquidity intent
    
    ## Layer 4: Decision Engine
    - Scenario-based output
    
  • backtest/backtest_engine.py429 B12514e1f11eeupstream ↗
    # backtest/backtest_engine.py
    
    class BacktestEngine:
    
        def run(self, signals):
            results = []
    
            for s in signals:
                outcome = self._simulate_trade(s)
                results.append(outcome)
    
            return results
    
        def _simulate_trade(self, signal):
            # mock simulation
            return {
                "signal": signal,
                "result": "win" if signal["confidence"] > 0.6 else "loss"
            }
    
  • btc_analysis.py534 Bc17d38a4a3e6upstream ↗
    import asyncio
    from smc.smc_layer_masterpiece import load_ohlcv_csv, SMCLayerEngine
    
    async def main():
        candles = load_ohlcv_csv("examples/sample_data.csv")
    
        engine = SMCLayerEngine()
    
        result = await engine.analyze(
            symbol="BTCUSDT",
            timeframe="4H",
            candles=candles
        )
    
        for layer in result.layers:
            print(f"Layer {layer.layer}: {layer.price_low} - {layer.price_high}")
            print(f"State: {layer.state}, Confidence: {layer.confidence}")
            print("-" * 40)
    
    asyncio.run(main())
    
  • CITATION.cff769 Bbadd598d95bfupstream ↗
    cff-version: 1.2.0
    title: "Money Atlas Intelligence OS"
    message: "If you use this system, please cite it as below."
    type: software
    authors:
      - family-names: Dechanon
        given-names: Bunyawat
        alias: ElmatadorZ
    repository-code: 'https://github.com/ElmatadorZ/MoneyAtlas-ClaudeSkill-Agent'
    abstract: >-
      Financial market strategic intelligence as a Claude Skill. Combines Genesis
      Protocol reasoning (first principles, system thinking) with a Smart Money
      Concepts market-structure layer to produce structured scenarios with explicit
      entry/exit zones and stated uncertainty. Analysis only — not financial advice.
    keywords:
      - financial-analysis
      - market-structure
      - claude-skills
      - ai-reasoning
      - scenario-analysis
    license: Apache-2.0
    version: '2.0'
    
  • cli/run_analysis.py1.2 KB48a7cd3a2e5cupstream ↗
    # cli/run_analysis.py
    
    from core.genesis_protocol import GenesisProtocol
    from core.first_principle_codex import FirstPrincipleCodex
    from core.ai_fluency_4d import AIFluency4D
    from core.discernment_engine import DiscernmentEngine
    from core.decision_engine import DecisionEngine
    from core.meta_cognition import MetaCognition
    from orchestrator.multi_agent_orchestrator import MultiAgentOrchestrator
    
    
    def main():
    
        problem = "Should we invest in gold now?"
        context = {}
    
        gp = GenesisProtocol()
        state = gp.initialize(problem, context)
    
        fp = FirstPrincipleCodex()
        decomposition = fp.deconstruct(problem)
    
        af = AIFluency4D()
        structured = af.apply(decomposition)
    
        orchestrator = MultiAgentOrchestrator()
        analysis = orchestrator.run(structured)
    
        de = DiscernmentEngine()
        verified = de.evaluate(analysis)
    
        decider = DecisionEngine()
        decision = decider.decide([
            {"name": "buy", "reward": 8, "risk": 5},
            {"name": "wait", "reward": 5, "risk": 2}
        ])
    
        meta = MetaCognition()
        audit = meta.audit(decision)
    
        print({
            "analysis": analysis,
            "verified": verified,
            "decision": decision,
            "audit": audit
        })
    
    
    if __name__ == "__main__":
        main()
    
  • cli/run_piw.py382 Be994b5518212upstream ↗
    # cli/run_piw.py
    
    from orchestrator.war_brain import WarBrain
    
    def main():
    
        smc_layers = [
            type("Layer", (), {
                "state": "accumulating",
                "confidence": 0.8,
                "cost_basis": 1900,
                "layer": 1
            })()
        ]
    
        brain = WarBrain()
        result = brain.run(smc_layers)
    
        print(result)
    
    if __name__ == "__main__":
        main()
    
  • cli/run_realtime.py834 B1948f0a0e287upstream ↗
    from data_pipeline.ingestion_engine import IngestionEngine
    from data_pipeline.normalization_engine import NormalizationEngine
    from orchestrator.war_brain import WarBrain
    
    def main():
    
        ingestion = IngestionEngine()
        norm = NormalizationEngine()
        brain = WarBrain()
    
        def loop():
    
            raw = ingestion.fetch_all()
            clean = norm.process(raw)
    
            smc_layers = [
                type("Layer", (), {
                    "state": "accumulating",
                    "confidence": 0.8,
                    "cost_basis": 1900,
                    "layer": 1
                })()
            ]
    
            result = brain.run(smc_layers, clean)
    
            print("=== REAL-TIME INTELLIGENCE ===")
            print(result)
    
        # simulate stream
        import time
        while True:
            loop()
            time.sleep(15)
    
    if __name__ == "__main__":
        main()
    
  • cli/run_v2.py1.2 KB242b6f9c9a9dupstream ↗
    # cli/run_v2.py
    
    from memory.memory_store import MemoryStore
    from memory.learning_engine import LearningEngine
    from backtest.backtest_engine import BacktestEngine
    from signals.signal_engine import SignalEngine
    from evolution.reinforcement import ReinforcementEngine
    
    def main():
    
        # Initialize systems
        memory = MemoryStore()
        learner = LearningEngine()
        backtest = BacktestEngine()
        signal_engine = SignalEngine()
        reinforce = ReinforcementEngine()
    
        # Mock SMC Layer Output
        smc_layers = [
            type("Layer", (), {
                "state": "accumulating",
                "confidence": 0.8,
                "cost_basis": 1900
            })()
        ]
    
        # Generate signals
        signals = signal_engine.generate(smc_layers)
    
        # Backtest
        results = backtest.run(signals)
    
        # Log results
        for r in results:
            memory.log_decision(r)
    
        # Learn
        history = memory.get_history()
        performance = learner.evaluate_performance(history)
    
        # Reinforce
        updated = reinforce.update(signals, performance)
    
        print({
            "signals": signals,
            "performance": performance,
            "updated": updated
        })
    
    
    if __name__ == "__main__":
        main()
    
  • CODE_OF_CONDUCT.md1.8 KBe75ca6ddc27dupstream ↗
    # Code of Conduct
    
    ## Our pledge
    
    We pledge to make participation in this project a harassment-free experience for everyone,
    regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics,
    gender identity and expression, level of experience, education, socio-economic status, nationality,
    personal appearance, race, religion, or sexual identity and orientation.
    
    ## Our standards
    
    Positive behaviour includes demonstrating empathy and kindness, respecting differing viewpoints,
    giving and gracefully accepting constructive feedback, accepting responsibility for mistakes, and
    focusing on what is best for the community.
    
    Unacceptable behaviour includes sexualised language or imagery and unwelcome sexual attention;
    trolling, insulting or derogatory comments, and personal or political attacks; public or private
    harassment; publishing others' private information without permission; and other conduct that would
    reasonably be considered inappropriate in a professional setting.
    
    ## Specific to this project
    
    - **Challenging an analysis is welcome; challenging a person is not.** Showing that a scenario is
      wrong, or that the system produced overconfident output, is a contribution.
    - **No solicitation.** Do not use issues, discussions, or pull requests to promote trading
      services, signal groups, tokens, or investment products.
    - **No sharing of individual trades or positions as advice.** This project analyses market
      structure; it is not a venue for telling people what to buy.
    
    ## Enforcement
    
    Report unacceptable behaviour to the maintainer via [GitHub](https://github.com/ElmatadorZ).
    Reports will be reviewed promptly and fairly, and the reporter's privacy respected.
    
    ## Attribution
    
    Adapted from the [Contributor Covenant](https://www.contributor-covenant.org/), version 2.1.
    
  • cognition/meta_cognition.py260 B82ebd77e50d3upstream ↗
    # cognition/meta_cognition.py
    
    class MetaCognition:
    
        def check(self, decisions):
    
            warnings = []
    
            for d in decisions:
                if "high" in str(d):
                    warnings.append("Potential overconfidence bias")
    
            return warnings
    
  • core/ai_fluency_4d.py830 B1dffdedc4821upstream ↗
    # core/ai_fluency_4d.py
    
    class AIFluency4D:
    
        def apply(self, problem_struct: dict):
            return {
                "delegation": self._delegation(problem_struct),
                "description": self._description(problem_struct),
                "execution": self._execution(problem_struct),
                "discernment": self._discernment(problem_struct)
            }
    
        def _delegation(self, ps):
            return {
                "ai_tasks": ["data analysis", "pattern recognition"],
                "human_tasks": ["decision making", "value judgment"]
            }
    
        def _description(self, ps):
            return {
                "structured_problem": ps
            }
    
        def _execution(self, ps):
            return {
                "multi_perspective": True
            }
    
        def _discernment(self, ps):
            return {
                "bias_check": True
            }
    
  • core/decision_engine.py431 B2e0a8f3357aeupstream ↗
    # core/decision_engine.py
    
    class DecisionEngine:
    
        def decide(self, options: list):
            scored = []
    
            for opt in options:
                score = opt["reward"] - opt["risk"]
                scored.append((score, opt))
    
            best = sorted(scored, key=lambda x: x[0], reverse=True)[0][1]
    
            return {
                "decision": best,
                "confidence": 0.7,
                "reason": "Best risk-reward ratio"
            }
    
  • core/discernment_engine.py633 B94c11f08762bupstream ↗
    # core/discernment_engine.py
    
    class DiscernmentEngine:
    
        def evaluate(self, analysis: dict):
            return {
                "bias": self._check_bias(analysis),
                "missing_data": self._check_missing(analysis),
                "narrative_trap": self._check_narrative(analysis),
                "uncertainty": self._unknowns(analysis)
            }
    
        def _check_bias(self, a):
            return "Check for timeframe bias"
    
        def _check_missing(self, a):
            return "Check missing variables"
    
        def _check_narrative(self, a):
            return "Story vs reality?"
    
        def _unknowns(self, a):
            return "Unknown unknowns exist"
    
  • core/genesis_core.py1.9 KB0ab46307b9b6upstream ↗
    # core/genesis_core.py
    
    from typing import Dict, Any
    
    
    class GenesisCore:
    
        def __init__(self):
            pass
    
        def first_principle(self, context: Dict[str, Any]) -> Dict[str, Any]:
            """
            Reduce asset to fundamental drivers
            """
            symbol = context.get("symbol")
    
            if "BTC" in symbol:
                return {
                    "asset_type": "digital scarcity",
                    "value_driver": "liquidity + adoption",
                    "risk": "macro liquidity tightening"
                }
    
            if "GOLD" in symbol:
                return {
                    "asset_type": "store of value",
                    "value_driver": "real rates",
                    "risk": "strong dollar"
                }
    
            return {
                "asset_type": "unknown",
                "value_driver": "unknown",
                "risk": "unknown"
            }
    
        def system_map(self, context: Dict[str, Any]) -> Dict[str, Any]:
            """
            Map macro → liquidity → asset
            """
            macro = context.get("macro", {})
    
            if macro.get("macro_bias") == "bearish":
                return {
                    "liquidity": "tightening",
                    "impact": "risk_off"
                }
    
            return {
                "liquidity": "neutral",
                "impact": "sideways"
            }
    
        def narrative(self, context: Dict[str, Any]) -> str:
            """
            Money Atlas narrative layer
            """
            smc = context.get("smc", {})
    
            if smc:
                return "Smart money is positioning around key liquidity zones"
    
            return "Market lacks clear dominant force"
    
        def run(self, context: Dict[str, Any]) -> Dict[str, Any]:
            """
            Full Genesis Execution
            """
    
            fp = self.first_principle(context)
            sm = self.system_map(context)
            narrative = self.narrative(context)
    
            return {
                "first_principle": fp,
                "system_map": sm,
                "narrative": narrative
            }
    
  • core/meta_cognition.py296 B198e6fe533edupstream ↗
    # core/meta_cognition.py
    
    class MetaCognition:
    
        def audit(self, decision: dict):
            return {
                "possible_error": "Model assumption may be wrong",
                "alternative": "Opposite scenario analysis",
                "confidence_check": decision.get("confidence", 0.5)
            }
    
  • data/market_data_loader.py235 B65d3800620c3upstream ↗
    # data/market_data_loader.py
    
    import random
    
    class MarketDataLoader:
    
        def load(self):
            # mock data
            return {
                "price": random.uniform(1800, 2000),
                "volume": random.uniform(1000, 5000)
            }
    
  • data_feed.py307 Bc115b64ebb03upstream ↗
    import requests
    
    def get_btc_price():
        url = "https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT"
        return float(requests.get(url).json()["price"])
    
    def get_macro_news():
        url = "https://newsapi.org/v2/top-headlines?category=business&apiKey=YOUR_API_KEY"
        return requests.get(url).json()
    
  • data_pipeline/ingestion_engine.py508 Bbd8d5855240eupstream ↗
    # data_pipeline/ingestion_engine.py
    
    from integration.market_api import MarketAPI
    from integration.macro_api import MacroAPI
    from integration.news_api import NewsAPI
    
    class IngestionEngine:
    
        def __init__(self):
            self.market = MarketAPI()
            self.macro = MacroAPI()
            self.news = NewsAPI()
    
        def fetch_all(self):
    
            return {
                "price": self.market.get_price(),
                "macro": self.macro.get_macro_state(),
                "news": self.news.get_headlines()
            }
    
  • data_pipeline/normalization_engine.py327 B50464079b302upstream ↗
    # data_pipeline/normalization_engine.py
    
    class NormalizationEngine:
    
        def process(self, raw):
    
            return {
                "price": raw["price"],
                "macro_bias": "bearish" if raw["macro"]["liquidity"] == "tightening" else "bullish",
                "geo_risk": any("risk" in n.lower() for n in raw["news"])
            }
    
  • evolution/reinforcement.py346 B9db27b87b3c3upstream ↗
    # evolution/reinforcement.py
    
    class ReinforcementEngine:
    
        def update(self, decisions, performance):
            for d in decisions:
                d["weight"] = d.get("weight", 1.0)
    
                if performance > 0.7:
                    d["weight"] *= 1.1
                elif performance < 0.5:
                    d["weight"] *= 0.9
    
            return decisions
    
  • examples/full_system_demo.py544 B05c389f87537upstream ↗
    # examples/full_system_demo.py
    
    import asyncio
    from agents.orchestrator import Orchestrator
    from smc.smc_layer_masterpiece import load_ohlcv_csv
    
    async def main():
    
        candles = load_ohlcv_csv("examples/sample_data.csv")
    
        context = {
            "symbol": "BTCUSDT",
            "timeframe": "4H",
            "candles": candles,
            "macro_data": {}
        }
    
        system = Orchestrator()
    
        result = await system.run(context)
    
        print("\n=== FINAL INTELLIGENCE ===")
        for k, v in result.items():
            print(k, ":", v)
    
    asyncio.run(main())
    
  • examples/worked/01-btc-light-mode.md1.4 KBa0a19f9e7755upstream ↗
    # Worked example — LIGHT mode
    
    **User:** Quick read on BTC?
    
    This is a single-asset question with no decision attached, so the skill runs in
    LIGHT mode: one primary scenario, its confidence, and the one thing that would
    prove it wrong. It does **not** invent a current price — it reasons from what the
    user supplies or asks the user for the missing input.
    
    ---
    
    **Output (shape):**
    
    > **BTC — LIGHT read**
    >
    > **Structure:** price holding above the prior accumulation range; higher-low
    > sequence intact on the higher timeframe. *(observed — from your chart/input)*
    >
    > **Primary scenario (confidence ~60%):** continuation higher while the range low
    > holds. The move is structural, not narrative — it rests on the higher-low
    > sequence, not on sentiment.
    >
    > **Invalidation:** a decisive close back **inside** the prior range. That breaks
    > the higher-low sequence and the read is void.
    >
    > **What would sharpen this:** current price relative to the range low, and
    > volume on the last leg up.
    
    ---
    
    **Why it is shaped this way**
    
    - One scenario, because LIGHT mode is for a quick read, not a full deliberation.
    - A confidence number, because a read without one hides how much to trust it.
    - An invalidation, because the FAILURE SYSTEM rejects any output without one.
    - A "what would sharpen this" line, because naming the missing input is honest;
      inventing the input is not.
    
  • examples/worked/02-gold-full-mode.md2.1 KB7890617b4617upstream ↗
    # Worked example — FULL mode
    
    **User:** Should I add gold to the portfolio here?
    
    A "should I" question triggers FULL mode: the full Genesis Protocol pipeline
    (First Principle → System Thinking → SMC layer), multiple scenarios, and explicit
    entry/exit zones. The skill gives the structured decision **inputs** — the human
    makes the decision. It does not issue personalized investment advice.
    
    ---
    
    **Output (shape):**
    
    > **GOLD — FULL analysis**
    >
    > **First Principle.** Gold has no yield, so its case is a function of *real*
    > yields and confidence in fiat. Strip the narrative: what actually moves it is
    > the real-rate path and central-bank demand, not headlines. *(inference — labelled)*
    >
    > **Observed inputs** *(from your data)*: real 10y yield ≈ −0.4%; central-bank net
    > buying positive three quarters running; price consolidating under a prior high.
    >
    > **SMC structure:** accumulation range holding; no distribution signature yet.
    >
    > **Scenarios**
    > | # | Path | Confidence | Entry zone | Invalidation |
    > |---|------|-----------|-----------|-------------|
    > | 1 | Break and hold above the prior high on continued negative real yields | ~55% | on the retest of the breakout, not the breakout candle | a close back below the range midpoint |
    > | 2 | Range-bound while real yields drift up | ~30% | scale at range low only | range low gives way on volume |
    > | 3 | Risk-off spike (exogenous) | ~15% | not chased | fades back into the range within days |
    >
    > **Position note:** this is scenario structure, not a recommendation to buy. Size
    > and the buy/sell/hold decision are yours.
    >
    > **What would change the read:** a sharp move in real yields, or a distribution
    > signature appearing in the SMC layer.
    
    ---
    
    **Why it is shaped this way**
    
    - The First Principle step is labelled inference, kept separate from the observed
      inputs — the Known / Inferred / Unknown discipline.
    - Every scenario carries its own invalidation, not a single global one.
    - Entry zones are conditional on stated inputs; nothing rests on an invented price.
    - The decision is handed back to the human. The skill informs; it does not advise.
    
  • examples/worked/03-insufficient-data.md1.5 KB3a952e56ada5upstream ↗
    # Worked example — honest degradation
    
    **User:** Where's BTC headed? *(no chart, no price, no data attached)*
    
    This is the case most skills fail: asked to predict with nothing to reason from,
    they invent a price and a target. This one does not. It has no live feed by
    design (`requires_tools: false`, `not_for` names real-time price), so it states
    the framework and names the missing inputs.
    
    ---
    
    **Output (shape):**
    
    > **BTC — I can't give a directional read without inputs, but here is the frame.**
    >
    > A directional call needs at least: current price relative to the last
    > accumulation range, the higher-timeframe trend structure, and whether the SMC
    > layer shows accumulation or distribution. I don't have those.
    >
    > **What I can do right now:**
    > - Lay out the two structural paths (continuation vs. range-break) and the
    >   condition that decides between them.
    > - Tell you exactly which three inputs would let me commit to one.
    >
    > **What I will not do:** quote a current price or a target I cannot source. An
    > invented number is worse than an admitted gap.
    >
    > Give me the current price and the higher-timeframe structure and I'll return a
    > LIGHT read with a confidence and an invalidation.
    
    ---
    
    **Why it is shaped this way**
    
    This is the behaviour the skill's *When information is insufficient* rule
    requires, and the reason `metadata.not_for` names real-time price feeds: the skill
    is a reasoning framework, not a data source. Abstaining is a valid output;
    fabricating a level is a failure.
    
  • execution/broker_adapter.py123 Bb5311fe67ba1upstream ↗
    class BrokerAdapter:
    
        def place_order(self, symbol, direction, size, entry, sl, tp):
            raise NotImplementedError
    
  • execution/execution_engine.py604 B2b8ef96fa044upstream ↗
    class ExecutionEngine:
    
        def __init__(self, broker, risk_engine):
            self.broker = broker
            self.risk_engine = risk_engine
    
        def execute(self, signal):
    
            size = self.risk_engine.calculate_position_size(
                signal.entry,
                signal.stop_loss
            )
    
            if size <= 0:
                return {"status": "rejected"}
    
            return self.broker.place_order(
                symbol=signal.symbol,
                direction=signal.direction,
                size=size,
                entry=signal.entry,
                sl=signal.stop_loss,
                tp=signal.take_profit
            )
    
  • execution/risk_engine.py463 B26c4fdabe7aeupstream ↗
    class RiskEngine:
    
        def __init__(self, capital: float, risk_per_trade: float = 0.01):
            self.capital = capital
            self.risk_per_trade = risk_per_trade
    
        def calculate_position_size(self, entry, stop_loss):
    
            risk_amount = self.capital * self.risk_per_trade
            risk_per_unit = abs(entry - stop_loss)
    
            if risk_per_unit == 0:
                return 0
    
            position_size = risk_amount / risk_per_unit
            return position_size
    
  • execution/signal_engine.py941 B20fb3b3f68aeupstream ↗
    from dataclasses import dataclass
    from typing import Optional
    
    @dataclass
    class TradeSignal:
        symbol: str
        direction: str   # "long" / "short"
        entry: float
        stop_loss: float
        take_profit: float
        confidence: float
    
    class SignalEngine:
    
        def generate_signal(self, layer_map) -> Optional[TradeSignal]:
    
            # ใช้ Layer 2-3 เป็น Entry Zone
            layer2 = layer_map.layers[1]
            layer3 = layer_map.layers[2]
    
            if layer2.state == "accumulating" and layer2.confidence > 0.6:
    
                entry = (layer2.price_low + layer2.price_high) / 2
                sl = layer2.price_low * 0.98
                tp = layer3.price_high
    
                return TradeSignal(
                    symbol=layer_map.symbol,
                    direction="long",
                    entry=entry,
                    stop_loss=sl,
                    take_profit=tp,
                    confidence=layer2.confidence
                )
    
            return None
    
  • execution/trade_logger.py543 B17c7022f7cbdupstream ↗
    import json
    from datetime import datetime
    
    class TradeLogger:
    
        def log(self, signal, result):
    
            log_entry = {
                "time": datetime.utcnow().isoformat(),
                "symbol": signal.symbol,
                "direction": signal.direction,
                "entry": signal.entry,
                "sl": signal.stop_loss,
                "tp": signal.take_profit,
                "confidence": signal.confidence,
                "result": result
            }
    
            with open("trade_log.json", "a") as f:
                f.write(json.dumps(log_entry) + "\n")
    
  • execution_engine.py310 B2d6f559a9bc0upstream ↗
    from binance.client import Client
    
    API_KEY = "YOUR_KEY"
    API_SECRET = "YOUR_SECRET"
    
    client = Client(API_KEY, API_SECRET)
    
    def place_order(symbol, side, quantity):
        order = client.create_order(
            symbol=symbol,
            side=side,
            type="MARKET",
            quantity=quantity
        )
        return order
    
  • first_principle_codex.py3.6 KB1d3af198c48aupstream ↗
    # first_principle_codex.py
    # ------------------------------------------------------------
    # Genesis Protocol: First Principle Reasoning Kernel
    # ------------------------------------------------------------
    
    from dataclasses import dataclass
    from typing import List, Dict, Any
    
    
    # ============================================================
    # 1) Atomic Truth Layer
    # ============================================================
    
    @dataclass
    class AtomicTruth:
        statement: str
        certainty: float  # 0..1
        source: str       # data / logic / empirical
    
    
    # ============================================================
    # 2) Problem Decomposition
    # ============================================================
    
    def decompose_problem(problem: str) -> List[str]:
        """
        Break problem into irreducible components
        """
        # Simple version (can upgrade with LLM later)
        return [
            f"What are the fundamental parts of: {problem}?",
            f"What must be true for {problem} to exist?",
            f"What constraints define {problem}?"
        ]
    
    
    # ============================================================
    # 3) Extract Atomic Truths
    # ============================================================
    
    def extract_atomic_truths(context: Dict[str, Any]) -> List[AtomicTruth]:
        """
        Convert raw context into irreducible truths
        """
        truths = []
    
        for k, v in context.items():
            if isinstance(v, (int, float, str)):
                truths.append(AtomicTruth(
                    statement=f"{k} = {v}",
                    certainty=0.9,
                    source="data"
                ))
    
        return truths
    
    
    # ============================================================
    # 4) Constraint Engine
    # ============================================================
    
    def derive_constraints(truths: List[AtomicTruth]) -> List[str]:
        constraints = []
        for t in truths:
            constraints.append(f"If {t.statement}, then system must respect it")
        return constraints
    
    
    # ============================================================
    # 5) Reconstruction Engine
    # ============================================================
    
    def reconstruct_solutions(truths: List[AtomicTruth]) -> List[str]:
        """
        Build solutions from ground up
        """
        solutions = []
    
        for t in truths:
            solutions.append(f"Exploit: {t.statement}")
    
        return solutions
    
    
    # ============================================================
    # 6) Contradiction Detector
    # ============================================================
    
    def detect_contradictions(truths: List[AtomicTruth]) -> List[str]:
        issues = []
    
        for i in range(len(truths)):
            for j in range(i + 1, len(truths)):
                if truths[i].statement == truths[j].statement:
                    continue
    
                # naive contradiction check
                if ">" in truths[i].statement and "<" in truths[j].statement:
                    issues.append(f"Conflict between {truths[i]} and {truths[j]}")
    
        return issues
    
    
    # ============================================================
    # 7) Codex Execution
    # ============================================================
    
    def run_first_principle_codex(problem: str, context: Dict[str, Any]) -> Dict[str, Any]:
    
        decomposition = decompose_problem(problem)
        truths = extract_atomic_truths(context)
        constraints = derive_constraints(truths)
        solutions = reconstruct_solutions(truths)
        contradictions = detect_contradictions(truths)
    
        return {
            "problem": problem,
            "decomposition": decomposition,
            "atomic_truths": [t.statement for t in truths],
            "constraints": constraints,
            "solutions": solutions,
            "contradictions": contradictions
        }
    
  • full_mode.txt206 B05ac307fdd30upstream ↗
    Output Structure:
    
    1. First Principle Breakdown
    2. System Map (Macro + Liquidity)
    3. SMC Layer Map
    4. Narrative (Money Atlas)
    5. Scenarios (Bull / Bear / Chaos)
    6. Decision Framework
    7. Risk & Failure Mode
    
  • integration/macro_api.py269 Bd76f27a00960upstream ↗
    # integration/macro_api.py
    
    class MacroAPI:
    
        def get_macro_state(self):
    
            # mock → replace with FRED / TradingEconomics later
            return {
                "interest_rate": 5.25,
                "inflation": 3.2,
                "liquidity": "tightening"
            }
    
  • integration/market_api.py371 B872dfa6fff5aupstream ↗
    import requests
    
    class MarketAPI:
    
        def get_price(self, symbol="XAUUSD"):
            # Example: use free endpoint or broker API
            url = f"https://api.binance.com/api/v3/ticker/price?symbol=BTCUSDT"
    
            try:
                r = requests.get(url, timeout=5)
                data = r.json()
                return float(data["price"])
            except:
                return None
    
  • integration/news_api.py258 Bcaece504099aupstream ↗
    # integration/news_api.py
    
    class NewsAPI:
    
        def get_headlines(self):
    
            # mock → replace with real RSS / news API
            return [
                "Oil supply risk increases in Middle East",
                "Fed signals higher rates for longer"
            ]
    
  • integration/smc_adapter.py222 B2dd4c3370f9dupstream ↗
    # integration/smc_adapter.py
    
    class SMCAdapter:
    
        def integrate(self, smc_output, cognitive_output):
            return {
                "market_structure": smc_output,
                "decision_layer": cognitive_output
            }
    
  • intelligence/alpha_engine.py688 Bb63553e2c836upstream ↗
    # intelligence/alpha_engine.py
    
    class AlphaEngine:
    
        def detect(self, smc_layers):
    
            alpha = []
    
            for l in smc_layers:
    
                if l.state == "accumulating" and l.confidence > 0.75:
                    alpha.append({
                        "type": "SMART_MONEY_ENTRY",
                        "layer": l.layer,
                        "price": l.cost_basis,
                        "edge": "institutional accumulation"
                    })
    
                if l.state == "distributing":
                    alpha.append({
                        "type": "EXIT_SIGNAL",
                        "layer": l.layer,
                        "risk": "distribution detected"
                    })
    
            return alpha
    
  • intelligence/geopolitic_engine.py352 Bc9b06eab0e49upstream ↗
    # intelligence/geopolitic_engine.py
    
    class GeopoliticEngine:
    
        def evaluate(self):
    
            return {
                "conflict_zone": "Middle East",
                "impact": "energy supply risk",
                "asset_effect": {
                    "oil": "bullish",
                    "gold": "bullish",
                    "equity": "risk-off"
                }
            }
    
  • intelligence/macro_engine.py268 B6fce0484da4fupstream ↗
    # intelligence/macro_engine.py
    
    class MacroEngine:
    
        def analyze(self):
    
            return {
                "liquidity_cycle": "tightening",
                "interest_rate": "high",
                "risk_asset_bias": "bearish",
                "safe_haven_bias": "bullish"
            }
    
  • intelligence/news_intelligence/bias_engine.py391 B9ceb464ebcc2upstream ↗
    class BiasEngine:
    
        def analyze(self, narratives):
    
            bias_score = {
                "bullish": 0,
                "bearish": 0,
                "risk_off": 0
            }
    
            for n in narratives:
    
                if n["bias"] == "hawkish":
                    bias_score["bearish"] += 1
    
                if n["bias"] == "risk_off":
                    bias_score["risk_off"] += 1
    
            return bias_score
    
  • intelligence/news_intelligence/impact_mapper.py391 B2e666f4d2406upstream ↗
    class ImpactMapper:
    
        def map(self, bias):
    
            impact = []
    
            if bias["risk_off"] > 0:
                impact.append({
                    "asset": "gold",
                    "direction": "bullish"
                })
    
            if bias["bearish"] > 0:
                impact.append({
                    "asset": "equities",
                    "direction": "bearish"
                })
    
            return impact
    
  • intelligence/news_intelligence/narrative_engine.py573 Bf762b6f2dbd2upstream ↗
    class NarrativeEngine:
    
        def detect(self, parsed_news):
    
            narratives = []
    
            for item in parsed_news:
    
                text = item["text"].lower()
    
                if "rate" in text or "inflation" in text:
                    narratives.append({
                        "theme": "MONETARY_POLICY",
                        "bias": "hawkish"
                    })
    
                if "war" in text or "conflict" in text:
                    narratives.append({
                        "theme": "GEOPOLITICS",
                        "bias": "risk_off"
                    })
    
            return narratives
    
  • intelligence/news_intelligence/news_collector.py331 B503a79409170upstream ↗
    import requests
    
    class NewsCollector:
    
        def fetch(self):
    
            url = "https://newsapi.org/v2/top-headlines?category=business&apiKey=YOUR_KEY"
    
            try:
                r = requests.get(url, timeout=5)
                data = r.json()
                return [a["title"] for a in data["articles"]]
            except:
                return []
    
  • intelligence/news_intelligence/nlp_engine.py269 B059b34381e01upstream ↗
    class NLPEngine:
    
        def extract(self, headlines):
    
            parsed = []
    
            for h in headlines:
    
                parsed.append({
                    "text": h,
                    "keywords": [w for w in h.lower().split() if len(w) > 4]
                })
    
            return parsed
    
  • intelligence/news_intelligence/signal_engine.py479 B768320dfcb5eupstream ↗
    class SignalEngine:
    
        def generate(self, impact, smc_layers):
    
            signals = []
    
            for l in smc_layers:
    
                for i in impact:
    
                    if l.state == "accumulating" and i["direction"] == "bullish":
    
                        signals.append({
                            "type": "HIGH_CONVICTION_SETUP",
                            "logic": "Narrative + Smart Money alignment",
                            "layer": l.layer
                        })
    
            return signals
    
  • LICENSE11 KBfbcf9e3d4f74upstream ↗
                                     Apache License
                               Version 2.0, January 2004
                            http://www.apache.org/licenses/
    
       TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
    
       1. Definitions.
    
          "License" shall mean the terms and conditions for use, reproduction,
          and distribution as defined by Sections 1 through 9 of this document.
    
          "Licensor" shall mean the copyright owner or entity authorized by
          the copyright owner that is granting the License.
    
          "Legal Entity" shall mean the union of the acting entity and all
          other entities that control, are controlled by, or are under common
          control with that entity. For the purposes of this definition,
          "control" means (i) the power, direct or indirect, to cause the
          direction or management of such entity, whether by contract or
          otherwise, or (ii) ownership of fifty percent (50%) or more of the
          outstanding shares, or (iii) beneficial ownership of such entity.
    
          "You" (or "Your") shall mean an individual or Legal Entity
          exercising permissions granted by this License.
    
          "Source" form shall mean the preferred form for making modifications,
          including but not limited to software source code, documentation
          source, and configuration files.
    
          "Object" form shall mean any form resulting from mechanical
          transformation or translation of a Source form, including but
          not limited to compiled object code, generated documentation,
          and conversions to other media types.
    
          "Work" shall mean the work of authorship, whether in Source or
          Object form, made available under the License, as indicated by a
          copyright notice that is included in or attached to the work
          (an example is provided in the Appendix below).
    
          "Derivative Works" shall mean any work, whether in Source or Object
          form, that is based on (or derived from) the Work and for which the
          editorial revisions, annotations, elaborations, or other modifications
          represent, as a whole, an original work of authorship. For the purposes
          of this License, Derivative Works shall not include works that remain
          separable from, or merely link (or bind by name) to the interfaces of,
          the Work and Derivative Works thereof.
    
          "Contribution" shall mean any work of authorship, including
          the original version of the Work and any modifications or additions
          to that Work or Derivative Works thereof, that is intentionally
          submitted to Licensor for inclusion in the Work by the copyright owner
          or by an individual or Legal Entity authorized to submit on behalf of
          the copyright owner. For the purposes of this definition, "submitted"
          means any form of electronic, verbal, or written communication sent
          to the Licensor or its representatives, including but not limited to
          communication on electronic mailing lists, source code control systems,
          and issue tracking systems that are managed by, or on behalf of, the
          Licensor for the purpose of discussing and improving the Work, but
          excluding communication that is conspicuously marked or otherwise
          designated in writing by the copyright owner as "Not a Contribution."
    
          "Contributor" shall mean Licensor and any individual or Legal Entity
          on behalf of whom a Contribution has been received by Licensor and
          subsequently incorporated within the Work.
    
       2. Grant of Copyright License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          copyright license to reproduce, prepare Derivative Works of,
          publicly display, publicly perform, sublicense, and distribute the
          Work and such Derivative Works in Source or Object form.
    
       3. Grant of Patent License. Subject to the terms and conditions of
          this License, each Contributor hereby grants to You a perpetual,
          worldwide, non-exclusive, no-charge, royalty-free, irrevocable
          (except as stated in this section) patent license to make, have made,
          use, offer to sell, sell, import, and otherwise transfer the Work,
          where such license applies only to those patent claims licensable
          by such Contributor that are necessarily infringed by their
          Contribution(s) alone or by combination of their Contribution(s)
          with the Work to which such Contribution(s) was submitted. If You
          institute patent litigation against any entity (including a
          cross-claim or counterclaim in a lawsuit) alleging that the Work
          or a Contribution incorporated within the Work constitutes direct
          or contributory patent infringement, then any patent licenses
          granted to You under this License for that Work shall terminate
          as of the date such litigation is filed.
    
       4. Redistribution. You may reproduce and distribute copies of the
          Work or Derivative Works thereof in any medium, with or without
          modifications, and in Source or Object form, provided that You
          meet the following conditions:
    
          (a) You must give any other recipients of the Work or
              Derivative Works a copy of this License; and
    
          (b) You must cause any modified files to carry prominent notices
              stating that You changed the files; and
    
          (c) You must retain, in the Source form of any Derivative Works
              that You distribute, all copyright, patent, trademark, and
              attribution notices from the Source form of the Work,
              excluding those notices that do not pertain to any part of
              the Derivative Works; and
    
          (d) If the Work includes a "NOTICE" text file as part of its
              distribution, then any Derivative Works that You distribute must
              include a readable copy of the attribution notices contained
              within such NOTICE file, excluding those notices that do not
              pertain to any part of the Derivative Works, in at least one
              of the following places: within a NOTICE text file distributed
              as part of the Derivative Works; within the Source form or
              documentation, if provided along with the Derivative Works; or,
              within a display generated by the Derivative Works, if and
              wherever such third-party notices normally appear. The contents
              of the NOTICE file are for informational purposes only and
              do not modify the License. You may add Your own attribution
              notices within Derivative Works that You distribute, alongside
              or as an addendum to the NOTICE text from the Work, provided
              that such additional attribution notices cannot be construed
              as modifying the License.
    
          You may add Your own copyright statement to Your modifications and
          may provide additional or different license terms and conditions
          for use, reproduction, or distribution of Your modifications, or
          for any such Derivative Works as a whole, provided Your use,
          reproduction, and distribution of the Work otherwise complies with
          the conditions stated in this License.
    
       5. Submission of Contributions. Unless You explicitly state otherwise,
          any Contribution intentionally submitted for inclusion in the Work
          by You to the Licensor shall be under the terms and conditions of
          this License, without any additional terms or conditions.
          Notwithstanding the above, nothing herein shall supersede or modify
          the terms of any separate license agreement you may have executed
          with Licensor regarding such Contributions.
    
       6. Trademarks. This License does not grant permission to use the trade
          names, trademarks, service marks, or product names of the Licensor,
          except as required for reasonable and customary use in describing the
          origin of the Work and reproducing the content of the NOTICE file.
    
       7. Disclaimer of Warranty. Unless required by applicable law or
          agreed to in writing, Licensor provides the Work (and each
          Contributor provides its Contributions) on an "AS IS" BASIS,
          WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
          implied, including, without limitation, any warranties or conditions
          of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
          PARTICULAR PURPOSE. You are solely responsible for determining the
          appropriateness of using or redistributing the Work and assume any
          risks associated with Your exercise of permissions under this License.
    
       8. Limitation of Liability. In no event and under no legal theory,
          whether in tort (including negligence), contract, or otherwise,
          unless required by applicable law (such as deliberate and grossly
          negligent acts) or agreed to in writing, shall any Contributor be
          liable to You for damages, including any direct, indirect, special,
          incidental, or consequential damages of any character arising as a
          result of this License or out of the use or inability to use the
          Work (including but not limited to damages for loss of goodwill,
          work stoppage, computer failure or malfunction, or any and all
          other commercial damages or losses), even if such Contributor
          has been advised of the possibility of such damages.
    
       9. Accepting Warranty or Additional Liability. While redistributing
          the Work or Derivative Works thereof, You may choose to offer,
          and charge a fee for, acceptance of support, warranty, indemnity,
          or other liability obligations and/or rights consistent with this
          License. However, in accepting such obligations, You may act only
          on Your own behalf and on Your sole responsibility, not on behalf
          of any other Contributor, and only if You agree to indemnify,
          defend, and hold each Contributor harmless for any liability
          incurred by, or claims asserted against, such Contributor by reason
          of your accepting any such warranty or additional liability.
    
       END OF TERMS AND CONDITIONS
    
       APPENDIX: How to apply the Apache License to your work.
    
          To apply the Apache License to your work, attach the following
          boilerplate notice, with the fields enclosed by brackets "[]"
          replaced with your own identifying information. (Don't include
          the brackets!)  The text should be enclosed in the appropriate
          comment syntax for the file format. We also recommend that a
          file or class name and description of purpose be included on the
          same "printed page" as the copyright notice for easier
          identification within third-party archives.
    
       Copyright 2025-2026 Bunyawat Dechanon (ElmatadorZ)
    
       Licensed under the Apache License, Version 2.0 (the "License");
       you may not use this file except in compliance with the License.
       You may obtain a copy of the License at
    
           http://www.apache.org/licenses/LICENSE-2.0
    
       Unless required by applicable law or agreed to in writing, software
       distributed under the License is distributed on an "AS IS" BASIS,
       WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
       See the License for the specific language governing permissions and
       limitations under the License.
    
  • light_mode.txt81 Bca2c136dfa16upstream ↗
    Output Structure:
    
    1. Market Structure Insight
    2. Key Risk
    3. Strategic Takeaway
    
  • main.py1.3 KB4f4bd65ae492upstream ↗
    import asyncio
    
    from smc.smc_layer_masterpiece import SMCLayerEngine
    from execution.signal_engine import SignalEngine
    from execution.risk_engine import RiskEngine
    from execution.execution_engine import ExecutionEngine
    from execution.broker_adapter import MockBroker
    from execution.trade_logger import TradeLogger
    
    async def run():
    
        # 1. Load Data
        candles = []  # ใส่ OHLCV จริง
    
        # 2. Analyze Market
        smc_engine = SMCLayerEngine()
        layer_map = await smc_engine.analyze(
            symbol="BTCUSDT",
            timeframe="4H",
            candles=candles
        )
    
        # 3. Generate Signal
        signal_engine = SignalEngine()
        signal = signal_engine.generate_signal(layer_map)
    
        if not signal:
            print("No Trade Signal")
            return
    
        # 4. Risk Management
        risk_engine = RiskEngine(capital=10000)
    
        # 5. Execute Trade
        broker = MockBroker()
        execution_engine = ExecutionEngine(broker, risk_engine)
    
        result = execution_engine.execute(signal)
    
        # 6. Log
        logger = TradeLogger()
        logger.log(signal, result)
    
    asyncio.run(run())
    from data_feed import get_btc_price
    from memory_engine import log_trade
    
    def run():
        price = get_btc_price()
        
        context = f"""
        BTC current price: {price}
        Analyze using Money Atlas system.
        """
    
        print(context)
    
    if __name__ == "__main__":
        run()
    
  • memory.json55 Ba4bce0640046upstream ↗
    {
      "trades": [],
      "insights": [],
      "patterns": []
    }
    
  • memory/learning_engine.py448 B3e0a8749686eupstream ↗
    # memory/learning_engine.py
    
    class LearningEngine:
    
        def evaluate_performance(self, history):
            wins = sum(1 for h in history if h.get("result") == "win")
            total = len(history)
            return wins / total if total > 0 else 0.0
    
        def adjust_strategy(self, performance):
            if performance < 0.5:
                return "reduce risk"
            elif performance > 0.7:
                return "increase position"
            return "maintain"
    
  • memory/memory_store.py732 B16d5f4f7bd81upstream ↗
    # memory/memory_store.py
    
    import json
    from typing import Dict, Any
    
    class MemoryStore:
    
        def __init__(self, path="memory.json"):
            self.path = path
            self.memory = self._load()
    
        def _load(self):
            try:
                with open(self.path, "r") as f:
                    return json.load(f)
            except:
                return {}
    
        def save(self):
            with open(self.path, "w") as f:
                json.dump(self.memory, f, indent=2)
    
        def log_decision(self, decision: Dict[str, Any]):
            if "history" not in self.memory:
                self.memory["history"] = []
            self.memory["history"].append(decision)
            self.save()
    
        def get_history(self):
            return self.memory.get("history", [])
    
  • memory_engine.py728 Bed6a43cf1ebfupstream ↗
    import json
    from datetime import datetime
    
    MEMORY_FILE = "memory.json"
    
    def load_memory():
        with open(MEMORY_FILE, "r") as f:
            return json.load(f)
    
    def save_memory(data):
        with open(MEMORY_FILE, "w") as f:
            json.dump(data, f, indent=2)
    
    def log_trade(symbol, entry, sl, tp, result=None):
        data = load_memory()
        trade = {
            "symbol": symbol,
            "entry": entry,
            "sl": sl,
            "tp": tp,
            "result": result,
            "time": str(datetime.utcnow())
        }
        data["trades"].append(trade)
        save_memory(data)
    
    def log_insight(text):
        data = load_memory()
        data["insights"].append({
            "text": text,
            "time": str(datetime.utcnow())
        })
        save_memory(data)
    
  • NOTICE2.8 KB4efa21254365upstream ↗
    Money Atlas Intelligence OS
    Financial market strategic intelligence as a Claude Skill.
    
    Copyright 2025-2026 Bunyawat Dechanon (ElmatadorZ)
    
    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at
    
        http://www.apache.org/licenses/LICENSE-2.0
    
    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    
    --------------------------------------------------------------------------------
    Attribution
    --------------------------------------------------------------------------------
    Requested (not required beyond this NOTICE):
    
        Built on Money Atlas Intelligence OS by Bunyawat Dechanon (ElmatadorZ)
    
    This system inherits the First Principle Codex OS (FPCOS) reasoning base layer,
    also Apache-2.0: https://github.com/ElmatadorZ/FirstPrincipleCodex-OS-Skill
    
    --------------------------------------------------------------------------------
    NOT FINANCIAL ADVICE
    --------------------------------------------------------------------------------
    This software analyses markets. It does not advise.
    
    Nothing produced by this system is investment, financial, legal, or tax advice.
    It is an analytical instrument that outputs structured scenarios and explicit
    uncertainty, and it can be wrong. Markets can move against any scenario it
    produces. You are solely responsible for your own decisions and their outcomes.
    
    Consult a licensed financial adviser before acting on any output. Do not deploy
    this system to execute trades with capital you cannot afford to lose. The
    warranty disclaimer in the Apache License (Sections 7 and 8) applies in full.
    
    --------------------------------------------------------------------------------
    Naming
    --------------------------------------------------------------------------------
    The Apache License grants broad rights to use and modify this work but does not
    grant rights to its names or marks (Apache-2.0 Section 6, "Trademarks"). A
    derivative that removes the system's uncertainty disclosure, scenario structure,
    or its refusal to present analysis as advice MUST NOT be presented as "Money
    Atlas Intelligence OS" and MUST NOT imply endorsement by the author.
    
    --------------------------------------------------------------------------------
    History
    --------------------------------------------------------------------------------
    Earlier releases used the custom "Open Cognitive License v1.0", which carried a
    2% contribution clause above $10M USD/year revenue. From this release forward the
    project is Apache-2.0. The prior text remains in the git history.
    
  • orchestrator/multi_agent_orchestrator.py735 B07352c6ea9beupstream ↗
    # orchestrator/multi_agent_orchestrator.py
    
    from agents.analyst_agent import AnalystAgent
    from agents.strategist_agent import StrategistAgent
    from agents.skeptic_agent import SkepticAgent
    from agents.macro_agent import MacroAgent
    
    class MultiAgentOrchestrator:
    
        def __init__(self):
            self.analyst = AnalystAgent()
            self.strategist = StrategistAgent()
            self.skeptic = SkepticAgent()
            self.macro = MacroAgent()
    
        def run(self, data):
            a = self.analyst.run(data)
            s = self.strategist.run(a)
            sk = self.skeptic.run(a)
            m = self.macro.run(data)
    
            return {
                "analysis": a,
                "strategy": s,
                "critique": sk,
                "macro": m
            }
    
  • orchestrator/news_intelligence_orchestrator.py1019 B96d2f955a44fupstream ↗
    from .news_collector import NewsCollector
    from .nlp_engine import NLPEngine
    from .narrative_engine import NarrativeEngine
    from .bias_engine import BiasEngine
    from .impact_mapper import ImpactMapper
    from .signal_engine import SignalEngine
    
    class NewsIntelligence:
    
        def __init__(self):
            self.collector = NewsCollector()
            self.nlp = NLPEngine()
            self.narrative = NarrativeEngine()
            self.bias = BiasEngine()
            self.impact = ImpactMapper()
            self.signal = SignalEngine()
    
        def run(self, smc_layers):
    
            headlines = self.collector.fetch()
            parsed = self.nlp.extract(headlines)
            narratives = self.narrative.detect(parsed)
            bias = self.bias.analyze(narratives)
            impact = self.impact.map(bias)
    
            signals = self.signal.generate(impact, smc_layers)
    
            return {
                "headlines": headlines[:5],
                "narratives": narratives,
                "bias": bias,
                "impact": impact,
                "signals": signals
            }
    
  • orchestrator/universal_orchestrator.py662 B366af5ac4860upstream ↗
    from analyzer.insight_engine import InsightEngine
    from analyzer.risk_engine import RiskEngine
    from strategic.scenario_engine import ScenarioEngine
    from strategic.decision_engine import DecisionEngine
    
    class UniversalOrchestrator:
    
        def __init__(self):
            self.insight = InsightEngine()
            self.risk = RiskEngine()
            self.scenario = ScenarioEngine()
            self.decision = DecisionEngine()
    
        def run(self, smc_layers):
    
            insights = self.insight.generate(smc_layers)
            risks = self.risk.evaluate(smc_layers)
            scenarios = self.scenario.simulate(smc_layers)
    
            return self.decision.advise(insights, risks, scenarios)
    
  • orchestrator/war_brain.py1.6 KBa76936a5cfbcupstream ↗
    # orchestrator/war_brain.py
    
    from intelligence.alpha_engine import AlphaEngine
    from intelligence.macro_engine import MacroEngine
    from intelligence.geopolitic_engine import GeopoliticEngine
    from strategy.asymmetric_engine import AsymmetricEngine
    from strategy.scenario_war_game import ScenarioWarGame
    from cognition.meta_cognition import MetaCognition
    
    class WarBrain:
    
        def __init__(self):
            self.alpha = AlphaEngine()
            self.macro = MacroEngine()
            self.geo = GeopoliticEngine()
            self.asym = AsymmetricEngine()
            self.scenario = ScenarioWarGame()
            self.meta = MetaCognition()
    
        def run(self, smc_layers):
    
            alpha = self.alpha.detect(smc_layers)
            macro = self.macro.analyze()
            geo = self.geo.evaluate()
    
            asym = self.asym.find(alpha, macro, geo)
            scenarios = self.scenario.simulate(macro, geo)
    
            warnings = self.meta.check(asym)
    
            return {
                "alpha": alpha,
                "macro": macro,
                "geopolitics": geo,
                "asymmetric_opportunities": asym,
                "scenarios": scenarios,
                "bias_warnings": warnings
            }
            # orchestrator/war_brain.py
    
    class WarBrain:
    
        def run(self, smc_layers, real_data):
    
            macro_bias = real_data["macro_bias"]
            geo_risk = real_data["geo_risk"]
    
            decisions = []
    
            for l in smc_layers:
    
                if l.state == "accumulating" and macro_bias == "bearish":
                    decisions.append("Hidden accumulation under macro fear")
    
                if geo_risk:
                    decisions.append("Geopolitical risk may distort price")
    
            return decisions
    
  • realtime/stream_engine.py182 B9a22dd29207dupstream ↗
    # realtime/stream_engine.py
    
    import time
    
    class StreamEngine:
    
        def run(self, callback, interval=10):
    
            while True:
                callback()
                time.sleep(interval)
    
  • SECURITY.md1.8 KB1f9db7cbf852upstream ↗
    # Security Policy
    
    ## Reporting
    
    Report privately via
    [GitHub Security Advisories](https://github.com/ElmatadorZ/MoneyAtlas-ClaudeSkill-Agent/security/advisories/new).
    **Acknowledgement within 7 days · initial assessment within 30 days.**
    
    ## In scope
    
    ### 1. Analytical integrity (most serious)
    Because this system reasons about money, the highest-severity issues are those that cause it to
    present unfounded output as sound:
    
    - an input that makes the skill emit a recommendation **without** its required uncertainty
      disclosure or scenario structure
    - a prompt that causes it to present analysis as **advice**, contrary to its stated contract
    - prompt injection through untrusted market content (a pasted article, a news feed, a tool result)
      that redirects the analysis
    - a path that bypasses the inherited FPCOS Shadow Gate (self-critique) before output
    
    ### 2. Execution safety
    Defects in `execution/` — signal, risk, or broker-adapter logic — that could place, size, or route
    an order incorrectly. Treat anything touching order flow as high severity by default.
    
    ### 3. Credential handling
    Any path that logs, echoes, or persists an API key, broker credential, or account identifier.
    Report privately and do **not** include the credential itself.
    
    ### 4. Tooling
    Defects in `tools/validate_skill.py` or CI — for example, a validator reporting PASS on a skill.md
    whose uncertainty requirements have been removed.
    
    ## Out of scope
    
    - **Losing money on a trade.** Market outcomes are not vulnerabilities. This system is analysis,
      not advice, and can be wrong — see [NOTICE](NOTICE).
    - Weaknesses of the underlying model (report to the model vendor).
    - Third-party market-data or broker APIs (report to that provider).
    
    ## Supported versions
    
    | Version | Supported |
    |---|---|
    | 2.x | ✅ |
    
  • session_boot.txt318 B4b3382b89dfeupstream ↗
    You are Money Atlas Strategic Intelligence System.
    
    Rules:
    - Use First Principle reasoning
    - Apply System Thinking across macro → micro
    - Always provide scenarios (bull / bear / base)
    - If financial → include entry, SL, TP
    - Always include risk and uncertainty
    - End with a clear decision
    
    Reject shallow answers.
    
  • signals/signal_engine.py422 B609818c55a52upstream ↗
    # signals/signal_engine.py
    
    class SignalEngine:
    
        def generate(self, smc_layers):
            signals = []
    
            for layer in smc_layers:
                if layer.confidence > 0.7 and layer.state == "accumulating":
                    signals.append({
                        "type": "BUY",
                        "price": layer.cost_basis,
                        "confidence": layer.confidence
                    })
    
            return signals
    
  • skill_config.json791 B236169342f71upstream ↗
    ---
    
    # ⚙️ 2. **skill_config.json (Claude Skill Definition)**
    
    ```json
    {
      "name": "Money Atlas – Genesis SMC Intelligence",
      "version": "1.0",
      "description": "Financial + macro + geopolitics analysis using Genesis Protocol + SMC Layer",
    
      "triggers": [
        "market analysis",
        "price prediction",
        "bitcoin",
        "gold",
        "macro economy",
        "geopolitics",
        "investment strategy"
      ],
    
      "modes": {
        "light": {
          "sections": [
            "Market Structure Insight",
            "Key Risk",
            "Strategic Takeaway"
          ]
        },
        "full": {
          "sections": [
            "First Principle Breakdown",
            "System Map",
            "SMC Layer Map",
            "Narrative",
            "Scenarios",
            "Decision Framework",
            "Risk Analysis"
          ]
        }
      }
    }
    
  • smc/smc_wrapper.py1.1 KB6c9f3cba2f37upstream ↗
    # smc/smc_wrapper.py
    
    from typing import Dict, Any
    from .smc_layer_masterpiece import SMCLayerEngine
    
    
    class SMCWrapper:
    
        def __init__(self):
            self.engine = SMCLayerEngine()
    
        async def analyze(self, context: Dict[str, Any]) -> Dict[str, Any]:
    
            result = await self.engine.analyze(
                symbol=context["symbol"],
                timeframe=context["timeframe"],
                candles=context["candles"]
            )
    
            layers = []
    
            for layer in result.layers:
                layers.append({
                    "layer": layer.layer,
                    "range": (layer.price_low, layer.price_high),
                    "state": layer.state,
                    "confidence": layer.confidence
                })
    
            return {
                "layers": layers,
                "summary": self._interpret_layers(layers)
            }
    
        def _interpret_layers(self, layers):
    
            if not layers:
                return "No structure detected"
    
            l1 = layers[0]
            l5 = layers[-1]
    
            return f"Market spans from accumulation ({l1['range']}) to distribution ({l5['range']})"
    
  • strategic/decision_engine.py459 B94122716f10fupstream ↗
    class DecisionEngine:
    
        def advise(self, insights, risks, scenarios):
    
            return {
                "insight_summary": insights,
                "risk_summary": risks,
                "possible_scenarios": scenarios,
                "note": "ระบบนี้ไม่ได้ให้คำแนะนำซื้อขาย แต่ช่วยให้คุณเข้าใจภาพรวมเพื่อการตัดสินใจ"
            }
    
  • strategic/scenario_engine.py770 B6a7542e300f2upstream ↗
    class ScenarioEngine:
    
        def simulate(self, smc_layers):
    
            scenarios = []
    
            for layer in smc_layers:
    
                if layer.state == "accumulating":
                    scenarios.append({
                        "scenario": "Bullish Continuation",
                        "description": "ราคามีโอกาสปรับตัวขึ้นต่อ",
                        "confidence": layer.confidence
                    })
    
                elif layer.state == "distributing":
                    scenarios.append({
                        "scenario": "Bearish Reversal",
                        "description": "ราคามีโอกาสกลับตัวลง",
                        "confidence": layer.confidence
                    })
    
            return scenarios
    
  • strategy/asymmetric_engine.py513 B044396b42115upstream ↗
    # strategy/asymmetric_engine.py
    
    class AsymmetricEngine:
    
        def find(self, alpha, macro, geo):
    
            opportunities = []
    
            for a in alpha:
    
                if a["type"] == "SMART_MONEY_ENTRY":
                    if macro["risk_asset_bias"] == "bearish":
                        opportunities.append({
                            "type": "CONTRARIAN_SETUP",
                            "logic": "smart money vs macro fear",
                            "conviction": "high"
                        })
    
            return opportunities
    
  • strategy/scenario_war_game.py382 B3d5238705cf9upstream ↗
    # strategy/scenario_war_game.py
    
    class ScenarioWarGame:
    
        def simulate(self, macro, geo):
    
            return [
                {
                    "scenario": "Global Risk-Off",
                    "result": "equities down, gold up"
                },
                {
                    "scenario": "Liquidity Injection",
                    "result": "crypto & risk assets rally"
                }
            ]
    
  • system_prompt.txt703 B8339e17294b7upstream ↗
    You are Money Atlas Intelligence System.
    
    You operate using:
    
    1. Genesis Protocol
    - First Principle Thinking
    - System Thinking
    - Cause → Effect Mapping
    
    2. SMC Layer Model
    - Layer 1: Accumulation
    - Layer 2: Early Trend
    - Layer 3: Decision Zone
    - Layer 4: Distribution
    - Layer 5: Exit Liquidity
    
    3. Narrative Intelligence
    - Identify Smart Money
    - Detect Liquidity Engineering
    - Interpret Intent behind price
    
    ---
    
    Rules:
    
    - Always think in systems, not isolated facts
    - Never give single prediction → give scenarios
    - Always connect price to liquidity + macro
    - If uncertainty is high → reduce confidence
    
    ---
    
    Mode Selection:
    
    - Default: LIGHT MODE
    - If user asks deep / says "FULL" → FULL MODE
    
  • tests/conftest.py1.2 KBb2e19aadd09eupstream ↗
    """Shared test fixtures for Money Atlas Intelligence OS.
    
    The repository root is importable so tests can exercise the reasoning modules
    directly (first_principle_codex, analyzer, signals, core) without installing the
    package.
    """
    from __future__ import annotations
    
    import sys
    from dataclasses import dataclass
    from pathlib import Path
    
    import pytest
    
    ROOT = Path(__file__).resolve().parent.parent
    if str(ROOT) not in sys.path:
        sys.path.insert(0, str(ROOT))
    
    
    @dataclass
    class FakeLayer:
        """A minimal stand-in for an SMC layer.
    
        The analyzer/signal/insight engines duck-type on these attributes, so the
        tests can drive them without the async SMCLayerEngine or any market data.
        """
        layer: int = 1
        state: str = "accumulating"      # accumulating | distributing | ranging
        confidence: float = 0.8
        cost_basis: float = 100.0
        price_low: float = 95.0
        price_high: float = 105.0
    
    
    @pytest.fixture
    def accumulating_layer() -> FakeLayer:
        return FakeLayer(layer=1, state="accumulating", confidence=0.82, cost_basis=100.0)
    
    
    @pytest.fixture
    def distributing_layer() -> FakeLayer:
        return FakeLayer(layer=3, state="distributing", confidence=0.40, cost_basis=140.0)
    
  • tests/test_first_principle_codex.py2.6 KBfa244c4922bcupstream ↗
    """First Principle Codex — the reasoning kernel that separates observed truth
    from inference. These tests lock its contract: what it extracts, what it treats
    as certain, and that the full pipeline stays internally consistent.
    """
    from __future__ import annotations
    
    import first_principle_codex as fpc
    
    
    def test_decompose_returns_irreducible_questions():
        parts = fpc.decompose_problem("BTC direction")
        assert isinstance(parts, list) and len(parts) >= 3
        # Every component is a question about the problem, not a restatement of it.
        assert all("BTC direction" in p and p.endswith("?") for p in parts)
    
    
    def test_atomic_truths_only_from_scalar_context():
        truths = fpc.extract_atomic_truths(
            {"price": 100, "trend": "up", "note": ["a", "list"], "meta": {"k": "v"}}
        )
        statements = [t.statement for t in truths]
        # Scalars become truths; containers are not invented into facts.
        assert "price = 100" in statements
        assert "trend = up" in statements
        assert not any("list" in s or "meta" in s for s in statements)
    
    
    def test_data_sourced_truths_are_not_certain():
        # A value read from context is high- but not full-certainty, and is labelled
        # as data — the K/I/U discipline the whole ecosystem rests on.
        truths = fpc.extract_atomic_truths({"cpi": 3.1})
        assert len(truths) == 1
        assert truths[0].source == "data"
        assert 0.0 < truths[0].certainty < 1.0
    
    
    def test_constraints_track_every_truth():
        truths = fpc.extract_atomic_truths({"a": 1, "b": 2})
        constraints = fpc.derive_constraints(truths)
        assert len(constraints) == len(truths)
    
    
    def test_contradiction_detector_flags_gt_vs_lt():
        truths = [
            fpc.AtomicTruth("price > 100", 0.9, "data"),
            fpc.AtomicTruth("price < 90", 0.9, "data"),
        ]
        assert fpc.detect_contradictions(truths)
    
    
    def test_no_false_contradiction_on_aligned_truths():
        truths = [
            fpc.AtomicTruth("price > 100", 0.9, "data"),
            fpc.AtomicTruth("volume > 1000", 0.9, "data"),
        ]
        assert fpc.detect_contradictions(truths) == []
    
    
    def test_full_pipeline_shape():
        out = fpc.run_first_principle_codex("gold outlook", {"spot": 2400, "real_yield": -0.5})
        for key in ("problem", "decomposition", "atomic_truths",
                    "constraints", "solutions", "contradictions"):
            assert key in out
        assert out["problem"] == "gold outlook"
        assert "spot = 2400" in out["atomic_truths"]
        # constraints and solutions are derived one-per-truth, so they stay in step.
        assert len(out["constraints"]) == len(out["atomic_truths"])
        assert len(out["solutions"]) == len(out["atomic_truths"])
    
  • tests/test_market_engines.py2.4 KB3ee2cd1ea583upstream ↗
    """The SMC-layer engines: signal, risk, insight, decision.
    
    These are the pieces that turn market structure into a recommendation, so their
    gates are exactly where a mistake would cost money. The tests pin the gates:
    a BUY only on high-confidence accumulation, risk raised on low confidence or
    distribution, and a decision that maximises reward minus risk.
    """
    from __future__ import annotations
    
    from analyzer.insight_engine import InsightEngine
    from analyzer.risk_engine import RiskEngine
    from core.decision_engine import DecisionEngine
    from signals.signal_engine import SignalEngine
    
    
    def test_signal_fires_buy_only_on_confident_accumulation(accumulating_layer):
        sigs = SignalEngine().generate([accumulating_layer])
        assert len(sigs) == 1
        assert sigs[0]["type"] == "BUY"
        assert sigs[0]["price"] == accumulating_layer.cost_basis
        assert sigs[0]["confidence"] == accumulating_layer.confidence
    
    
    def test_signal_withholds_on_low_confidence(accumulating_layer):
        accumulating_layer.confidence = 0.55   # below the 0.7 gate
        assert SignalEngine().generate([accumulating_layer]) == []
    
    
    def test_signal_withholds_when_distributing(distributing_layer):
        distributing_layer.confidence = 0.9    # high confidence, wrong phase
        assert SignalEngine().generate([distributing_layer]) == []
    
    
    def test_risk_flags_low_confidence(distributing_layer):
        risks = RiskEngine().evaluate([distributing_layer])
        # confidence 0.40 (< 0.5) AND distributing → two distinct risk notes.
        assert len(risks) == 2
    
    
    def test_risk_silent_on_healthy_layer(accumulating_layer):
        assert RiskEngine().evaluate([accumulating_layer]) == []
    
    
    def test_insight_distinguishes_accumulation_from_distribution(
        accumulating_layer, distributing_layer
    ):
        out = InsightEngine().generate([accumulating_layer, distributing_layer])
        assert len(out) == 2
        joined = " ".join(out)
        assert "สะสม" in joined       # accumulation note (Thai source strings)
        assert "แรงขาย" in joined     # distribution note
    
    
    def test_decision_picks_best_reward_minus_risk():
        options = [
            {"name": "hold", "reward": 2, "risk": 1},
            {"name": "long", "reward": 9, "risk": 3},   # best net = 6
            {"name": "short", "reward": 4, "risk": 4},
        ]
        out = DecisionEngine().decide(options)
        assert out["decision"]["name"] == "long"
        assert "confidence" in out and "reason" in out
    
  • tests/test_skill_contract.py2.2 KBd2f7ee3865acupstream ↗
    """The SKILL.md contract.
    
    A skill is installed and run by a model, so its guarantees live in the markdown,
    not only in the Python. These tests assert the promises the skill makes about
    itself hold in the file itself — the same properties tools/validate_skill.py
    checks, kept here so a contributor running pytest sees them too.
    """
    from __future__ import annotations
    
    import re
    from pathlib import Path
    
    import yaml
    
    ROOT = Path(__file__).resolve().parent.parent
    SKILL = ROOT / "SKILL.md"
    
    
    def _split():
        text = SKILL.read_text(encoding="utf-8")
        m = re.match(r"^---\n(.*?)\n---\n", text, re.S)
        assert m, "frontmatter must be present and delimited"
        return yaml.safe_load(m.group(1)), text[m.end():]
    
    
    def test_canonical_filename():
        # Strict skill-discovery tooling looks for uppercase SKILL.md.
        assert SKILL.exists(), "SKILL.md must exist at the repository root"
    
    
    def test_frontmatter_required_and_recommended_fields():
        fm, _ = _split()
        for f in ("name", "description"):
            assert f in fm, f"frontmatter must declare '{f}'"
        for f in ("license", "version"):
            assert f in fm, f"frontmatter should declare '{f}'"
        assert str(fm["license"]).lower().replace(" ", "-") == "apache-2.0"
    
    
    def test_name_is_slug_safe():
        fm, _ = _split()
        assert re.fullmatch(r"[a-z0-9][a-z0-9-]*", str(fm["name"]))
    
    
    def test_metadata_declares_scope_and_compatibility():
        fm, _ = _split()
        meta = fm.get("metadata", {})
        assert meta.get("compatibility"), "metadata.compatibility must state where it runs"
        assert meta.get("not_for"), "metadata.not_for must bound the skill's scope"
    
    
    def test_body_requires_scenarios_and_invalidation():
        _, body = _split()
        assert re.search(r"scenario", body, re.I)
        assert re.search(r"invalidation", body, re.I)
        assert re.search(r"uncertaint|confidence", body, re.I)
    
    
    def test_body_degrades_honestly_without_data():
        _, body = _split()
        assert re.search(r"insufficient|no live data|abstain", body, re.I), \
            "the skill must declare what it does when data is missing"
    
    
    def test_body_declines_personalized_advice():
        _, body = _split()
        assert re.search(r"not.{0,20}(financial|investment) advice|does not issue", body, re.I)
    
  • tools/validate_skill.py3.8 KBf7bf7d8450ddupstream ↗
    #!/usr/bin/env python3
    """
    validate_skill.py — integrity checks for Money Atlas Intelligence OS.
    
    READ-ONLY. Never modifies SKILL.md. Verifies the skill is installable
    (frontmatter well-formed) and that its safety-relevant structure is intact.
    
    Run:  python tools/validate_skill.py
    Exit: 0 pass · 1 fail
    """
    from __future__ import annotations
    
    import re
    import sys
    from pathlib import Path
    
    try:
        sys.stdout.reconfigure(encoding="utf-8")
    except Exception:  # pragma: no cover
        pass
    
    try:
        import yaml
    except ImportError:
        print("Missing dependency: pyyaml. Install with: pip install pyyaml")
        sys.exit(1)
    
    ROOT = Path(__file__).resolve().parent.parent
    # The Claude/Anthropic standard filename is SKILL.md (uppercase). A lowercase
    # skill.md is tolerated by a case-insensitive filesystem but missed by strict
    # discovery tooling, so the canonical name is preferred and the old one is a
    # fallback only.
    SKILL = ROOT / "SKILL.md"
    if not SKILL.exists() and (ROOT / "skill.md").exists():
        SKILL = ROOT / "skill.md"
    REQUIRED = ["name", "description"]
    RECOMMENDED = ["license", "version"]
    
    results: list[tuple[str, bool]] = []
    
    
    def check(name: str, cond: bool) -> None:
        results.append((name, bool(cond)))
        print(f"  {'PASS' if cond else 'FAIL'}  {name}")
    
    
    def main() -> int:
        if not SKILL.exists():
            print(f"FATAL: SKILL.md not found at {SKILL}")
            return 1
        text = SKILL.read_text(encoding="utf-8")
    
        print("\nINSTALLABILITY")
        m = re.match(r"^---\n(.*?)\n---\n", text, re.S)
        check("frontmatter present and delimited", m is not None)
        if not m:
            return 1
        try:
            fm = yaml.safe_load(m.group(1))
            check("frontmatter is valid YAML", isinstance(fm, dict))
        except yaml.YAMLError:
            check("frontmatter is valid YAML", False)
            return 1
        for f in REQUIRED:
            check(f"frontmatter has '{f}'", f in fm)
        check("name is slug-safe (a-z0-9-)",
              bool(re.fullmatch(r"[a-z0-9][a-z0-9-]*", str(fm.get("name", "")))))
        for f in RECOMMENDED:
            check(f"frontmatter declares '{f}'", f in fm)
        check("license is Apache-2.0 (matches LICENSE file)",
              str(fm.get("license", "")).lower().replace(" ", "-") == "apache-2.0")
        check("canonical filename is SKILL.md", SKILL.name == "SKILL.md")
    
        body = text[m.end():]
        print("\nINTEGRITY")
        check("activation modes declared", "LIGHT MODE" in body and "FULL MODE" in body)
        check("output requires explicit uncertainty",
              re.search(r"uncertaint|confidence", body, re.I) is not None)
        check("output requires scenarios",
              re.search(r"scenario", body, re.I) is not None)
        check("output requires an invalidation point",
              re.search(r"invalidation", body, re.I) is not None)
        check("declares graceful degradation when data is insufficient",
              re.search(r"insufficient|no live data|abstention|abstain", body, re.I) is not None)
        check("declares it is not personalized investment advice",
              re.search(r"not.{0,20}(financial|investment) advice|does not issue", body, re.I) is not None)
    
        print("\nREPOSITORY")
        check("LICENSE exists", (ROOT / "LICENSE").exists())
        check("NOTICE exists", (ROOT / "NOTICE").exists())
        notice = (ROOT / "NOTICE").read_text(encoding="utf-8") if (ROOT / "NOTICE").exists() else ""
        # A markets tool must carry an explicit not-advice disclaimer.
        check("NOTICE carries the not-financial-advice disclaimer",
              "NOT FINANCIAL ADVICE" in notice)
    
        passed = sum(1 for _, ok in results if ok)
        total = len(results)
        print(f"\n{'=' * 52}\nVALIDATION: {passed}/{total} passed")
        if passed != total:
            print("FAILED:", [n for n, ok in results if not ok])
            return 1
        print(f"{SKILL.name} is installable and structurally intact.")
        return 0
    
    
    if __name__ == "__main__":
        sys.exit(main())
    

Plain-text copy, no login: /skill-bundles/elmatadorz-moneyatlas-claudeskill-agent.md

// REPO STATS

59 stars
0 open issues
Last commit: 3mo ago