From 32c70c5a99f4297ab47bdbbc099f7cec8ab28201 Mon Sep 17 00:00:00 2001 From: Alex Schneider Date: Fri, 17 Apr 2026 08:28:52 +0200 Subject: [PATCH 1/2] Add optional Adanos sentiment data source --- docs/architecture/STRATEGY_MODULE.md | 21 ++ docs/architecture/STRATEGY_MODULE.zh-CN.md | 21 ++ kernel/adanos_sentiment_test.go | 195 ++++++++++ kernel/engine.go | 100 ++++- kernel/engine_analysis.go | 4 + kernel/engine_prompt.go | 63 ++++ provider/adanos/client.go | 345 ++++++++++++++++++ provider/adanos/client_test.go | 111 ++++++ store/strategy.go | 11 + .../components/strategy/IndicatorEditor.tsx | 117 ++++++ web/src/i18n/strategy-translations.ts | 8 + web/src/types/strategy.ts | 5 + 12 files changed, 1000 insertions(+), 1 deletion(-) create mode 100644 kernel/adanos_sentiment_test.go create mode 100644 provider/adanos/client.go create mode 100644 provider/adanos/client_test.go diff --git a/docs/architecture/STRATEGY_MODULE.md b/docs/architecture/STRATEGY_MODULE.md index 664626fbbc..10b5946969 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,26 @@ 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. It never blocks trading decisions: missing credentials, HTTP +errors, or empty responses are logged and skipped. + +```go +Indicators: IndicatorConfig{ + EnableAdanosSentiment: true, + AdanosAPIKey: "...", // optional; falls back to ADANOS_API_KEY + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, +} +``` + +Supported sources are `reddit_crypto`, `reddit_stocks`, `x_stocks`, `news_stocks`, +and `polymarket_stocks`. See the Adanos API docs at https://api.adanos.org/docs/. + --- ## 3. System Prompt diff --git a/docs/architecture/STRATEGY_MODULE.zh-CN.md b/docs/architecture/STRATEGY_MODULE.zh-CN.md index 1a3ce6c3f7..999ec98fe2 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,26 @@ QuantData { } ``` +### 2.6 Adanos 市场情绪 (可选) + +Adanos 是默认关闭的外部情绪数据源。启用 `EnableAdanosSentiment` 后, +策略引擎会在构建 AI 提示词前为已选币种补充 Adanos 情绪数据。它不会阻塞 +交易决策:缺少凭证、HTTP 错误或空响应都会被记录并跳过。 + +```go +Indicators: IndicatorConfig{ + EnableAdanosSentiment: true, + AdanosAPIKey: "...", // 可选;为空时使用 ADANOS_API_KEY + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, +} +``` + +支持的数据源包括 `reddit_crypto`、`reddit_stocks`、`x_stocks`、 +`news_stocks` 和 `polymarket_stocks`。Adanos API 文档: +https://api.adanos.org/docs/。 + --- ## 3. 系统提示词 (System Prompt) diff --git a/kernel/adanos_sentiment_test.go b/kernel/adanos_sentiment_test.go new file mode 100644 index 0000000000..60a1d8b937 --- /dev/null +++ b/kernel/adanos_sentiment_test.go @@ -0,0 +1,195 @@ +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 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") + 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 + config.Indicators.AdanosAPIKey = "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 != "3" { + t.Fatalf("days query = %q, want 3", 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 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 + config.Indicators.AdanosAPIKey = "" + 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 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 + config.Indicators.AdanosAPIKey = "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 + config.Indicators.AdanosAPIKey = "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 floatPtr(value float64) *float64 { + return &value +} + +func intPtr(value int) *int { + return &value +} diff --git a/kernel/engine.go b/kernel/engine.go index a5e1f0ceec..da54333bfc 100644 --- a/kernel/engine.go +++ b/kernel/engine.go @@ -6,13 +6,15 @@ import ( "fmt" "io" "net/http" - "os" "nofx/logger" "nofx/market" + "nofx/provider/adanos" "nofx/provider/hyperliquid" "nofx/provider/nofxos" "nofx/security" "nofx/store" + "os" + "sort" "strings" "time" ) @@ -106,6 +108,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:"-"` @@ -611,6 +614,101 @@ 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)) +} + +// FetchAdanosSentimentBatch fetches Adanos compare data for up to the configured +// symbol limit. It is intentionally best-effort and never blocks trading. +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(indicators.AdanosAPIKey) + if apiKey == "" { + apiKey = strings.TrimSpace(os.Getenv("ADANOS_API_KEY")) + } + if apiKey == "" { + logger.Infof("⚠️ Adanos sentiment enabled but no API key configured; skipping") + return result + } + + symbols = uniqueSymbols(symbols) + 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) []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 uniqueSymbols(symbols) +} + +func uniqueSymbols(symbols []string) []string { + seen := make(map[string]bool, len(symbols)) + unique := make([]string, 0, len(symbols)) + for _, symbol := range symbols { + normalized := market.Normalize(symbol) + if normalized == "" || seen[normalized] { + continue + } + seen[normalized] = true + unique = append(unique, normalized) + } + return unique +} + 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 8c08ba0b93..64c764b6ca 100644 --- a/kernel/engine_analysis.go +++ b/kernel/engine_analysis.go @@ -101,6 +101,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 9f1b7ee896..4b91fbcb7a 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/store" "strings" @@ -211,6 +212,10 @@ func (e *StrategyEngine) writeAvailableIndicators(sb *strings.Builder) { sb.WriteString("- 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("- AI500 / OI_Top filter tags (if available)\n") } @@ -368,6 +373,9 @@ func (e *StrategyEngine) BuildUserPrompt(ctx *Context) string { sb.WriteString(e.formatQuantData(quantData)) } } + if sentiment := lookupAdanosSentiment(ctx, coin.Symbol); sentiment != nil { + sb.WriteString(e.formatAdanosSentiment(sentiment)) + } sb.WriteString("\n") } sb.WriteString("\n") @@ -433,6 +441,9 @@ func (e *StrategyEngine) formatPositionInfo(index int, pos PositionInfo, ctx *Co sb.WriteString(e.formatQuantData(quantData)) } } + if sentiment := lookupAdanosSentiment(ctx, pos.Symbol); sentiment != nil { + sb.WriteString(e.formatAdanosSentiment(sentiment)) + } sb.WriteString("\n") } @@ -751,6 +762,58 @@ func (e *StrategyEngine) formatQuantData(data *QuantData) string { return sb.String() } +func lookupAdanosSentiment(ctx *Context, symbol string) *adanos.Sentiment { + if ctx == nil || len(ctx.AdanosSentimentMap) == 0 { + return nil + } + normalized := market.Normalize(symbol) + if sentiment, ok := ctx.AdanosSentimentMap[normalized]; ok { + return sentiment + } + return ctx.AdanosSentimentMap[symbol] +} + +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.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..d9d35e39ed --- /dev/null +++ b/provider/adanos/client.go @@ -0,0 +1,345 @@ +package adanos + +import ( + "context" + "encoding/json" + "fmt" + "io" + "net/http" + "net/url" + "strconv" + "strings" + "time" +) + +const ( + DefaultBaseURL = "https://api.adanos.org" + + 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 + 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 _, ok := sourceEndpoints[normalized]; ok { + return normalized + } + return SourceRedditCrypto +} + +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 := sourceEndpoints[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: %s", resp.StatusCode, strings.TrimSpace(string(body))) + } + + 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) + if original, ok := aliases[apiSymbol]; ok { + 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.Set("days", strconv.Itoa(c.days)) + 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 = 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, "$") + symbol = strings.ReplaceAll(symbol, "/", "") + symbol = strings.ReplaceAll(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 { + return &Sentiment{ + Symbol: firstString(item, "symbol", "ticker", "token"), + Source: firstStringWithDefault(item, source, "source", "platform"), + BuzzScore: firstFloat(item, "buzz_score", "buzz"), + SentimentScore: firstFloat(item, "sentiment_score", "sentiment"), + Mentions: firstInt(item, "mentions", "total_mentions", "mention_count", "trade_count"), + Trend: firstString(item, "trend"), + BullishPct: firstFloat(item, "bullish_pct", "bullish_percent"), + BearishPct: firstFloat(item, "bearish_pct", "bearish_percent"), + } +} + +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 firstStringWithDefault(item map[string]any, fallback string, keys ...string) string { + if value := firstString(item, keys...); value != "" { + return value + } + return fallback +} + +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..c912effb14 --- /dev/null +++ b/provider/adanos/client_test.go @@ -0,0 +1,111 @@ +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 != "reddit" { + t.Fatalf("source = %q, want reddit", 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 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/store/strategy.go b/store/strategy.go index 8860e8febb..3b1bc5f99a 100644 --- a/store/strategy.go +++ b/store/strategy.go @@ -206,6 +206,13 @@ 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 + AdanosAPIKey string `json:"adanos_api_key,omitempty"` // optional; falls back to ADANOS_API_KEY env var + 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"` @@ -340,6 +347,10 @@ func GetDefaultStrategyConfig(lang string) StrategyConfig { RSIPeriods: []int{7, 14}, ATRPeriods: []int{14}, BOLLPeriods: []int{20}, + // Adanos market sentiment is optional and disabled by default. + AdanosSource: "reddit_crypto", + AdanosDays: 7, + AdanosMaxSymbols: 10, // NofxOS unified API key NofxOSAPIKey: "cm_568c67eae410d912c54c", // Quant data diff --git a/web/src/components/strategy/IndicatorEditor.tsx b/web/src/components/strategy/IndicatorEditor.tsx index e54c1b5662..05a4e8ec29 100644 --- a/web/src/components/strategy/IndicatorEditor.tsx +++ b/web/src/components/strategy/IndicatorEditor.tsx @@ -6,6 +6,14 @@ import { NofxSelect } from '../ui/select' // Default NofxOS API Key const DEFAULT_NOFXOS_API_KEY = 'cm_568c67eae410d912c54c' +const adanosSourceOptions = [ + { value: 'reddit_crypto', label: 'Reddit Crypto' }, + { value: 'reddit_stocks', label: 'Reddit Stocks' }, + { value: 'x_stocks', label: 'X Stocks' }, + { value: 'news_stocks', label: 'News Stocks' }, + { value: 'polymarket_stocks', label: 'Polymarket Stocks' }, +] + interface IndicatorEditorProps { config: IndicatorConfig onChange: (config: IndicatorConfig) => void @@ -117,6 +125,7 @@ export function IndicatorEditor({ // Check if any NofxOS feature is enabled const hasNofxosEnabled = config.enable_quant_data || config.enable_oi_ranking || config.enable_netflow_ranking || config.enable_price_ranking const hasApiKey = !!config.nofxos_api_key + const hasAdanosApiKey = !!config.adanos_api_key return (
@@ -684,6 +693,114 @@ export function IndicatorEditor({
))} + +
+
+
+
+
+ {ts(indicator.adanosSentiment, language)} + e.stopPropagation()} + > + + {ts(indicator.adanosDocs, language)} + +
+

{ts(indicator.adanosSentimentDesc, language)}

+
+ !disabled && onChange({ + ...config, + enable_adanos_sentiment: e.target.checked, + ...(e.target.checked && !config.adanos_source ? { adanos_source: 'reddit_crypto' } : {}), + ...(e.target.checked && !config.adanos_days ? { adanos_days: 7 } : {}), + ...(e.target.checked && !config.adanos_max_symbols ? { adanos_max_symbols: 10 } : {}), + })} + disabled={disabled} + className="w-4 h-4 rounded accent-emerald-500" + /> +
+ + {config.enable_adanos_sentiment && ( +
+
+ + !disabled && onChange({ ...config, adanos_api_key: e.target.value })} + disabled={disabled} + placeholder={ts(indicator.adanosApiKeyPlaceholder, language)} + className="w-full pl-8 pr-3 py-2 rounded text-xs font-mono" + style={{ + background: '#1E2329', + border: hasAdanosApiKey ? '1px solid rgba(14, 203, 129, 0.3)' : '1px solid #2B3139', + color: '#EAECEF', + }} + /> +
+ +
+ + + +
+ + {!hasAdanosApiKey && ( +

{ts(indicator.adanosApiKeyEnvFallback, language)}

+ )} +
+ )} +
diff --git a/web/src/i18n/strategy-translations.ts b/web/src/i18n/strategy-translations.ts index 995ed2f427..41b3f0b939 100644 --- a/web/src/i18n/strategy-translations.ts +++ b/web/src/i18n/strategy-translations.ts @@ -229,6 +229,14 @@ 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' }, + adanosSentimentDesc: { zh: '可选 - 将社交、新闻或预测市场情绪加入 AI 上下文', en: 'Optional - enriches AI context with social, news or prediction-market sentiment', es: 'Opcional - agrega sentimiento social, noticias o mercados predictivos' }, + adanosApiKeyPlaceholder: { zh: '输入 Adanos API Key(可选)', en: 'Enter Adanos API Key (optional)', es: 'Ingresar Adanos API Key (opcional)' }, + adanosApiKeyEnvFallback: { zh: '留空时后端会尝试使用 ADANOS_API_KEY 环境变量。', en: 'Leave blank to let the backend use the ADANOS_API_KEY environment variable.', es: 'Dejar vacio para usar la variable de entorno ADANOS_API_KEY.' }, + 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/types/strategy.ts b/web/src/types/strategy.ts index 9c8de57532..9db7094f77 100644 --- a/web/src/types/strategy.ts +++ b/web/src/types/strategy.ts @@ -118,6 +118,11 @@ export interface IndicatorConfig { atr_periods?: number[]; boll_periods?: number[]; external_data_sources?: ExternalDataSource[]; + enable_adanos_sentiment?: boolean; + adanos_api_key?: string; + adanos_source?: 'reddit_crypto' | 'reddit_stocks' | 'x_stocks' | 'news_stocks' | 'polymarket_stocks'; + adanos_days?: number; + adanos_max_symbols?: number; // ========== NofxOS 数据源统一配置 ========== // Unified NofxOS API Key - used for all NofxOS data sources From 0e3a9773a7100898d0ceda3c71d547d0aa23d79b Mon Sep 17 00:00:00 2001 From: Alex Schneider Date: Fri, 17 Apr 2026 08:40:43 +0200 Subject: [PATCH 2/2] Tighten Adanos sentiment normalization --- kernel/adanos_sentiment_test.go | 118 ++++++++++++++++++++++++++++++++ kernel/engine.go | 52 ++++++++++++-- kernel/engine_prompt.go | 3 + provider/adanos/client_test.go | 32 +++++++++ 4 files changed, 199 insertions(+), 6 deletions(-) diff --git a/kernel/adanos_sentiment_test.go b/kernel/adanos_sentiment_test.go index 60a1d8b937..f43a4cf98b 100644 --- a/kernel/adanos_sentiment_test.go +++ b/kernel/adanos_sentiment_test.go @@ -75,6 +75,62 @@ func TestFetchAdanosSentimentBatchUsesOptionalAPIKeyAndLimit(t *testing.T) { } } +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 + config.Indicators.AdanosAPIKey = "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 + config.Indicators.AdanosAPIKey = "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 @@ -101,6 +157,32 @@ func TestFetchAdanosSentimentBatchFallsBackToEnvAPIKey(t *testing.T) { } } +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 + config.Indicators.AdanosAPIKey = "sk_live_test" + config.Indicators.AdanosSource = adanos.SourceXStocks + engine := NewStrategyEngine(&config) + + got := engine.FetchAdanosSentimentBatch([]string{"AAPL", "xyz:MSFT", "NVDAUSDT"}) + if gotTickers != "AAPL,MSFT,NVDA" { + t.Fatalf("tickers query = %q, want stock tickers without crypto quote suffixes", gotTickers) + } + if got["AAPL"] == nil { + t.Fatal("expected AAPL sentiment") + } +} + func TestFetchAdanosSentimentForContextPrioritizesPositions(t *testing.T) { var gotSymbols string @@ -186,6 +268,42 @@ func TestBuildUserPromptIncludesAdanosSentimentWithoutAPIKey(t *testing.T) { } } +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 } diff --git a/kernel/engine.go b/kernel/engine.go index da54333bfc..db30df75d6 100644 --- a/kernel/engine.go +++ b/kernel/engine.go @@ -617,7 +617,7 @@ func (e *StrategyEngine) FetchExternalData() (map[string]interface{}, error) { // 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)) + return e.FetchAdanosSentimentBatch(collectAdanosSymbols(ctx, e.config.Indicators.AdanosSource)) } // FetchAdanosSentimentBatch fetches Adanos compare data for up to the configured @@ -639,7 +639,7 @@ func (e *StrategyEngine) FetchAdanosSentimentBatch(symbols []string) map[string] return result } - symbols = uniqueSymbols(symbols) + symbols = uniqueAdanosSymbols(symbols, indicators.AdanosSource) maxSymbols := indicators.AdanosMaxSymbols if maxSymbols <= 0 || maxSymbols > 10 { maxSymbols = 10 @@ -671,7 +671,7 @@ func (e *StrategyEngine) FetchAdanosSentimentBatch(symbols []string) map[string] return data } -func collectAdanosSymbols(ctx *Context) []string { +func collectAdanosSymbols(ctx *Context, source string) []string { if ctx == nil { return nil } @@ -692,14 +692,14 @@ func collectAdanosSymbols(ctx *Context) []string { for _, symbol := range marketSymbols { symbols = append(symbols, symbol) } - return uniqueSymbols(symbols) + return uniqueAdanosSymbols(symbols, source) } -func uniqueSymbols(symbols []string) []string { +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 := market.Normalize(symbol) + normalized := normalizeAdanosSymbol(symbol, source) if normalized == "" || seen[normalized] { continue } @@ -709,6 +709,46 @@ func uniqueSymbols(symbols []string) []string { return unique } +func normalizeAdanosSymbol(symbol string, source string) string { + symbol = strings.TrimSpace(symbol) + if symbol == "" { + return "" + } + symbol = strings.TrimPrefix(symbol, "$") + + if adanos.NormalizeSource(source) == adanos.SourceRedditCrypto { + return normalizeAdanosCryptoSymbol(symbol) + } + + normalized := strings.ToUpper(symbol) + normalized = strings.TrimPrefix(normalized, "XYZ:") + 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) + } + } + return normalized +} + +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_prompt.go b/kernel/engine_prompt.go index 4b91fbcb7a..bcbd100d0d 100644 --- a/kernel/engine_prompt.go +++ b/kernel/engine_prompt.go @@ -770,6 +770,9 @@ func lookupAdanosSentiment(ctx *Context, symbol string) *adanos.Sentiment { if sentiment, ok := ctx.AdanosSentimentMap[normalized]; ok { return sentiment } + if sentiment, ok := ctx.AdanosSentimentMap[normalizeAdanosSymbol(symbol, adanos.SourceXStocks)]; ok { + return sentiment + } return ctx.AdanosSentimentMap[symbol] } diff --git a/provider/adanos/client_test.go b/provider/adanos/client_test.go index c912effb14..ba858856cc 100644 --- a/provider/adanos/client_test.go +++ b/provider/adanos/client_test.go @@ -101,6 +101,38 @@ func TestCompareSupportsStockSources(t *testing.T) { } } +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)