# money-atlas-intelligence-os

Adopt this skill: https://proskills.md/skills/finance/elmatadorz-moneyatlas-claudeskill-agent

Page: https://proskills.md/skills/finance/elmatadorz-moneyatlas-claudeskill-agent
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: SKILL.md
size: 6012
sha: 7f3d2f2c2e028e7d17aad21d82939ad9232f9523
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/SKILL.md

```text
---
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`
```

## File: examples/README.md
size: 1404
sha: 417ca0826bab1a8349d4dec2da9ef516c0623579
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/examples/README.md

````text
# 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.
````

## File: README.md
size: 10087
sha: f11dadfb4c99b17a19e5ec884c0a7919dffae1e5
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/README.md

````text
# 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."*
````

## File: .github/workflows/validate.yml
size: 2662
sha: 5f786014d3f88868958a07d38cea730b0b22800e
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/.github/workflows/validate.yml

```text
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
```

## File: .gitignore
size: 351
sha: e484fa782d88640cd7709de23fade8b1f5894497
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/.gitignore

```text
# 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/
```

## File: adapter.py
size: 358
sha: a88a022ac1bd6269383c75579b979c5aaeb8b02e
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/adapter.py

```text
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
```

## File: agents/analyst_agent.py
size: 155
sha: ebade9d1fa1304097624370bc5338650b322f399
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/analyst_agent.py

```text
class AnalystAgent:

    def run(self, data):
        return {
            "insight": "Market structure analyzed",
            "confidence": 0.7
        }
```

## File: agents/base_agent.py
size: 335
sha: 49842866644c93790cbfe694f353cdda00af7607
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/base_agent.py

```text
# 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
```

## File: agents/genesis_agent.py
size: 448
sha: a86a1fb9ba79d4b959e8eab73b553931f9542847
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/genesis_agent.py

```text
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"
        )
```

## File: agents/macro_agent.py
size: 444
sha: efa713cfd683e55831fa1a3d6399a032cd02899a
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/macro_agent.py

```text
# 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
        )
```

## File: agents/orchestrator.py
size: 729
sha: 9992602fefbb1a8c2a13b088c851d9d1dc807270
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/orchestrator.py

```text
# 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
```

## File: agents/portfolio_agent.py
size: 598
sha: 348c7fe24e7d5fabb5d81bed1c36b3940be43381
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/portfolio_agent.py

```text
# 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}"
        )
```

## File: agents/risk_agent.py
size: 341
sha: 7c1e6023e2ea10726e969a04f10ff3c678793d40
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/risk_agent.py

```text
# 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"
        )
```

## File: agents/sentiment_agent.py
size: 360
sha: 96b1debfaf61e505278c8eda15e6c8d3087a9b90
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/sentiment_agent.py

```text
# 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"
        )
```

## File: agents/skeptic_agent.py
size: 158
sha: 301021a30de4315ea2a0762cfadae484f3c1637d
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/skeptic_agent.py

```text
class SkepticAgent:

    def run(self, analysis):
        return {
            "critique": "Potential bias detected",
            "confidence": 0.6
        }
```

## File: agents/smc_agent.py
size: 449
sha: d5f75e0f48030f9be1a25b6604654fe2fa14f35a
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/smc_agent.py

```text
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"]
        )
```

## File: agents/strategist_agent.py
size: 166
sha: dd4ba4dfb5393ad32efb93d31dec26511198442f
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/agents/strategist_agent.py

```text
class StrategistAgent:

    def run(self, analysis):
        return {
            "strategy": "Optimal allocation strategy",
            "confidence": 0.75
        }
```

## File: analyzer/insight_engine.py
size: 557
sha: 805c90321027fbdb33c8dde9fb4353efc3bed6b0
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/analyzer/insight_engine.py

```text
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
```

## File: analyzer/risk_engine.py
size: 509
sha: 548173a7aa76a6f17712a7f1380eedbd2ea091a6
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/analyzer/risk_engine.py

```text
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
```

## File: architecture.md
size: 287
sha: 4469b8872df51ad2adbd483cda3e32047c64467b
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/architecture.md

```text
# 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
```

## File: backtest/backtest_engine.py
size: 429
sha: 12514e1f11ee799d9ccb0202a0702e55967939f2
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/backtest/backtest_engine.py

```text
# 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"
        }
```

## File: btc_analysis.py
size: 534
sha: c17d38a4a3e643a0e4740ab7f1d41a5550a4cf5c
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/btc_analysis.py

```text
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())
```

## File: CITATION.cff
size: 769
sha: badd598d95bfe59fdb34deeee949fd66da4725c8
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/CITATION.cff

```text
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'
```

## File: cli/run_analysis.py
size: 1246
sha: 48a7cd3a2e5c19ee6d3e556a528b4cb477e97d62
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/cli/run_analysis.py

```text
# 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()
```

## File: cli/run_piw.py
size: 382
sha: e994b55182129ffa2f1f5dd492904e3d97dd953d
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/cli/run_piw.py

```text
# 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()
```

## File: cli/run_realtime.py
size: 834
sha: 1948f0a0e287d6d248c3b00b90a4b5d81b738380
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/cli/run_realtime.py

```text
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()
```

## File: cli/run_v2.py
size: 1184
sha: 242b6f9c9a9df1e18e513bcab00cbb3c0d114396
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/cli/run_v2.py

```text
# 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()
```

## File: CODE_OF_CONDUCT.md
size: 1824
sha: e75ca6ddc27dd1163f3a48e28aefd087d771a7ef
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/CODE_OF_CONDUCT.md

```text
# 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.
```

## File: cognition/meta_cognition.py
size: 260
sha: 82ebd77e50d3dddb3b812aba4ca31893c317e81a
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/cognition/meta_cognition.py

```text
# 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
```

## File: core/ai_fluency_4d.py
size: 830
sha: 1dffdedc4821dd67625d2e89e5732b4eefe459e1
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/core/ai_fluency_4d.py

```text
# 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
        }
```

## File: core/decision_engine.py
size: 431
sha: 2e0a8f3357aea0feeb50b0f17d1ad7afefc628e4
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/core/decision_engine.py

```text
# 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"
        }
```

## File: core/discernment_engine.py
size: 633
sha: 94c11f08762b25eb8ee327aea703b69e9eb30480
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/core/discernment_engine.py

```text
# 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"
```

## File: core/genesis_core.py
size: 1960
sha: 0ab46307b9b60c722a9f0a5681160863cc26d5b3
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/core/genesis_core.py

```text
# 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
        }
```

## File: core/meta_cognition.py
size: 296
sha: 198e6fe533ed5557ffdefd8fef4fcd8d8b00ef4d
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/core/meta_cognition.py

```text
# 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)
        }
```

## File: data/market_data_loader.py
size: 235
sha: 65d3800620c3035f7474cf12a87cecef09d50fec
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/data/market_data_loader.py

```text
# 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)
        }
```

## File: data_feed.py
size: 307
sha: c115b64ebb03d2826236df99edad03e937b84400
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/data_feed.py

```text
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()
```

## File: data_pipeline/ingestion_engine.py
size: 508
sha: bd8d5855240ede50b14b52251cedcee0ba8c5289
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/data_pipeline/ingestion_engine.py

```text
# 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()
        }
```

## File: data_pipeline/normalization_engine.py
size: 327
sha: 50464079b302fbd2cb51b823778e636691d4cebd
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/data_pipeline/normalization_engine.py

```text
# 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"])
        }
```

## File: evolution/reinforcement.py
size: 346
sha: 9db27b87b3c301de4756d355e36b7fca62253ae8
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/evolution/reinforcement.py

```text
# 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
```

## File: examples/full_system_demo.py
size: 544
sha: 05c389f8753741fd840735490c45e95c7c090a86
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/examples/full_system_demo.py

```text
# 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())
```

## File: examples/worked/01-btc-light-mode.md
size: 1389
sha: a0a19f9e7755b21f435d271523cb054e21102329
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/examples/worked/01-btc-light-mode.md

```text
# 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.
```

## File: examples/worked/02-gold-full-mode.md
size: 2145
sha: 7890617b461722835554c68919bb612e2e6bed7c
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/examples/worked/02-gold-full-mode.md

```text
# 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.
```

## File: examples/worked/03-insufficient-data.md
size: 1511
sha: 3a952e56ada5056fdc441c1f08ecd1b7e5c0b157
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/examples/worked/03-insufficient-data.md

```text
# 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.
```

## File: execution/broker_adapter.py
size: 123
sha: b5311fe67ba1628b535505e89e92bb50c5f442c5
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution/broker_adapter.py

```text
class BrokerAdapter:

    def place_order(self, symbol, direction, size, entry, sl, tp):
        raise NotImplementedError
```

## File: execution/execution_engine.py
size: 604
sha: 2b8ef96fa044e0489edb0187a2605a338b9a3e37
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution/execution_engine.py

```text
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
        )
```

## File: execution/risk_engine.py
size: 463
sha: 26c4fdabe7ae00d66ef4adfbedf530526d9e7b94
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution/risk_engine.py

```text
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
```

## File: execution/signal_engine.py
size: 941
sha: 20fb3b3f68aedfaaf1d8db43df55e6438d42c739
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution/signal_engine.py

```text
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
```

## File: execution/trade_logger.py
size: 543
sha: 17c7022f7cbd758f2784a8d21aec2e77ce4bce35
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution/trade_logger.py

```text
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")
```

## File: execution_engine.py
size: 310
sha: 2d6f559a9bc07d2f1fbe0d5aeee19b5f165b8d9c
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/execution_engine.py

```text
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
```

## File: first_principle_codex.py
size: 3700
sha: 1d3af198c48a26fbbdd62e05b13c45ecd391b734
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/first_principle_codex.py

```text
# 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
    }
```

## File: full_mode.txt
size: 206
sha: 05ac307fdd307e3e6a326328eba3186f8af5e613
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/full_mode.txt

```text
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
```

## File: integration/macro_api.py
size: 269
sha: d76f27a00960555ee177229e9def6497d0a4de47
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/integration/macro_api.py

```text
# 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"
        }
```

## File: integration/market_api.py
size: 371
sha: 872dfa6fff5a80890f68bd59435b0e6d8c50a50e
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/integration/market_api.py

```text
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
```

## File: integration/news_api.py
size: 258
sha: caece504099aecd6840ec2eb8930eddaeb066c25
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/integration/news_api.py

```text
# 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"
        ]
```

## File: integration/smc_adapter.py
size: 222
sha: 2dd4c3370f9d837163d9735cd6a31008f5296863
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/integration/smc_adapter.py

```text
# integration/smc_adapter.py

class SMCAdapter:

    def integrate(self, smc_output, cognitive_output):
        return {
            "market_structure": smc_output,
            "decision_layer": cognitive_output
        }
```

## File: intelligence/alpha_engine.py
size: 688
sha: b63553e2c8366da385272a791e08dee23c14440a
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/alpha_engine.py

```text
# 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
```

## File: intelligence/geopolitic_engine.py
size: 352
sha: c9b06eab0e49b13c3c2700edb3d84e8289b69a6e
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/geopolitic_engine.py

```text
# 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"
            }
        }
```

## File: intelligence/macro_engine.py
size: 268
sha: 6fce0484da4f42191ad0b6691e2dc1ebe6d8ab39
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/macro_engine.py

```text
# intelligence/macro_engine.py

class MacroEngine:

    def analyze(self):

        return {
            "liquidity_cycle": "tightening",
            "interest_rate": "high",
            "risk_asset_bias": "bearish",
            "safe_haven_bias": "bullish"
        }
```

## File: intelligence/news_intelligence/bias_engine.py
size: 391
sha: 9ceb464ebcc23add24977b50bb95d5a76eff061c
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/bias_engine.py

```text
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
```

## File: intelligence/news_intelligence/impact_mapper.py
size: 391
sha: 2e666f4d2406c39b48c9d65ef3592ef07f8a8685
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/impact_mapper.py

```text
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
```

## File: intelligence/news_intelligence/narrative_engine.py
size: 573
sha: f762b6f2dbd293e9c6eddc9b78097e19d95ddb26
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/narrative_engine.py

```text
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
```

## File: intelligence/news_intelligence/news_collector.py
size: 331
sha: 503a7940917047be7f78088eb60f17284651ce9d
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/news_collector.py

```text
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 []
```

## File: intelligence/news_intelligence/nlp_engine.py
size: 269
sha: 059b34381e01b94cd87cb8fcac153cebbbb8f1e0
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/nlp_engine.py

```text
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
```

## File: intelligence/news_intelligence/signal_engine.py
size: 479
sha: 768320dfcb5efa7e45527811086f9b5fec1876e7
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/intelligence/news_intelligence/signal_engine.py

```text
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
```

## File: LICENSE
size: 11365
sha: fbcf9e3d4f7499ec4836afc5a060d03b96c2def3
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/LICENSE

```text
                                 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.
```

## File: light_mode.txt
size: 81
sha: ca2c136dfa16c0c50f12f841b036ebb86f18f9f3
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/light_mode.txt

```text
Output Structure:

1. Market Structure Insight
2. Key Risk
3. Strategic Takeaway
```

## File: main.py
size: 1354
sha: 4f4bd65ae492fbee273fdaa3da33d7865c0bc299
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/main.py

```text
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()
```

## File: memory.json
size: 55
sha: a4bce0640046306edc41e3d067c064a8a564cf79
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/memory.json

```text
{
  "trades": [],
  "insights": [],
  "patterns": []
}
```

## File: memory/learning_engine.py
size: 448
sha: 3e0a8749686efceead2f19bf455033206c838df5
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/memory/learning_engine.py

```text
# 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"
```

## File: memory/memory_store.py
size: 732
sha: 16d5f4f7bd811d0485d476aefbf1da8acab28144
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/memory/memory_store.py

```text
# 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", [])
```

## File: memory_engine.py
size: 728
sha: ed6a43cf1ebff1958496b5db8833789598abdfd2
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/memory_engine.py

```text
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)
```

## File: NOTICE
size: 2851
sha: 4efa21254365531efae513fe25b2be0a2f31e964
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/NOTICE

```text
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.
```

## File: orchestrator/multi_agent_orchestrator.py
size: 735
sha: 07352c6ea9be1d800a419133269c0073fb02e77f
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/orchestrator/multi_agent_orchestrator.py

```text
# 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
        }
```

## File: orchestrator/news_intelligence_orchestrator.py
size: 1019
sha: 96d2f955a44feddf26f9cd3b926a2da3991717d5
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/orchestrator/news_intelligence_orchestrator.py

```text
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
        }
```

## File: orchestrator/universal_orchestrator.py
size: 662
sha: 366af5ac48603bac2f4a1108723d20c9e57b29ca
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/orchestrator/universal_orchestrator.py

```text
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)
```

## File: orchestrator/war_brain.py
size: 1656
sha: a76936a5cfbc4123cd7e96d1341fcbff88a8488a
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/orchestrator/war_brain.py

```text
# 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
```

## File: realtime/stream_engine.py
size: 182
sha: 9a22dd29207d3ee21341e3acffff13021e83bf1d
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/realtime/stream_engine.py

```text
# realtime/stream_engine.py

import time

class StreamEngine:

    def run(self, callback, interval=10):

        while True:
            callback()
            time.sleep(interval)
```

## File: SECURITY.md
size: 1807
sha: 1f9db7cbf852d2b4563242c8ceef145262e491f1
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/SECURITY.md

```text
# 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 | ✅ |
```

## File: session_boot.txt
size: 318
sha: 4b3382b89dfe0ab1061e4a867da371f976b3b34b
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/session_boot.txt

```text
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.
```

## File: signals/signal_engine.py
size: 422
sha: 609818c55a522b37d0a3928ff4efe09439a642fd
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/signals/signal_engine.py

```text
# 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
```

## File: skill_config.json
size: 791
sha: 236169342f71c105d448157127bfe4fe3d979e17
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/skill_config.json

````text
---

# ⚙️ 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"
      ]
    }
  }
}
````

## File: smc/smc_wrapper.py
size: 1087
sha: 6c9f3cba2f37495261efa1dd8be6acfd8c4d83e3
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/smc/smc_wrapper.py

```text
# 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']})"
```

## File: strategic/decision_engine.py
size: 459
sha: 94122716f10fbb13e9ce0522cabc6a8803edcb88
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/strategic/decision_engine.py

```text
class DecisionEngine:

    def advise(self, insights, risks, scenarios):

        return {
            "insight_summary": insights,
            "risk_summary": risks,
            "possible_scenarios": scenarios,
            "note": "ระบบนี้ไม่ได้ให้คำแนะนำซื้อขาย แต่ช่วยให้คุณเข้าใจภาพรวมเพื่อการตัดสินใจ"
        }
```

## File: strategic/scenario_engine.py
size: 770
sha: 6a7542e300f23bf4956be64db18ee775bf7c9e68
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/strategic/scenario_engine.py

```text
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
```

## File: strategy/asymmetric_engine.py
size: 513
sha: 044396b42115cd5a464cff2b331fe43cee4a9e13
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/strategy/asymmetric_engine.py

```text
# 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
```

## File: strategy/scenario_war_game.py
size: 382
sha: 3d5238705cf982eb9e885b3b51a6e0bbefdc61e0
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/strategy/scenario_war_game.py

```text
# 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"
            }
        ]
```

## File: system_prompt.txt
size: 703
sha: 8339e17294b7ef713c69305296c7aa4f917fc9ff
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/system_prompt.txt

```text
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
```

## File: tests/conftest.py
size: 1201
sha: b2e19aadd09e6f95f33978686f95b89bda1ff9e8
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/tests/conftest.py

```text
"""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)
```

## File: tests/test_first_principle_codex.py
size: 2645
sha: fa244c4922bc409a17d1bfaf2ec77f26b9337dec
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/tests/test_first_principle_codex.py

```text
"""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"])
```

## File: tests/test_market_engines.py
size: 2420
sha: 3ee2cd1ea58357439ea96952f509bf34794f8874
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/tests/test_market_engines.py

```text
"""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
```

## File: tests/test_skill_contract.py
size: 2238
sha: d2f7ee3865ac9e9ebf9b9d4ef4f536b5e4b8c518
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/tests/test_skill_contract.py

```text
"""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)
```

## File: tools/validate_skill.py
size: 3884
sha: f7bf7d8450ddd3cc6c44752357aa1e3d934470c2
upstream: https://github.com/elmatadorz/moneyatlas-claudeskill-agent/blob/HEAD/tools/validate_skill.py

```text
#!/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())
```
