Skip to content

feat(kernel): add macro-micro multi-turn AI flow with trace#1404

Draft
nn87200 wants to merge 31 commits intoNoFxAiOS:devfrom
nn87200:feature/macro-micro-ai
Draft

feat(kernel): add macro-micro multi-turn AI flow with trace#1404
nn87200 wants to merge 31 commits intoNoFxAiOS:devfrom
nn87200:feature/macro-micro-ai

Conversation

@nn87200
Copy link

@nn87200 nn87200 commented Mar 7, 2026

📝 Description

Adds macro-micro multi-turn AI flow: macro → deep-dives (per symbol) → position check. Supports preview, test run, live trading, backtest, and debate. Single-turn flow unchanged. UI shows per-step prompts when multi-turn is enabled.


🎯 Type of Change

  • ✨ New feature
  • 🐛 Bug fix (defensive nil checks, primary timeframe fallback, AI response truncation)
  • 💥 Breaking change
  • ♻️ Refactoring
  • ⚡ Performance improvement
  • 🔒 Security fix
  • 🔧 Build/config change

🔗 Related Issues

  • Closes #
  • Related to #

📋 Changes Made

  • API: preview-prompt returns steps for macro-micro; test run runs full flow with trace
  • Kernel: GetFullDecisionMacroMicroWithTrace, per-symbol bias/risk/conviction in macro output
  • Trader/Backtest: persist and display multi-turn steps; hide single-turn prompts when steps exist
  • Debate: per-participant macro-micro market context
  • Market: primary timeframe fallback when normalization fails
  • Backtest: replay_only incompatible with macro-micro; symbolSeries nil checks

🧪 Testing

Test Environment

  • OS: Linux, macOS
  • Go Version: (local)
  • Exchange: Hyperliquid
  • AI Models: Gemini, Grok

Manual Testing

  • Tested on Linux
  • Tested on macOS
  • Hyperliquid exchange
  • Gemini AI
  • Grok AI
  • Backtest without multi-turn
  • Testnet (if applicable)

Test Results

  • Backend: go test ./... (kernel schema tests may fail pre-existing)
  • Build: go build -o nofx
  • Frontend: npm run build
  • Live trading: verified macro-micro flow with Hyperliquid, Gemini, Grok
  • Backtest: macro-micro flow, replay_only blocked when enabled

🔒 Security Considerations

  • No API keys or secrets hardcoded
  • User inputs properly validated
  • N/A (no new auth paths)

⚡ Performance Impact

  • Macro-micro adds multiple AI calls per cycle; expected for multi-turn

✅ Checklist

Code Quality

  • Code follows project style
  • Self-review completed
  • Comments added for complex logic
  • Code compiles successfully (go build)
  • Ran go fmt

Documentation

  • Updated relevant documentation (as needed)
  • Inline comments for macro-micro flow

Git

  • Commits follow conventional format
  • Rebased on latest dev branch
  • No merge conflicts

📚 Additional Notes

Tested on Linux and macOS with Hyperliquid exchange and Gemini/Grok AI providers. Single-turn flow unchanged and backward compatible.


image

nn87200 added 14 commits March 6, 2026 23:51
- Add EnableMacroMicroFlow, MacroDeepDiveLimit to strategy config
- Add kernel macro phase (BuildMacroBrief, GetMacroDecision, symbols_for_deep_dive)
- Add GetFullDecisionMacroMicroWithTrace for multi-turn flow with step trace
- Wire macro-micro flow into API (preview-prompt, test-run), backtest, debate
- Add replay_only vs macro-micro incompatibility check
- Add DecisionStepTrace for UI display of macro/deep-dive/position-check steps
- Add MacroDeepDivePromptEditor, multi-step preview and test run UI
- Add tests for macro parsing, backtest replay check, API preview shapes, store config
- Fallback used hard-coded 5 symbols, could exceed maxDeepDives
- Add fallbackCap = min(5, maxDeepDives) when maxDeepDives > 0
- Add final truncation to maxDeepDives before returning
- Add TestRestrictDeepDiveSymbolsToContext_FallbackRespectsMaxDeepDives
- Fix AuthContext malformed register type (parse error)
- Fix duplicate 'active' key in translations (rename to strategyActiveSuffix)
- Fix TraderConfigModal strategy option label to use strategy.name
- Fix strategy-translations.ts first line comment
- Fix DecisionCard unused cycleNumber (rename to _cycleNumber)
- Add StrategyStudioMacroMicro.test.ts for prompt/test response shapes
…ions

- Add Steps column to decision_records (store)
- Use GetFullDecisionMacroMicroWithTrace when macro-micro enabled
- Populate and persist record.Steps for UI multi-turn display
- Add PostgreSQL migration for steps column
- Filter excluded symbols from SymbolsForDeepDive in ValidateAndMergeMacroOutput
- Skip excluded symbols when filling from context in restrictDeepDiveSymbolsToContext
- Position symbols kept even if excluded (for hold/close decisions)
- Add TestValidateAndMergeMacroOutput_ExcludedCoinsFiltered
…chema

- Introduce MacroSymbolEntry with symbol, bias, risk, conviction per symbol
- Update macro prompts to request per-symbol metadata (bullish/bearish/neutral)
- Support both new format (objects) and legacy (string array) in JSON parse
- Pass per-symbol metadata to deep-dive prompts for richer context
- Add SymbolStrings/NewMacroSymbolsFromStrings helpers for debate engine
- Update debate engine to use new schema
…rames

- Update logic to fall back to the first valid timeframe if the primary timeframe is not specified or fails normalization.
- Log a warning message when the primary timeframe is invalid or unsupported, providing better debugging information.
- Add StopReason to ClaudeClient response structure for better error handling.
- Log warnings for truncated responses based on stop and finish reasons, suggesting users to adjust AI_MAX_TOKENS.
- Update parsing logic to accommodate new response fields in both ClaudeClient and Client.
…ngle-turn interactions

- Modify rendering logic for system and user input prompts to only display when there are no multi-turn steps present.
- Enhance clarity in comments to indicate the conditional nature of prompt visibility.
…rames

- Update logic to fall back to the first valid timeframe if the primary timeframe is not specified or fails normalization.
- Log a warning message when the primary timeframe is invalid or unsupported, providing better debugging information.
- Add StopReason to ClaudeClient response structure for better error handling.
- Log warnings for truncated responses based on stop and finish reasons, suggesting users to adjust AI_MAX_TOKENS.
- Update parsing logic to accommodate new response fields in both ClaudeClient and Client.
…ngle-turn interactions

- Modify rendering logic for system and user input prompts to only display when there are no multi-turn steps present.
- Enhance clarity in comments to indicate the conditional nature of prompt visibility.
…nfig checks

- Add checks for nil series data in DataFeed to prevent runtime errors.
- Ensure strategy config is not nil before proceeding with macro-micro flows in GetFullDecision functions.
- Improve error messaging for better debugging in case of missing configurations.
@nn87200
Copy link
Author

nn87200 commented Mar 7, 2026

Verified that all found issues exist on the current dev branch.
e.g. in backtesting on the non multi-turn
image

@nn87200 nn87200 marked this pull request as ready for review March 7, 2026 11:23
nn87200 added 12 commits March 7, 2026 13:09
…flow

- Add explicit prompt instructions for reasoning on hold/wait
- Add extractReasoningFallback when model omits reasoning
- Add appendHoldWaitFrom to preserve hold/wait through sizing step
- Apply fallback in deep-dive, position-check, and GetSymbolDeepDive
- Set record.CycleNumber from callCount so UI shows correct cycle
- Use pos.OpenTime for UpdateTime (entry time for holding duration)
- Add Entry time UTC timestamp to macro position brief
…uration to positions

- Use cycleNumber+1 instead of callCount for ctx.CallCount in trader prompt
  (matches record cycle number in UI)
- Add EntryTime to store.PositionSnapshot and backtest snapshotPositions
- Add precomputed Holding duration and prompt instruction in macro brief
  (Entry time - Time at top; do not use Runtime)
…time and current open positions

- Replace "Draft decisions" section with "Current open positions" that lists each position's details including entry time, quantity, value, and PnL.
- Ensure clarity in the prompt by providing a structured overview of open positions before presenting draft decisions.
- Resolve TraderConfigModal: use activeTag (upstream rename from strategyActiveSuffix)
- Resolve AuthContext: single-line register return type (upstream)
- Resolve translations: activeTag in en/zh/id
- Macro: return raw response from GetMacroDecision for deep-dive context
- Deep-dive: include macro AI assessment in user prompt; return raw response for position-check
- Position check: include deep-dive responses for open-position symbols in user prompt
- Sizing: already receives all merged decisions (no change)
- Debate: update GetMacroDecision call sites for 3-value return
nn87200 added 2 commits March 10, 2026 18:00
- Resolve api/strategy.go: add minimax case from dev, keep single SetAPIKey after switch
…etAPIKey calls

- Updated getAIClientForUserModel to set API keys for all providers within their respective cases, removing the redundant call after the switch statement. This enhances code clarity and maintainability.
@nn87200 nn87200 marked this pull request as draft March 12, 2026 11:32
nn87200 added 3 commits March 12, 2026 12:40
…isk parameters

- Added MinRiskRewardRatio and MinPositionSize to decision validation functions to improve risk management.
- Updated user prompts to reflect new margin constraints and detailed explanations for risk-reward ratios, enhancing clarity for users.
- Adjusted related functions to accommodate the new parameters, ensuring comprehensive decision-making guidance.
…trading decisions

- Replaced the previous decision validation method with a new function to filter invalid open_long/open_short decisions, downgrading them to "wait" if they fail risk/reward or size criteria.
- Introduced a new function to merge stop loss and take profit values from pre-adjusted decisions into adjusted decisions, ensuring critical parameters are retained.
- Updated macro brief generation to use a consistent parameter for OI and NetFlow summaries, improving clarity in reporting.
- Adjusted tests to align with the new validation parameters, ensuring comprehensive coverage.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant