diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000..78f28c4 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,6 @@ +.git +.env +.env.* +target +failed.md +references diff --git a/.env.example b/.env.example index 873ebd4..48162ff 100644 --- a/.env.example +++ b/.env.example @@ -20,6 +20,9 @@ NOTION_DATABASE_ID= ENABLE_SCREENSHOT=false # The API URL of the TradeSnap service TRADESNAP_URL=http://tradesnap:8003 +# Optional flat YAML mapping from raw Hyperliquid HIP-3 symbols to TradingView tickers. +# Example file entry: "xyz:GOLD": "TVC:GOLD" +REDIRECT_PATH=./redirect.yml # Ticker type switch: true to use BINANCE:{coin}USDT.P (USDT perp), false to use BINANCE:{coin}USDC.P (USDC perp) BTCUSDT_SNAPSHOT=false # Switch to enable/disable 15m screenshots @@ -30,5 +33,3 @@ SYMBOL_1H_SNAPSHOT=false SYMBOL_4H_SNAPSHOT=false # Switch to enable/disable 1D screenshots SYMBOL_1D_SNAPSHOT=false - - diff --git a/CHANGELOG.md b/CHANGELOG.md index 7fc85aa..6a5bded 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,7 @@ ## [Unreleased] ### Added +- 新增 `REDIRECT_PATH` 配置,支持通过扁平 YAML 文件将 HIP-3 原始 symbol 重定向到准确的 TradingView ticker。 - 支持对接 TradeSnap 截图服务,自动抓取新交易对应的 TradingView 图表快照。 - 新增 `ENABLE_SCREENSHOT` 与 `TRADESNAP_URL` 配置,控制截图的开关和请求地址。 - 新增 `BTCUSDT_SNAPSHOT` 配置,控制使用 `BINANCE:{coin}USDT.P` 还是 `BINANCE:{coin}USDC.P` 格式生成图表截图。 @@ -22,6 +23,7 @@ - 添加外部参考库作为 Git 子模块:`noc` (notion-client) 与 `hype` (hyperliquid-rust-sdk)。 ### Changed +- HIP-3 交易写入 Notion 时自动移除 DEX namespace(如 `xyz:GOLD` 写为 `GOLD`);未配置截图重定向时安全跳过截图。 - 将项目与 Crate 命名从 `nosync` 统一重命名为 `tradesync`,并同步更新了所有 Rust 源码包导入和 Docker 镜像名称。 - 更新 Docker Compose 配置,移除了 `tradesnap` 和 `tradesync` (原 `nosync`)多余的 volumes 目录挂载,并统一使用 `:latest` 镜像标签以替代固定版本。 - 移除 `Level` 字段的相关计算与 Notion 写入逻辑(交由用户后续手动设置)。 diff --git a/Cargo.lock b/Cargo.lock index a5cd260..90e3728 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4137,6 +4137,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "serde_yaml" +version = "0.9.34+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" +dependencies = [ + "indexmap 2.14.0", + "itoa", + "ryu", + "serde", + "unsafe-libyaml", +] + [[package]] name = "serdect" version = "0.2.0" @@ -4764,6 +4777,7 @@ dependencies = [ "reqwest 0.13.4", "serde", "serde_json", + "serde_yaml", "thiserror 2.0.18", "tokio", "tracing", @@ -4844,6 +4858,12 @@ version = "0.2.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" +[[package]] +name = "unsafe-libyaml" +version = "0.2.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "673aac59facbab8a9007c7f6108d11f63b603f7cabff99fabf650fea5c32b861" + [[package]] name = "untrusted" version = "0.9.0" diff --git a/Cargo.toml b/Cargo.toml index 76dc634..6a6d3f7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,6 +13,7 @@ notion-client = { git = "https://github.com/takassh/notion-client.git" } reqwest = "0.13.4" serde = { version = "1.0.218", features = ["derive"] } serde_json = "1.0.150" +serde_yaml = "0.9.34" thiserror = "2.0.18" tokio = { version = "1.52.3", features = ["full"] } tracing = "0.1.44" diff --git a/README.md b/README.md index 28ae506..a8ab007 100644 --- a/README.md +++ b/README.md @@ -133,12 +133,23 @@ cargo run --example demo | `RUST_LOG` | Logging verbosity level (error, warn, info, debug) | No | `info` | | `ENABLE_SCREENSHOT` | Enable TradingView chart screenshots in Notion pages (`true`/`false`) | No | `false` | | `TRADESNAP_URL` | The API endpoint URL of the TradeSnap service | No | `http://tradesnap:8003` | +| `REDIRECT_PATH` | Optional path to a YAML file mapping raw HIP-3 symbols to exact TradingView tickers | No | `./redirect.yml` | | `BTCUSDT_SNAPSHOT` | Use Binance USDT perps (`true`) instead of USDC perps (`false`) for screenshots | No | `false` | | `SYMBOL_15M_SNAPSHOT` | Capture and insert 15m interval screenshot (`true`/`false`) | No | `false` | | `SYMBOL_1H_SNAPSHOT` | Capture and insert 1h interval screenshot (`true`/`false`) | No | `false` | | `SYMBOL_4H_SNAPSHOT` | Capture and insert 4h interval screenshot (`true`/`false`) | No | `false` | | `SYMBOL_1D_SNAPSHOT` | Capture and insert 1D interval screenshot (`true`/`false`) | No | `false` | +HIP-3 symbols are written to Notion without their DEX prefix (`xyz:GOLD` becomes `GOLD`). To enable screenshots for them, create a flat redirect file and set `REDIRECT_PATH`: + +```yaml +"xyz:GOLD": "TVC:GOLD" +"xyz:NVDA": "NASDAQ:NVDA" +``` + +An unmapped HIP-3 symbol is still written to Notion, but its screenshots are skipped instead of guessing a data source. +When using the included Docker Compose file, `REDIRECT_PATH` is the host path to the YAML file; Compose mounts it read-only at `/app/redirect.yml`. + ## 7. Development & Testing ### Git Branching Strategy diff --git a/README_CN.md b/README_CN.md index 3245ce3..d300869 100644 --- a/README_CN.md +++ b/README_CN.md @@ -133,12 +133,23 @@ cargo run --example demo | `RUST_LOG` | 日志详细级别(error、warn、info、debug) | 否 | `info` | | `ENABLE_SCREENSHOT` | 在 Notion 页面中启用 TradingView 图表截图(`true`/`false`) | 否 | `false` | | `TRADESNAP_URL` | TradeSnap 服务的 API 端点 URL | 否 | `http://tradesnap:8003` | +| `REDIRECT_PATH` | 可选的 YAML 文件路径,将 HIP-3 原始 symbol 映射到准确的 TradingView ticker | 否 | `./redirect.yml` | | `BTCUSDT_SNAPSHOT` | 截图使用币安 USDT 合约(`true`)而非 USDC 合约(`false`) | 否 | `false` | | `SYMBOL_15M_SNAPSHOT` | 捕获并插入 15m 周期截图(`true`/`false`) | 否 | `false` | | `SYMBOL_1H_SNAPSHOT` | 捕获并插入 1h 周期截图(`true`/`false`) | 否 | `false` | | `SYMBOL_4H_SNAPSHOT` | 捕获并插入 4h 周期截图(`true`/`false`) | 否 | `false` | | `SYMBOL_1D_SNAPSHOT` | 捕获并插入 1D 周期截图(`true`/`false`) | 否 | `false` | +HIP-3 symbol 写入 Notion 时会去掉 DEX 前缀(例如 `xyz:GOLD` 写为 `GOLD`)。如需截图,请创建扁平的 redirect 文件并设置 `REDIRECT_PATH`: + +```yaml +"xyz:GOLD": "TVC:GOLD" +"xyz:NVDA": "NASDAQ:NVDA" +``` + +未配置映射的 HIP-3 symbol 仍会写入 Notion,但会跳过截图,不会猜测数据源。 +使用仓库自带的 Docker Compose 时,`REDIRECT_PATH` 填宿主机上的 YAML 路径;Compose 会将它只读挂载到容器内的 `/app/redirect.yml`。 + ## 7. 开发与测试 ### Git 分支策略 diff --git a/docker-compose.yml b/docker-compose.yml index 84f2d6c..97786e4 100644 --- a/docker-compose.yml +++ b/docker-compose.yml @@ -4,6 +4,10 @@ services: container_name: tradesync env_file: - .env + environment: + REDIRECT_PATH: /app/redirect.yml + volumes: + - ${REDIRECT_PATH:-./redirect.yml}:/app/redirect.yml:ro networks: - cycle restart: unless-stopped diff --git a/examples/demo.rs b/examples/demo.rs index 3e1ff39..9669580 100644 --- a/examples/demo.rs +++ b/examples/demo.rs @@ -1,9 +1,9 @@ use alloy::primitives::address; use anyhow::Result; -use tradesync::HyperliquidMonitor; use tokio::sync::mpsc; use tracing::info; use tracing_subscriber::{EnvFilter, FmtSubscriber}; +use tradesync::HyperliquidMonitor; #[tokio::main] async fn main() -> Result<()> { diff --git a/redirect.example.yml b/redirect.example.yml new file mode 100644 index 0000000..0c9ebef --- /dev/null +++ b/redirect.example.yml @@ -0,0 +1,3 @@ +# Hyperliquid raw symbol: TradingView ticker +"xyz:GOLD": "TVC:GOLD" +"xyz:NVDA": "NASDAQ:NVDA" diff --git a/redirect.yml b/redirect.yml new file mode 100644 index 0000000..0c9ebef --- /dev/null +++ b/redirect.yml @@ -0,0 +1,3 @@ +# Hyperliquid raw symbol: TradingView ticker +"xyz:GOLD": "TVC:GOLD" +"xyz:NVDA": "NASDAQ:NVDA" diff --git a/src/lib.rs b/src/lib.rs index a35922f..a22ec57 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,7 +1,9 @@ pub mod hyperliquid; pub mod notion; +pub mod redirect; pub mod structs; pub use hyperliquid::{HyperliquidMonitor, HyperliquidMonitorError}; pub use notion::{NotionWriter, NotionWriterError}; +pub use redirect::{RedirectError, ResolvedSymbol, SymbolRedirects}; pub use structs::{NotionRowData, PositionTradeEvent, TradeAction}; diff --git a/src/main.rs b/src/main.rs index 5be4d11..e824849 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,11 +1,12 @@ use anyhow::{Context, Result}; use chrono::{TimeZone, Utc}; use dotenvy::dotenv; -use tradesync::{HyperliquidMonitor, NotionRowData, NotionWriter}; use std::env; +use std::path::PathBuf; use tokio::sync::mpsc; use tracing::{error, info}; use tracing_subscriber::{EnvFilter, FmtSubscriber}; +use tradesync::{HyperliquidMonitor, NotionRowData, NotionWriter, SymbolRedirects}; #[tokio::main] async fn main() -> Result<()> { @@ -48,6 +49,13 @@ async fn main() -> Result<()> { .parse::() .unwrap_or(false); + let redirect_path = env::var("REDIRECT_PATH").ok().map(PathBuf::from); + let symbol_redirects = SymbolRedirects::load(redirect_path.as_deref()) + .context("Failed to load symbol redirects")?; + if let Some(path) = &redirect_path { + info!(path = %path.display(), "Loaded symbol redirects"); + } + let snapshot_15m = env::var("SYMBOL_15M_SNAPSHOT") .or_else(|_| env::var("SYMBOL_15m_SNAPSHOT")) .unwrap_or_else(|_| "false".to_string()) @@ -79,7 +87,6 @@ async fn main() -> Result<()> { notion_database_id, enable_screenshot, tradesnap_url, - btcusdt_snapshot, snapshot_15m, snapshot_1h, snapshot_4h, @@ -105,8 +112,7 @@ async fn main() -> Result<()> { .unwrap_or_else(Utc::now); let date_time_str = dt.format("%Y/%m/%d %H:%M").to_string(); - // Map Symbol to appends USDC - let symbol_formatted = format!("{}USDC", event.coin); + let resolved_symbol = symbol_redirects.resolve(&event.coin, btcusdt_snapshot); // Map Direction: B -> Long, S -> Short let direction_str = if event.side == "B" { @@ -136,7 +142,7 @@ async fn main() -> Result<()> { // Construct Notion Row Data let row = NotionRowData { - symbol: symbol_formatted, + symbol: resolved_symbol.notion_symbol, quantity: event.sz, filled_price: event.px, direction: direction_str, @@ -146,6 +152,7 @@ async fn main() -> Result<()> { order_id: event.oid, check: false, order_type: order_type_str, + snapshot_ticker: resolved_symbol.snapshot_ticker, }; // Write row to Notion diff --git a/src/notion.rs b/src/notion.rs index 367b182..cf6bfab 100644 --- a/src/notion.rs +++ b/src/notion.rs @@ -13,7 +13,7 @@ use reqwest::ClientBuilder; use serde_json::Number; use std::collections::BTreeMap; use thiserror::Error; -use tracing::{error, info}; +use tracing::{error, info, warn}; /// Errors specific to the NotionWriter. #[derive(Error, Debug)] @@ -30,7 +30,6 @@ pub struct NotionWriter { database_id: String, enable_screenshot: bool, tradesnap_url: Option, - btcusdt_snapshot: bool, snapshot_15m: bool, snapshot_1h: bool, snapshot_4h: bool, @@ -45,7 +44,6 @@ impl NotionWriter { database_id: String, enable_screenshot: bool, tradesnap_url: Option, - btcusdt_snapshot: bool, snapshot_15m: bool, snapshot_1h: bool, snapshot_4h: bool, @@ -58,7 +56,6 @@ impl NotionWriter { database_id, enable_screenshot, tradesnap_url, - btcusdt_snapshot, snapshot_15m, snapshot_1h, snapshot_4h, @@ -217,22 +214,19 @@ impl NotionWriter { info!(page_id = %page.id, "Successfully wrote row to Notion Database"); if let (true, Some(url)) = (self.enable_screenshot, &self.tradesnap_url) { - let coin = if data.symbol.ends_with("USDC") { - data.symbol.trim_end_matches("USDC").to_string() - } else if data.symbol.ends_with("USDT") { - data.symbol.trim_end_matches("USDT").to_string() - } else { - data.symbol.clone() - }; - - let ticker = if self.btcusdt_snapshot { - format!("BINANCE:{}USDT.P", coin.to_uppercase()) - } else { - format!("BINANCE:{}USDC.P", coin.to_uppercase()) + let Some(ticker) = data.snapshot_ticker.as_deref() else { + warn!( + symbol = %data.symbol, + order_id = data.order_id, + "Skipping screenshots because no TradingView redirect is configured" + ); + return Ok(()); }; let tradesnap_url = url.trim_end_matches('/'); let http_client = reqwest::Client::builder() - .timeout(std::time::Duration::from_secs(15)) + // Must be longer than TradeSnap's default 20-second hard + // deadline so its HTTP error reaches us before we disconnect. + .timeout(std::time::Duration::from_secs(25)) .build() .unwrap_or_else(|_| reqwest::Client::new()); let mut children = Vec::new(); diff --git a/src/redirect.rs b/src/redirect.rs new file mode 100644 index 0000000..a445f10 --- /dev/null +++ b/src/redirect.rs @@ -0,0 +1,116 @@ +use serde::Deserialize; +use std::collections::HashMap; +use std::fs; +use std::path::Path; +use thiserror::Error; + +#[derive(Debug, Error)] +pub enum RedirectError { + #[error("failed to read redirect file {path}: {source}")] + Read { + path: String, + source: std::io::Error, + }, + #[error("failed to parse redirect file {path}: {source}")] + Parse { + path: String, + source: serde_yaml::Error, + }, +} + +/// Exact Hyperliquid symbol to TradingView ticker redirects. +#[derive(Debug, Default, Deserialize)] +#[serde(transparent)] +pub struct SymbolRedirects(HashMap); + +#[derive(Debug, PartialEq, Eq)] +pub struct ResolvedSymbol { + pub notion_symbol: String, + pub snapshot_ticker: Option, +} + +impl SymbolRedirects { + pub fn load(path: Option<&Path>) -> Result { + let Some(path) = path else { + return Ok(Self::default()); + }; + + let path_display = path.display().to_string(); + let contents = fs::read_to_string(path).map_err(|source| RedirectError::Read { + path: path_display.clone(), + source, + })?; + + serde_yaml::from_str(&contents).map_err(|source| RedirectError::Parse { + path: path_display, + source, + }) + } + + pub fn resolve(&self, raw_symbol: &str, use_usdt_snapshot: bool) -> ResolvedSymbol { + if let Some((_, symbol)) = raw_symbol.split_once(':') { + return ResolvedSymbol { + notion_symbol: symbol.to_string(), + snapshot_ticker: self.0.get(raw_symbol).cloned(), + }; + } + + let snapshot_quote = if use_usdt_snapshot { "USDT" } else { "USDC" }; + ResolvedSymbol { + notion_symbol: format!("{raw_symbol}USDC"), + snapshot_ticker: Some(format!( + "BINANCE:{}{}.P", + raw_symbol.to_uppercase(), + snapshot_quote + )), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn redirects() -> SymbolRedirects { + serde_yaml::from_str( + r#" +"xyz:GOLD": "TVC:GOLD" +"xyz:NVDA": "NASDAQ:NVDA" +"#, + ) + .unwrap() + } + + #[test] + fn resolves_standard_hyperliquid_symbol() { + assert_eq!( + redirects().resolve("BTC", true), + ResolvedSymbol { + notion_symbol: "BTCUSDC".to_string(), + snapshot_ticker: Some("BINANCE:BTCUSDT.P".to_string()), + } + ); + } + + #[test] + fn strips_hip3_prefix_and_applies_redirect() { + assert_eq!( + redirects().resolve("xyz:GOLD", true), + ResolvedSymbol { + notion_symbol: "GOLD".to_string(), + snapshot_ticker: Some("TVC:GOLD".to_string()), + } + ); + } + + #[test] + fn skips_snapshot_for_unmapped_hip3_symbol() { + assert_eq!( + redirects().resolve("xyz:SPCX", true), + ResolvedSymbol { + notion_symbol: "SPCX".to_string(), + snapshot_ticker: None, + } + ); + } +} diff --git a/src/structs.rs b/src/structs.rs index 9cc1fc2..6d90915 100644 --- a/src/structs.rs +++ b/src/structs.rs @@ -30,16 +30,17 @@ pub struct PositionTradeEvent { /// Represents the structured row data formatted for Notion database insertion. #[derive(Debug, Clone)] pub struct NotionRowData { - pub symbol: String, // e.g., "BTCUSDC" - pub quantity: String, // e.g., "0.02484" - pub filled_price: String, // e.g., "72543" - pub direction: String, // "Long" or "Short" - pub exchange: String, // e.g., "Hyperliquid" - pub date_time: String, // Format: "YYYY/MM/DD HH:MM" - pub time: u64, // Unix timestamp in milliseconds - pub order_id: u64, // Hyperliquid order ID (oid) - pub check: bool, // false - pub order_type: String, // "MARKET" or "LIMIT" + pub symbol: String, // e.g., "BTCUSDC" + pub quantity: String, // e.g., "0.02484" + pub filled_price: String, // e.g., "72543" + pub direction: String, // "Long" or "Short" + pub exchange: String, // e.g., "Hyperliquid" + pub date_time: String, // Format: "YYYY/MM/DD HH:MM" + pub time: u64, // Unix timestamp in milliseconds + pub order_id: u64, // Hyperliquid order ID (oid) + pub check: bool, // false + pub order_type: String, // "MARKET" or "LIMIT" + pub snapshot_ticker: Option, // Exact TradingView ticker, if configured } impl NotionRowData { diff --git a/tests/monitor_test.rs b/tests/monitor_test.rs index 11af865..fc7fd2f 100644 --- a/tests/monitor_test.rs +++ b/tests/monitor_test.rs @@ -1,7 +1,7 @@ use alloy::primitives::address; -use tradesync::HyperliquidMonitor; use tokio::sync::mpsc; use tokio::time::{Duration, timeout}; +use tradesync::HyperliquidMonitor; #[tokio::test] async fn test_monitor_initialization() {