diff --git a/api/strategy.go b/api/strategy.go index 1555ca6207..df0fad8196 100644 --- a/api/strategy.go +++ b/api/strategy.go @@ -669,6 +669,7 @@ func (s *Server) handleStrategyTestRun(c *gin.Context) { MarketDataMap: marketDataMap, QuantDataMap: quantDataMap, VergexDataMap: vergexDataMap, + AdanosSentimentMap: engine.FetchAdanosSentimentBatch(symbols), OIRankingData: oiRankingData, NetFlowRankingData: netFlowRankingData, PriceRankingData: priceRankingData, diff --git a/api/strategy_adanos_test.go b/api/strategy_adanos_test.go new file mode 100644 index 0000000000..ea6541e4f0 --- /dev/null +++ b/api/strategy_adanos_test.go @@ -0,0 +1,159 @@ +package api + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "nofx/store" + "reflect" + "strings" + "testing" + + "github.com/gin-gonic/gin" +) + +func TestAdanosCredentialNeverEntersSharedStrategyConfig(t *testing.T) { + st, err := store.New(t.TempDir() + "/nofx.db") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + t.Setenv("ADANOS_API_KEY", "fixture-server-only") + s := &Server{store: st} + router := gin.New() + router.Use(func(c *gin.Context) { c.Set("user_id", c.GetHeader("X-Fixture-User")); c.Next() }) + router.POST("/strategies", s.handleCreateStrategy) + router.GET("/public", s.handlePublicStrategies) + router.POST("/strategies/:id/duplicate", s.handleDuplicateStrategy) + request := func(method, path, user, body string) *httptest.ResponseRecorder { + req := httptest.NewRequest(method, path, strings.NewReader(body)) + req.Header.Set("Content-Type", "application/json") + req.Header.Set("X-Fixture-User", user) + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + return recorder + } + created := request(http.MethodPost, "/strategies", "owner", `{"name":"Fixture","is_public":true,"config_visible":true,"config":{"strategy_type":"ai_trading","ai_config":{"indicators":{"enable_adanos_sentiment":true,"adanos_api_key":"fixture-unshipped-config-key","adanos_source":"reddit_crypto"}}}}`) + if created.Code != http.StatusOK { + t.Fatalf("create status %d", created.Code) + } + var id struct { + ID string `json:"id"` + } + if err := json.Unmarshal(created.Body.Bytes(), &id); err != nil { + t.Fatal(err) + } + public := request(http.MethodGet, "/public", "", "") + if public.Code != http.StatusOK { + t.Fatalf("public status %d", public.Code) + } + if strings.Contains(public.Body.String(), "fixture-unshipped-config-key") || strings.Contains(public.Body.String(), "adanos_api_key") || strings.Contains(public.Body.String(), "fixture-server-only") { + t.Error("public config exposed an Adanos credential") + } + duplicate := request(http.MethodPost, "/strategies/"+id.ID+"/duplicate", "owner", `{"name":"Duplicate"}`) + if duplicate.Code != http.StatusOK { + t.Fatalf("duplicate status %d", duplicate.Code) + } + var dupID struct { + ID string `json:"id"` + } + if err := json.Unmarshal(duplicate.Body.Bytes(), &dupID); err != nil { + t.Fatal(err) + } + dup, err := st.Strategy().Get("owner", dupID.ID) + if err != nil { + t.Fatal(err) + } + if strings.Contains(dup.Config, "adanos_api_key") { + t.Error("duplicate persisted an Adanos credential") + } + denied := request(http.MethodPost, "/strategies/"+id.ID+"/duplicate", "other", `{"name":"Unauthorized"}`) + if denied.Code == http.StatusOK { + t.Error("cross-user duplicate unexpectedly allowed") + } + var listing struct { + Strategies []struct { + Config json.RawMessage `json:"config"` + } `json:"strategies"` + } + if err := json.Unmarshal(public.Body.Bytes(), &listing); err != nil { + t.Fatal(err) + } + if len(listing.Strategies) != 1 { + t.Fatalf("public rows=%d", len(listing.Strategies)) + } + copyBody, err := json.Marshal(map[string]any{"name": "Public copy", "config": listing.Strategies[0].Config}) + if err != nil { + t.Fatal(err) + } + copyResponse := request(http.MethodPost, "/strategies", "other", string(copyBody)) + if copyResponse.Code != http.StatusOK { + t.Fatalf("copy status %d", copyResponse.Code) + } + if err := json.Unmarshal(copyResponse.Body.Bytes(), &dupID); err != nil { + t.Fatal(err) + } + copied, err := st.Strategy().Get("other", dupID.ID) + if err != nil { + t.Fatal(err) + } + if strings.Contains(copied.Config, "adanos_api_key") { + t.Error("public cross-user copy persisted an Adanos credential") + } +} + +func TestAdanosPartialUpdatePreservesTradingConfig(t *testing.T) { + st, err := store.New(t.TempDir() + "/nofx.db") + if err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = st.Close() }) + config := store.GetDefaultStrategyConfig("en") + config.CoinSource.SourceType = "static" + config.CoinSource.StaticCoins = []string{"xyz:AAPL"} + config.CoinSource.ExcludedCoins = []string{"BTCUSDT"} + config.Indicators.EnableEMA = true + config.RiskControl.BTCETHMaxLeverage = 3 + config.RiskControl.AltcoinMaxLeverage = 5 + config.ClampLimits() + strategy := &store.Strategy{ID: "fixture", UserID: "owner", Name: "Fixture", IsPublic: true, ConfigVisible: true} + if err := strategy.SetConfig(&config); err != nil { + t.Fatal(err) + } + if err := st.Strategy().Create(strategy); err != nil { + t.Fatal(err) + } + want, err := strategy.ParseConfig() + if err != nil { + t.Fatal(err) + } + want.Indicators.EnableAdanosSentiment = true + want.Indicators.AdanosSource = "reddit_stocks" + want.Indicators.AdanosDays = 3 + want.Indicators.AdanosMaxSymbols = 2 + s := &Server{store: st} + router := gin.New() + router.Use(func(c *gin.Context) { c.Set("user_id", "owner"); c.Next() }) + router.PUT("/strategies/:id", s.handleUpdateStrategy) + req := httptest.NewRequest(http.MethodPut, "/strategies/fixture", strings.NewReader(`{"is_public":true,"config_visible":true,"config":{"ai_config":{"indicators":{"enable_adanos_sentiment":true,"adanos_source":"reddit_stocks","adanos_days":3,"adanos_max_symbols":2,"adanos_api_key":"fixture-must-drop"}}}}`)) + req.Header.Set("Content-Type", "application/json") + recorder := httptest.NewRecorder() + router.ServeHTTP(recorder, req) + if recorder.Code != http.StatusOK { + t.Fatalf("update status %d", recorder.Code) + } + updated, err := st.Strategy().Get("owner", "fixture") + if err != nil { + t.Fatal(err) + } + got, err := updated.ParseConfig() + if err != nil { + t.Fatal(err) + } + if !reflect.DeepEqual(got, want) { + t.Fatalf("optional update changed trading config: got=%+v want=%+v", got, want) + } + if !updated.IsPublic || !updated.ConfigVisible || strings.Contains(updated.Config, "adanos_api_key") { + t.Fatal("optional update changed sharing or persisted credentials") + } +} diff --git a/docs/architecture/STRATEGY_MODULE.md b/docs/architecture/STRATEGY_MODULE.md index 664626fbbc..1b7ab2569f 100644 --- a/docs/architecture/STRATEGY_MODULE.md +++ b/docs/architecture/STRATEGY_MODULE.md @@ -228,6 +228,7 @@ func (e *StrategyEngine) fetchMarketDataWithStrategy(symbols []string) map[strin | **Volume** | `EnableVolume` | Raw volume data | | **OI** | `EnableOI` | Open interest data | | **Funding Rate** | `EnableFundingRate` | Funding rate | +| **Adanos Market Sentiment** | `EnableAdanosSentiment` | Optional social, news, and prediction-market sentiment enrichment | ### 2.5 Quant Data (Optional) @@ -256,6 +257,40 @@ QuantData { } ``` +### 2.6 Adanos Market Sentiment (Optional) + +Adanos is a disabled-by-default external sentiment source. When `EnableAdanosSentiment` +is true, the strategy engine enriches selected symbols with Adanos sentiment before +building the AI prompt. Missing credentials, HTTP errors, or empty responses do +not abort decisions. The synchronous fetch can take up to 15 seconds. +Set `ADANOS_API_KEY` on the server. Credentials are not stored in strategy config +or sent to the browser, public strategy listings, or strategy copies. + +```go +Indicators: IndicatorConfig{ + EnableAdanosSentiment: true, + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, +} +``` + +Supported sources are `reddit_crypto`, `reddit_stocks`, `x_stocks`, `news_stocks`, +and `polymarket_stocks`. The default origin is `https://api.adanos.com`. +`ADANOS_BASE_URL` retains an explicit origin override. `AdanosDays` becomes an +inclusive UTC `from`/`to` window. No HTTP `days` parameter is sent. + +Reddit Crypto accepts native crypto symbols and pairs. Stock sources accept only +recognized native stock identities with an unchanged API ticker. Unsupported +assets, including commodities, indices, forex, unknown XYZ assets, and unmapped +foreign listings, are skipped with a log message. Stock sources never receive +crypto pairs. Selecting an unsupported source does not fall back to another source. +Polymarket `trade_count` stays distinct from social/news `mentions`. Null metrics +are omitted, not converted to zero. API and decoding errors leave the optional +context empty. A missing key skips the request. Configure the feed in Strategy +Studio or `ai_config.indicators`; credentials come only from the server environment. +See the [Adanos API docs](https://api.adanos.com/docs/). + --- ## 3. System Prompt diff --git a/docs/architecture/STRATEGY_MODULE.zh-CN.md b/docs/architecture/STRATEGY_MODULE.zh-CN.md index 1a3ce6c3f7..bddcde1780 100644 --- a/docs/architecture/STRATEGY_MODULE.zh-CN.md +++ b/docs/architecture/STRATEGY_MODULE.zh-CN.md @@ -228,6 +228,7 @@ func (e *StrategyEngine) fetchMarketDataWithStrategy(symbols []string) map[strin | **Volume** | `EnableVolume` | 原始成交量数据 | | **OI** | `EnableOI` | 持仓量数据 | | **Funding Rate** | `EnableFundingRate` | 资金费率 | +| **Adanos Market Sentiment** | `EnableAdanosSentiment` | 可选的社交、新闻和预测市场情绪增强 | ### 2.5 量化数据 (可选) @@ -256,6 +257,35 @@ QuantData { } ``` +### 2.6 Adanos 市场情绪 (可选) + +Adanos 是默认关闭的外部情绪数据源。启用 `EnableAdanosSentiment` 后, +策略引擎会在构建 AI 提示词前为已选币种补充 Adanos 情绪数据。请求错误不会中止 +交易决策:缺少凭证、HTTP 错误或空响应都会被记录并跳过。 + +```go +Indicators: IndicatorConfig{ + EnableAdanosSentiment: true, + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, +} +``` + +支持的数据源包括 `reddit_crypto`、`reddit_stocks`、`x_stocks`、 +`news_stocks` 和 `polymarket_stocks`。Adanos API 文档: +https://api.adanos.com/docs/。 + +默认地址为 `https://api.adanos.com`,可用 `ADANOS_BASE_URL` 显式覆盖。 +`AdanosDays` 转为含首尾日期的 UTC `from`/`to`,不发送 HTTP `days`。 +Reddit Crypto 仅接收加密资产;股票来源仅接收已识别且 API 代码不变的股票。 +商品、指数、外汇、未知 XYZ 资产和未映射的境外上市代码会跳过并记录日志。 +Polymarket 的 `trade_count` 不会标记为 `mentions`,空指标不会转换成零。 +缺少密钥时不发送请求,来源无效或请求失败时不切换来源。 +在 Strategy Studio 或 `ai_config.indicators` 中配置。密钥仅使用后端环境变量 +`ADANOS_API_KEY`,不存入策略、不发送到浏览器,也不进入公开策略或复制结果。 +同步请求最多耗时 15 秒。 + --- ## 3. 系统提示词 (System Prompt) diff --git a/kernel/adanos_contract_test.go b/kernel/adanos_contract_test.go new file mode 100644 index 0000000000..9c5d459ded --- /dev/null +++ b/kernel/adanos_contract_test.go @@ -0,0 +1,80 @@ +package kernel + +import ( + "net/http" + "net/http/httptest" + "nofx/market" + "nofx/provider/adanos" + "nofx/store" + "strings" + "testing" +) + +func TestAdanosContractRejectsWrongAssetClass(t *testing.T) { + for _, tc := range []struct { + source string + symbols []string + }{ + {adanos.SourceXStocks, []string{"BTCUSDT", "ETH", "xyz:GOLD", "xyz:SKHX", "xyz:SMSN"}}, + {adanos.SourceRedditCrypto, []string{"xyz:AAPL", "AAPL", "GOLD"}}, + } { + t.Run(tc.source, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; _, _ = w.Write([]byte(`[]`)) })) + defer server.Close() + t.Setenv("ADANOS_BASE_URL", server.URL) + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "fixture") + config.Indicators.AdanosSource = tc.source + result := NewStrategyEngine(&config).FetchAdanosSentimentBatch(tc.symbols) + if calls != 0 || len(result) != 0 { + t.Fatalf("unsupported asset reached HTTP: calls=%d result=%v", calls, result) + } + }) + } +} + +func TestAdanosContractPromptRespectsDisableAndSource(t *testing.T) { + config := store.GetDefaultStrategyConfig("en") + ctx := &Context{CandidateCoins: []CandidateCoin{{Symbol: "BTCUSDT"}}, MarketDataMap: map[string]*market.Data{"BTCUSDT": {Symbol: "BTCUSDT"}}, AdanosSentimentMap: map[string]*adanos.Sentiment{"BTC": {Symbol: "BTC", Source: adanos.SourceXStocks, BuzzScore: floatPtr(99)}, "BTCUSDT": {Symbol: "BTCUSDT", Source: adanos.SourceRedditCrypto, BuzzScore: floatPtr(88)}}} + if prompt := NewStrategyEngine(&config).BuildUserPrompt(ctx); strings.Contains(prompt, "Adanos Market Sentiment") { + t.Fatal("disabled feed leaked into prompt") + } + config.Indicators.EnableAdanosSentiment = true + config.Indicators.AdanosSource = adanos.SourceXStocks + if prompt := NewStrategyEngine(&config).BuildUserPrompt(ctx); strings.Contains(prompt, "Adanos Market Sentiment") { + t.Fatal("crypto asset received stock or stale feed sentiment") + } +} + +func TestAdanosContractOptionalFailures(t *testing.T) { + for _, tc := range []struct { + name, key, body string + status int + calls int + }{ + {"no key", "", "", 200, 0}, + {"rate limited", "fixture", "private fixture", 429, 1}, + {"bad json", "fixture", "{", 200, 1}, + {"empty", "fixture", `{"tokens":[]}`, 200, 1}, + } { + t.Run(tc.name, func(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + calls++ + w.WriteHeader(tc.status) + _, _ = w.Write([]byte(tc.body)) + })) + defer server.Close() + t.Setenv("ADANOS_API_KEY", tc.key) + t.Setenv("ADANOS_BASE_URL", server.URL) + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + result := NewStrategyEngine(&config).FetchAdanosSentimentBatch([]string{"BTCUSDT"}) + if len(result) != 0 || calls != tc.calls { + t.Fatalf("optional failure returned data or requested without a key: result=%v calls=%d", result, calls) + } + }) + } +} diff --git a/kernel/adanos_sentiment_test.go b/kernel/adanos_sentiment_test.go new file mode 100644 index 0000000000..bf9ed94cfe --- /dev/null +++ b/kernel/adanos_sentiment_test.go @@ -0,0 +1,314 @@ +package kernel + +import ( + "encoding/json" + "net/http" + "net/http/httptest" + "nofx/market" + "nofx/provider/adanos" + "nofx/store" + "strings" + "testing" +) + +func TestFetchAdanosSentimentBatchDisabled(t *testing.T) { + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = false + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"BTCUSDT"}) + if len(got) != 0 { + t.Fatalf("disabled Adanos sentiment returned %d entries, want 0", len(got)) + } +} + +func TestFetchAdanosSentimentBatchUsesOptionalAPIKeyAndLimit(t *testing.T) { + var gotPath string + var gotSymbols string + var gotFrom, gotTo, gotDays string + var gotAPIKey string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotSymbols = r.URL.Query().Get("symbols") + gotDays = r.URL.Query().Get("days") + gotFrom = r.URL.Query().Get("from") + gotTo = r.URL.Query().Get("to") + gotAPIKey = r.Header.Get("X-API-Key") + + _ = json.NewEncoder(w).Encode([]map[string]any{ + { + "symbol": "BTC", + "source": "reddit_crypto", + "buzz_score": 88.5, + "sentiment_score": 0.42, + "mentions": 144, + "trend": "rising", + }, + }) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_test") + config.Indicators.AdanosSource = adanos.SourceRedditCrypto + config.Indicators.AdanosDays = 3 + config.Indicators.AdanosMaxSymbols = 1 + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"BTCUSDT", "ETHUSDT"}) + if gotPath != "/reddit/crypto/v1/compare" { + t.Fatalf("path = %q, want Adanos crypto compare endpoint", gotPath) + } + if gotSymbols != "BTC" { + t.Fatalf("symbols query = %q, want only BTC because max symbols is 1", gotSymbols) + } + if gotDays != "" || gotFrom == "" || gotTo == "" { + t.Fatalf("expected explicit UTC dates and no days, got from=%q to=%q days=%q", gotFrom, gotTo, gotDays) + } + if gotAPIKey != "sk_live_test" { + t.Fatalf("API key header = %q, want configured key", gotAPIKey) + } + if got["BTCUSDT"] == nil { + t.Fatal("expected BTCUSDT sentiment mapped from BTC response") + } +} + +func TestFetchAdanosSentimentBatchIgnoresBlankSymbols(t *testing.T) { + var gotSymbols string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotSymbols = r.URL.Query().Get("symbols") + _ = json.NewEncoder(w).Encode([]map[string]any{{"symbol": "BTC", "buzz_score": 72.0}}) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_test") + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"", " ", "$BTC"}) + if gotSymbols != "BTC" { + t.Fatalf("symbols query = %q, want only BTC", gotSymbols) + } + if got["BTCUSDT"] == nil { + t.Fatal("expected BTCUSDT sentiment") + } +} + +func TestFetchAdanosSentimentBatchNormalizesCryptoPairs(t *testing.T) { + var gotSymbols string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotSymbols = r.URL.Query().Get("symbols") + _ = json.NewEncoder(w).Encode([]map[string]any{ + {"symbol": "BTC", "buzz_score": 72.0}, + {"symbol": "ETH", "buzz_score": 71.0}, + {"symbol": "SOL", "buzz_score": 70.0}, + }) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_test") + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"BTC/USD", "ETH-USDC", "SOL_USDT"}) + if gotSymbols != "BTC,ETH,SOL" { + t.Fatalf("symbols query = %q, want normalized crypto bases", gotSymbols) + } + for _, symbol := range []string{"BTCUSDT", "ETHUSDT", "SOLUSDT"} { + if got[symbol] == nil { + t.Fatalf("expected %s sentiment", symbol) + } + } +} + +func TestFetchAdanosSentimentBatchFallsBackToEnvAPIKey(t *testing.T) { + var gotAPIKey string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotAPIKey = r.Header.Get("X-API-Key") + _ = json.NewEncoder(w).Encode([]map[string]any{{"symbol": "BTC", "buzz_score": 72.0}}) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + t.Setenv("ADANOS_API_KEY", "sk_live_env") + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"BTCUSDT"}) + if gotAPIKey != "sk_live_env" { + t.Fatalf("API key header = %q, want env key", gotAPIKey) + } + if got["BTCUSDT"] == nil { + t.Fatal("expected BTCUSDT sentiment") + } +} + +func TestFetchAdanosSentimentBatchKeepsStockTickers(t *testing.T) { + var gotTickers string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotTickers = r.URL.Query().Get("tickers") + _ = json.NewEncoder(w).Encode([]map[string]any{{"ticker": "AAPL", "buzz_score": 72.0}}) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_test") + config.Indicators.AdanosSource = adanos.SourceXStocks + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"AAPL", "xyz:MSFT", "NVDAUSDT"}) + if gotTickers != "AAPL,MSFT" { + t.Fatalf("tickers query = %q, want only native stock tickers", gotTickers) + } + if got["AAPL"] == nil { + t.Fatal("expected AAPL sentiment") + } +} + +func TestFetchAdanosSentimentForContextPrioritizesPositions(t *testing.T) { + var gotSymbols string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotSymbols = r.URL.Query().Get("symbols") + _ = json.NewEncoder(w).Encode([]map[string]any{{"symbol": "ETH", "buzz_score": 72.0}}) + })) + defer server.Close() + + t.Setenv("ADANOS_BASE_URL", server.URL) + + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_test") + config.Indicators.AdanosMaxSymbols = 1 + engine := NewStrategyEngine(&config) + + ctx := &Context{ + Positions: []PositionInfo{{Symbol: "ETHUSDT"}}, + CandidateCoins: []CandidateCoin{{Symbol: "BTCUSDT", Sources: []string{"static"}}}, + MarketDataMap: map[string]*market.Data{ + "ADAUSDT": {Symbol: "ADAUSDT"}, + }, + } + + got := engine.FetchAdanosSentimentForContext(ctx) + if gotSymbols != "ETH" { + t.Fatalf("symbols query = %q, want position symbol ETH first", gotSymbols) + } + if got["ETHUSDT"] == nil { + t.Fatal("expected ETHUSDT sentiment") + } +} + +func TestBuildUserPromptIncludesAdanosSentimentWithoutAPIKey(t *testing.T) { + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + t.Setenv("ADANOS_API_KEY", "sk_live_secret") + engine := NewStrategyEngine(&config) + + ctx := &Context{ + CurrentTime: "2026-04-17 08:00:00 UTC", + RuntimeMinutes: 10, + CallCount: 2, + Account: AccountInfo{ + TotalEquity: 1000, + AvailableBalance: 800, + PositionCount: 0, + }, + CandidateCoins: []CandidateCoin{{Symbol: "BTCUSDT", Sources: []string{"static"}}}, + MarketDataMap: map[string]*market.Data{ + "BTCUSDT": { + Symbol: "BTCUSDT", + CurrentPrice: 65000, + }, + }, + AdanosSentimentMap: map[string]*adanos.Sentiment{ + "BTCUSDT": { + Symbol: "BTCUSDT", + Source: adanos.SourceRedditCrypto, + BuzzScore: floatPtr(88.5), + SentimentScore: floatPtr(0.42), + Mentions: intPtr(144), + Trend: "rising", + }, + }, + } + + prompt := engine.BuildUserPrompt(ctx) + for _, want := range []string{ + "Adanos Market Sentiment", + "buzz_score=88.50", + "sentiment_score=0.420", + "mentions=144", + "trend=rising", + } { + if !strings.Contains(prompt, want) { + t.Fatalf("prompt missing %q:\n%s", want, prompt) + } + } + if strings.Contains(prompt, "sk_live_secret") { + t.Fatal("prompt must not include Adanos API keys") + } +} + +func TestBuildUserPromptFindsStockSentimentForXyzSymbols(t *testing.T) { + config := store.GetDefaultStrategyConfig("en") + config.Indicators.EnableAdanosSentiment = true + config.Indicators.AdanosSource = adanos.SourceXStocks + engine := NewStrategyEngine(&config) + + ctx := &Context{ + CurrentTime: "2026-04-17 08:00:00 UTC", + RuntimeMinutes: 10, + CallCount: 2, + Account: AccountInfo{ + TotalEquity: 1000, + AvailableBalance: 800, + }, + CandidateCoins: []CandidateCoin{{Symbol: "xyz:AAPL", Sources: []string{"static"}}}, + MarketDataMap: map[string]*market.Data{ + "xyz:AAPL": { + Symbol: "xyz:AAPL", + CurrentPrice: 180, + }, + }, + AdanosSentimentMap: map[string]*adanos.Sentiment{ + "AAPL": { + Symbol: "AAPL", + Source: adanos.SourceXStocks, + BuzzScore: floatPtr(70.5), + }, + }, + } + + prompt := engine.BuildUserPrompt(ctx) + if !strings.Contains(prompt, "AAPL Adanos Market Sentiment") { + t.Fatalf("prompt missing stock Adanos sentiment:\n%s", prompt) + } +} + +func floatPtr(value float64) *float64 { + return &value +} + +func intPtr(value int) *int { + return &value +} diff --git a/kernel/engine.go b/kernel/engine.go index 65c8492d53..1e3a6a3e45 100644 --- a/kernel/engine.go +++ b/kernel/engine.go @@ -8,6 +8,7 @@ import ( "net/http" "nofx/logger" "nofx/market" + "nofx/provider/adanos" "nofx/provider/hyperliquid" "nofx/provider/nofxos" "nofx/provider/vergex" @@ -110,6 +111,7 @@ type Context struct { OIRankingData *nofxos.OIRankingData `json:"-"` // Market-wide OI ranking data NetFlowRankingData *nofxos.NetFlowRankingData `json:"-"` // Market-wide fund flow ranking data PriceRankingData *nofxos.PriceRankingData `json:"-"` // Market-wide price gainers/losers + AdanosSentimentMap map[string]*adanos.Sentiment `json:"-"` // Optional Adanos market sentiment by symbol BTCETHLeverage int `json:"-"` AltcoinLeverage int `json:"-"` Timeframes []string `json:"-"` @@ -963,6 +965,148 @@ func (e *StrategyEngine) FetchExternalData() (map[string]interface{}, error) { return externalData, nil } +// FetchAdanosSentimentForContext fetches optional Adanos sentiment for symbols +// already selected by the strategy. Missing configuration returns an empty map. +func (e *StrategyEngine) FetchAdanosSentimentForContext(ctx *Context) map[string]*adanos.Sentiment { + return e.FetchAdanosSentimentBatch(collectAdanosSymbols(ctx, e.config.Indicators.AdanosSource)) +} + +// FetchAdanosSentimentBatch fetches Adanos compare data for up to the configured +// symbol limit. Errors omit optional context rather than abort the decision. +func (e *StrategyEngine) FetchAdanosSentimentBatch(symbols []string) map[string]*adanos.Sentiment { + result := make(map[string]*adanos.Sentiment) + + indicators := e.config.Indicators + if !indicators.EnableAdanosSentiment { + return result + } + + apiKey := strings.TrimSpace(os.Getenv("ADANOS_API_KEY")) + if apiKey == "" { + logger.Infof("⚠️ Adanos sentiment enabled but no API key configured; skipping") + return result + } + + symbols = uniqueAdanosSymbols(symbols, indicators.AdanosSource) + maxSymbols := indicators.AdanosMaxSymbols + if maxSymbols <= 0 || maxSymbols > 10 { + maxSymbols = 10 + } + if len(symbols) > maxSymbols { + symbols = symbols[:maxSymbols] + } + if len(symbols) == 0 { + return result + } + + ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second) + defer cancel() + + client := adanos.NewClient(adanos.Config{ + BaseURL: os.Getenv("ADANOS_BASE_URL"), + APIKey: apiKey, + Source: indicators.AdanosSource, + Days: indicators.AdanosDays, + }) + + data, err := client.Compare(ctx, symbols) + if err != nil { + logger.Infof("⚠️ Failed to fetch Adanos sentiment: %v", err) + return result + } + + logger.Infof("✓ Adanos sentiment ready for %d symbols", len(data)) + return data +} + +func collectAdanosSymbols(ctx *Context, source string) []string { + if ctx == nil { + return nil + } + + symbols := make([]string, 0, len(ctx.Positions)+len(ctx.CandidateCoins)+len(ctx.MarketDataMap)) + for _, pos := range ctx.Positions { + symbols = append(symbols, pos.Symbol) + } + for _, coin := range ctx.CandidateCoins { + symbols = append(symbols, coin.Symbol) + } + + marketSymbols := make([]string, 0, len(ctx.MarketDataMap)) + for symbol := range ctx.MarketDataMap { + marketSymbols = append(marketSymbols, symbol) + } + sort.Strings(marketSymbols) + for _, symbol := range marketSymbols { + symbols = append(symbols, symbol) + } + return uniqueAdanosSymbols(symbols, source) +} + +func uniqueAdanosSymbols(symbols []string, source string) []string { + seen := make(map[string]bool, len(symbols)) + unique := make([]string, 0, len(symbols)) + for _, symbol := range symbols { + normalized := normalizeAdanosSymbol(symbol, source) + if normalized == "" || seen[normalized] { + if normalized == "" && strings.TrimSpace(symbol) != "" { + logger.Infof("Adanos: skipping unsupported asset for selected source") + } + continue + } + seen[normalized] = true + unique = append(unique, normalized) + } + return unique +} + +func normalizeAdanosSymbol(symbol string, source string) string { + symbol = strings.ToUpper(strings.TrimSpace(symbol)) + if symbol == "" { + return "" + } + symbol = strings.TrimPrefix(symbol, "$") + + source = adanos.NormalizeSource(source) + if source == adanos.SourceRedditCrypto { + if strings.HasPrefix(symbol, "XYZ:") { + return "" + } + normalized := normalizeAdanosCryptoSymbol(symbol) + base := strings.TrimSuffix(normalized, "USDT") + if hyperliquid.IsXYZAsset(base) || strings.ContainsAny(base, ":., ") { + return "" + } + return normalized + } + switch source { + case adanos.SourceRedditStocks, adanos.SourceXStocks, adanos.SourceNewsStocks, adanos.SourcePolymarketStocks: + default: + return "" + } + // Only native stock identities with an unchanged API ticker are supported. + base := hyperliquid.NormalizeXYZAlias(symbol) + if !hyperliquid.IsStockPerp(base) || base == "SKHX" || strings.HasSuffix(symbol, "USDT") { + return "" + } + return base +} + +func normalizeAdanosCryptoSymbol(symbol string) string { + normalized := strings.ToUpper(symbol) + normalized = strings.ReplaceAll(normalized, "/", "") + normalized = strings.ReplaceAll(normalized, "_", "") + normalized = strings.ReplaceAll(normalized, "-SWAP", "") + normalized = strings.ReplaceAll(normalized, "-", "") + + for _, suffix := range []string{"USDT", "USDC", "USD"} { + if strings.HasSuffix(normalized, suffix) && len(normalized) > len(suffix) { + return strings.TrimSuffix(normalized, suffix) + "USDT" + } + } + return normalized + "USDT" +} + func (e *StrategyEngine) fetchSingleExternalSource(source store.ExternalDataSource) (interface{}, error) { // SSRF Protection: Validate URL before making request if err := security.ValidateURL(source.URL); err != nil { diff --git a/kernel/engine_analysis.go b/kernel/engine_analysis.go index a9687e482b..71d565c7ab 100644 --- a/kernel/engine_analysis.go +++ b/kernel/engine_analysis.go @@ -103,6 +103,10 @@ func GetFullDecisionWithStrategy(ctx *Context, mcpClient mcp.AIClient, engine *S } } + if ctx.AdanosSentimentMap == nil { + ctx.AdanosSentimentMap = engine.FetchAdanosSentimentForContext(ctx) + } + // 2. Build System Prompt using strategy engine riskConfig := engine.GetRiskControlConfig() systemPrompt := engine.BuildSystemPrompt(ctx.Account.TotalEquity, variant) diff --git a/kernel/engine_prompt.go b/kernel/engine_prompt.go index d51e59e460..ca63f61211 100644 --- a/kernel/engine_prompt.go +++ b/kernel/engine_prompt.go @@ -3,6 +3,7 @@ package kernel import ( "fmt" "nofx/market" + "nofx/provider/adanos" "nofx/provider/nofxos" "nofx/provider/vergex" "nofx/store" @@ -741,6 +742,11 @@ func (e *StrategyEngine) writeAvailableIndicators(sb *strings.Builder, zh bool) if indicators.EnableFundingRate { sb.WriteString("- " + label("Funding rate", "Funding rate") + "\n") } + + if indicators.EnableAdanosSentiment { + sb.WriteString("- Adanos market sentiment (social/news/prediction-market buzz, direction, and trend)\n") + } + if len(e.config.CoinSource.StaticCoins) > 0 || e.config.CoinSource.UseAI500 || e.config.CoinSource.UseOITop { sb.WriteString("- " + label("AI500 / OI_Top filter tags (if available)", "AI500 / OI_Top filter tags (if available)") + "\n") } @@ -897,6 +903,9 @@ func (e *StrategyEngine) BuildUserPrompt(ctx *Context) string { sb.WriteString(e.formatQuantData(quantData)) } } + if sentiment := e.lookupAdanosSentiment(ctx, coin.Symbol); sentiment != nil { + sb.WriteString(e.formatAdanosSentiment(sentiment)) + } if data := vergexDataForSymbol(ctx, coin.Symbol); data != nil { sb.WriteString(e.formatVergexData(data)) } @@ -965,6 +974,9 @@ func (e *StrategyEngine) formatPositionInfo(index int, pos PositionInfo, ctx *Co sb.WriteString(e.formatQuantData(quantData)) } } + if sentiment := e.lookupAdanosSentiment(ctx, pos.Symbol); sentiment != nil { + sb.WriteString(e.formatAdanosSentiment(sentiment)) + } sb.WriteString("\n") } // Signals remain essential even when the candle request failed. Position @@ -1307,6 +1319,65 @@ func (e *StrategyEngine) formatQuantData(data *QuantData) string { return sb.String() } +func (e *StrategyEngine) lookupAdanosSentiment(ctx *Context, symbol string) *adanos.Sentiment { + if !e.config.Indicators.EnableAdanosSentiment || ctx == nil { + return nil + } + source := adanos.NormalizeSource(e.config.Indicators.AdanosSource) + normalized := normalizeAdanosSymbol(symbol, source) + if normalized == "" { + return nil + } + if sentiment := ctx.AdanosSentimentMap[normalized]; sentiment != nil && sentiment.Source == source { + return sentiment + } + return nil +} + +func (e *StrategyEngine) formatAdanosSentiment(data *adanos.Sentiment) string { + if data == nil { + return "" + } + + var sb strings.Builder + sb.WriteString(fmt.Sprintf("🧭 %s Adanos Market Sentiment", data.Symbol)) + if data.Source != "" { + sb.WriteString(fmt.Sprintf(" (%s)", data.Source)) + } + sb.WriteString(":\n") + + var fields []string + if data.BuzzScore != nil { + fields = append(fields, fmt.Sprintf("buzz_score=%.2f", *data.BuzzScore)) + } + if data.SentimentScore != nil { + fields = append(fields, fmt.Sprintf("sentiment_score=%.3f", *data.SentimentScore)) + } + if data.Mentions != nil { + fields = append(fields, fmt.Sprintf("mentions=%d", *data.Mentions)) + } + if data.TradeCount != nil { + fields = append(fields, fmt.Sprintf("trade_count=%d", *data.TradeCount)) + } + if data.Trend != "" { + fields = append(fields, fmt.Sprintf("trend=%s", data.Trend)) + } + if data.BullishPct != nil { + fields = append(fields, fmt.Sprintf("bullish_pct=%.2f", *data.BullishPct)) + } + if data.BearishPct != nil { + fields = append(fields, fmt.Sprintf("bearish_pct=%.2f", *data.BearishPct)) + } + + if len(fields) == 0 { + return "" + } + + sb.WriteString(strings.Join(fields, ", ")) + sb.WriteString("\n\n") + return sb.String() +} + func formatFlowValue(v float64) string { sign := "" if v >= 0 { diff --git a/provider/adanos/client.go b/provider/adanos/client.go new file mode 100644 index 0000000000..ea486ee6a1 --- /dev/null +++ b/provider/adanos/client.go @@ -0,0 +1,351 @@ +package adanos + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + DefaultBaseURL = "https://api.adanos.com" + + SourceRedditCrypto = "reddit_crypto" + SourceRedditStocks = "reddit_stocks" + SourceXStocks = "x_stocks" + SourceNewsStocks = "news_stocks" + SourcePolymarketStocks = "polymarket_stocks" +) + +type sourceEndpoint struct { + Path string + QueryParam string + Crypto bool +} + +var sourceEndpoints = map[string]sourceEndpoint{ + SourceRedditCrypto: {Path: "/reddit/crypto/v1/compare", QueryParam: "symbols", Crypto: true}, + SourceRedditStocks: {Path: "/reddit/stocks/v1/compare", QueryParam: "tickers"}, + SourceXStocks: {Path: "/x/stocks/v1/compare", QueryParam: "tickers"}, + SourceNewsStocks: {Path: "/news/stocks/v1/compare", QueryParam: "tickers"}, + SourcePolymarketStocks: {Path: "/polymarket/stocks/v1/compare", QueryParam: "tickers"}, +} + +type Config struct { + BaseURL string + APIKey string + Source string + Days int + HTTPClient *http.Client +} + +type Client struct { + baseURL string + apiKey string + source string + days int + httpClient *http.Client +} + +type Sentiment struct { + Symbol string + Source string + BuzzScore *float64 + SentimentScore *float64 + Mentions *int + TradeCount *int + Trend string + BullishPct *float64 + BearishPct *float64 +} + +func NewClient(cfg Config) *Client { + baseURL := strings.TrimSpace(cfg.BaseURL) + if baseURL == "" { + baseURL = DefaultBaseURL + } + + source := NormalizeSource(cfg.Source) + days := cfg.Days + if days <= 0 { + days = 7 + } + + httpClient := cfg.HTTPClient + if httpClient == nil { + httpClient = &http.Client{Timeout: 10 * time.Second} + } + + return &Client{ + baseURL: strings.TrimRight(baseURL, "/"), + apiKey: strings.TrimSpace(cfg.APIKey), + source: source, + days: days, + httpClient: httpClient, + } +} + +func NormalizeSource(source string) string { + normalized := strings.ToLower(strings.TrimSpace(source)) + normalized = strings.ReplaceAll(normalized, "-", "_") + if normalized == "" { + return SourceRedditCrypto + } + return normalized +} + +func (c *Client) Compare(ctx context.Context, symbols []string) (map[string]*Sentiment, error) { + result := make(map[string]*Sentiment) + if c.apiKey == "" { + return result, fmt.Errorf("adanos API key is required") + } + + endpoint, ok := sourceEndpoints[c.source] + if !ok { + return result, fmt.Errorf("unsupported Adanos source: %s", c.source) + } + apiSymbols, aliases := normalizeSymbols(symbols, endpoint.Crypto) + if len(apiSymbols) == 0 { + return result, nil + } + + requestURL, err := c.compareURL(endpoint, apiSymbols) + if err != nil { + return result, err + } + + req, err := http.NewRequestWithContext(ctx, http.MethodGet, requestURL, nil) + if err != nil { + return result, err + } + req.Header.Set("Accept", "application/json") + req.Header.Set("X-API-Key", c.apiKey) + + resp, err := c.httpClient.Do(req) + if err != nil { + return result, err + } + defer resp.Body.Close() + + body, err := io.ReadAll(resp.Body) + if err != nil { + return result, err + } + if resp.StatusCode < 200 || resp.StatusCode >= 300 { + return result, fmt.Errorf("adanos compare request failed: status %d", resp.StatusCode) + } + + var payload any + if err := json.Unmarshal(body, &payload); err != nil { + return result, err + } + + for _, item := range extractRows(payload) { + sentiment := parseSentiment(item, c.source) + if sentiment.Symbol == "" { + continue + } + + apiSymbol := normalizeAPISymbol(sentiment.Symbol) + original, ok := aliases[apiSymbol] + if !ok { + continue + } + sentiment.Symbol = original + result[sentiment.Symbol] = sentiment + } + + return result, nil +} + +func (c *Client) compareURL(endpoint sourceEndpoint, symbols []string) (string, error) { + base, err := url.Parse(c.baseURL) + if err != nil { + return "", err + } + pathBase := strings.TrimRight(base.Path, "/") + base.Path = pathBase + endpoint.Path + + q := base.Query() + q.Set(endpoint.QueryParam, strings.Join(symbols, ",")) + q.Del("days") + to := time.Now().UTC() + q.Set("from", to.AddDate(0, 0, 1-c.days).Format("2006-01-02")) + q.Set("to", to.Format("2006-01-02")) + base.RawQuery = q.Encode() + return base.String(), nil +} + +func normalizeSymbols(symbols []string, crypto bool) ([]string, map[string]string) { + seen := make(map[string]bool) + aliases := make(map[string]string) + apiSymbols := make([]string, 0, len(symbols)) + + for _, symbol := range symbols { + original := normalizeAPISymbol(symbol) + if original == "" { + continue + } + + apiSymbol := original + if crypto { + apiSymbol = strings.NewReplacer("/", "", "_", "", "-SWAP", "", "-", "").Replace(apiSymbol) + apiSymbol = trimQuoteSuffix(apiSymbol) + } + if apiSymbol == "" || seen[apiSymbol] { + continue + } + + seen[apiSymbol] = true + aliases[apiSymbol] = original + apiSymbols = append(apiSymbols, apiSymbol) + } + + return apiSymbols, aliases +} + +func normalizeAPISymbol(symbol string) string { + symbol = strings.ToUpper(strings.TrimSpace(symbol)) + symbol = strings.TrimPrefix(symbol, "$") + return symbol +} + +func trimQuoteSuffix(symbol string) string { + for _, suffix := range []string{"USDT", "USDC", "USD"} { + if strings.HasSuffix(symbol, suffix) && len(symbol) > len(suffix) { + return strings.TrimSuffix(symbol, suffix) + } + } + return symbol +} + +func extractRows(payload any) []map[string]any { + switch data := payload.(type) { + case []any: + return mapRows(data) + case map[string]any: + for _, key := range []string{"data", "results", "items", "stocks", "tokens"} { + if rows, ok := data[key].([]any); ok { + return mapRows(rows) + } + } + if row, ok := asMap(data); ok { + return []map[string]any{row} + } + } + return nil +} + +func mapRows(rows []any) []map[string]any { + mapped := make([]map[string]any, 0, len(rows)) + for _, row := range rows { + if item, ok := asMap(row); ok { + mapped = append(mapped, item) + } + } + return mapped +} + +func asMap(value any) (map[string]any, bool) { + item, ok := value.(map[string]any) + return item, ok +} + +func parseSentiment(item map[string]any, source string) *Sentiment { + sentiment := &Sentiment{ + Symbol: firstString(item, "symbol", "ticker", "token"), + Source: source, + BuzzScore: firstFloat(item, "buzz_score", "buzz"), + SentimentScore: firstFloat(item, "sentiment_score", "sentiment"), + Mentions: firstInt(item, "mentions", "total_mentions", "mention_count"), + Trend: firstString(item, "trend"), + BullishPct: firstFloat(item, "bullish_pct", "bullish_percent"), + BearishPct: firstFloat(item, "bearish_pct", "bearish_percent"), + } + if source == SourcePolymarketStocks { + sentiment.Mentions = nil + sentiment.TradeCount = firstInt(item, "trade_count") + } + return sentiment +} + +func firstString(item map[string]any, keys ...string) string { + for _, key := range keys { + if value, ok := item[key]; ok { + switch typed := value.(type) { + case string: + if trimmed := strings.TrimSpace(typed); trimmed != "" { + return trimmed + } + } + } + } + return "" +} + +func firstFloat(item map[string]any, keys ...string) *float64 { + for _, key := range keys { + if value, ok := item[key]; ok { + if parsed, ok := parseFloat(value); ok { + return &parsed + } + } + } + return nil +} + +func firstInt(item map[string]any, keys ...string) *int { + for _, key := range keys { + if value, ok := item[key]; ok { + if parsed, ok := parseInt(value); ok { + return &parsed + } + } + } + return nil +} + +func parseFloat(value any) (float64, bool) { + switch typed := value.(type) { + case float64: + return typed, true + case float32: + return float64(typed), true + case int: + return float64(typed), true + case int64: + return float64(typed), true + case json.Number: + parsed, err := typed.Float64() + return parsed, err == nil + case string: + parsed, err := strconv.ParseFloat(strings.TrimSpace(typed), 64) + return parsed, err == nil + default: + return 0, false + } +} + +func parseInt(value any) (int, bool) { + switch typed := value.(type) { + case int: + return typed, true + case int64: + return int(typed), true + case float64: + return int(typed), true + case json.Number: + parsed, err := typed.Int64() + return int(parsed), err == nil + case string: + parsed, err := strconv.Atoi(strings.TrimSpace(typed)) + return parsed, err == nil + default: + return 0, false + } +} diff --git a/provider/adanos/client_test.go b/provider/adanos/client_test.go new file mode 100644 index 0000000000..3c34448aef --- /dev/null +++ b/provider/adanos/client_test.go @@ -0,0 +1,143 @@ +package adanos + +import ( + "context" + "encoding/json" + "net/http" + "net/http/httptest" + "testing" +) + +func TestCompareFetchesCryptoSentiment(t *testing.T) { + var gotPath string + var gotQuery string + var gotAPIKey string + + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotPath = r.URL.Path + gotQuery = r.URL.Query().Get("symbols") + gotAPIKey = r.Header.Get("X-API-Key") + + _ = json.NewEncoder(w).Encode([]map[string]any{ + { + "symbol": "BTC", + "source": "reddit", + "buzz_score": 82.5, + "sentiment_score": 0.41, + "mentions": 123, + "trend": "rising", + "bullish_pct": 67.2, + "bearish_pct": 18.4, + }, + }) + })) + defer server.Close() + + client := NewClient(Config{ + BaseURL: server.URL, + APIKey: "sk_live_test", + Source: SourceRedditCrypto, + Days: 3, + }) + + result, err := client.Compare(context.Background(), []string{"BTCUSDT", "BTCUSDT"}) + if err != nil { + t.Fatalf("Compare returned error: %v", err) + } + + if gotPath != "/reddit/crypto/v1/compare" { + t.Fatalf("path = %q, want crypto compare endpoint", gotPath) + } + if gotQuery != "BTC" { + t.Fatalf("symbols query = %q, want BTC", gotQuery) + } + if gotAPIKey != "sk_live_test" { + t.Fatalf("API key header = %q, want sk_live_test", gotAPIKey) + } + + sentiment := result["BTCUSDT"] + if sentiment == nil { + t.Fatal("expected BTCUSDT sentiment mapped back from BTC response") + } + if sentiment.Source != SourceRedditCrypto { + t.Fatalf("source = %q, want reddit_crypto", sentiment.Source) + } + if sentiment.BuzzScore == nil || *sentiment.BuzzScore != 82.5 { + t.Fatalf("buzz score = %v, want 82.5", sentiment.BuzzScore) + } + if sentiment.Mentions == nil || *sentiment.Mentions != 123 { + t.Fatalf("mentions = %v, want 123", sentiment.Mentions) + } +} + +func TestCompareSupportsStockSources(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path != "/x/stocks/v1/compare" { + t.Fatalf("path = %q, want x stocks compare endpoint", r.URL.Path) + } + if got := r.URL.Query().Get("tickers"); got != "AAPL,NVDA" { + t.Fatalf("tickers query = %q, want AAPL,NVDA", got) + } + _ = json.NewEncoder(w).Encode(map[string]any{ + "data": []map[string]any{ + {"ticker": "AAPL", "sentiment": "0.12", "total_mentions": "42"}, + }, + }) + })) + defer server.Close() + + client := NewClient(Config{ + BaseURL: server.URL, + APIKey: "sk_live_test", + Source: SourceXStocks, + }) + + result, err := client.Compare(context.Background(), []string{"AAPL", "NVDA"}) + if err != nil { + t.Fatalf("Compare returned error: %v", err) + } + if _, ok := result["AAPL"]; !ok { + t.Fatal("expected AAPL sentiment") + } +} + +func TestCompareRequiresAPIKey(t *testing.T) { + client := NewClient(Config{APIKey: ""}) + + result, err := client.Compare(context.Background(), []string{"BTCUSDT"}) + if err == nil { + t.Fatal("expected missing API key error") + } + if len(result) != 0 { + t.Fatalf("result length = %d, want 0", len(result)) + } +} + +func TestCompareReturnsStatusErrors(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + http.Error(w, "rate limited", http.StatusTooManyRequests) + })) + defer server.Close() + + client := NewClient(Config{ + BaseURL: server.URL, + APIKey: "sk_live_test", + }) + + result, err := client.Compare(context.Background(), []string{"BTCUSDT"}) + if err == nil { + t.Fatal("expected non-2xx status error") + } + if len(result) != 0 { + t.Fatalf("result length = %d, want 0", len(result)) + } +} + +func TestNormalizeSourceDefaultsToRedditCrypto(t *testing.T) { + if got := NormalizeSource(""); got != SourceRedditCrypto { + t.Fatalf("empty source = %q, want %q", got, SourceRedditCrypto) + } + if got := NormalizeSource("x-stocks"); got != SourceXStocks { + t.Fatalf("x-stocks source = %q, want %q", got, SourceXStocks) + } +} diff --git a/provider/adanos/contract_test.go b/provider/adanos/contract_test.go new file mode 100644 index 0000000000..73aba435ce --- /dev/null +++ b/provider/adanos/contract_test.go @@ -0,0 +1,107 @@ +package adanos + +import ( + "context" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestCompareContractUTCWindow(t *testing.T) { + var query string + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + query = r.URL.RawQuery + _, _ = w.Write([]byte(`{"tokens":[]}`)) + })) + defer server.Close() + before := time.Now().UTC() + _, err := NewClient(Config{BaseURL: server.URL, APIKey: "fixture", Days: 3}).Compare(context.Background(), []string{"BTC"}) + if err != nil { + t.Fatal(err) + } + after := time.Now().UTC() + if strings.Contains(query, "days=") || !strings.Contains(query, "from="+before.AddDate(0, 0, -2).Format("2006-01-02")) || !strings.Contains(query, "to="+after.Format("2006-01-02")) { + t.Fatalf("expected explicit inclusive 3-day UTC window without days, got %s", query) + } +} + +func TestCompareContractSourceIdentity(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + _, _ = w.Write([]byte(`{"stocks":[{"ticker":"AAPL","source":"reddit","trade_count":12,"buzz_score":null,"sentiment_score":null,"bullish_pct":null,"bearish_pct":null,"trend":null},{"ticker":"MSFT","trade_count":99}]}`)) + })) + defer server.Close() + result, err := NewClient(Config{BaseURL: server.URL, APIKey: "fixture", Source: SourcePolymarketStocks}).Compare(context.Background(), []string{"AAPL"}) + if err != nil { + t.Fatal(err) + } + item := result["AAPL"] + if item == nil || item.Source != SourcePolymarketStocks || item.Mentions != nil || len(result) != 1 { + t.Fatalf("source, count meaning or requested identity changed: %#v; rows=%d", item, len(result)) + } + if item.TradeCount == nil || *item.TradeCount != 12 { + t.Fatalf("Polymarket trade count lost: %#v", item) + } + if item.BuzzScore != nil || item.SentimentScore != nil || item.BullishPct != nil || item.BearishPct != nil || item.Trend != "" { + t.Fatalf("null metrics must remain absent: %#v", item) + } +} + +type roundTripFunc func(*http.Request) (*http.Response, error) + +func (f roundTripFunc) RoundTrip(req *http.Request) (*http.Response, error) { return f(req) } + +func TestCompareContractNativeSources(t *testing.T) { + for _, tc := range []struct{ source, path, param, symbol, body string }{ + {SourceRedditCrypto, "/reddit/crypto/v1/compare", "symbols", "BTC", `{"tokens":[{"symbol":"BTC","buzz_score":0,"mentions":0}]}`}, + {SourceRedditStocks, "/reddit/stocks/v1/compare", "tickers", "AAPL", `{"stocks":[{"ticker":"AAPL","buzz_score":0,"mentions":0}]}`}, + {SourceXStocks, "/x/stocks/v1/compare", "tickers", "AAPL", `{"stocks":[{"ticker":"AAPL","buzz_score":0,"mentions":0}]}`}, + {SourceNewsStocks, "/news/stocks/v1/compare", "tickers", "AAPL", `{"stocks":[{"ticker":"AAPL","buzz_score":0,"mentions":0}]}`}, + {SourcePolymarketStocks, "/polymarket/stocks/v1/compare", "tickers", "AAPL", `{"stocks":[{"ticker":"AAPL","buzz_score":0,"trade_count":0}]}`}, + } { + t.Run(tc.source, func(t *testing.T) { + transport := roundTripFunc(func(req *http.Request) (*http.Response, error) { + if req.URL.Scheme != "https" || req.URL.Host != "api.adanos.com" || req.URL.Path != tc.path || req.URL.Query().Get(tc.param) != tc.symbol { + t.Errorf("wrong source request %s", req.URL) + } + return &http.Response{StatusCode: 200, Body: io.NopCloser(strings.NewReader(tc.body)), Header: make(http.Header)}, nil + }) + result, err := NewClient(Config{APIKey: "fixture", Source: tc.source, HTTPClient: &http.Client{Transport: transport}}).Compare(context.Background(), []string{tc.symbol}) + if err != nil { + t.Fatal(err) + } + item := result[tc.symbol] + if item == nil || item.Source != tc.source || item.BuzzScore == nil || *item.BuzzScore != 0 { + t.Fatalf("zero metric or source lost: %#v", item) + } + if tc.source == SourcePolymarketStocks { + if item.Mentions != nil || item.TradeCount == nil || *item.TradeCount != 0 { + t.Fatalf("invalid trade count: %#v", item) + } + } else if item.Mentions == nil || *item.Mentions != 0 || item.TradeCount != nil { + t.Fatalf("invalid mentions: %#v", item) + } + }) + } +} + +func TestCompareContractUnknownSource(t *testing.T) { + calls := 0 + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { calls++; _, _ = w.Write([]byte(`{"tokens":[]}`)) })) + defer server.Close() + _, err := NewClient(Config{BaseURL: server.URL, APIKey: "fixture", Source: "x_crypto"}).Compare(context.Background(), []string{"BTC"}) + if err == nil || calls != 0 { + t.Fatalf("unsupported source must fail before HTTP, err=%v calls=%d", err, calls) + } +} + +func TestCompareContractErrorRedaction(t *testing.T) { + server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { http.Error(w, "fixture-private-payload", 429) })) + defer server.Close() + _, err := NewClient(Config{BaseURL: server.URL, APIKey: "fixture"}).Compare(context.Background(), []string{"BTC"}) + if err == nil || strings.Contains(err.Error(), "fixture-private-payload") || !strings.Contains(err.Error(), "429") { + t.Fatalf("status error must not echo response payload: %v", err) + } +} diff --git a/store/strategy.go b/store/strategy.go index f2e18d3431..4f0b626458 100644 --- a/store/strategy.go +++ b/store/strategy.go @@ -905,6 +905,12 @@ type IndicatorConfig struct { // external data sources ExternalDataSources []ExternalDataSource `json:"external_data_sources,omitempty"` + // Adanos market sentiment data source (optional) + EnableAdanosSentiment bool `json:"enable_adanos_sentiment,omitempty"` // whether to enrich prompts with Adanos sentiment + AdanosSource string `json:"adanos_source,omitempty"` // reddit_crypto, reddit_stocks, x_stocks, news_stocks, polymarket_stocks + AdanosDays int `json:"adanos_days,omitempty"` // lookback window, default 7 + AdanosMaxSymbols int `json:"adanos_max_symbols,omitempty"` // max symbols per compare request, default 10 + // ========== NofxOS Unified API Configuration ========== // Unified API Key for all NofxOS data sources NofxOSAPIKey string `json:"nofxos_api_key,omitempty"` @@ -1046,6 +1052,9 @@ func GetDefaultStrategyConfig(lang string) StrategyConfig { RSIPeriods: []int{7, 14}, ATRPeriods: []int{14}, BOLLPeriods: []int{20}, + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, // Hyperliquid strategies must use native Hyperliquid market data by default. // NofxOS datasets do not cover all Hyperliquid XYZ assets, so keep them off. NofxOSAPIKey: "", diff --git a/web/src/components/strategy/AdanosSentimentEditor.tsx b/web/src/components/strategy/AdanosSentimentEditor.tsx new file mode 100644 index 0000000000..592eaa12e9 --- /dev/null +++ b/web/src/components/strategy/AdanosSentimentEditor.tsx @@ -0,0 +1,109 @@ +import { ExternalLink } from 'lucide-react' +import type { IndicatorConfig } from '../../types' +import { indicator, ts } from '../../i18n/strategy-translations' + +export function AdanosSentimentEditor({ + config, + onChange, + disabled, + language, +}: { + config: IndicatorConfig + onChange: (patch: Partial) => void + disabled?: boolean + language: string +}) { + const inputClass = + 'w-full rounded-lg border border-[rgba(25,36,52,0.14)] bg-nofx-bg px-3 py-2 text-sm text-nofx-text' + return ( +
+
+ + + + {ts(indicator.adanosDocs, language)} + +
+ {config.enable_adanos_sentiment && ( +
+ + + +
+ )} +
+ ) +} diff --git a/web/src/i18n/strategy-translations.ts b/web/src/i18n/strategy-translations.ts index 8b444f908f..2c2be4ad6e 100644 --- a/web/src/i18n/strategy-translations.ts +++ b/web/src/i18n/strategy-translations.ts @@ -233,6 +233,20 @@ export const indicator = { oiDesc: { zh: '合约未平仓量', en: 'Futures open interest', es: 'Posiciones abiertas' }, fundingRate: { zh: '资金费率', en: 'Funding Rate', es: 'Funding Rate' }, fundingRateDesc: { zh: '永续合约资金费率', en: 'Perpetual funding rate', es: 'Rate de perpetuo' }, + adanosSentiment: { + zh: 'Adanos 市场情绪', + en: 'Adanos Market Sentiment', + es: 'Sentimiento Adanos', + }, + adanosSave: { + zh: '保存情绪设置', + en: 'Save sentiment settings', + es: 'Guardar ajustes de sentimiento', + }, + adanosSource: { zh: '来源', en: 'Source', es: 'Fuente' }, + adanosDays: { zh: '天数', en: 'Days', es: 'Dias' }, + adanosMaxSymbols: { zh: '最大币种数', en: 'Max Symbols', es: 'Max Simbolos' }, + adanosDocs: { zh: '文档', en: 'Docs', es: 'Docs' }, oiRanking: { zh: 'OI 排行', en: 'OI Ranking', es: 'Ranking OI' }, oiRankingDesc: { zh: '持仓量增减排行', en: 'OI change ranking', es: 'Cambios de OI' }, oiRankingNote: { zh: '显示持仓量增加/减少的币种排行,帮助发现资金流向', en: 'Shows coins with OI increase/decrease, helps identify capital flow', es: 'Identificar flujo de capital' }, diff --git a/web/src/pages/StrategyStudioPage.test.tsx b/web/src/pages/StrategyStudioPage.test.tsx new file mode 100644 index 0000000000..99e41b1b74 --- /dev/null +++ b/web/src/pages/StrategyStudioPage.test.tsx @@ -0,0 +1,93 @@ +import { afterEach, expect, it, vi } from 'vitest' +import { + cleanup, + fireEvent, + render, + screen, + waitFor, +} from '@testing-library/react' +import { MemoryRouter } from 'react-router-dom' +import type { ReactNode } from 'react' +import { StrategyStudioPage } from './StrategyStudioPage' + +const api = vi.hoisted(() => ({ + getStrategies: vi.fn(), + getSymbols: vi.fn().mockResolvedValue({ symbols: [] }), + getVergexDirectionChangeLeaderboard: vi.fn().mockResolvedValue({ items: [] }), +})) +vi.mock('../lib/api', () => ({ api })) +vi.mock('../contexts/AuthContext', () => ({ + useAuth: () => ({ token: 'fixture' }), +})) +vi.mock('../contexts/LanguageContext', () => ({ + useLanguage: () => ({ language: 'en' }), +})) +vi.mock('../components/common/DeepVoidBackground', () => ({ + DeepVoidBackground: ({ children }: { children: ReactNode }) => ( +
{children}
+ ), +})) +vi.mock('../lib/notify', () => ({ + notify: { success: vi.fn(), error: vi.fn() }, + confirmToast: vi.fn(), +})) +afterEach(() => { + cleanup() + vi.unstubAllGlobals() +}) + +it('preserves explicit optional sentiment settings when loading and saving native strategies', async () => { + api.getStrategies.mockResolvedValue([ + { + id: 'fixture', + name: 'Fixture strategy', + is_active: true, + config: { + strategy_type: 'ai_trading', + ai_config: { + coin_source: { source_type: 'static', static_coins: ['xyz:AAPL'] }, + indicators: { + klines: { primary_timeframe: '15m', primary_count: 30 }, + enable_adanos_sentiment: true, + adanos_api_key: 'fixture-key', + adanos_source: 'news_stocks', + adanos_days: 3, + adanos_max_symbols: 2, + }, + risk_control: {}, + }, + }, + }, + ]) + const fetcher = vi.fn().mockResolvedValue({ ok: true }) + vi.stubGlobal('fetch', fetcher) + render( + + + + ) + fireEvent.change(await screen.findByDisplayValue('Fixture strategy'), { + target: { value: 'Updated fixture' }, + }) + expect(screen.queryByLabelText('Adanos API Key')).toBeNull() + expect(screen.getByRole('combobox', { name: 'Source' })).toHaveValue( + 'news_stocks' + ) + fireEvent.change(screen.getByRole('spinbutton', { name: 'Max Symbols' }), { + target: { value: '3' }, + }) + fireEvent.click( + screen.getByRole('button', { name: 'Save sentiment settings' }) + ) + await waitFor(() => expect(fetcher).toHaveBeenCalledOnce()) + const body = JSON.parse(fetcher.mock.calls[0][1].body) + expect(Object.keys(body.config)).toEqual(['ai_config']) + expect(Object.keys(body.config.ai_config)).toEqual(['indicators']) + expect(body.config.ai_config.indicators).toMatchObject({ + enable_adanos_sentiment: true, + adanos_source: 'news_stocks', + adanos_days: 3, + adanos_max_symbols: 3, + }) + expect(body.config.ai_config.indicators).not.toHaveProperty('adanos_api_key') +}) diff --git a/web/src/pages/StrategyStudioPage.tsx b/web/src/pages/StrategyStudioPage.tsx index 5a6b35490a..c933a6fb27 100644 --- a/web/src/pages/StrategyStudioPage.tsx +++ b/web/src/pages/StrategyStudioPage.tsx @@ -17,6 +17,8 @@ import { import { useAuth } from '../contexts/AuthContext' import { useLanguage } from '../contexts/LanguageContext' import { DeepVoidBackground } from '../components/common/DeepVoidBackground' +import { AdanosSentimentEditor } from '../components/strategy/AdanosSentimentEditor' +import { indicator, ts } from '../i18n/strategy-translations' import { api } from '../lib/api' import { confirmToast, notify } from '../lib/notify' import type { @@ -220,6 +222,10 @@ function defaultIndicators( enable_volume: false, enable_oi: false, enable_funding_rate: false, + enable_adanos_sentiment: indicators?.enable_adanos_sentiment || false, + adanos_source: indicators?.adanos_source || 'reddit_crypto', + adanos_days: indicators?.adanos_days || 7, + adanos_max_symbols: indicators?.adanos_max_symbols || 10, nofxos_api_key: '', enable_quant_data: false, enable_quant_oi: false, @@ -1162,6 +1168,46 @@ export function StrategyStudioPage() { } } + const saveAdanosSettings = async () => { + if (!token || !selectedStrategy || !indicators) return + setSaving(true) + try { + const response = await fetch( + `${API_BASE}/api/strategies/${selectedStrategy.id}`, + { + method: 'PUT', + headers: { + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ + is_public: selectedStrategy.is_public, + config_visible: selectedStrategy.config_visible, + config: { + ai_config: { + indicators: { + enable_adanos_sentiment: indicators.enable_adanos_sentiment, + adanos_source: indicators.adanos_source, + adanos_days: indicators.adanos_days, + adanos_max_symbols: indicators.adanos_max_symbols, + }, + }, + }, + }), + } + ) + if (!response.ok) throw new Error('Failed to save sentiment settings') + notify.success(ts(indicator.adanosSave, language)) + await loadStrategies(selectedStrategy.id) + } catch (err) { + notify.error( + err instanceof Error ? err.message : 'Failed to save sentiment settings' + ) + } finally { + setSaving(false) + } + } + const buildUnifiedClaw402Config = (): StrategyConfig => { const base = simplifyConfig(editingConfig) base.language = language as 'zh' | 'en' @@ -1965,6 +2011,22 @@ export function StrategyStudioPage() { ) : null} + + +
{text(language, 'Advanced settings', 'Advanced settings')} diff --git a/web/src/types/strategy.ts b/web/src/types/strategy.ts index 4919fa03b7..b144f2e6fe 100644 --- a/web/src/types/strategy.ts +++ b/web/src/types/strategy.ts @@ -145,6 +145,15 @@ export interface IndicatorConfig { atr_periods?: number[]; boll_periods?: number[]; external_data_sources?: ExternalDataSource[]; + enable_adanos_sentiment?: boolean + adanos_source?: + | 'reddit_crypto' + | 'reddit_stocks' + | 'x_stocks' + | 'news_stocks' + | 'polymarket_stocks' + adanos_days?: number + adanos_max_symbols?: number // ========== Unified NofxOS data source configuration ========== // Unified NofxOS API Key - used for all NofxOS data sources