# Project export: NerTzh Metrics Control Plane

This document was generated by HackStack to give an AI agent context about a hackathon project. Sections are labeled with their provenance; content marked as truncated was cut to keep this document small.

## Project metadata

- Hackathon: OpenAI Build Week
- Tagline: An auditable local control plane for market-signal evidence and protected GPT-5.6/Codex-assisted analysis.
- Devpost: https://devpost.com/software/nertzh
- GitHub: https://github.com/NerTzhuLz/NerTzh
- Demo: https://github.com/NerTzhuLz/NerTzh/releases/tag/v0.1.0-build-week
- Video: https://www.youtube.com/embed/RXj2eeqYVLc?enablejsapi=1&hl=en_US&rel=0&start=&version=3&wmode=transparent
- Team: 1 GitHub contributor(s) — AngeL (23 commits)

## Devpost submission (written by the team)

### Overview

NerTzh Metrics Control Plane NerTzh is an evidence-first local developer control plane for inspecting Bybit spot market metrics, reconciliation state, Context Bridge evidence, and optional protected GPT-5.6/Codex-assisted analysis. What it solves Trading systems expose several independent states: market data, generated signals, database rows, exchange orders, and project-agent context. NerTzh makes those states inspectable from one judge-facing surface without pretending that saved evidence is a live trade or an AI decision. How it works FastAPI control plane and responsive local viewer on port 8081. Optional attended Bybit demo engine isolated on port 8082. PostgreSQL for engine state and reconciliation. DuckDB plus Markdown for the local Context Bridge. Read-only health, metrics, validation, order-status and context routes. Protected chat boundary requiring an explicit local control token. Virtual local TP/SL monitoring; native exchange TP/SL orders are disabled in the judge path. Demo-safe configuration with live trading disabled by default. The viewer does not start the trading engine, call a remote model, or spend API credits when opened. The optional analysis route is explicit and protected. Bybit execution remains outside the judge-facing read-only surface. Codex and GPT-5.6 Codex was used to audit the architecture, reconcile WebSocket/PostgreSQL/Bybit state, simplify the delivery path, harden the demo boundary, prepare documentation, and verify the captured walkthrough. GPT-5.6/Codex-assisted analysis is integrated as an optional protected capability, not as an automatic trading dependency. The submitted video and repository describe those boundaries explicitly. Evidence and delivery Repository: https://github.com/NerTzhuLz/NerTzh Demo release and video assets: https://github.com/NerTzhuLz/NerTzh/releases/tag/v0.1.0-build-week The release includes a verified 1080p H.264/AAC render with English narration and burned-in subtitles, plus a 4K upscale. Safety The repository defaults to demo mode and excludes secrets. The engine is attended and separated from the judge surface. No live/mainnet execution, autonomous profit claim, or native TP/SL claim is made by this submission. Built during OpenAI Build Week The project demonstrates how Codex and GPT-5.6-assisted engineering can turn a trading prototype into a reproducible, auditable developer tool.

## README (from the GitHub repository)

# NerTzh Metrics Control Plane

NerTzh is a local control plane for inspecting Bybit spot market metrics, a Context Bridge snapshot, and optional GPT-5.6/Codex-assisted analysis. It is built for the **Developer Tools** track of OpenAI Build Week.

The project keeps the judge-facing API separate from the optional trading engine. The default configuration is **Bybit demo**. No LLM request or trade is made simply by opening the UI.

## Developer profile

**AngeL / NerTzhuLz** builds evidence-first developer tools at the intersection of real-time systems, automation and community operations. The public work visible across the project history covers:

- FastAPI and Python services with PostgreSQL state and operational runbooks.
- Bybit market-data, order-reconciliation and metrics research in demo mode.
- Discord and community automation projects dating back to 2020.
- Local agent tooling, Context Bridge workflows and protected GPT-5.6/Codex-assisted development.
- Leadership and operations in Latin gaming communities, documented publicly only at an aggregate level and without member or financial data.

The current portfolio is intentionally curated: this repository is the flagship control-plane project; older experiments and backups remain separate until their licenses, dependencies, secrets and reproducibility are reviewed.

## What judges can run

```bash
git clone https://github.com/NerTzhuLz/NerTzh.git
cd NerTzh
uv sync
cp .env.example .env
make demo
```

Open <http://127.0.0.1:8081/web/>.

The demo surface provides:

- `GET /health` — local API status and environment.
- `GET /agent/context` — local Context Bridge and the last persisted snapshot.
- `GET /metrics` — Prometheus metrics.
- `GET /agent/bybit/tools` — discoverable read-only Bybit tools.
- `POST /agent/chat` — optional GPT-5.6/Codex-assisted analysis, protected by `CONTROL_API_TOKEN`.

The demo API does not start the trading engine. To use the protected chat form, set a random `CONTROL_API_TOKEN` in `.env`, then paste it into the browser session when prompted. The token is never written by the UI.

## Running the optional engine

The engine is intentionally separate from the judge demo:

```bash
# Docker Desktop is disabled at login on this workstation: start it deliberately.
systemctl --user start docker-desktop.service
docker ps -a --format '{{.Names}}\\t{{.Status}}\\t{{.Ports}}'
docker compose up -d --wait postgres
make run
```

`make run` starts `src/nertzh.py` and its bot loop in the attended terminal; it
is not a boot-time service. It runs only on localhost at `ENGINE_API_PORT`
(default `8082`) and uses `ENV=demo` by default. When
`LIVE_TRADING_ENABLED=true`, it can send orders to the Bybit **demo**
environment. Do not set `ENV=mainnet` unless you explicitly intend to use live
funds.

## Verification

```bash
PYTHONPATH=src .venv/bin/python -m unittest discover -s tests -v
# Start Docker Desktop manually first when it is disabled at login.
docker compose up -d --wait postgres
make check
```

The unit suite and judge-facing UI do not need PostgreSQL. `make check` validates the optional engine prerequisites, so run `make db-up` before it.

## Architecture

```text
Bybit REST / WebSocket ──> optional engine (src/nertzh.py, :8082)
                                 │
                                 ├── PostgreSQL metrics snapshots
                                 └── metrics and execution logic

Context Bridge (Markdown + DuckDB) ──> demo API (src/api_app.py, :8081)
                                         ├── local UI (/web/)
                                         ├── read-only tools and metrics
                                         └── GPTClient (optional, protected)
```

The project uses one GPT implementation: `src/gpt_integration.py`. It can use an authenticated Codex session or the OpenAI API only when explicitly configured. The trading loop does not require an LLM.

## OpenAI Build Week evidence

This project was extended with Codex and GPT-5.6 during the submission period. Before submission, complete the evidence items in [docs/DEVPOST_SUBMISSION.md](docs/DEVPOST_SUBMISSION.md):

1. Verify the candidate Codex `/feedback` Session ID recorded in
   `docs/DEVPOST_SUBMISSION.md`.
2. Explain the concrete GPT-5.6 and Codex contribution in the Devpost description and video.
3. Upload the final 150-second video with English narration to a public or
   unlisted YouTube URL, then test it in a private window.
4. Confirm the public repository has the committed MIT license.

The rendered Build Week video is published with the release artifacts at
[`v0.1.0-build-week`](https://github.com/NerTzhuLz/NerTzh/releases/tag/v0.1.0-build-week).

## Documentation

- [Architecture](docs/ARCHITECTURE.md)
- [Demo runbook](docs/DEMO_RUNBOOK.md)
- [DevOps runbook](docs/ops/DEVOPS_RUNBOOK.md)
- [Devpost submission checklist](docs/DEVPOST_SUBMISSION.md)
- [Operations readiness](docs/ops/READY.md)

## Security and scope

- `.env` is local and ignored by Git. Never commit API keys or a control token.
- POST, PUT, PATCH and DELETE routes require `X-Control-Token`.
- The UI makes only local GET requests until a user submits the protected chat form.
- The project has no non-OpenAI LLM runtime dependency.
- `metrics-pg` uses `restart: unless-stopped`: if Docker Desktop is started
  later, inspect `docker ps -a` because the database container may resume. It
  never starts the engine by itself.


## Detected evidence (automated analysis)

Indexed codebase: 105 recognized source files, 555 KB.
- FastAPI (technology) — detected in the code
- HTML (language) — detected in the code
- OpenAI (technology) — detected in the code
- Python (language) — detected in the code
- PostgreSQL (technology) — claimed on Devpost, not found in the code
- AI coding agent: Codex — evidence: config files committed to the repository

## Codebase structure (from repository index)

### Files (120 of 132)

```
.codex/project.json
.env.example
.envrc
.gitignore
.vscode/mcp.json
.vscode/settings.json
AGENTS.md
archive/analysis_2026-07-13/analysis_exact.json
archive/analysis_2026-07-13/analysis_report.json
archive/analysis_2026-07-13/ANALYSIS_RESULTS.md
archive/README.md
archive/refactor_memory.json
archive/scripts_legacy/uninstall_jetbrains_snaps.sh
assets/branding/.gitkeep
assets/branding/README.md
config/regimes.json
config/sweep/default_matrix.json
config/sweep/hft_micro_quant.json
context_bridge/conversation.json
context_bridge/CURRENT_STATE.md
context_bridge/DECISIONS.md
context_bridge/TASK_QUEUE.json
context_bridge/TODO.md
data/session_2026-07-14_opcion_b.json
docker-compose.yml
docs/ARCHITECTURE.md
docs/DEMO_RUNBOOK.md
docs/DEVPOST_SUBMISSION.md
docs/ops/DEVOPS_RUNBOOK.md
docs/ops/EXECUTION_STATE_RECONCILIATION_AUDIT.md
docs/ops/HFT_MICRO_QUANT.md
docs/ops/HISTORICAL_SESSION_RECOVERY_AUDIT.md
docs/ops/READY.md
docs/ops/REPO_LAYOUT.md
docs/ops/RESULTS_JSON_SCHEMA.md
docs/ops/SWEEP_RUNBOOK.md
docs/README.md
docs/video/CAPTURE_SCRIPT.md
docs/video/NARRATION_DRAFT.srt
docs/video/NARRATION_EN.md
docs/video/QUALITY_GATE.md
docs/video/STORYBOARD.md
LICENSE
logs/.gitkeep
Makefile
pyproject.toml
README.md
scripts/activate_all_skills.sh
scripts/bridge.py
scripts/check_isolation.sh
scripts/check_ready.sh
scripts/check_tools.sh
scripts/codex_here.sh
scripts/extract_system_inventory.py
scripts/gpt_here.sh
scripts/gpt_session_https.sh
scripts/hackathon_smoke.py
scripts/mcp_context_bridge.py
scripts/mcp_hackathon.py
scripts/monitor_sweep.sh
scripts/openai_dev_shell.sh
scripts/probe_latencies.py
scripts/pycharm_fix_root.sh
scripts/pycharm_validate.py
scripts/run_engine.sh
scripts/run_hour_monitor.py
scripts/setup_all.sh
scripts/setup_pycharm.sh
scripts/snapshot_run.py
scripts/sweep_matrix.py
skills-lock.json
skills/agent-code-analyzer
skills/api-live/SKILL.md
skills/architectural-analysis
skills/auditable-control-plane-ui/agents/openai.yaml
skills/auditable-control-plane-ui/references/data-contract.md
skills/auditable-control-plane-ui/SKILL.md
skills/bybit-mcp/SKILL.md
skills/bybit-rest/SKILL.md
skills/bybit-websocket/SKILL.md
skills/console-ops/SKILL.md
skills/context-bridge/SKILL.md
skills/demo-evidence-delivery/agents/openai.yaml
skills/demo-evidence-delivery/references/evidence-rules.md
skills/demo-evidence-delivery/SKILL.md
skills/exchange-safety/SKILL.md
skills/fastapi-cloud/SKILL.md
skills/fastapi-ops/SKILL.md
skills/golden-rule-no-patches/SKILL.md
skills/hackathon/SKILL.md
skills/ml-xgboost/SKILL.md
skills/observability-stack/SKILL.md
skills/requesting-code-review
skills/ruflo
skills/SKILLS_INDEX.md
skills/sweep-monitor/SKILL.md
skills/websocket-ops/SKILL.md
src/__init__.py
src/agent_routes.py
src/api_app.py
src/bybit_mcp_service.py
src/bybit_v5.py
src/context_bridge.py
src/control_access.py
src/gpt_integration.py
src/hackathon/__init__.py
src/hackathon/fs_ops.py
src/hackathon/paths.py
src/hackathon/reason.py
src/hackathon/session.py
src/mcp_bybit/__init__.py
src/mcp_bybit/client.py
src/mcp_bybit/probes.py
src/ml_signals.py
src/models.py
src/nertzh.py
src/observability.py
src/regime_config.py
src/settings.py
src/utils.py
[12 more files omitted for size]
```

### Dependencies

- pyproject.toml: aiohttp@>=3.14.1, asyncpg@>=0.30.0, duckdb@>=1.1.3, fastapi@>=0.139.0, langfuse@>=4.14.0, mcp@>=1.28.1, numpy@>=2.5.1, openai@>=1.53.0, prometheus-client@>=0.25.0, psycopg2-binary@>=2.9.0, pydantic@>=2.13.4, python-dotenv@>=1.2.2, scikit-learn@>=1.9.0, sqlalchemy[asyncio]@>=2.0.51, uvicorn@>=0.51.0, websockets@>=16.1, xgboost@>=3.3.0

### Recent commits (newest first)

- docs: add developer profile and portfolio focus
- docs: link published demo release
- docs: link published demo release
- chore: finalize Build Week delivery evidence
- chore: finalize Build Week delivery evidence
- chore: PyCharm run configs y validación de modos
- fix: spot sell cierra long con payload condicional completo
- fix: spot payload completo sin campos linear
- revert: baseline trading loop + keep outcome handoff
- fix: spot long must close with sell order, not DB-only finalize
- fix: restore trade outcome finalization with sync handoff
- feat: regime-adaptive weights and thresholds for combined signal
- chore: simplify spot orders and dedupe agent routes
- fix: spot order payloads validated on Bybit demo + engine agent routes
- feat: integrate real trading results, fix duckdb crash & update devpost submission
- actualizasion martes
- docs: complete architecture guide for judge (no hardcoded secrets)
- feat: OpenAI GPT-5 integration + multi-agent orchestration (Build Week)
- docs: track clean IDE setup status checklist
- docs: clean JetBrains reinstall order after backup

## Key source files (fetched from GitHub, selected and truncated for size)

### AGENTS.md

```markdown
# Agents — NerTzh / `_Metrics_`

OpenAI Build Week project. **Context Bridge first** — no browser hacks, no quota bypass.

## Regla de oro (anti-Restructured)

**Ante bugs: NO parches masivos.** Preferir un parámetro / umbral / número de indicador.

Orden: reproducir → causa mínima → **cambio 1–15 líneas** → medir → solo entonces otro micro-fix.

- Prohibido reescribir el motor “por un umbral”.
- Si es red/API/WS: `python scripts/probe_latencies.py` antes de tocar arquitectura.
- Skill: `skills/golden-rule-no-patches/SKILL.md`
- Frase: *Un número bien puesto vale más que un parche de trescientas líneas.*

## Context Bridge (obligatorio al empezar)

```text
ChatGPT / Codex / Grok / PyCharm
        │  (paste autorizado o CLI)
        ▼
 co                     ntext_bridge/     ← fuente de verdad legible
 data/context_bridge.duckdb  ← historial (no SQLite)
```

```bash
cd /home/angel/Documentos/_Metrics_
./scripts/bridge.py status      # leer antes de codear
./scripts/bridge.py sync-bot    # snapshot logs/results.json
./scripts/bridge.py paste assistant "…texto que el humano pegó de ChatGPT…"
```

Files: `CURRENT_STATE.md`, `TASK_QUEUE.json`, `DECISIONS.md`, `TODO.md`, `conversation.json`  
Skill: `skills/context-bridge/SKILL.md`  
MCP local: `scripts/mcp_context_bridge.py` (registrado en `~/.grok/config.toml`)  
MCP hackathon (fs + reason): `scripts/mcp_hackathon.py` → `metrics-hackathon`  
Módulo: `src/hackathon/` · sesión HTTPS: `./scripts/gpt_session_https.sh` / `make gpt-session`

## Storage map

| Data | Store |
|------|--------|
| Trading / metrics bot | **PostgreSQL** `metrics-pg:5433` |
| Market TS (optional) | **QuestDB** when running |
| Multi-agent memory | **DuckDB** + markdown bridge |
| ~~SQLite for bridge~~ | **No** |

## LLM / API discipline

- Do **not** spam OpenAI/Codex API for memory recovery — use the bridge.
- Codex usage limits are account-side; bridge does not bypass them.
- Optional analysis: `gpt_integration.py` (API key or Codex when available).

## Trading safety

- Default `ENV=demo`. Mainnet only if human asks.

## Run

```bash
make check
make run
./scripts/codex_here.sh   # when quota allows
```

## Skills runtime (consola / exchange / WS)

Índice: `skills/SKILLS_INDEX.md`  
Cargar `console-ops`, `bybit-rest`, `bybit-websocket`, `exchange-safety`, `api-live` en sesiones de runtime.

```

### context_bridge/TODO.md

```markdown
# TODO

- [ ] Read `context_bridge/CURRENT_STATE.md` before coding
- [ ] After meaningful work: update DECISIONS.md + TASK_QUEUE.json
- [ ] Demo video + `/feedback` session id for Devpost
- [ ] Logo in `assets/branding/logo.png`
- [ ] Avoid saturating OpenAI/Codex API — batch context here

```

### docker-compose.yml

```yaml
services:
  postgres:
    image: postgres:16
    container_name: metrics-pg
    restart: unless-stopped
    environment:
      POSTGRES_USER: metrics
      POSTGRES_PASSWORD: metrics_pass
      POSTGRES_DB: metrics_db
    ports:
      - "5433:5432"
    volumes:
      - metrics_pg_data:/var/lib/postgresql/data
    healthcheck:
      test: ["CMD-SHELL", "pg_isready -U metrics -d metrics_db"]
      interval: 5s
      timeout: 5s
      retries: 10

volumes:
  metrics_pg_data:

```

### pyproject.toml

```
[project]
name = "metrics"
version = "0.1.0"
description = "NertzMetalEngine — Bybit spot metrics engine (OpenAI Build Week)"
readme = "README.md"
requires-python = ">=3.12"
dependencies = [
    "aiohttp>=3.14.1",
    "asyncpg>=0.30.0",
    "duckdb>=1.1.3",
    "fastapi>=0.139.0",
    "langfuse>=4.14.0",
    "mcp>=1.28.1",
    "numpy>=2.5.1",
    "openai>=1.53.0",
    "prometheus-client>=0.25.0",
    "psycopg2-binary>=2.9.0",
    "pydantic>=2.13.4",
    "python-dotenv>=1.2.2",
    "scikit-learn>=1.9.0",
    "sqlalchemy[asyncio]>=2.0.51",
    "uvicorn>=0.51.0",
    "websockets>=16.1",
    "xgboost>=3.3.0",
]

[build-system]
requires = ["hatchling"]
build-backend = "hatchling.build"

[tool.hatch.build.targets.wheel]
packages = ["src"]

[tool.uv]
package = false

```

### scripts/hackathon_smoke.py

```python
#!/usr/bin/env python3
from hackathon import list_tree, session_status
import json

print(json.dumps(session_status(), indent=2, default=str)[:800])
print("entries", len(list_tree(".", max_entries=20)))
```

### src/control_access.py

```python
"""Fail-closed authorization helpers for HTTP control-plane requests."""

from __future__ import annotations

from hmac import compare_digest
from typing import Optional


def control_token_is_valid(expected: Optional[str], provided: Optional[str]) -> bool:
    """Accept only an explicitly configured, matching control token."""
    return bool(expected and provided and compare_digest(expected, provided))

```

### tests/test_control_access.py

```python
import unittest

from control_access import control_token_is_valid


class ControlAccessTests(unittest.TestCase):
    def test_rejects_missing_or_wrong_token(self):
        self.assertFalse(control_token_is_valid(None, "token"))
        self.assertFalse(control_token_is_valid("token", None))
        self.assertFalse(control_token_is_valid("token", "wrong"))

    def test_accepts_matching_token(self):
        self.assertTrue(control_token_is_valid("token", "token"))

```

### tests/test_settings_ports.py

```python
import os
import unittest
from unittest.mock import patch

from settings import ConfigSettings


class EnginePortSettingsTests(unittest.TestCase):
    def test_engine_port_defaults_to_a_separate_local_port(self):
        with patch.dict(os.environ, {"ENGINE_API_PORT": "8082"}, clear=False):
            settings = ConfigSettings()

        self.assertEqual(settings.ENGINE_API_PORT, 8082)

    def test_engine_port_rejects_out_of_range_values(self):
        with patch.dict(os.environ, {"ENGINE_API_PORT": "70000"}, clear=False):
            with self.assertRaises(ValueError):
                ConfigSettings()


if __name__ == "__main__":
    unittest.main()

```

### scripts/monitor_sweep.sh

```shell
#!/usr/bin/env bash
# Monitorea una barrida en curso (consola)
set -euo pipefail
ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
RUN_ID="${1:-}"
if [ -z "$RUN_ID" ]; then
  # latest run dir
  RUN_ID=$(ls -1dt "$ROOT/logs/runs"/sweep_* 2>/dev/null | head -1 | xargs -r basename)
fi
if [ -z "$RUN_ID" ]; then
  echo "usage: $0 <run_id>"; exit 1
fi
DIR="$ROOT/logs/runs/$RUN_ID"
echo "Monitoring $DIR (Ctrl+C stop)"
while true; do
  clear
  date -u +"UTC %Y-%m-%dT%H:%M:%SZ"
  echo "=== manifest ==="
  cat "$DIR/manifest.json" 2>/dev/null | head -20 || echo "(no manifest yet)"
  echo
  echo "=== last 8 combos ==="
  tail -8 "$DIR/index.jsonl" 2>/dev/null | while read -r line; do
    echo "$line" | python3 -c "import sys,json; d=json.loads(sys.stdin.read()); print(d.get('combo_id'), d.get('status'), d.get('params'))" 2>/dev/null || echo "$line"
  done
  echo
  echo "=== engine health :${ENGINE_API_PORT:-8082} ==="
  curl -sS -m 2 "http://127.0.0.1:${ENGINE_API_PORT:-8082}/health" 2>/dev/null || echo "down"
  sleep 3
done

```

### scripts/pycharm_fix_root.sh

```shell
#!/usr/bin/env bash
# Reset PyCharm project root to _Metrics_ (not parent Documentos/).
set -euo pipefail

ROOT="$(cd "$(dirname "$0")/.." && pwd)"
WS_ID="3GSlshgrhMbDP380WvnmvGXnKEv"
JB="$HOME/.config/JetBrains/PyCharm2026.1"

echo "==> Fixing PyCharm root: $ROOT"

# Stop PyCharm so it does not overwrite .idea on exit.
if pgrep -x pycharm >/dev/null 2>&1 || pgrep -f '/snap/pycharm/.*/bin/pycharm' >/dev/null 2>&1; then
  echo "==> Closing PyCharm..."
  pkill -x pycharm 2>/dev/null || pkill -f '/snap/pycharm/.*/bin/pycharm' 2>/dev/null || true
  sleep 2
fi

# Remove duplicate/broken module descriptors inside .idea/.
rm -f "$ROOT/.idea/_Metrics_.iml" "$ROOT/.idea/metrics.iml"

# Drop cached workspace that pins Documentos as module root.
rm -f "$JB/workspace/${WS_ID}.xml" "$JB/workspace/${WS_ID}.xml.bak"

echo "==> Module file: $ROOT/_Metrics_.iml"
echo "==> Reopen with: pycharm \"$ROOT\""

if command -v pycharm >/dev/null 2>&1; then
  nohup pycharm "$ROOT" >/dev/null 2>&1 &
  echo "==> PyCharm relaunch requested."
else
  echo "==> pycharm CLI not found; open manually: $ROOT"
fi
```

[90 more indexed source files omitted to keep this export small. The full file list is in the Codebase structure section above.]