Compare commits
16 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 391169761a | |||
| a54ec0dbb7 | |||
| a4644f5982 | |||
| a36eb7aad0 | |||
| 82b0f2f1a8 | |||
| 6e8a2e8f68 | |||
| 194a235065 | |||
| c841ca4421 | |||
| 95e9217ef4 | |||
| 88de029e14 | |||
| 2f875032f6 | |||
| b376eba674 | |||
| e565503f24 | |||
| 77036f2211 | |||
| d13c76a93d | |||
| cdd5f8d4af |
@@ -1 +1,2 @@
|
|||||||
/.env
|
/.env
|
||||||
|
/.worktrees/
|
||||||
|
|||||||
@@ -1 +1,31 @@
|
|||||||
# crypto price bot
|
# crypto price bot
|
||||||
|
|
||||||
|
Telegram bot tra giá crypto (Spot / Future / Alpha), funding rate và margin APR.
|
||||||
|
|
||||||
|
## Environment variables
|
||||||
|
|
||||||
|
Tạo file `.env` ở root project với các biến sau:
|
||||||
|
|
||||||
|
```env
|
||||||
|
# BẮT BUỘC: token bot Telegram
|
||||||
|
TELEGRAM_TOKEN=your_telegram_bot_token
|
||||||
|
|
||||||
|
# TÙY CHỌN: bật/tắt log env mode (mặc định true nếu không set)
|
||||||
|
# giá trị hợp lệ: true / false
|
||||||
|
LOG_ENV=true
|
||||||
|
|
||||||
|
# TÙY CHỌN nhưng KHUYẾN NGHỊ: Telegram user id được phép dùng /refresh
|
||||||
|
# nếu không set hoặc set sai format -> /refresh sẽ bị từ chối cho tất cả user
|
||||||
|
ADMIN_CHAT_ID=123456789
|
||||||
|
```
|
||||||
|
|
||||||
|
## Run
|
||||||
|
|
||||||
|
```bash
|
||||||
|
go run ./cmd/tele
|
||||||
|
```
|
||||||
|
|
||||||
|
## Notes
|
||||||
|
|
||||||
|
- `TELEGRAM_TOKEN` sai/thiếu: bot sẽ fail khi khởi tạo Telegram service.
|
||||||
|
- `/refresh` dùng để refresh trading pair cache thủ công và chỉ cho `ADMIN_CHAT_ID`.
|
||||||
|
|||||||
@@ -0,0 +1,130 @@
|
|||||||
|
# Token message rich design
|
||||||
|
|
||||||
|
## Context
|
||||||
|
|
||||||
|
Current token message flow returns early for Alpha tokens, so users cannot see Spot/Future together with Alpha when multiple sources are available. Message content is also rigid and less informative for partial-source cases.
|
||||||
|
|
||||||
|
Goal: redesign Telegram token message so each available price source is shown in one rich message, with stable ordering and conditional rows.
|
||||||
|
|
||||||
|
## Scope
|
||||||
|
|
||||||
|
Applies to token query message rendering in Telegram bot (`OnTokenInfoByToken` flow and price view formatting).
|
||||||
|
|
||||||
|
Out of scope:
|
||||||
|
- changing market data fetch logic
|
||||||
|
- changing command routing
|
||||||
|
- trend arrows / historical diff
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
1. Rich, multi-line Telegram message format.
|
||||||
|
2. Spot is primary source when present.
|
||||||
|
3. Show all available sources in a single message: Spot, Future, Alpha.
|
||||||
|
4. Hide rows for missing data.
|
||||||
|
5. Show Basis only when both Spot and Future exist.
|
||||||
|
6. Show Alpha 24h when Alpha data exists.
|
||||||
|
7. No trend arrows.
|
||||||
|
8. Preserve current behavior of no reply when no Spot/Future/Alpha data exists.
|
||||||
|
|
||||||
|
## Message format
|
||||||
|
|
||||||
|
Fixed row order (hide missing rows):
|
||||||
|
|
||||||
|
1. `🪙 TOKEN`
|
||||||
|
2. `💵 Spot: ...` (primary if exists)
|
||||||
|
3. `📈 Future: ...`
|
||||||
|
4. `🅰️ Alpha: ...`
|
||||||
|
5. `🧭 Basis: Future-Spot` (only if Spot+Future)
|
||||||
|
6. `💸 Funding: ... in ...` (if Future exists)
|
||||||
|
7. `🏦 Margin: ... APR` (if margin exists)
|
||||||
|
8. `📊 Alpha 24h: ...` (if Alpha change exists)
|
||||||
|
|
||||||
|
## Fallback rules
|
||||||
|
|
||||||
|
- **All three available**: render all rows above (except any missing optional fields).
|
||||||
|
- **Spot + Future**: render Spot, Future, Basis, Funding, Margin.
|
||||||
|
- **Alpha only**: render Alpha and Alpha 24h.
|
||||||
|
- **Future only**: render Future, Funding, Margin.
|
||||||
|
- **Spot only**: render Spot, Margin.
|
||||||
|
- **No Spot/Future/Alpha**: no reply.
|
||||||
|
|
||||||
|
## Data flow behavior
|
||||||
|
|
||||||
|
1. Resolve token to candidate futures symbol(s) using existing resolver.
|
||||||
|
2. Collect available values from Spot/Future/Alpha/margin sources.
|
||||||
|
3. Build one unified message model.
|
||||||
|
4. Render rows in fixed order; each row is conditional on availability.
|
||||||
|
5. Send single Telegram message.
|
||||||
|
|
||||||
|
Important behavioral change: remove alpha-first early-return behavior; Alpha becomes a peer data source in unified rendering.
|
||||||
|
|
||||||
|
## Formatting notes
|
||||||
|
|
||||||
|
- Reuse existing numeric formatter (`RenderPrice`) for price values.
|
||||||
|
- Keep current funding icon and countdown style.
|
||||||
|
- Basis format:
|
||||||
|
- absolute delta: `Future - Spot`
|
||||||
|
- percent delta: `(Future-Spot)/Spot*100`
|
||||||
|
- sign preserved (`+`/`-`)
|
||||||
|
|
||||||
|
## Example outputs
|
||||||
|
|
||||||
|
### A) Spot + Future + Alpha
|
||||||
|
|
||||||
|
```text
|
||||||
|
🪙 ETH
|
||||||
|
💵 Spot: $3,245
|
||||||
|
📈 Future: $3,251
|
||||||
|
🅰️ Alpha: $3,248
|
||||||
|
🧭 Basis: +$6 (+0.18%)
|
||||||
|
💸 Funding: +0.0123% 🟢 in 05m
|
||||||
|
🏦 Margin: 7.665% APR
|
||||||
|
📊 Alpha 24h: 🔴 -3.21%
|
||||||
|
```
|
||||||
|
|
||||||
|
### B) Spot + Future
|
||||||
|
|
||||||
|
```text
|
||||||
|
🪙 SOL
|
||||||
|
💵 Spot: $182.4
|
||||||
|
📈 Future: $183.0
|
||||||
|
🧭 Basis: +$0.6 (+0.33%)
|
||||||
|
💸 Funding: -0.0041% 🔴 in 42m
|
||||||
|
🏦 Margin: 5.110% APR
|
||||||
|
```
|
||||||
|
|
||||||
|
### C) Alpha only
|
||||||
|
|
||||||
|
```text
|
||||||
|
🪙 ABC
|
||||||
|
🅰️ Alpha: $0.1234
|
||||||
|
📊 Alpha 24h: 🟢 +12.40%
|
||||||
|
```
|
||||||
|
|
||||||
|
### D) Future only
|
||||||
|
|
||||||
|
```text
|
||||||
|
🪙 TOKEN
|
||||||
|
📈 Future: $1,234
|
||||||
|
💸 Funding: +0.0081% 🟢 in 17m
|
||||||
|
🏦 Margin: 6.200% APR
|
||||||
|
```
|
||||||
|
|
||||||
|
### E) Spot only
|
||||||
|
|
||||||
|
```text
|
||||||
|
🪙 TOKEN
|
||||||
|
💵 Spot: $1,228
|
||||||
|
🏦 Margin: 6.200% APR
|
||||||
|
```
|
||||||
|
|
||||||
|
## Verification checklist
|
||||||
|
|
||||||
|
- Token with all 3 sources -> all expected rows appear, ordered correctly.
|
||||||
|
- Token with Spot+Future but no Alpha -> no Alpha rows.
|
||||||
|
- Token with Alpha only -> no Spot/Future/Basis/Funding rows.
|
||||||
|
- Token with Future only -> no Spot/Basis/Alpha rows.
|
||||||
|
- Token with Spot only -> no Future/Basis/Funding/Alpha rows.
|
||||||
|
- Token with no data -> no reply.
|
||||||
|
- Basis not shown unless both Spot and Future exist.
|
||||||
|
- No trend arrows anywhere.
|
||||||
@@ -5,7 +5,7 @@ go 1.25.0
|
|||||||
require (
|
require (
|
||||||
github.com/adshao/go-binance/v2 v2.8.11
|
github.com/adshao/go-binance/v2 v2.8.11
|
||||||
github.com/go-resty/resty/v2 v2.17.2
|
github.com/go-resty/resty/v2 v2.17.2
|
||||||
github.com/jedib0t/go-pretty/v6 v6.5.5
|
github.com/jedib0t/go-pretty/v6 v6.7.10
|
||||||
github.com/joho/godotenv v1.5.1
|
github.com/joho/godotenv v1.5.1
|
||||||
github.com/rs/zerolog v1.32.0
|
github.com/rs/zerolog v1.32.0
|
||||||
github.com/samber/lo v1.53.0
|
github.com/samber/lo v1.53.0
|
||||||
@@ -20,8 +20,8 @@ require (
|
|||||||
github.com/jpillora/backoff v1.0.0 // indirect
|
github.com/jpillora/backoff v1.0.0 // indirect
|
||||||
github.com/mattn/go-colorable v0.1.13 // indirect
|
github.com/mattn/go-colorable v0.1.13 // indirect
|
||||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||||
github.com/mattn/go-runewidth v0.0.15 // indirect
|
github.com/mattn/go-runewidth v0.0.16 // indirect
|
||||||
github.com/rivo/uniseg v0.2.0 // indirect
|
github.com/rivo/uniseg v0.4.7 // indirect
|
||||||
github.com/shopspring/decimal v1.4.0 // indirect
|
github.com/shopspring/decimal v1.4.0 // indirect
|
||||||
golang.org/x/net v0.43.0 // indirect
|
golang.org/x/net v0.43.0 // indirect
|
||||||
golang.org/x/sys v0.35.0 // indirect
|
golang.org/x/sys v0.35.0 // indirect
|
||||||
|
|||||||
@@ -257,8 +257,8 @@ github.com/hashicorp/serf v0.9.6/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpT
|
|||||||
github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=
|
github.com/hashicorp/serf v0.9.7/go.mod h1:TXZNMjZQijwlDvp+r0b63xZ45H7JmCmgg4gpTwn9UV4=
|
||||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||||
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
github.com/ianlancetaylor/demangle v0.0.0-20200824232613-28f6c0f3b639/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.5.5 h1:PpIU8lOjxvVYGGKule0QxxJfNysUSbC9lggQU2cpZJc=
|
github.com/jedib0t/go-pretty/v6 v6.7.10 h1:B/2qW2Bkv2L6n14PP8o1kx75kWzHOQ3YTluWzg9icac=
|
||||||
github.com/jedib0t/go-pretty/v6 v6.5.5/go.mod h1:5LQIxa52oJ/DlDSLv0HEkWOFMDGoWkJb9ss5KqPpJBg=
|
github.com/jedib0t/go-pretty/v6 v6.7.10/go.mod h1:YwC5CE4fJ1HFUDeivSV1r//AmANFHyqczZk+U6BDALU=
|
||||||
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0=
|
||||||
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4=
|
||||||
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
|
github.com/jpillora/backoff v1.0.0 h1:uvFg412JmmHBHw7iwprIxkPMI+sGQ4kzOWsMeHnm2EA=
|
||||||
@@ -306,8 +306,8 @@ github.com/mattn/go-isatty v0.0.16/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/
|
|||||||
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||||
github.com/mattn/go-runewidth v0.0.15 h1:UNAjwbU9l54TA3KzvqLGxwWjHmMgBUVhBiTjelZgg3U=
|
github.com/mattn/go-runewidth v0.0.16 h1:E5ScNMtiwvlvB5paMFdw9p4kSQzbXFikJ5SQO6TULQc=
|
||||||
github.com/mattn/go-runewidth v0.0.15/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
github.com/mattn/go-runewidth v0.0.16/go.mod h1:Jdepj2loyihRzMpdS35Xk/zdY8IAYHsh153qUoGf23w=
|
||||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||||
github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
|
github.com/miekg/dns v1.1.26/go.mod h1:bPDLeHnStXmXAq1m/Ch/hvfNHr14JKNPMBo3VZKjuso=
|
||||||
github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI=
|
github.com/miekg/dns v1.1.41/go.mod h1:p6aan82bvRIyn+zDIv9xYNUpwa73JcSh9BKwknJysuI=
|
||||||
@@ -355,8 +355,9 @@ github.com/prometheus/procfs v0.0.2/go.mod h1:TjEm7ze935MbeOT/UhFTIMYKhuLP4wbCsT
|
|||||||
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
|
github.com/prometheus/procfs v0.0.8/go.mod h1:7Qr8sr6344vo1JqZ6HhLceV9o3AJ1Ff+GxbHq6oeK9A=
|
||||||
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
github.com/prometheus/procfs v0.1.3/go.mod h1:lV6e/gmhEcM9IjHGsFOCxxuZ+z1YqCvr4OA4YeYWdaU=
|
||||||
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
github.com/prometheus/procfs v0.6.0/go.mod h1:cz+aTbrPOrUb4q7XlbU9ygM+/jj0fzG6c1xBZuNvfVA=
|
||||||
github.com/rivo/uniseg v0.2.0 h1:S1pD9weZBuJdFmowNwbpi7BJ8TNftyUImj/0WQi72jY=
|
|
||||||
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
github.com/rivo/uniseg v0.2.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||||
|
github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||||
|
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||||
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
github.com/rogpeppe/fastuuid v1.2.0/go.mod h1:jVj6XXZzXRy/MSR5jhDC/2q6DgLz+nrA6LYCDYWNEvQ=
|
||||||
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
github.com/rogpeppe/go-internal v1.3.0/go.mod h1:M8bDsm7K2OlrFYOpmOWEs/qY81heoFRclV5y23lUDJ4=
|
||||||
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
github.com/rogpeppe/go-internal v1.6.1 h1:/FiVV8dS/e+YqF2JvO3yXRFbBLTIuSDkuC7aBOAvL+k=
|
||||||
@@ -394,8 +395,8 @@ github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/
|
|||||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||||
github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.7.5/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||||
github.com/stretchr/testify v1.8.4 h1:CcVxjf3Q8PM0mHUKJCdn+eZZtm5yQwehR5yeSVQQcUk=
|
github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
|
||||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||||
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
|
github.com/subosito/gotenv v1.4.1/go.mod h1:ayKnFf/c6rvx/2iiLrJUk1e6plDbT3edrFNGqEflhK0=
|
||||||
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
|
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
|
||||||
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
github.com/yuin/goldmark v1.1.25/go.mod h1:3hX8gzYuyVAZsxl0MRgGTJEmQBFcNTphYh9decYSb74=
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ type IMarket interface {
|
|||||||
// Alpha token methods
|
// Alpha token methods
|
||||||
IsAlphaToken(symbol string) bool
|
IsAlphaToken(symbol string) bool
|
||||||
GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool)
|
GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool)
|
||||||
|
GetAlphaPrice(symbol string) (float64, bool)
|
||||||
|
|
||||||
// Trading pair methods
|
// Trading pair methods
|
||||||
IsSpotPair(symbol string) bool
|
IsSpotPair(symbol string) bool
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import (
|
|||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"net/http"
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strconv"
|
"strconv"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -60,6 +61,17 @@ type AlphaTokenResponse struct {
|
|||||||
Data []AlphaTokenInfo `json:"data"`
|
Data []AlphaTokenInfo `json:"data"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type AlphaTickerData struct {
|
||||||
|
Price string `json:"price"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type AlphaTickerResponse struct {
|
||||||
|
Code string `json:"code"`
|
||||||
|
Message *string `json:"message"`
|
||||||
|
MessageDetail *string `json:"messageDetail"`
|
||||||
|
Data AlphaTickerData `json:"data"`
|
||||||
|
}
|
||||||
|
|
||||||
// GetPrice returns the price as float64
|
// GetPrice returns the price as float64
|
||||||
func (a *AlphaTokenInfo) GetPrice() float64 {
|
func (a *AlphaTokenInfo) GetPrice() float64 {
|
||||||
price, err := strconv.ParseFloat(a.Price, 64)
|
price, err := strconv.ParseFloat(a.Price, 64)
|
||||||
@@ -150,3 +162,37 @@ func (ms *MarketData) IsAlphaToken(symbol string) bool {
|
|||||||
_, exists := ms.GetAlphaToken(symbol)
|
_, exists := ms.GetAlphaToken(symbol)
|
||||||
return exists
|
return exists
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (ms *MarketData) GetAlphaPrice(symbol string) (float64, bool) {
|
||||||
|
const alphaTickerURL = "https://www.binance.com/bapi/defi/v1/public/alpha-trade/ticker"
|
||||||
|
|
||||||
|
client := &http.Client{Timeout: 5 * time.Second}
|
||||||
|
endpoint := alphaTickerURL + "?" + url.Values{"symbol": []string{symbol}}.Encode()
|
||||||
|
|
||||||
|
resp, err := client.Get(endpoint)
|
||||||
|
if err != nil {
|
||||||
|
log.Error().Err(err).Str("symbol", symbol).Msg("Failed to fetch Alpha ticker")
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
defer resp.Body.Close()
|
||||||
|
|
||||||
|
if resp.StatusCode != http.StatusOK {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
var tickerResp AlphaTickerResponse
|
||||||
|
if err := json.NewDecoder(resp.Body).Decode(&tickerResp); err != nil {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
if tickerResp.Code != "000000" {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
price, err := strconv.ParseFloat(tickerResp.Data.Price, 64)
|
||||||
|
if err != nil || price <= 0 {
|
||||||
|
return 0, false
|
||||||
|
}
|
||||||
|
|
||||||
|
return price, true
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,15 +2,54 @@ package commands
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"strings"
|
"strings"
|
||||||
|
"sync"
|
||||||
|
|
||||||
"gopkg.in/telebot.v3"
|
"gopkg.in/telebot.v3"
|
||||||
"me.thuanle/bbot/internal/configs/tele"
|
"me.thuanle/bbot/internal/configs/tele"
|
||||||
"me.thuanle/bbot/internal/data"
|
"me.thuanle/bbot/internal/data"
|
||||||
"me.thuanle/bbot/internal/helper/binancex"
|
|
||||||
"me.thuanle/bbot/internal/services/tele/chat"
|
"me.thuanle/bbot/internal/services/tele/chat"
|
||||||
"me.thuanle/bbot/internal/services/tele/view"
|
"me.thuanle/bbot/internal/services/tele/view"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
type buildRichTokenMessageArgs struct {
|
||||||
|
Token string
|
||||||
|
|
||||||
|
HasSpot bool
|
||||||
|
SpotPrice float64
|
||||||
|
|
||||||
|
HasFuture bool
|
||||||
|
FuturePrice float64
|
||||||
|
FundingRate float64
|
||||||
|
FundingTimeMs int64
|
||||||
|
|
||||||
|
HasAlpha bool
|
||||||
|
AlphaPrice float64
|
||||||
|
|
||||||
|
HasAlpha24h bool
|
||||||
|
Alpha24h float64
|
||||||
|
|
||||||
|
HasMarginAPR bool
|
||||||
|
MarginAPRPercent float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func buildRichTokenMessageInput(a buildRichTokenMessageArgs) view.RichTokenMessageInput {
|
||||||
|
return view.RichTokenMessageInput{
|
||||||
|
Token: a.Token,
|
||||||
|
HasSpot: a.HasSpot,
|
||||||
|
SpotPrice: a.SpotPrice,
|
||||||
|
HasFuture: a.HasFuture,
|
||||||
|
FuturePrice: a.FuturePrice,
|
||||||
|
FundingRate: a.FundingRate,
|
||||||
|
FundingTimeMs: a.FundingTimeMs,
|
||||||
|
HasAlpha: a.HasAlpha,
|
||||||
|
AlphaPrice: a.AlphaPrice,
|
||||||
|
HasAlpha24h: a.HasAlpha24h,
|
||||||
|
Alpha24hChange: a.Alpha24h,
|
||||||
|
HasMarginAPR: a.HasMarginAPR,
|
||||||
|
MarginAPRPercent: a.MarginAPRPercent,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
func showStickerMode(context telebot.Context, token string) {
|
func showStickerMode(context telebot.Context, token string) {
|
||||||
token = strings.ToUpper(token)
|
token = strings.ToUpper(token)
|
||||||
stickerIdx, ok := tele.Token2StickerIdxMap[token]
|
stickerIdx, ok := tele.Token2StickerIdxMap[token]
|
||||||
@@ -23,39 +62,80 @@ func showStickerMode(context telebot.Context, token string) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func collectRichTokenData(token string) buildRichTokenMessageArgs {
|
||||||
|
a := buildRichTokenMessageArgs{Token: token}
|
||||||
|
|
||||||
|
marginRates := data.Market.GetMarginInterestRates()
|
||||||
|
a.MarginAPRPercent = marginRates[token] * 365 * 100
|
||||||
|
a.HasMarginAPR = marginRates[token] != 0
|
||||||
|
|
||||||
|
futureSymbol := token + "USDT"
|
||||||
|
spotSymbol := token + "USDT"
|
||||||
|
|
||||||
|
var (
|
||||||
|
wg sync.WaitGroup
|
||||||
|
mu sync.Mutex
|
||||||
|
)
|
||||||
|
wg.Add(3)
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
if alphaToken, ok := data.Market.GetAlphaToken(token); ok {
|
||||||
|
alpha24h := alphaToken.GetPercentChange24h()
|
||||||
|
alphaPrice := alphaToken.GetPrice()
|
||||||
|
if p, ok := data.Market.GetAlphaPrice(token + "USDT"); ok {
|
||||||
|
alphaPrice = p
|
||||||
|
}
|
||||||
|
mu.Lock()
|
||||||
|
a.HasAlpha = true
|
||||||
|
a.HasAlpha24h = true
|
||||||
|
a.Alpha24h = alpha24h
|
||||||
|
a.AlphaPrice = alphaPrice
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
if data.Market.IsFuturesPair(futureSymbol) {
|
||||||
|
if fp, fr, ft, ok := data.Market.GetFuturePrice(futureSymbol); ok {
|
||||||
|
mu.Lock()
|
||||||
|
a.HasFuture = true
|
||||||
|
a.FuturePrice = fp
|
||||||
|
a.FundingRate = fr
|
||||||
|
a.FundingTimeMs = ft
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
go func() {
|
||||||
|
defer wg.Done()
|
||||||
|
if data.Market.IsSpotPair(spotSymbol) {
|
||||||
|
if sp, ok := data.Market.GetSpotPrice(spotSymbol); ok {
|
||||||
|
mu.Lock()
|
||||||
|
a.HasSpot = true
|
||||||
|
a.SpotPrice = sp
|
||||||
|
mu.Unlock()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
|
||||||
|
wg.Wait()
|
||||||
|
return a
|
||||||
|
}
|
||||||
|
|
||||||
func OnTokenInfoByToken(context telebot.Context, token string) error {
|
func OnTokenInfoByToken(context telebot.Context, token string) error {
|
||||||
token = strings.ToUpper(token)
|
token = strings.ToUpper(token)
|
||||||
|
|
||||||
// Check if it's an Alpha token first
|
|
||||||
if data.Market.IsAlphaToken(token) {
|
|
||||||
showStickerMode(context, token)
|
showStickerMode(context, token)
|
||||||
|
|
||||||
if alphaToken, exists := data.Market.GetAlphaToken(token); exists {
|
args := collectRichTokenData(token)
|
||||||
sp := alphaToken.GetPrice()
|
if !args.HasSpot && !args.HasFuture && !args.HasAlpha {
|
||||||
change24h := alphaToken.GetPercentChange24h()
|
|
||||||
_ = chat.ReplyMessage(context, view.RenderOnAlphaPriceMessage(token, sp, change24h))
|
|
||||||
}
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
// Regular token handling
|
msg := view.RenderRichTokenMessage(buildRichTokenMessageInput(args))
|
||||||
symbols := binancex.Token2Symbols(token)
|
_ = chat.ReplyMessage(context, msg)
|
||||||
if len(symbols) == 0 {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
|
|
||||||
showStickerMode(context, token)
|
|
||||||
|
|
||||||
fp, fundRate, fundTime, ok := data.Market.GetFuturePrice(symbols[0])
|
|
||||||
marginRates := data.Market.GetMarginInterestRates()
|
|
||||||
tokenInterestRate := marginRates[token]
|
|
||||||
if !ok {
|
|
||||||
return nil
|
|
||||||
}
|
|
||||||
sSymbol := binancex.Future2SpotSymbol(symbols[0])
|
|
||||||
sp, _ := data.Market.GetSpotPrice(sSymbol)
|
|
||||||
|
|
||||||
_ = chat.ReplyMessage(context, view.RenderOnPriceMessage(symbols[0], sp, fp, fundRate, fundTime, tokenInterestRate))
|
|
||||||
return nil
|
return nil
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,230 @@
|
|||||||
|
package commands
|
||||||
|
|
||||||
|
import (
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"me.thuanle/bbot/internal/data"
|
||||||
|
"me.thuanle/bbot/internal/data/market"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestBuildRichTokenMessageInput_AllSources(t *testing.T) {
|
||||||
|
in := buildRichTokenMessageInput(buildRichTokenMessageArgs{
|
||||||
|
Token: "ETH",
|
||||||
|
SpotPrice: 3245,
|
||||||
|
HasSpot: true,
|
||||||
|
FuturePrice: 3251,
|
||||||
|
FundingRate: 0.000123,
|
||||||
|
FundingTimeMs: 1740000000000,
|
||||||
|
HasFuture: true,
|
||||||
|
AlphaPrice: 3248,
|
||||||
|
HasAlpha: true,
|
||||||
|
Alpha24h: -3.21,
|
||||||
|
HasAlpha24h: true,
|
||||||
|
MarginAPRPercent: 7.665,
|
||||||
|
HasMarginAPR: true,
|
||||||
|
})
|
||||||
|
|
||||||
|
if !in.HasSpot || !in.HasFuture || !in.HasAlpha || !in.HasAlpha24h || !in.HasMarginAPR {
|
||||||
|
t.Fatalf("expected all source flags true: %+v", in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestBuildRichTokenMessageInput_OnlyAlpha(t *testing.T) {
|
||||||
|
in := buildRichTokenMessageInput(buildRichTokenMessageArgs{
|
||||||
|
Token: "ABC",
|
||||||
|
HasAlpha: true,
|
||||||
|
AlphaPrice: 0.1234,
|
||||||
|
HasAlpha24h: true,
|
||||||
|
Alpha24h: 12.4,
|
||||||
|
})
|
||||||
|
|
||||||
|
if !in.HasAlpha || !in.HasAlpha24h {
|
||||||
|
t.Fatalf("expected alpha flags true: %+v", in)
|
||||||
|
}
|
||||||
|
if in.HasSpot || in.HasFuture {
|
||||||
|
t.Fatalf("did not expect spot/future flags true: %+v", in)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type marketStub struct {
|
||||||
|
spotPairs map[string]bool
|
||||||
|
futuresPairs map[string]bool
|
||||||
|
spotPrices map[string]float64
|
||||||
|
futurePrices map[string]struct {
|
||||||
|
price float64
|
||||||
|
rate float64
|
||||||
|
time int64
|
||||||
|
}
|
||||||
|
alphaTokens map[string]market.AlphaTokenInfo
|
||||||
|
alphaPrices map[string]float64
|
||||||
|
marginRates map[string]float64
|
||||||
|
|
||||||
|
gate *sync.WaitGroup
|
||||||
|
ready chan struct{}
|
||||||
|
done chan struct{}
|
||||||
|
mu sync.Mutex
|
||||||
|
starts int
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *marketStub) waitConcurrentGate() {
|
||||||
|
if m.gate == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
m.mu.Lock()
|
||||||
|
m.starts++
|
||||||
|
m.mu.Unlock()
|
||||||
|
m.gate.Done()
|
||||||
|
<-m.ready
|
||||||
|
}
|
||||||
|
|
||||||
|
func (m *marketStub) GetFuturePrice(symbol string) (float64, float64, int64, bool) {
|
||||||
|
m.waitConcurrentGate()
|
||||||
|
v, ok := m.futurePrices[symbol]
|
||||||
|
if !ok {
|
||||||
|
return 0, 0, 0, false
|
||||||
|
}
|
||||||
|
return v.price, v.rate, v.time, true
|
||||||
|
}
|
||||||
|
func (m *marketStub) GetAllPremiumIndex() (map[string]market.PremiumIndex, error) { return nil, nil }
|
||||||
|
func (m *marketStub) GetAllFundRate() (map[string]float64, map[string]int64) { return nil, nil }
|
||||||
|
func (m *marketStub) GetSpotPrice(symbol string) (float64, bool) {
|
||||||
|
m.waitConcurrentGate()
|
||||||
|
v, ok := m.spotPrices[symbol]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
func (m *marketStub) GetMarginInterestRates() map[string]float64 { return m.marginRates }
|
||||||
|
func (m *marketStub) IsAlphaToken(symbol string) bool {
|
||||||
|
_, ok := m.alphaTokens[symbol]
|
||||||
|
return ok
|
||||||
|
}
|
||||||
|
func (m *marketStub) GetAlphaToken(symbol string) (market.AlphaTokenInfo, bool) {
|
||||||
|
v, ok := m.alphaTokens[symbol]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
func (m *marketStub) GetAlphaPrice(symbol string) (float64, bool) {
|
||||||
|
m.waitConcurrentGate()
|
||||||
|
v, ok := m.alphaPrices[symbol]
|
||||||
|
return v, ok
|
||||||
|
}
|
||||||
|
func (m *marketStub) IsSpotPair(symbol string) bool { return m.spotPairs[symbol] }
|
||||||
|
func (m *marketStub) IsFuturesPair(symbol string) bool { return m.futuresPairs[symbol] }
|
||||||
|
func (m *marketStub) RefreshTradingPairCache() error { return nil }
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_SpotOnlyReachable(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
data.Market = &marketStub{
|
||||||
|
spotPairs: map[string]bool{"ABCUSDT": true},
|
||||||
|
spotPrices: map[string]float64{"ABCUSDT": 1.23},
|
||||||
|
}
|
||||||
|
|
||||||
|
args := collectRichTokenData("ABC")
|
||||||
|
if !args.HasSpot {
|
||||||
|
t.Fatalf("expected spot to be reachable for spot-only token: %+v", args)
|
||||||
|
}
|
||||||
|
if args.HasFuture || args.HasAlpha {
|
||||||
|
t.Fatalf("did not expect future/alpha for spot-only token: %+v", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_FutureFailureStillKeepsSpot(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
data.Market = &marketStub{
|
||||||
|
spotPairs: map[string]bool{"ETHUSDT": true},
|
||||||
|
futuresPairs: map[string]bool{"ETHUSDT": true},
|
||||||
|
spotPrices: map[string]float64{"ETHUSDT": 3245},
|
||||||
|
futurePrices: map[string]struct {
|
||||||
|
price float64
|
||||||
|
rate float64
|
||||||
|
time int64
|
||||||
|
}{},
|
||||||
|
}
|
||||||
|
|
||||||
|
args := collectRichTokenData("ETH")
|
||||||
|
if !args.HasSpot {
|
||||||
|
t.Fatalf("expected spot to remain available when future lookup fails: %+v", args)
|
||||||
|
}
|
||||||
|
if args.HasFuture {
|
||||||
|
t.Fatalf("did not expect future when future lookup fails: %+v", args)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_AlphaUsesSymbolPrice(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
data.Market = &marketStub{
|
||||||
|
alphaTokens: map[string]market.AlphaTokenInfo{
|
||||||
|
"ABC": {Symbol: "ABC", PercentChange24h: "12.4", Price: "0.1"},
|
||||||
|
},
|
||||||
|
alphaPrices: map[string]float64{"ABCUSDT": 0.1234},
|
||||||
|
}
|
||||||
|
|
||||||
|
args := collectRichTokenData("ABC")
|
||||||
|
if !args.HasAlpha {
|
||||||
|
t.Fatalf("expected alpha to be available: %+v", args)
|
||||||
|
}
|
||||||
|
if !args.HasAlpha24h {
|
||||||
|
t.Fatalf("expected alpha 24h to be available: %+v", args)
|
||||||
|
}
|
||||||
|
if args.AlphaPrice != 0.1234 {
|
||||||
|
t.Fatalf("expected alpha price from symbol lookup, got %.4f", args.AlphaPrice)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestCollectRichTokenData_RunsLookupsConcurrently(t *testing.T) {
|
||||||
|
orig := data.Market
|
||||||
|
defer func() { data.Market = orig }()
|
||||||
|
|
||||||
|
gate := &sync.WaitGroup{}
|
||||||
|
gate.Add(3)
|
||||||
|
st := &marketStub{
|
||||||
|
spotPairs: map[string]bool{"ABCUSDT": true},
|
||||||
|
futuresPairs: map[string]bool{"ABCUSDT": true},
|
||||||
|
spotPrices: map[string]float64{"ABCUSDT": 1.23},
|
||||||
|
futurePrices: map[string]struct {
|
||||||
|
price float64
|
||||||
|
rate float64
|
||||||
|
time int64
|
||||||
|
}{"ABCUSDT": {price: 1.24, rate: 0.0001, time: 1740000000000}},
|
||||||
|
alphaTokens: map[string]market.AlphaTokenInfo{
|
||||||
|
"ABC": {Symbol: "ABC", PercentChange24h: "2.5", Price: "1.22"},
|
||||||
|
},
|
||||||
|
alphaPrices: map[string]float64{"ABCUSDT": 1.22},
|
||||||
|
gate: gate,
|
||||||
|
ready: make(chan struct{}),
|
||||||
|
}
|
||||||
|
data.Market = st
|
||||||
|
|
||||||
|
finished := make(chan buildRichTokenMessageArgs, 1)
|
||||||
|
go func() {
|
||||||
|
finished <- collectRichTokenData("ABC")
|
||||||
|
}()
|
||||||
|
|
||||||
|
waitDone := make(chan struct{})
|
||||||
|
go func() {
|
||||||
|
gate.Wait()
|
||||||
|
close(waitDone)
|
||||||
|
}()
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-waitDone:
|
||||||
|
close(st.ready)
|
||||||
|
case <-time.After(200 * time.Millisecond):
|
||||||
|
t.Fatalf("expected price lookups to run concurrently")
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case args := <-finished:
|
||||||
|
if !args.HasSpot || !args.HasFuture || !args.HasAlpha {
|
||||||
|
t.Fatalf("expected all lookups present: %+v", args)
|
||||||
|
}
|
||||||
|
case <-time.After(200 * time.Millisecond):
|
||||||
|
t.Fatalf("collectRichTokenData did not finish")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -2,13 +2,16 @@ package view
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
|
||||||
"github.com/jedib0t/go-pretty/v6/table"
|
"github.com/jedib0t/go-pretty/v6/table"
|
||||||
"golang.org/x/text/language"
|
"golang.org/x/text/language"
|
||||||
"golang.org/x/text/message"
|
"golang.org/x/text/message"
|
||||||
"me.thuanle/bbot/internal/helper/binancex"
|
"me.thuanle/bbot/internal/helper/binancex"
|
||||||
"me.thuanle/bbot/internal/services/tele/view/helper"
|
"me.thuanle/bbot/internal/services/tele/view/helper"
|
||||||
"me.thuanle/bbot/internal/utils/timex"
|
"me.thuanle/bbot/internal/utils/timex"
|
||||||
"time"
|
|
||||||
)
|
)
|
||||||
|
|
||||||
func RenderPrice(price float64) string {
|
func RenderPrice(price float64) string {
|
||||||
@@ -63,6 +66,73 @@ func RenderOnAlphaPriceMessage(symbol string, price float64, change24h float64)
|
|||||||
)
|
)
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type RichTokenMessageInput struct {
|
||||||
|
Token string
|
||||||
|
|
||||||
|
HasSpot bool
|
||||||
|
SpotPrice float64
|
||||||
|
|
||||||
|
HasFuture bool
|
||||||
|
FuturePrice float64
|
||||||
|
FundingRate float64
|
||||||
|
FundingTimeMs int64
|
||||||
|
|
||||||
|
HasAlpha bool
|
||||||
|
AlphaPrice float64
|
||||||
|
|
||||||
|
HasAlpha24h bool
|
||||||
|
Alpha24hChange float64
|
||||||
|
|
||||||
|
HasMarginAPR bool
|
||||||
|
MarginAPRPercent float64
|
||||||
|
}
|
||||||
|
|
||||||
|
func RenderRichTokenMessage(in RichTokenMessageInput) string {
|
||||||
|
rows := []string{fmt.Sprintf("🪙 %s", strings.ToUpper(in.Token))}
|
||||||
|
|
||||||
|
if in.HasSpot {
|
||||||
|
rows = append(rows, fmt.Sprintf("💵 Spot: $%s", RenderPrice(in.SpotPrice)))
|
||||||
|
}
|
||||||
|
if in.HasFuture {
|
||||||
|
rows = append(rows, fmt.Sprintf("📈 Future: $%s", RenderPrice(in.FuturePrice)))
|
||||||
|
}
|
||||||
|
if in.HasAlpha {
|
||||||
|
rows = append(rows, fmt.Sprintf("🅰️ Alpha: $%s", RenderPrice(in.AlphaPrice)))
|
||||||
|
}
|
||||||
|
|
||||||
|
if in.HasSpot && in.HasFuture && in.SpotPrice > 0 {
|
||||||
|
delta := in.FuturePrice - in.SpotPrice
|
||||||
|
deltaPct := delta / in.SpotPrice * 100
|
||||||
|
sign := "+"
|
||||||
|
if delta < 0 {
|
||||||
|
sign = "-"
|
||||||
|
}
|
||||||
|
rows = append(rows, fmt.Sprintf("🧭 Basis: %s$%s (%+.2f%%)", sign, RenderPrice(math.Abs(delta)), deltaPct))
|
||||||
|
}
|
||||||
|
|
||||||
|
if in.HasFuture {
|
||||||
|
rows = append(rows, fmt.Sprintf("💸 Funding: %.4f%% %s in %s",
|
||||||
|
in.FundingRate*100,
|
||||||
|
IconOfFundingFeeDirection(in.FundingRate),
|
||||||
|
timex.CdMinuteStringTime(time.UnixMilli(in.FundingTimeMs)),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
if in.HasMarginAPR {
|
||||||
|
rows = append(rows, fmt.Sprintf("🏦 Margin: %.3f%% APR", in.MarginAPRPercent))
|
||||||
|
}
|
||||||
|
|
||||||
|
if in.HasAlpha24h {
|
||||||
|
icon := "🟢"
|
||||||
|
if in.Alpha24hChange < 0 {
|
||||||
|
icon = "🔴"
|
||||||
|
}
|
||||||
|
rows = append(rows, fmt.Sprintf("📊 Alpha 24h: %s%+.2f%%", icon, in.Alpha24hChange))
|
||||||
|
}
|
||||||
|
|
||||||
|
return strings.Join(rows, "\n")
|
||||||
|
}
|
||||||
|
|
||||||
func RenderOnGetTopPricesMessage(symbols []string, price []float64, fundRate []float64) string {
|
func RenderOnGetTopPricesMessage(symbols []string, price []float64, fundRate []float64) string {
|
||||||
t := helper.NewNoBorderTableWriter("", "Price", "Fund")
|
t := helper.NewNoBorderTableWriter("", "Price", "Fund")
|
||||||
mFmt := message.NewPrinter(language.AmericanEnglish)
|
mFmt := message.NewPrinter(language.AmericanEnglish)
|
||||||
|
|||||||
@@ -0,0 +1,137 @@
|
|||||||
|
package view
|
||||||
|
|
||||||
|
import (
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func assertContainsAll(t *testing.T, msg string, rows ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, r := range rows {
|
||||||
|
if !strings.Contains(msg, r) {
|
||||||
|
t.Fatalf("expected row %q in message:\n%s", r, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func assertContainsNone(t *testing.T, msg string, rows ...string) {
|
||||||
|
t.Helper()
|
||||||
|
for _, r := range rows {
|
||||||
|
if strings.Contains(msg, r) {
|
||||||
|
t.Fatalf("unexpected row %q in message:\n%s", r, msg)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_AllSources(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "ETH",
|
||||||
|
HasSpot: true,
|
||||||
|
SpotPrice: 3245,
|
||||||
|
HasFuture: true,
|
||||||
|
FuturePrice: 3251,
|
||||||
|
FundingRate: 0.000123,
|
||||||
|
FundingTimeMs: 1740000000000,
|
||||||
|
HasAlpha: true,
|
||||||
|
AlphaPrice: 3248,
|
||||||
|
HasAlpha24h: true,
|
||||||
|
Alpha24hChange: -3.21,
|
||||||
|
HasMarginAPR: true,
|
||||||
|
MarginAPRPercent: 7.665,
|
||||||
|
})
|
||||||
|
|
||||||
|
expectedOrder := []string{
|
||||||
|
"🪙 ETH",
|
||||||
|
"💵 Spot:",
|
||||||
|
"📈 Future:",
|
||||||
|
"🅰️ Alpha:",
|
||||||
|
"🧭 Basis:",
|
||||||
|
"💸 Funding:",
|
||||||
|
"🏦 Margin:",
|
||||||
|
"📊 Alpha 24h:",
|
||||||
|
}
|
||||||
|
|
||||||
|
last := -1
|
||||||
|
for _, part := range expectedOrder {
|
||||||
|
i := strings.Index(msg, part)
|
||||||
|
if i == -1 {
|
||||||
|
t.Fatalf("missing row %q in message:\n%s", part, msg)
|
||||||
|
}
|
||||||
|
if i < last {
|
||||||
|
t.Fatalf("row %q appears out of order in message:\n%s", part, msg)
|
||||||
|
}
|
||||||
|
last = i
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_FutureOnly(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "ABC",
|
||||||
|
HasFuture: true,
|
||||||
|
FuturePrice: 1234,
|
||||||
|
FundingRate: 0.000081,
|
||||||
|
FundingTimeMs: 1740000000000,
|
||||||
|
HasMarginAPR: true,
|
||||||
|
MarginAPRPercent: 6.2,
|
||||||
|
})
|
||||||
|
|
||||||
|
assertContainsAll(t, msg, "🪙 ABC", "📈 Future:", "💸 Funding:", "🏦 Margin:")
|
||||||
|
assertContainsNone(t, msg, "💵 Spot:", "🅰️ Alpha:", "🧭 Basis:", "📊 Alpha 24h:")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_SpotOnly(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "XRP",
|
||||||
|
HasSpot: true,
|
||||||
|
SpotPrice: 2.1,
|
||||||
|
HasMarginAPR: true,
|
||||||
|
MarginAPRPercent: 5.11,
|
||||||
|
})
|
||||||
|
|
||||||
|
assertContainsAll(t, msg, "🪙 XRP", "💵 Spot:", "🏦 Margin:")
|
||||||
|
assertContainsNone(t, msg, "📈 Future:", "🅰️ Alpha:", "🧭 Basis:", "💸 Funding:", "📊 Alpha 24h:")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_AlphaOnly(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "ABC",
|
||||||
|
HasAlpha: true,
|
||||||
|
AlphaPrice: 0.1234,
|
||||||
|
HasAlpha24h: true,
|
||||||
|
Alpha24hChange: 12.4,
|
||||||
|
})
|
||||||
|
|
||||||
|
assertContainsAll(t, msg, "🪙 ABC", "🅰️ Alpha:", "📊 Alpha 24h:")
|
||||||
|
assertContainsNone(t, msg, "💵 Spot:", "📈 Future:", "🧭 Basis:", "💸 Funding:", "🏦 Margin:")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_SpotAndFuture(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "SOL",
|
||||||
|
HasSpot: true,
|
||||||
|
SpotPrice: 182.4,
|
||||||
|
HasFuture: true,
|
||||||
|
FuturePrice: 183.0,
|
||||||
|
FundingRate: -0.000041,
|
||||||
|
FundingTimeMs: 1740000000000,
|
||||||
|
HasMarginAPR: true,
|
||||||
|
MarginAPRPercent: 5.11,
|
||||||
|
})
|
||||||
|
|
||||||
|
assertContainsAll(t, msg, "🪙 SOL", "💵 Spot:", "📈 Future:", "🧭 Basis: +$0.6000", "💸 Funding:", "🏦 Margin:")
|
||||||
|
assertContainsNone(t, msg, "🅰️ Alpha:", "📊 Alpha 24h:")
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestRenderRichTokenMessage_SpotAndFutureNegativeBasis(t *testing.T) {
|
||||||
|
msg := RenderRichTokenMessage(RichTokenMessageInput{
|
||||||
|
Token: "ADA",
|
||||||
|
HasSpot: true,
|
||||||
|
SpotPrice: 1.2,
|
||||||
|
HasFuture: true,
|
||||||
|
FuturePrice: 1.1,
|
||||||
|
FundingRate: 0.000011,
|
||||||
|
FundingTimeMs: 1740000000000,
|
||||||
|
})
|
||||||
|
|
||||||
|
assertContainsAll(t, msg, "🧭 Basis: -$0.10000 (-8.33%)")
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user