Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions api/strategy.go
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
159 changes: 159 additions & 0 deletions api/strategy_adanos_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
35 changes: 35 additions & 0 deletions docs/architecture/STRATEGY_MODULE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)

Expand Down Expand Up @@ -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
Expand Down
30 changes: 30 additions & 0 deletions docs/architecture/STRATEGY_MODULE.zh-CN.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 量化数据 (可选)

Expand Down Expand Up @@ -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)
Expand Down
80 changes: 80 additions & 0 deletions kernel/adanos_contract_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
})
}
}
Loading