Skip to content

Instantly share code, notes, and snippets.

@chokolademilch7
Created June 11, 2026 12:22
Show Gist options
  • Select an option

  • Save chokolademilch7/4e9380478d85c376510723c4c2d52d1f to your computer and use it in GitHub Desktop.

Select an option

Save chokolademilch7/4e9380478d85c376510723c4c2d52d1f to your computer and use it in GitHub Desktop.

bit-labo: 戦略自律進化システムの実装

現在の状態

Bit-labo は Funding Rate 裁定戦略の観測・ペーパートレードシミュレーション基盤。コードは Daytona sandbox 内の /workspace/bit-labo にあり、GitHub (chokolademilch7/bit-labo) に push 済み。

起動済みのもの

  • PostgreSQL 15: 稼働中、bitlabo DB あり、DATABASE_URL=postgresql://postgres:postgres@localhost:5432/bitlabo
  • Redis: 未起動(必要なら起動)
  • バックエンド: ビルド済み(backend/dist/)
  • フロントエンド: ビルド済み(frontend/.next/)

コード構造(モノレポ、npm workspaces)

/workspace/bit-labo/
├── packages/db/       # Prisma スキーマ + client
│   └── prisma/schema.prisma  # MarketSnapshot, FundingEvent, PaperPosition, Strategy, SignalLog, EquityCurve
├── backend/src/       # TypeScript バックエンド
│   ├── collector/     # Binance から実データ収集
│   ├── analyzer/      # シグナル評価
│   ├── simulator/     # ペーパートレードエンジン
│   │   ├── engine.ts      # メインエンジン(exit→entry→refresh→equity)
│   │   ├── conditions.ts  # 汎用条件評価器
│   │   ├── positionManager.ts
│   │   ├── pnl.ts
│   │   └── pnl.test.ts
│   ├── strategies/seed.ts # 戦略定義(1つだけseed済み)
│   ├── pipeline.ts   # 1 tick: collect→analyze→simulate
│   ├── worker.ts     # cron定期実行
│   └── config.ts     # 設定 + ALLOW_REAL_ORDERS=false ハードコード
└── frontend/         # Next.js Dashboard

現状の戦略(1つだけ)

positive_funding_cash_and_carry:
  entry: fundingApr >= 10% AND spread <= 0.05% AND volume24h >= $100M AND |basisRate| <= 1.0%
  exit:  fundingApr < 3% OR |basisRate| > 2.0% OR holdingDays > 7

戦略は strategy テーブルに JSON として保存。条件は汎用評価器(conditions.ts)で gte/lte/abs_gt などの演算子を解釈する。新しい戦略は DB INSERT だけで追加可能。

今すぐ動かすコマンド

cd /workspace/bit-labo

# 1回だけ収集
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/bitlabo node backend/dist/index.js

# worker起動(120秒間隔で pipeline を回す)
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/bitlabo node backend/dist/worker.js

# フロントエンド起動
DATABASE_URL=postgresql://postgres:postgres@localhost:5432/bitlabo node node_modules/.bin/next start frontend -p 3000

投資パラメータ(固定)

  • 初期資金: 10万円(シミュレーション用、USD換算 $10,000)
  • レバレッジ: 1x(レバレッジなし)
  • 最大ポジション数: 5
  • ポジションサイズ: 資金の10%
  • 手数料: 0.1%(常時減算)
  • スリッページ: 0.03%(常時減算)
  • ALLOW_REAL_ORDERS: false(ハードコード、実トレード不可)

実装タスク

1. worker を起動して定期収集+シミュレーションを回す

  • backend/dist/worker.js を起動(screen セッション内で永続化)
  • 120秒間隔で pipeline が回る(collect → analyze → simulate → equity)
  • 初期戦略(positive_funding_cash_and_carry)の条件を現実的な値に下げる(例: fundingApr >= 3%、現状のBTC APR +3.7% で entry できるように)

2. 1時間ごとの LLM 戦略最適化機構を実装(中核)

新しいモジュール backend/src/strategist/strategist.ts を作成:

何をするか

1時間ごとに以下を実行:

  1. パフォーマンスデータ収集: 直近1時間の全ポジション・シグナル・スナップショットを DB から取得
  2. LLM 分析: Strix vLLM に分析を依頼
  3. 戦略更新: LLM の提案に基づいて strategy テーブルの条件を UPDATE
  4. ログ: 分析結果と変更内容を記録

Strix vLLM へのアクセス方法

API Base: http://strix:8041/v1
Model: qwen3.6-35b
OpenAI-compatible API(openai ライブラリ or fetch でOK)

重要: enable_thinking: false を指定
{
  model: "qwen3.6-35b",
  messages: [...],
  chat_template_kwargs: { enable_thinking: false }
}

LLM に渡すプロンプト(日本語)

あなたは Funding Rate 裁定戦略のアナリスト兼トレーダーです。
直近のパフォーマンスデータに基づき、戦略条件の最適化を提案してください。

【現在の戦略条件】
{現在のstrategy条件をJSONで表示}

【直近1時間の市場データ】
{直近の snapshot データ: 銘柄ごとの fundingApr, spread, volume24h, basisRate}

【保有ポジション】
{現在の open ポジション一覧}

【直近のクローズ済みポジション(exit reason 付き)】
{exit 理由でソート}

【直近のシグナル評価】
{entry/exit シグナルとその評価結果}

【現在の累積損益】
{equity curve データ}

以下の4つを分析して回答してください:
1. 現在の戦略条件の問題点(チャンスを逃してないか?リスクを取リ過ぎてないか?)
2. 改善提案(具体的な条件変更案: fundingApr の閾値を X に変更、等)
3. 市場環境の変化(ボラティリティ、トレンド、相場観)
4. 新しい戦略アイデア(現在の市場環境に適した別のアプローチ)

回答は以下の JSON フォーマットで:
{
  "analysis": "分析結果の説明",
  "strategy_updates": [
    {
      "name": "positive_funding_cash_and_carry",
      "entryConditions": { "mode": "all", "rules": [...] },
      "exitConditions": { "mode": "any", "rules": [...] },
      "params": { "maxPositions": 5 }
    }
  ],
  "new_strategies": [
    {
      "name": "新しい戦略名",
      "description": "説明",
      "entryConditions": { ... },
      "exitConditions": { ... },
      "params": { ... }
    }
  ],
  "reasoning": "この判断に至った理由"
}

スケジューリング

  • node-cron で hourly ジョブを worker 内に追加
  • 初回は worker 起動時に実行
  • ジョブが重複しないように Redis ロック(既存の acquireLock を流用)

3. 戦略更新の履歴テーブル(オプション)

LLM による戦略変更の履歴を残すテーブルを Prisma に追加:

model StrategyChangeLog {
  id              BigInt   @id @default(autoincrement())
  strategyName    String
  previousEntry   Json?
  previousExit    Json?
  newEntry        Json
  newExit         Json
  analysisSummary String
  triggeredBy     String   @default("llm")
  createdAt       DateTime @default(now())
  
  @@map("strategy_change_log")
}

4. フロントエンドの改善(オプション)

  • Dashboard に「戦略変更履歴」パネル追加
  • 現在の戦略条件を表示
  • 直近の LLM 分析サマリ表示

Daytona 操作コマンドリファレンス

# サンドボックス内でコマンド実行
daytona exec <sandbox-id> -- <command>
daytona exec <sandbox-id> --cwd /workspace/bit-labo -- <command>

# バックグラウンドでサーバー起動
screen -dmS <name> bash -c 'cd /workspace/bit-labo && <command>'

# Preview URL 取得
daytona sandbox preview-url <sandbox-id> --port <port>

# ファイル一覧
daytona sandbox info <sandbox-id>

重要制約

  1. ALLOW_REAL_ORDERS は絶対に触らない。config.ts の ALLOW_REAL_ORDERS = false as const はハードコードで不変
  2. 戦略条件の変更は DB の strategy テーブルを UPDATE するだけで OK(conditions.ts が汎用評価する)
  3. すべての変更は git commit && git push して GitHub に保存すること
  4. Node.js v20.20.2, npm 10.8.2(bun はインストールされていない)
  5. Sandbox は auto-stop するので、長期運用には注意

検証基準

  • node backend/dist/index.js でデータ収集が成功すること
  • node backend/dist/worker.js で定期収集が回ること
  • Strix vLLM にリクエストが飛び、JSON が返ってくること
  • LLM の提案で strategy テーブルの条件が更新されること
  • 更新された条件で次の pipeline tick が entry 判定すること
  • 戦略変更履歴が DB に記録されること
  • フロントエンドが Preview URL で見えること
  • テストが全部通ること(npm run test in root)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment