20 Commits
Author SHA1 Message Date
discountry 8d79ace8b3 Refactor triggerType handling in order placement logic
- Updated the triggerType assignment in placeStopLossOrder and related functions to default to "STOP_LOSS" instead of conditionally setting it based on the order side.
- This change simplifies the logic for stop market orders across the order coordinator and GRVT exchange gateway, ensuring consistent behavior.
2026-02-01 11:15:00 +08:00
discountry 1fb6d3d62d Add swing trading configuration options to .env.example
- Added new environment variables for swing trading, including SWING_DIRECTION and SWING_STOP_LOSS_PCT.
- Updated documentation in .env.example to reflect the new swing trading parameters for better clarity and usability.
2026-01-31 16:19:19 +08:00
discountry c4559cb0d7 Add swing trading strategy with RSI signals and Binance integration
- Introduced a new swing trading strategy utilizing the RSI indicator on the ETHBTC pair from Binance.
- Implemented the `SwingEngine` to manage trading logic, including entry and exit conditions based on RSI thresholds.
- Added configuration options for swing direction, trade amount, and RSI parameters in `config.ts`.
- Created new documentation for the swing strategy, detailing its behavior and configuration.
- Enhanced CLI to support the new swing strategy option.
- Added tests for swing logic to ensure correct behavior under various market conditions.
2026-01-31 16:15:07 +08:00
discountry 1d88ddefb5 Enhance account snapshot handling and staleness checks in MakerPointsEngine
- Updated `emitAccountSnapshot` method in `StandxGateway` to accept an optional `updateTime` parameter, allowing for more accurate timestamping.
- Introduced logic to determine the appropriate `updateTime` based on the latest position or balance data.
- Added `time` property to `StandxPosition` interface for improved timestamp management.
- Implemented `applyAccountSnapshot` method in `MakerPointsEngine` to streamline account snapshot processing and ensure accurate time tracking.
- Added tests to validate the behavior of account staleness checks and defense mode activation based on account data freshness.
2026-01-24 23:53:36 +08:00
discountry 683352f737 Add changeMarginMode method to ExchangeAdapter and Standx classes
- Introduced `changeMarginMode` method in `ExchangeAdapter` interface to allow margin mode adjustments.
- Implemented the `changeMarginMode` method in `StandxExchangeAdapter` to interact with the gateway for changing margin modes.
- Added corresponding `changeMarginMode` method in `StandxGateway` to handle API requests for margin mode changes.
- Enhanced `MakerPointsEngine` to ensure isolated margin mode before order placement, with appropriate logging and defense mode activation if the change fails.
- Created tests for margin mode functionality to validate behavior under different scenarios.
2026-01-24 22:57:03 +08:00
discountry a629bc940c Enhance environment variable parsing and account snapshot validation
- Introduced `normalizeEnvValue` function to improve handling of environment variable values, including trimming, unquoting, and stripping inline comments.
- Updated `resolveSymbolFromEnv` and parsing functions to utilize the new normalization logic.
- Added `validateAccountSnapshotForSymbol` function to validate account snapshots, ensuring numeric fields are correctly formatted and flagging any issues.
- Implemented tests for environment variable parsing and account snapshot validation to ensure robustness and correctness.
2026-01-24 22:46:14 +08:00
discountry fe7b8eb6f3 Update Binance WebSocket configuration and enhance depth handling
- Changed WebSocket base URL to support both spot and futures trading.
- Adjusted depth tracking parameters for improved performance, increasing the ratio and reducing speed.
- Enhanced payload parsing to accommodate additional data structures from Binance, ensuring robust handling of bids and asks.
- Updated comments for clarity on connection behavior and heartbeat monitoring.
2026-01-22 10:23:07 +08:00
discountry 24339929dc Enhance MakerPoints functionality and configuration
- Updated `filterMinDepth` in `config.ts` from 1 to 50 to improve depth filtering logic.
- Added new translation entries for band depth display in `i18n/index.ts`.
- Introduced `bandDepths` to `MakerPointsSnapshot` in `maker-points-engine.ts` to track depth across different bands.
- Enhanced `BinanceDepthTracker` to support dynamic depth levels and speed settings.
- Updated `MakerPointsApp` to display band depth information, improving user interface clarity.
2026-01-22 02:27:45 +08:00
discountry ed855f6859 Refine data staleness checks in MakerPointsEngine
- Updated the logic to only consider depth data for staleness checks, excluding account data from the criteria.
- Removed unnecessary account staleness checks from defense mode activation, streamlining the data validation process.
- Enhanced comments for clarity on the rationale behind the changes.
2026-01-21 16:30:51 +08:00
discountry e144c1822f Implement data staleness defense mode in MakerPointsEngine
- Introduced a defense mode that activates when data from StandX or Binance is stale for over 5 seconds.
- Added methods to check data freshness, enter and exit defense mode, and cancel all orders during defense mode.
- Enhanced logging to provide insights into data staleness and defense mode transitions.
- Updated connection state management for clarity and consistency.
2026-01-21 16:24:17 +08:00
discountry 69271d33ca Refactor MakerPointsEngine and BinanceDepthTracker for improved connection management
- Renamed connection state variable in MakerPointsEngine for clarity.
- Added connection state change listeners in BinanceDepthTracker to handle connection status updates.
- Implemented heartbeat monitoring and connection duration checks in BinanceDepthTracker to enhance WebSocket reliability.
- Introduced data staleness checks and improved error handling for WebSocket connections.
- Enhanced logging for connection events to provide better insights into connection status changes.
2026-01-21 16:03:34 +08:00
discountry f1140f106a Enhance WebSocket connection management and data handling
- Introduced constants for WebSocket reconnection delays, heartbeat timeout, and data staleness thresholds.
- Implemented heartbeat monitoring to ensure timely reconnections on inactivity.
- Added data staleness checks to trigger REST API calls when market or account data is outdated.
- Enhanced the StandxGateway class with methods for managing heartbeat and data checks, improving overall connection reliability and data integrity.
2026-01-21 15:40:28 +08:00
discountry 3b935b7979 Refactor MakerPoints configuration and depth handling
- Renamed `band0To10MinDepth` to `filterMinDepth` in `config.ts` for clarity.
- Updated `MakerPointsEngine` to utilize the new `filterMinDepth` for depth checks across all bands.
- Introduced a method to track depth status changes, enhancing order placement logic based on market depth.
- Improved logging for depth-related order skips to provide clearer insights into trading decisions.
2026-01-21 11:26:21 +08:00
discountry 00388f9166 add filter 2026-01-21 11:11:58 +08:00
discountry a32efa2ba0 Refine target price calculation in LiquidityMakerEngine
- Updated target price logic to consider entry price when no recent fills are available, enhancing order placement accuracy.
- Adjusted conditions to ensure target prices are set appropriately based on market conditions and entry prices, preventing potential losses.
- Improved comments for clarity on the logic behind target price adjustments.
2026-01-20 01:28:24 +08:00
discountry 76704b6bdd Enhance entry price logic in Maker and Liquidity Maker strategies
- Added `entryDepthLevel` configuration option to `MakerConfig` and `LiquidityMakerConfig` for specifying order entry levels.
- Implemented `getPricesAtLevel` utility function to retrieve bid and ask prices at specified depth levels.
- Updated `MakerEngine`, `LiquidityMakerEngine`, and `OffsetMakerEngine` to utilize the new entry level logic for determining opening prices based on market depth.
- Improved price handling to ensure more accurate order placements in varying market conditions.
2026-01-20 01:03:38 +08:00
discountry 168d8cbb08 Add Claude instructions and enhance stop-loss logic
- Introduced a new `CLAUDE.md` file with instructions for using Bun as the package manager.
- Adjusted stop-loss cooldown and check intervals in `MakerPointsEngine` for improved responsiveness.
- Implemented a new method to compute real-time PnL using live depth data, enhancing stop-loss decision-making.
- Added retry logic for stop-loss execution to ensure positions are closed effectively, with detailed logging for failures.
2026-01-20 00:51:15 +08:00
discountry 9629c22496 Enhance MakerPoints configuration and logic
- Added new configuration options for band-specific order amounts in `config.ts`.
- Implemented conditional logic in `MakerPointsEngine` to utilize the new band amounts based on the Binance depth cancel setting.
- Refactored order amount handling to improve clarity and maintainability.
2026-01-18 01:49:36 +08:00
discountry a34d06f9b4 fix slprice 2026-01-16 23:05:30 +08:00
discountry 2ba3e80ad9 fix sl 2026-01-16 22:59:38 +08:00
43 changed files with 4829 additions and 157 deletions
+4
View File
@@ -27,6 +27,10 @@ STANDX_SYMBOL=BTC-USD
TRADE_SYMBOL=BTCUSDT # Trading pair symbol TRADE_SYMBOL=BTCUSDT # Trading pair symbol
TRADE_AMOUNT=0.001 # Base order quantity (base asset, e.g. BTC) TRADE_AMOUNT=0.001 # Base order quantity (base asset, e.g. BTC)
# Swing Trading
SWING_DIRECTION=short # short | long | both
SWING_STOP_LOSS_PCT=0.05 # 0.05 = 5%
# Risk management (USD amounts unless noted) # Risk management (USD amounts unless noted)
LOSS_LIMIT=0.04 # Max loss per trade in USDT before forced close LOSS_LIMIT=0.04 # Max loss per trade in USDT before forced close
TRAILING_PROFIT=0.2 # Trailing stop activation profit (USDT) TRAILING_PROFIT=0.2 # Trailing stop activation profit (USDT)
+12
View File
@@ -0,0 +1,12 @@
# RitMEX Bot - Claude Instructions
## Package Manager
**必须使用 Bun** - 这个项目使用 Bun 作为包管理器和运行时。所有能用 bun 执行的命令都必须使用 bun:
- 安装依赖: `bun install`
- 运行脚本: `bun run <script>`
- 执行测试: `bun test`
- 类型检查: `bun run typecheck`
**不要使用 npm、yarn 或 npx**
+4
View File
@@ -1,5 +1,6 @@
{ {
"lockfileVersion": 1, "lockfileVersion": 1,
"configVersion": 0,
"workspaces": { "workspaces": {
"": { "": {
"name": "ritmex-bot", "name": "ritmex-bot",
@@ -14,6 +15,7 @@
"ethereum-cryptography": "^2.1.3", "ethereum-cryptography": "^2.1.3",
"ink": "^6.3.1", "ink": "^6.3.1",
"react": "^19.1.1", "react": "^19.1.1",
"trading-signals": "^7.4.3",
"viem": "^2.43.1", "viem": "^2.43.1",
"ws": "^8.18.3", "ws": "^8.18.3",
}, },
@@ -381,6 +383,8 @@
"tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="], "tinyspy": ["tinyspy@4.0.4", "", {}, "sha512-azl+t0z7pw/z958Gy9svOTuzqIk6xq+NSheJzn5MMWtWTFywIacg2wUlzKFGtt3cthx0r2SxMK0yzJOR0IES7Q=="],
"trading-signals": ["trading-signals@7.4.3", "", {}, "sha512-kOyzd85qhuhU7yGkB5z74MVP6j30xBCfZy5+bgBnvfxY1ZdvaQsdD+C5j+CoIRtCAgSOuxB7jmPpBrqO6h17sQ=="],
"ts-mixer": ["ts-mixer@6.0.4", "", {}, "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="], "ts-mixer": ["ts-mixer@6.0.4", "", {}, "sha512-ufKpbmrugz5Aou4wcr5Wc1UUFWOLhq+Fm6qa6P0w0K5Qw2yhaUoiWszhCVuNQyNwrlGiscHOmqYoAox1PtvgjA=="],
"type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="], "type-fest": ["type-fest@4.41.0", "", {}, "sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA=="],
+369
View File
@@ -0,0 +1,369 @@
- The following base endpoints are available. Please use whichever works best for your setup:
- **[https://api.binance.com](https://api.binance.com/)**
- **[https://api-gcp.binance.com](https://api-gcp.binance.com/)**
- **[https://api1.binance.com](https://api1.binance.com/)**
- **[https://api2.binance.com](https://api2.binance.com/)**
- **[https://api3.binance.com](https://api3.binance.com/)**
- **[https://api4.binance.com](https://api4.binance.com/)**
- The last 4 endpoints in the point above (`api1` - `api4`) should give better performance but have less stability.
- Responses are in JSON by default. To receive responses in SBE, refer to the [SBE FAQ](https://developers.binance.com/docs/binance-spot-api-docs/faqs/sbe_faq) page.
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
- Data is returned in **chronological order**, unless noted otherwise.
- Without `startTime` or `endTime`, returns the most recent items up to the limit.
- With `startTime`, returns oldest items from `startTime` up to the limit.
- With `endTime`, returns most recent items up to `endTime` and the limit.
- With both, behaves like `startTime` but does not exceed `endTime`.
- All time and timestamp related fields in the JSON responses are in **milliseconds by default.** To receive the information in microseconds, please add the header `X-MBX-TIME-UNIT:MICROSECOND` or `X-MBX-TIME-UNIT:microsecond`.
- We support HMAC, RSA, and Ed25519 keys. For more information, please see [API Key types](https://developers.binance.com/docs/binance-spot-api-docs/faqs/api_key_types).
- Timestamp parameters (e.g. `startTime`, `endTime`, `timestamp`) can be passed in milliseconds or microseconds.
- For APIs that only send public market data, please use the base endpoint **[https://data-api.binance.vision](https://data-api.binance.vision/)**. Please refer to [Market Data Only](https://developers.binance.com/docs/binance-spot-api-docs/faqs/market_data_only) page.
- If there are enums or terms you want clarification on, please see the [SPOT Glossary](https://developers.binance.com/docs/binance-spot-api-docs/faqs/spot_glossary) for more information.
- APIs have a timeout of 10 seconds when processing a request. If a response from the Matching Engine takes longer than this, the API responds with "Timeout waiting for response from backend server. Send status unknown; execution status unknown." [(-1007 TIMEOUT)](https://developers.binance.com/docs/binance-spot-api-docs/errors#-1007-timeout)
- This does not always mean that the request failed in the Matching Engine.
- If the status of the request has not appeared in [User Data Stream](https://developers.binance.com/docs/binance-spot-api-docs/user-data-stream), please perform an API query for its status.
- **Please avoid SQL keywords in requests** as they may trigger a security block by a WAF (Web Application Firewall) rule. See [https://www.binance.com/en/support/faq/detail/360004492232](https://www.binance.com/en/support/faq/detail/360004492232) for more details.
- If your request contains a symbol name containing non-ASCII characters, then the response may contain non-ASCII characters encoded in UTF-8.
- Some endpoints may return asset and/or symbol names containing non-ASCII characters encoded in UTF-8 even if the request did not contain non-ASCII characters.
Kline/Candlestick data
GET /api/v3/klines
Kline/candlestick bars for a symbol. Klines are uniquely identified by their open time.
Weight: 2
Parameters:
Name Type Mandatory Description
symbol STRING YES
interval ENUM YES
startTime LONG NO
endTime LONG NO
timeZone STRING NO Default: 0 (UTC)
limit INT NO Default: 500; Maximum: 1000.
Supported kline intervals (case-sensitive):
Interval interval value
seconds 1s
minutes 1m, 3m, 5m, 15m, 30m
hours 1h, 2h, 4h, 6h, 8h, 12h
days 1d, 3d
weeks 1w
months 1M
Notes:
If startTime and endTime are not sent, the most recent klines are returned.
Supported values for timeZone:
Hours and minutes (e.g. -1:00, 05:45)
Only hours (e.g. 0, 8, 4)
Accepted range is strictly [-12:00 to +14:00] inclusive
If timeZone provided, kline intervals are interpreted in that timezone instead of UTC.
Note that startTime and endTime are always interpreted in UTC, regardless of timeZone.
Data Source: Database
Response:
[
[
1499040000000, // Kline open time
"0.01634790", // Open price
"0.80000000", // High price
"0.01575800", // Low price
"0.01577100", // Close price
"148976.11427815", // Volume
1499644799999, // Kline Close time
"2434.19055334", // Quote asset volume
308, // Number of trades
"1756.87402397", // Taker buy base asset volume
"28.46694368", // Taker buy quote asset volume
"0" // Unused field, ignore.
]
]
## WebSocket Streams for Binance
## General WSS information
- The base endpoint is: **wss://stream.binance.com:9443** or **wss://stream.binance.com:443**.
- Streams can be accessed either in a single raw stream or in a combined stream.
- Raw streams are accessed at **/ws/<streamName>**
- Combined streams are accessed at **/stream?streams=<streamName1>/<streamName2>/<streamName3>**
- Combined stream events are wrapped as follows: **{"stream":"<streamName>","data":<rawPayload>}**
- All symbols for streams are **lowercase**
- A single connection to **stream.binance.com** is only valid for 24 hours; expect to be disconnected at the 24 hour mark
- The WebSocket server will send a `ping frame` every 20 seconds.
- If the WebSocket server does not receive a `pong frame` back from the connection within a minute the connection will be disconnected.
- When you receive a ping, you must send a pong with a copy of ping's payload as soon as possible.
- Unsolicited `pong frames` are allowed, but will not prevent disconnection. **It is recommended that the payload for these pong frames are empty.**
- The base endpoint **wss://data-stream.binance.vision** can be subscribed to receive **only** market data messages.
User data stream is **NOT** available from this URL.
- All time and timestamp related fields are **milliseconds by default**. To receive the information in microseconds, please add the parameter `timeUnit=MICROSECOND or timeUnit=microsecond` in the URL.
- For example: `/stream?streams=btcusdt@trade&timeUnit=MICROSECOND`
- If your request contains a symbol name containing non-ASCII characters, then the stream events may contain non-ASCII characters encoded in UTF-8.
- \[All Market Mini Tickers Stream\](#all-market-mini-tickers-stream and [All Market Rolling Window Statistics Streams](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#all-market-rolling-window-statistics-streams) events may contain non-ASCII characters encoded in UTF-8.
## WebSocket Limits
- WebSocket connections have a limit of 5 incoming messages per second. A message is considered:
- A PING frame
- A PONG frame
- A JSON controlled message (e.g. subscribe, unsubscribe)
- A connection that goes beyond the limit will be disconnected; IPs that are repeatedly disconnected may be banned.
- A single connection can listen to a maximum of 1024 streams.
- There is a limit of **300 connections per attempt every 5 minutes per IP**.
## Live Subscribing/Unsubscribing to streams
- The following data can be sent through the WebSocket instance in order to subscribe/unsubscribe from streams. Examples can be seen below.
- The `id` is used as an identifier to uniquely identify the messages going back and forth. The following formats are accepted:
- 64-bit signed integer
- alphanumeric strings; max length 36
- `null`
- In the response, if the `result` received is `null` this means the request sent was a success for non-query requests (e.g. Subscribing/Unsubscribing).
### Subscribe to a stream
- Request
- Response
```javascript
{
"result": null,
"id": 1
}
```
### Unsubscribe to a stream
- Request
- Response
```javascript
{
"result": null,
"id": 312
}
```
### Listing Subscriptions
- Request
```javascript
{
"method": "LIST_SUBSCRIPTIONS",
"id": 3
}
```
- Response
```javascript
{
"result": ["btcusdt@aggTrade"],
"id": 3
}
```
### Setting Properties
Currently, the only property that can be set is whether `combined` stream payloads are enabled or not. The combined property is set to `false` when connecting using `/ws/` ("raw streams") and `true` when connecting using `/stream/`.
- Request
```javascript
{
"method": "SET_PROPERTY",
"params": ["combined", true],
"id": 5
}
```
- Response
```javascript
{
"result": null,
"id": 5
}
```
### Retrieving Properties
- Request
```javascript
{
"method": "GET_PROPERTY",
"params": ["combined"],
"id": 2
}
```
- Response
```javascript
{
"result": true, // Indicates that combined is set to true.
"id": 2
}
```
| Error Message | Description |
| --- | --- |
| {"code": 0, "msg": "Unknown property","id": %s} | Parameter used in the `SET_PROPERTY` or `GET_PROPERTY` was invalid |
| {"code": 1, "msg": "Invalid value type: expected Boolean"} | Value should only be `true` or `false` |
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name provided was invalid |
| {"code": 2, "msg": "Invalid request: request ID must be an unsigned integer"} | Parameter `id` had to be provided or the value provided in the `id` parameter is an unsupported type |
| {"code": 2, "msg": "Invalid request: unknown variant %s, expected one of `SUBSCRIBE`, `UNSUBSCRIBE`, `LIST_SUBSCRIPTIONS`, `SET_PROPERTY`, `GET_PROPERTY` at line 1 column 28"} | Possible typo in the provided method or provided method was neither of the expected values |
| {"code": 2, "msg": "Invalid request: too many parameters"} | Unnecessary parameters provided in the data |
| {"code": 2, "msg": "Invalid request: property name must be a string"} | Property name was not provided |
| {"code": 2, "msg": "Invalid request: missing field `method` at line 1 column 73"} | `method` was not provided in the data |
| {"code":3,"msg":"Invalid JSON: expected value at line %s column %s"} | JSON data sent has incorrect syntax. |
## Detailed Stream information
## Aggregate Trade Streams
The Aggregate Trade Streams push trade information that is aggregated for a single taker order.
**Stream Name:** <symbol>@aggTrade
**Update Speed:** Real-time
**Payload:**
```javascript
{
"e": "aggTrade", // Event type
"E": 1672515782136, // Event time
"s": "BNBBTC", // Symbol
"a": 12345, // Aggregate trade ID
"p": "0.001", // Price
"q": "100", // Quantity
"f": 100, // First trade ID
"l": 105, // Last trade ID
"T": 1672515782136, // Trade time
"m": true, // Is the buyer the market maker?
"M": true // Ignore
}
```
## Trade Streams
The Trade Streams push raw trade information; each trade has a unique buyer and seller.
**Stream Name:** <symbol>@trade
**Update Speed:** Real-time
**Payload:**
```javascript
{
"e": "trade", // Event type
"E": 1672515782136, // Event time
"s": "BNBBTC", // Symbol
"t": 12345, // Trade ID
"p": "0.001", // Price
"q": "100", // Quantity
"T": 1672515782136, // Trade time
"m": true, // Is the buyer the market maker?
"M": true // Ignore
}
```
## Kline/Candlestick Streams for UTC
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+0` timezone
**Kline/Candlestick chart intervals:**
s-> seconds; m -> minutes; h -> hours; d -> days; w -> weeks; M -> months
- 1s
- 1m
- 3m
- 5m
- 15m
- 30m
- 1h
- 2h
- 4h
- 6h
- 8h
- 12h
- 1d
- 3d
- 1w
- 1M
**Stream Name:** <symbol>@kline\_<interval>
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
**Payload:**
```javascript
{
"e": "kline", // Event type
"E": 1672515782136, // Event time
"s": "BNBBTC", // Symbol
"k": {
"t": 1672515780000, // Kline start time
"T": 1672515839999, // Kline close time
"s": "BNBBTC", // Symbol
"i": "1m", // Interval
"f": 100, // First trade ID
"L": 200, // Last trade ID
"o": "0.0010", // Open price
"c": "0.0020", // Close price
"h": "0.0025", // High price
"l": "0.0015", // Low price
"v": "1000", // Base asset volume
"n": 100, // Number of trades
"x": false, // Is this kline closed?
"q": "1.0000", // Quote asset volume
"V": "500", // Taker buy base asset volume
"Q": "0.500", // Taker buy quote asset volume
"B": "123456" // Ignore
}
}
```
## Kline/Candlestick Streams with timezone offset
The Kline/Candlestick Stream push updates to the current klines/candlestick every second in `UTC+8` timezone
**Kline/Candlestick chart intervals:**
Supported intervals: See [`Kline/Candlestick chart intervals`](https://developers.binance.com/docs/binance-spot-api-docs/web-socket-streams#kline-intervals)
**UTC+8 timezone offset:**
- Kline intervals open and close in the `UTC+8` timezone. For example the `1d` klines will open at the beginning of the `UTC+8` day, and close at the end of the `UTC+8` day.
- Note that `E` (event time), `t` (start time) and `T` (close time) in the payload are Unix timestamps, which are always interpreted in UTC.
**Stream Name:** <symbol>@kline\_<interval>@+08:00
**Update Speed:** 1000ms for `1s`, 2000ms for the other intervals
**Payload:**
```javascript
{
"e": "kline", // Event type
"E": 1672515782136, // Event time
"s": "BNBBTC", // Symbol
"k": {
"t": 1672515780000, // Kline start time
"T": 1672515839999, // Kline close time
"s": "BNBBTC", // Symbol
"i": "1m", // Interval
"f": 100, // First trade ID
"L": 200, // Last trade ID
"o": "0.0010", // Open price
"c": "0.0020", // Close price
"h": "0.0025", // High price
"l": "0.0015", // Low price
"v": "1000", // Base asset volume
"n": 100, // Number of trades
"x": false, // Is this kline closed?
"q": "1.0000", // Quote asset volume
"V": "500", // Taker buy base asset volume
"Q": "0.500", // Taker buy quote asset volume
"B": "123456" // Ignore
}
}
```
+287
View File
@@ -0,0 +1,287 @@
# Trading Signals
![Language Details](https://img.shields.io/github/languages/top/bennycode/trading-signals) ![Code Coverage](https://img.shields.io/codecov/c/github/bennycode/trading-signals/main) ![License](https://img.shields.io/npm/l/trading-signals.svg) ![Package Version](https://img.shields.io/npm/v/trading-signals.svg)
Technical indicators and overlays to run [technical analysis](https://en.wikipedia.org/wiki/Technical_analysis) with JavaScript / TypeScript.
## Motivation
The "trading-signals" library provides a TypeScript implementation for common technical indicators. It is well-suited for algorithmic trading, allowing developers to perform signal computations for automated trading strategies.
All indicators can be updated over time by streaming data (prices or [candles](https://en.wikipedia.org/wiki/Candlestick_chart)) to the `add` method. Some indicators also provide `static` batch methods for further performance improvements when providing data up-front during a backtest or historical data import. You can try it out streaming input data by running the provided [demo script](./src/start/demo.ts) with `npm start`, which uses a keyboard input stream.
## Features
- **Streaming Updates:** No need to reprocess historical data
- **Replace Mode:** Efficient live chart updates
- **Lazy Evaluation:** Indicators only calculate when stable
- **Memory Efficiency:** Rolling windows, not full history storage
- **Excellent Test Coverage:** 100% across all metrics
- **Zero Runtime Dependencies:** Minimal bundle size
- **Type Safety:** Full TypeScript with strict mode
## Installation
```bash
npm install trading-signals
```
## Usage
**CommonJS:**
```ts
const {SMA} = require('trading-signals');
```
**ESM:**
```ts
import {SMA} from 'trading-signals';
```
**Example:**
```typescript
import {SMA} from 'trading-signals';
const sma = new SMA(3);
// You can add values individually:
sma.add(40);
sma.add(30);
sma.add(20);
// You can add multiple values at once:
sma.updates([20, 40, 80]);
// You can replace a previous value (useful for live charting):
sma.replace(40);
// You can check if an indicator is stable:
console.log(sma.isStable); // true
// If an indicator is stable, you can get its result:
console.log(sma.getResult()); // 50.0003
// You can also get the result without optional chaining:
console.log(sma.getResultOrThrow()); // 50.0003
// Various precisions are available too:
console.log(sma.getResultOrThrow().toFixed(2)); // "50.00"
console.log(sma.getResultOrThrow().toFixed(4)); // "50.0003"
// Each indicator also includes convenient features such as "lowest" and "highest" lifetime values:
console.log(sma.lowest?.toFixed(2)); // "23.33"
console.log(sma.highest?.toFixed(2)); // "53.33"
```
### When to use `add(...)`?
To input data, you need to call the indicator's `add` method. Depending on whether the minimum required input data for the interval has been reached, the `add` method may or may not return a result from the indicator.
### When to use `getResultOrThrow()`?
You can call `getResultOrThrow()` at any point in time, but it throws errors unless an indicator has received the minimum amount of data. If you call `getResultOrThrow()` before an indicator has received the required amount of input values, a `NotEnoughDataError` will be thrown.
**Example:**
```ts
import {SMA} from 'trading-signals';
// Our interval is 3, so we need 3 input values
const sma = new SMA(3);
// We supply 2 input values
sma.add(10);
sma.add(40);
try {
// We will get an error, because the minimum amount of inputs is 3
sma.getResultOrThrow();
} catch (error) {
console.log(error.constructor.name); // "NotEnoughDataError"
}
// We will supply the 3rd input value
sma.add(70);
// Now, we will receive a proper result
console.log(sma.getResultOrThrow()); // 40
```
Most of the time, the minimum amount of data depends on the interval / time period used. If you're not sure, take a look at the test files for the indicator to see examples of correct usage.
### When to use `getRequiredInputs()`?
Every indicator provides a `getRequiredInputs()` method that returns the minimum number of input values needed before the indicator becomes stable and can produce results. This is useful for validation and understanding when an indicator will start producing return values.
**Example:**
```ts
import {SMA, EMA, RSI} from 'trading-signals';
const sma = new SMA(5);
console.log(sma.getRequiredInputs()); // 5
```
The required inputs often depend on the indicator's configuration (like interval/period) and its internal calculation requirements. Some indicators like **MACD** or **Stochastic Oscillator** may require more inputs than their primary period because they use multiple moving averages or lookback periods internally.
### When to use `getSignal()`?
Many momentum and trend indicators provide a `getSignal()` method that returns the current trading signal state along with change detection. This is useful for identifying potential trading opportunities.
**Example:**
```ts
import {RSI} from 'trading-signals';
const rsi = new RSI(14);
// Add price data
// ...
// Get the trading signal
const signal = rsi.getSignal();
console.log(signal.state); // "BEARISH", "BULLISH", "SIDEWAYS", or "UNKNOWN"
console.log(signal.hasChanged); // true if the signal state changed from the previous value
```
## Technical Indicator Types
### Indicator Function
- Momentum indicators: Measure the speed and strength (intensity) of price movements in a particular direction (overbought/oversold)
- Trend indicators: Measure the direction of a trend (bullish/bearish)
- Volatility indicators: Measure the degree of variation in prices over time, regardless of direction
- Volume indicators: Measure the strength of a trend based on volume
**Key readings:**
- Bullish sentiment: expect prices to rise
- Bearish sentiment: expect prices to fall
- Overbought condition: price may have risen too much too fast, meaning its trending up, but traders expect a short-term dip before continuing higher
- Oversold condition: price may have dropped too much too fast, meaning its trending down, but traders expect a short-term bounce before continuing lower or reversing upward
### Indicator Timing
- Leading Indicators: Predictive tools that try to signal future price movements before they happen (i.e. RSI, Stochastic Oscillator, Volume spikes)
- Lagging Indicators: Confirmative tools that signal after a trend or move has already started (i.e. Moving Averages, MACD, ADX)
### Indicator Scale
- Indicators: Have no upper or lower limits
- Oscillators: Move within a fixed range (e.g. 0-100, 1 to +1)
## Supported Technical Indicators
1. Acceleration Bands (ABANDS)
1. Accelerator Oscillator (AC)
1. Average Directional Index (ADX)
1. Average True Range (ATR)
1. Awesome Oscillator (AO)
1. Bollinger Bands (BBANDS)
1. Bollinger Bands Width (BBW)
1. Center of Gravity (CG)
1. Commodity Channel Index (CCI)
1. Directional Movement Index (DMI / DX)
1. Double Exponential Moving Average (DEMA)
1. Dual Moving Average (DMA)
1. Exponential Moving Average (EMA)
1. Interquartile Range (IQR)
1. Linear Regression (LINREG)
1. Mean Absolute Deviation (MAD)
1. Momentum (MOM / MTM)
1. Moving Average Convergence Divergence (MACD)
1. On-Balance Volume (OBV)
1. Parabolic SAR (PSAR)
1. Range Expansion Index (REI)
1. Rate-of-Change (ROC)
1. Relative Moving Average (RMA)
1. Relative Strength Index (RSI)
1. Simple Moving Average (SMA)
1. Spencer's 15-Point Moving Average (SMA15)
1. Stochastic Oscillator (STOCH)
1. Stochastic RSI (STOCHRSI)
1. Tom Demark's Sequential Indicator (TDS)
1. True Range (TR)
1. Volume-Weighted Average Price (VWAP)
1. Weighted Moving Average (WMA)
1. Wilder's Smoothed Moving Average (WSMA / WWS / SMMA / MEMA)
1. Williams %R (WILLR)
1. Zig Zag Indicator (ZigZag)
Utility Methods:
1. Average / Mean
1. Grid Sizing (for [grid trading bots](https://b2broker.com/news/understanding-grid-trading-purpose-pros-cons/))
1. Maximum
1. Median
1. Minimum
1. Quartile
1. Standard Deviation
1. Streaks
1. Weekday
## Performance
### Floating-point arithmetic caveats
JavaScript uses double-precision floating-point arithmetic. For example, `0.1 + 0.2` yields `0.30000000000000004` due to binary floating-point representation.
![JavaScript arithmetic](https://raw.githubusercontent.com/bennycode/trading-signals/main/packages/trading-signals/js-arithmetic.png)
While this isnt perfectly accurate, it usually doesnt matter in practice since indicators often work with averages, which already smooth out precision. In test cases, you can control precision by using Vitests [toBeCloseTo](https://vitest.dev/api/expect.html#tobecloseto) assertion.
Earlier versions of this library (up to version 6) used [big.js][1] for arbitrary-precision arithmetic, but that made calculations about 100x slower on average. For this reason, support for [big.js][1] was removed starting with version 7.
## Disclaimer
The information and publications of [trading-signals](https://github.com/bennycode/trading-signals) do not constitute financial advice, investment advice, trading advice or any other form of advice. All results from [trading-signals](https://github.com/bennycode/trading-signals) are intended for information purposes only.
It is very important to do your own analysis before making any investment based on your own personal circumstances. If you need financial advice or further advice in general, it is recommended that you identify a relevantly qualified individual in your jurisdiction who can advise you accordingly.
## Alternatives
- [Cloud9Trader Indicators (JavaScript)](https://github.com/Cloud9Trader/TechnicalIndicators)
- [Crypto Trading Hub Indicators (TypeScript)](https://github.com/anandanand84/technicalindicators)
- [Highcharts Indicators (TypeScript)](https://github.com/highcharts/highcharts/tree/v12.3.0/ts/Stock/Indicators)
- [Indicator TS (TypeScript)](https://github.com/cinar/indicatorts)
- [Jesse Trading Bot Indicators (Python)](https://docs.jesse.trade/docs/indicators/reference.html)
- [LEAN Indicators (C#)](https://github.com/QuantConnect/Lean/tree/master/Indicators)
- [libindicators (C#)](https://github.com/mgfx/libindicators)
- [Pandas TA (Python)](https://github.com/twopirllc/pandas-ta)
- [Stock Indicators for .NET (C#)](https://github.com/DaveSkender/Stock.Indicators)
- [StockSharp (C#)](https://github.com/StockSharp/StockSharp)
- [ta-lib (C)](https://github.com/TA-Lib/ta-lib/tree/main/src/ta_func)
- [ta-math (TypeScript)](https://github.com/munrocket/ta-math)
- [ta4j (Java)](https://github.com/ta4j/ta4j)
- [Technical Analysis for Rust (Rust)](https://github.com/greyblake/ta-rs)
- [Technical Analysis Library using Pandas and Numpy (Python)](https://github.com/bukosabino/ta)
- [Tulip Indicators (ANSI C)](https://github.com/TulipCharts/tulipindicators)
## Documentation
Build and run the documentation:
```bash
npm run docs
```
## Maintainers
[![Benny Neugebauer on Stack Exchange][stack_exchange_bennycode_badge]][stack_exchange_bennycode_url]
## ⭐️ Become a TypeScript rockstar! ⭐️
This package was built by Benny Neugebauer. Checkout my [**TypeScript course**](https://typescript.tv/) to become a coding rockstar!
[<img src="https://raw.githubusercontent.com/bennycode/trading-signals/main/packages/trading-signals/tstv.png">](https://typescript.tv/)
[1]: http://mikemcl.github.io/big.js/
[stack_exchange_bennycode_badge]: https://stackexchange.com/users/flair/203782.png?theme=default
[stack_exchange_bennycode_url]: https://stackexchange.com/users/203782/benny-neugebauer?tab=accounts
## License
This project is [MIT](./LICENSE) licensed.
+43
View File
@@ -0,0 +1,43 @@
# Swing strategy (RSI on Binance ETHBTC)
This repos `swing` strategy **trades the exchange symbol you run the bot with** (e.g. `TRADE_SYMBOL`), but **uses Binance spot `ETHBTC` 4h RSI(14)** as the global signal source (per `docs/swingtrading/strategy.md`).
## Key behavior
- **Signal source**: Binance spot `ETHBTC`, `4h` klines, RSI period `14`.
- **Trade target**: your selected exchanges `TRADE_SYMBOL` / `*_SYMBOL` (same as other strategies).
- **Default mode**: short-only (configurable to long / short / both).
- **Stop-loss**:
- Tries to place a stop-loss order when supported by the venue.
- Always runs a real-time “kill-switch”: if price crosses the stop threshold, it market-closes.
- **Spot accounts**: if the connected account is `marketType=spot` and you configure `SWING_DIRECTION=short` (or `both`), the strategy will refuse to trade.
## Environment variables
- **Core**
- `SWING_DIRECTION`: `short` (default) | `long` | `both`
- `SWING_TRADE_AMOUNT`: position size (falls back to `TRADE_AMOUNT`)
- `SWING_POLL_INTERVAL_MS`: loop interval (default `500`)
- **RSI / signal**
- `SWING_RSI_PERIOD`: default `14`
- `SWING_RSI_HIGH`: default `70`
- `SWING_RSI_LOW`: default `30`
- `SWING_SIGNAL_SYMBOL`: default `ETHBTC`
- `SWING_SIGNAL_INTERVAL`: default `4h`
- **Risk / precision**
- `SWING_STOP_LOSS_PCT`: default `0.05` (5%)
- `SWING_MAX_CLOSE_SLIPPAGE_PCT`: default `0.05`
- `SWING_PRICE_TICK`, `SWING_QTY_STEP`: optional overrides (otherwise synced from exchange when supported)
## Run
```bash
bun run index.ts --strategy swing
```
Silent mode:
```bash
bun run index.ts --strategy swing --silent
```
+24
View File
@@ -0,0 +1,24 @@
无论在任何交易所或者平台运行,都遵循以下逻辑:
无论交易任何交易对,都参照 ETHBTC 数据进行交易
从binance现货接口获取 ETHBTC 交易对 4 小时k线数据,rest 接口获取历史数据,获取500条即可
订阅ws获取最新一根K线的数据
参考 trading-signals 库,计算 RSI 指标,RSI 参数为 14
我们的策略仅单边做空,但需要预留配置,可以支持单边做多,单边做空,双向交易
下面针对单边做空的情况进行说明
RSI 指标上穿 70 时,进入等待做空状态,后续当 RSI 指标下穿 70 时,执行做空开仓操作
如果对应的平台支持挂止损 stop loss,则在开仓的同时需要挂一个开仓成本价上涨 5% 的止损单,止损百分比可以设置参数调整,同时也需要有实时监控的止损逻辑,如果在持仓状态下,当前交易对比开仓价格上涨超过 5% ,则执行主动的市价止损操作
策略需要实时监控当前的交易对ticker数据、orderbook数据,open orders、position,支持ws的全都使用ws数据实时更新
在有仓位的情况下,如果发现 ETHBTC 的 RSI 指标下穿 30,则进入等待平空状态,如果后续 RSI 指标上穿 30,并且确认仓位有盈利,则执行平空操作
如此循环往复
+1
View File
@@ -34,6 +34,7 @@
"ethereum-cryptography": "^2.1.3", "ethereum-cryptography": "^2.1.3",
"ink": "^6.3.1", "ink": "^6.3.1",
"react": "^19.1.1", "react": "^19.1.1",
"trading-signals": "^7.4.3",
"viem": "^2.43.1", "viem": "^2.43.1",
"ws": "^8.18.3" "ws": "^8.18.3"
} }
+3 -2
View File
@@ -1,4 +1,4 @@
export type StrategyId = "trend" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid"; export type StrategyId = "trend" | "swing" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid";
export interface CliOptions { export interface CliOptions {
strategy?: StrategyId; strategy?: StrategyId;
@@ -9,6 +9,7 @@ export interface CliOptions {
const STRATEGY_VALUES = new Set<StrategyId>([ const STRATEGY_VALUES = new Set<StrategyId>([
"trend", "trend",
"swing",
"guardian", "guardian",
"maker", "maker",
"maker-points", "maker-points",
@@ -98,7 +99,7 @@ function assignExchange(options: CliOptions, raw: string): void {
export function printCliHelp(): void { export function printCliHelp(): void {
// eslint-disable-next-line no-console // eslint-disable-next-line no-console
console.log(`Usage: bun run index.ts [--strategy <trend|guardian|maker|maker-points|offset-maker|liquidity-maker|basis|grid>] [--exchange <aster|grvt|lighter|backpack|paradex|nado|standx>] [--silent]\n\n` + console.log(`Usage: bun run index.ts [--strategy <trend|swing|guardian|maker|maker-points|offset-maker|liquidity-maker|basis|grid>] [--exchange <aster|grvt|lighter|backpack|paradex|nado|standx>] [--silent]\n\n` +
`Options:\n` + `Options:\n` +
` --strategy, -s Automatically start the specified strategy without the interactive menu.\n` + ` --strategy, -s Automatically start the specified strategy without the interactive menu.\n` +
` Aliases: offset, offset-maker for the offset maker engine.\n` + ` Aliases: offset, offset-maker for the offset maker engine.\n` +
+17 -1
View File
@@ -1,4 +1,4 @@
import { basisConfig, gridConfig, isBasisStrategyEnabled, liquidityMakerConfig, makerConfig, makerPointsConfig, tradingConfig } from "../config"; import { basisConfig, gridConfig, isBasisStrategyEnabled, liquidityMakerConfig, makerConfig, makerPointsConfig, swingConfig, tradingConfig } from "../config";
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter"; import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
import type { ExchangeAdapter } from "../exchanges/adapter"; import type { ExchangeAdapter } from "../exchanges/adapter";
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env"; import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
@@ -7,6 +7,7 @@ import { OffsetMakerEngine, type OffsetMakerEngineSnapshot } from "../strategy/o
import { LiquidityMakerEngine, type LiquidityMakerEngineSnapshot } from "../strategy/liquidity-maker-engine"; import { LiquidityMakerEngine, type LiquidityMakerEngineSnapshot } from "../strategy/liquidity-maker-engine";
import { MakerPointsEngine, type MakerPointsSnapshot } from "../strategy/maker-points-engine"; import { MakerPointsEngine, type MakerPointsSnapshot } from "../strategy/maker-points-engine";
import { TrendEngine, type TrendEngineSnapshot } from "../strategy/trend-engine"; import { TrendEngine, type TrendEngineSnapshot } from "../strategy/trend-engine";
import { SwingEngine, type SwingEngineSnapshot } from "../strategy/swing-engine";
import { GuardianEngine, type GuardianEngineSnapshot } from "../strategy/guardian-engine"; import { GuardianEngine, type GuardianEngineSnapshot } from "../strategy/guardian-engine";
import { BasisArbEngine, type BasisArbSnapshot } from "../strategy/basis-arb-engine"; import { BasisArbEngine, type BasisArbSnapshot } from "../strategy/basis-arb-engine";
import { GridEngine, type GridEngineSnapshot } from "../strategy/grid-engine"; import { GridEngine, type GridEngineSnapshot } from "../strategy/grid-engine";
@@ -21,6 +22,7 @@ type StrategyRunner = (options: RunnerOptions) => Promise<void>;
export const STRATEGY_LABELS: Record<StrategyId, string> = { export const STRATEGY_LABELS: Record<StrategyId, string> = {
trend: "Trend Following", trend: "Trend Following",
swing: "Swing",
guardian: "Guardian", guardian: "Guardian",
maker: "Maker", maker: "Maker",
"maker-points": "Maker Points", "maker-points": "Maker Points",
@@ -52,6 +54,19 @@ const STRATEGY_FACTORIES: Record<StrategyId, StrategyRunner> = {
offUpdate: (emitter) => engine.off("update", emitter), offUpdate: (emitter) => engine.off("update", emitter),
}); });
}, },
swing: async (opts) => {
const config = swingConfig;
const adapter = createAdapterOrThrow(config.symbol);
const engine = new SwingEngine(config, adapter);
await runEngine({
engine,
strategy: "swing",
silent: opts.silent,
getSnapshot: () => engine.getSnapshot(),
onUpdate: (emitter) => engine.on("update", emitter),
offUpdate: (emitter) => engine.off("update", emitter),
});
},
guardian: async (opts) => { guardian: async (opts) => {
const config = tradingConfig; const config = tradingConfig;
const adapter = createAdapterOrThrow(config.symbol); const adapter = createAdapterOrThrow(config.symbol);
@@ -167,6 +182,7 @@ interface EngineHarness<TSnapshot> {
async function runEngine< async function runEngine<
TSnapshot extends TSnapshot extends
| TrendEngineSnapshot | TrendEngineSnapshot
| SwingEngineSnapshot
| GuardianEngineSnapshot | GuardianEngineSnapshot
| MakerEngineSnapshot | MakerEngineSnapshot
| MakerPointsSnapshot | MakerPointsSnapshot
+107 -8
View File
@@ -105,23 +105,51 @@ export function resolveSymbolFromEnv(explicitExchangeId?: SupportedExchangeId |
: resolveExchangeId(); : resolveExchangeId();
const { envKeys, fallback } = SYMBOL_PRIORITY_BY_EXCHANGE[exchangeId]; const { envKeys, fallback } = SYMBOL_PRIORITY_BY_EXCHANGE[exchangeId];
for (const key of envKeys) { for (const key of envKeys) {
const value = process.env[key]; const value = normalizeEnvValue(process.env[key]);
if (value && value.trim()) { if (value) {
return value.trim(); return value;
} }
} }
return fallback; return fallback;
} }
function normalizeEnvValue(value: string | undefined): string | undefined {
if (!value) return undefined;
const trimmed = value.trim();
if (!trimmed) return undefined;
const quote = trimmed[0];
if ((quote === "'" || quote === "\"") && trimmed.endsWith(quote)) {
const unquoted = trimmed.slice(1, -1).trim();
return unquoted ? unquoted : undefined;
}
// Allow shell-style inline comments: KEY=value # comment
const commentIndexHash = trimmed.search(/\s#/);
const commentIndexSemi = trimmed.search(/\s;/);
const commentIndex =
commentIndexHash === -1
? commentIndexSemi
: commentIndexSemi === -1
? commentIndexHash
: Math.min(commentIndexHash, commentIndexSemi);
if (commentIndex !== -1) {
const withoutComment = trimmed.slice(0, commentIndex).trim();
return withoutComment ? withoutComment : undefined;
}
return trimmed;
}
function parseNumber(value: string | undefined, fallback: number): number { function parseNumber(value: string | undefined, fallback: number): number {
if (!value) return fallback; const normalized = normalizeEnvValue(value);
const next = Number(value); if (!normalized) return fallback;
const next = Number(normalized);
return Number.isFinite(next) ? next : fallback; return Number.isFinite(next) ? next : fallback;
} }
function parseBoolean(value: string | undefined, fallback: boolean): boolean { function parseBoolean(value: string | undefined, fallback: boolean): boolean {
if (!value) return fallback; const normalized = normalizeEnvValue(value)?.toLowerCase();
const normalized = value.trim().toLowerCase();
if (!normalized) return fallback; if (!normalized) return fallback;
if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") return true; if (normalized === "1" || normalized === "true" || normalized === "yes" || normalized === "on") return true;
if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off") return false; if (normalized === "0" || normalized === "false" || normalized === "no" || normalized === "off") return false;
@@ -157,6 +185,8 @@ export interface MakerConfig {
maxLogEntries: number; maxLogEntries: number;
maxCloseSlippagePct: number; maxCloseSlippagePct: number;
priceTick: number; priceTick: number;
/** 开仓挂单档位:1=买1/卖1,2=买2/卖2,以此类推。仅影响无仓位时的开仓挂单,平仓逻辑不受影响。默认1 */
entryDepthLevel: number;
} }
export const makerConfig: MakerConfig = { export const makerConfig: MakerConfig = {
@@ -172,6 +202,7 @@ export const makerConfig: MakerConfig = {
0.05 0.05
), ),
priceTick: parseNumber(process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1), priceTick: parseNumber(process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
entryDepthLevel: Math.max(1, Math.floor(parseNumber(process.env.MAKER_ENTRY_DEPTH_LEVEL, 1))),
}; };
export interface MakerPointsConfig { export interface MakerPointsConfig {
@@ -187,12 +218,24 @@ export interface MakerPointsConfig {
enableBand0To10: boolean; enableBand0To10: boolean;
enableBand10To30: boolean; enableBand10To30: boolean;
enableBand30To100: boolean; enableBand30To100: boolean;
/** 0-10 bps 档位挂单数量,未配置时使用 perOrderAmount */
band0To10Amount: number;
/** 10-30 bps 档位挂单数量,未配置时使用 perOrderAmount */
band10To30Amount: number;
/** 30-100 bps 档位挂单数量,未配置时使用 perOrderAmount */
band30To100Amount: number;
minRepriceBps: number; minRepriceBps: number;
/** 是否根据 Binance 盘口深度失衡自动取消单边挂单,默认 true */
enableBinanceDepthCancel: boolean;
/** 各档位最小深度阈值 (BTC),盘口到目标价之间的挂单量低于此值则跳过该档位,默认 50 */
filterMinDepth: number;
} }
const defaultMakerPointsAmount = parseNumber(process.env.MAKER_POINTS_ORDER_AMOUNT, parseNumber(process.env.TRADE_AMOUNT, 0.001));
export const makerPointsConfig: MakerPointsConfig = { export const makerPointsConfig: MakerPointsConfig = {
symbol: resolveSymbolFromEnv("standx"), symbol: resolveSymbolFromEnv("standx"),
perOrderAmount: parseNumber(process.env.MAKER_POINTS_ORDER_AMOUNT, parseNumber(process.env.TRADE_AMOUNT, 0.001)), perOrderAmount: defaultMakerPointsAmount,
closeThreshold: parseNumber(process.env.MAKER_POINTS_CLOSE_THRESHOLD, 0), closeThreshold: parseNumber(process.env.MAKER_POINTS_CLOSE_THRESHOLD, 0),
stopLossUsd: parseNumber(process.env.MAKER_POINTS_STOP_LOSS_USD, 0), stopLossUsd: parseNumber(process.env.MAKER_POINTS_STOP_LOSS_USD, 0),
refreshIntervalMs: parseNumber(process.env.MAKER_POINTS_REFRESH_INTERVAL_MS, 500), refreshIntervalMs: parseNumber(process.env.MAKER_POINTS_REFRESH_INTERVAL_MS, 500),
@@ -206,7 +249,12 @@ export const makerPointsConfig: MakerPointsConfig = {
enableBand0To10: parseBoolean(process.env.MAKER_POINTS_BAND_0_10, true), enableBand0To10: parseBoolean(process.env.MAKER_POINTS_BAND_0_10, true),
enableBand10To30: parseBoolean(process.env.MAKER_POINTS_BAND_10_30, true), enableBand10To30: parseBoolean(process.env.MAKER_POINTS_BAND_10_30, true),
enableBand30To100: parseBoolean(process.env.MAKER_POINTS_BAND_30_100, true), enableBand30To100: parseBoolean(process.env.MAKER_POINTS_BAND_30_100, true),
band0To10Amount: parseNumber(process.env.MAKER_POINTS_BAND_0_10_AMOUNT, defaultMakerPointsAmount),
band10To30Amount: parseNumber(process.env.MAKER_POINTS_BAND_10_30_AMOUNT, defaultMakerPointsAmount),
band30To100Amount: parseNumber(process.env.MAKER_POINTS_BAND_30_100_AMOUNT, defaultMakerPointsAmount),
minRepriceBps: parseNumber(process.env.MAKER_POINTS_MIN_REPRICE_BPS, 3), minRepriceBps: parseNumber(process.env.MAKER_POINTS_MIN_REPRICE_BPS, 3),
enableBinanceDepthCancel: parseBoolean(process.env.MAKER_POINTS_BINANCE_DEPTH_CANCEL, true),
filterMinDepth: parseNumber(process.env.MAKER_POINTS_FILTER_MIN_DEPTH, 50),
}; };
export interface BasisArbConfig { export interface BasisArbConfig {
@@ -333,6 +381,8 @@ export interface LiquidityMakerConfig {
closeTickOffset: number; closeTickOffset: number;
/** 偏移判断阈值倍数,当一侧深度超出另一侧此倍数时取消薄端订单,默认2 */ /** 偏移判断阈值倍数,当一侧深度超出另一侧此倍数时取消薄端订单,默认2 */
depthImbalanceRatio: number; depthImbalanceRatio: number;
/** 开仓挂单档位:1=买1/卖1,2=买2/卖2,以此类推。仅影响无仓位时的开仓挂单,平仓逻辑不受影响。默认1 */
entryDepthLevel: number;
} }
export const liquidityMakerConfig: LiquidityMakerConfig = { export const liquidityMakerConfig: LiquidityMakerConfig = {
@@ -350,6 +400,55 @@ export const liquidityMakerConfig: LiquidityMakerConfig = {
priceTick: parseNumber(process.env.LIQUIDITY_MAKER_PRICE_TICK ?? process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1), priceTick: parseNumber(process.env.LIQUIDITY_MAKER_PRICE_TICK ?? process.env.MAKER_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
closeTickOffset: Math.max(1, Math.floor(parseNumber(process.env.LIQUIDITY_MAKER_CLOSE_TICK_OFFSET, 1))), closeTickOffset: Math.max(1, Math.floor(parseNumber(process.env.LIQUIDITY_MAKER_CLOSE_TICK_OFFSET, 1))),
depthImbalanceRatio: Math.max(1.1, parseNumber(process.env.LIQUIDITY_MAKER_DEPTH_IMBALANCE_RATIO, 2)), depthImbalanceRatio: Math.max(1.1, parseNumber(process.env.LIQUIDITY_MAKER_DEPTH_IMBALANCE_RATIO, 2)),
entryDepthLevel: Math.max(1, Math.floor(parseNumber(process.env.MAKER_ENTRY_DEPTH_LEVEL, 1))),
};
export type SwingDirection = "both" | "long" | "short";
export interface SwingConfig {
symbol: string;
tradeAmount: number;
pollIntervalMs: number;
maxLogEntries: number;
maxCloseSlippagePct: number;
priceTick: number;
qtyStep: number;
direction: SwingDirection;
rsiPeriod: number;
rsiHigh: number;
rsiLow: number;
stopLossPct: number;
signalSymbol: string;
signalInterval: string;
}
const resolveSwingDirection = (raw: string | undefined, fallback: SwingDirection): SwingDirection => {
if (!raw) return fallback;
const normalized = raw.trim().toLowerCase();
if (normalized === "long" || normalized === "long-only") return "long";
if (normalized === "short" || normalized === "short-only") return "short";
if (normalized === "both" || normalized === "dual" || normalized === "bi" || normalized === "two-way") return "both";
return fallback;
};
export const swingConfig: SwingConfig = {
symbol: resolveSymbolFromEnv(),
tradeAmount: parseNumber(process.env.SWING_TRADE_AMOUNT ?? process.env.TRADE_AMOUNT, 0.001),
pollIntervalMs: parseNumber(process.env.SWING_POLL_INTERVAL_MS, parseNumber(process.env.POLL_INTERVAL_MS, 500)),
maxLogEntries: parseNumber(process.env.SWING_MAX_LOG_ENTRIES, parseNumber(process.env.MAX_LOG_ENTRIES, 200)),
maxCloseSlippagePct: parseNumber(
process.env.SWING_MAX_CLOSE_SLIPPAGE_PCT ?? process.env.MAX_CLOSE_SLIPPAGE_PCT,
0.05
),
priceTick: parseNumber(process.env.SWING_PRICE_TICK ?? process.env.PRICE_TICK, 0.1),
qtyStep: parseNumber(process.env.SWING_QTY_STEP ?? process.env.QTY_STEP, 0.001),
direction: resolveSwingDirection(process.env.SWING_DIRECTION, "short"),
rsiPeriod: Math.max(1, Math.floor(parseNumber(process.env.SWING_RSI_PERIOD, 14))),
rsiHigh: parseNumber(process.env.SWING_RSI_HIGH, 70),
rsiLow: parseNumber(process.env.SWING_RSI_LOW, 30),
stopLossPct: Math.max(0, parseNumber(process.env.SWING_STOP_LOSS_PCT, 0.05)),
signalSymbol: (process.env.SWING_SIGNAL_SYMBOL ?? "ETHBTC").trim().toUpperCase(),
signalInterval: (process.env.SWING_SIGNAL_INTERVAL ?? "4h").trim(),
}; };
export function isBasisStrategyEnabled(): boolean { export function isBasisStrategyEnabled(): boolean {
+1 -1
View File
@@ -296,7 +296,7 @@ export async function placeStopLossOrder(
timeInForce: "GTC", timeInForce: "GTC",
reduceOnly: true, reduceOnly: true,
closePosition: true, closePosition: true,
triggerType: side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS", triggerType: "STOP_LOSS",
}); });
pendings[type] = String(order.orderId); pendings[type] = String(order.orderId);
log("stop", `挂止损单: ${side} STOP_MARKET @ ${normalizedStop}`); log("stop", `挂止损单: ${side} STOP_MARKET @ ${normalizedStop}`);
+15
View File
@@ -37,6 +37,17 @@ export interface FundingRateListener {
(snapshot: FundingRateSnapshot): void; (snapshot: FundingRateSnapshot): void;
} }
export type RestHealthState = "healthy" | "unhealthy";
export interface RestHealthInfo {
consecutiveErrors: number;
method?: string;
path?: string;
error?: string;
}
export interface RestHealthListener {
(state: RestHealthState, info: RestHealthInfo): void;
}
export interface ExchangePrecision { export interface ExchangePrecision {
priceTick: number; priceTick: number;
qtyStep: number; qtyStep: number;
@@ -69,6 +80,10 @@ export interface ExchangeAdapter {
// 连接保护相关方法(可选,仅 StandX 支持) // 连接保护相关方法(可选,仅 StandX 支持)
onConnectionEvent?(listener: ConnectionEventListener): void; onConnectionEvent?(listener: ConnectionEventListener): void;
offConnectionEvent?(listener: ConnectionEventListener): void; offConnectionEvent?(listener: ConnectionEventListener): void;
onRestHealthEvent?(listener: RestHealthListener): void;
offRestHealthEvent?(listener: RestHealthListener): void;
queryOpenOrders?(): Promise<AsterOrder[]>; queryOpenOrders?(): Promise<AsterOrder[]>;
queryAccountSnapshot?(): Promise<AsterAccountSnapshot | null>;
changeMarginMode?(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void>;
forceCancelAllOrders?(): Promise<boolean>; forceCancelAllOrders?(): Promise<boolean>;
} }
+1 -1
View File
@@ -1337,7 +1337,7 @@ function buildUnsignedOrder(params: {
function buildTriggerMetadata(params: CreateOrderParams): GrvtUnsignedOrder["metadata"]["trigger"] | undefined { function buildTriggerMetadata(params: CreateOrderParams): GrvtUnsignedOrder["metadata"]["trigger"] | undefined {
if (params.type === "STOP_MARKET") { if (params.type === "STOP_MARKET") {
const triggerType = params.triggerType ?? (params.side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS"); const triggerType = params.triggerType ?? "STOP_LOSS";
const stopPrice = params.stopPrice ?? params.activationPrice; const stopPrice = params.stopPrice ?? params.activationPrice;
if (!stopPrice) { if (!stopPrice) {
throw new Error("GRVT stop orders require a stopPrice or activationPrice"); throw new Error("GRVT stop orders require a stopPrice or activationPrice");
+1 -1
View File
@@ -62,7 +62,7 @@ export async function createStopOrder(intent: StopOrderIntent): Promise<AsterOrd
quantity: intent.quantity, quantity: intent.quantity,
stopPrice: intent.stopPrice, stopPrice: intent.stopPrice,
timeInForce: intent.timeInForce ?? "GTC", timeInForce: intent.timeInForce ?? "GTC",
triggerType: intent.triggerType ?? (intent.side === "BUY" ? "TAKE_PROFIT" : "STOP_LOSS"), triggerType: intent.triggerType ?? "STOP_LOSS",
closePosition: toStringBoolean(intent.closePosition ?? true), closePosition: toStringBoolean(intent.closePosition ?? true),
reduceOnly: toStringBoolean(intent.reduceOnly ?? true), reduceOnly: toStringBoolean(intent.reduceOnly ?? true),
}, },
+19
View File
@@ -7,6 +7,7 @@ import type {
FundingRateListener, FundingRateListener,
KlineListener, KlineListener,
OrderListener, OrderListener,
RestHealthListener,
TickerListener, TickerListener,
} from "../adapter"; } from "../adapter";
import type { AsterOrder, CreateOrderParams } from "../types"; import type { AsterOrder, CreateOrderParams } from "../types";
@@ -138,6 +139,14 @@ export class StandxExchangeAdapter implements ExchangeAdapter {
this.gateway.offConnectionEvent(listener); this.gateway.offConnectionEvent(listener);
} }
onRestHealthEvent(listener: RestHealthListener): void {
this.gateway.onRestHealthEvent(listener);
}
offRestHealthEvent(listener: RestHealthListener): void {
this.gateway.offRestHealthEvent(listener);
}
/** /**
* 查询当前真实的挂单状态(通过 HTTP API) * 查询当前真实的挂单状态(通过 HTTP API)
* 用于验证实际挂单情况,防止取消请求丢失 * 用于验证实际挂单情况,防止取消请求丢失
@@ -147,6 +156,16 @@ export class StandxExchangeAdapter implements ExchangeAdapter {
return this.gateway.queryOpenOrders(this.symbol); return this.gateway.queryOpenOrders(this.symbol);
} }
async queryAccountSnapshot() {
await this.ensureInitialized("queryAccountSnapshot");
return this.gateway.queryAccountSnapshot();
}
async changeMarginMode(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void> {
await this.ensureInitialized("changeMarginMode");
await this.gateway.changeMarginMode(params.symbol, params.marginMode);
}
/** /**
* 强制取消所有挂单 * 强制取消所有挂单
* 会查询当前挂单然后取消,并验证取消成功 * 会查询当前挂单然后取消,并验证取消成功
+381 -27
View File
@@ -8,6 +8,9 @@ import type {
FundingRateListener, FundingRateListener,
KlineListener, KlineListener,
OrderListener, OrderListener,
RestHealthInfo,
RestHealthListener,
RestHealthState,
TickerListener, TickerListener,
} from "../adapter"; } from "../adapter";
import type { import type {
@@ -48,7 +51,21 @@ const DEFAULT_WS_URL = "wss://perps.standx.com/ws-stream/v1";
const DEFAULT_KLINE_LIMIT = 200; const DEFAULT_KLINE_LIMIT = 200;
const KLINE_REFRESH_MS = 30_000; const KLINE_REFRESH_MS = 30_000;
const FUNDING_REFRESH_MS = 60_000; const FUNDING_REFRESH_MS = 60_000;
const WS_RECONNECT_DELAY = 2000;
// ========== WebSocket 连接管理常量 ==========
// 基础重连延迟(毫秒)
const WS_RECONNECT_DELAY_BASE = 2000;
// 最大重连延迟(毫秒)- 指数退避上限
const WS_RECONNECT_DELAY_MAX = 30_000;
// 心跳超时(毫秒)- StandX 服务器 5 分钟无 pong 会断连,我们设置 2 分钟作为安全阈值
const WS_HEARTBEAT_TIMEOUT = 120_000;
// 心跳检查间隔(毫秒)- 每 30 秒检查一次是否收到消息
const WS_HEARTBEAT_CHECK_INTERVAL = 30_000;
// 数据过时阈值(毫秒)- 超过此时间未收到行情/仓位数据,启动 REST 主动拉取
const WS_DATA_STALE_THRESHOLD = 3000;
// REST 轮询间隔(毫秒)- WS 断连或数据过时时的 REST 拉取间隔
const REST_POLL_INTERVAL = 2000;
const REST_ERROR_DEFENSE_THRESHOLD = 3;
const SUPPORTED_QUOTES = ["USD", "USDT", "USDC", "DUSD"]; const SUPPORTED_QUOTES = ["USD", "USDT", "USDC", "DUSD"];
@@ -100,7 +117,7 @@ class StandxRequestSigner {
const requestId = crypto.randomUUID(); const requestId = crypto.randomUUID();
const timestamp = Date.now(); const timestamp = Date.now();
const signMessage = `${version},${requestId},${timestamp},${payload}`; const signMessage = `${version},${requestId},${timestamp},${payload}`;
const signatureBytes = await sign(Buffer.from(signMessage, "utf-8"), this.privateKey); const signatureBytes = sign(Buffer.from(signMessage, "utf-8"), this.privateKey);
return { return {
"x-request-sign-version": version, "x-request-sign-version": version,
"x-request-id": requestId, "x-request-id": requestId,
@@ -407,6 +424,10 @@ export class StandxGateway {
private readonly virtualStops = new Map<string, VirtualStop>(); private readonly virtualStops = new Map<string, VirtualStop>();
private accountSnapshot: AsterAccountSnapshot | null = null; private accountSnapshot: AsterAccountSnapshot | null = null;
private readonly restHealthListeners = new Set<RestHealthListener>();
private restConsecutiveErrors = 0;
private restUnhealthy = false;
private restLastError: string | null = null;
private fundingState = new Map<string, FundingState>(); private fundingState = new Map<string, FundingState>();
private marketWs: WebSocket | null = null; private marketWs: WebSocket | null = null;
@@ -416,6 +437,26 @@ export class StandxGateway {
private marketReconnectTimer: ReturnType<typeof setTimeout> | null = null; private marketReconnectTimer: ReturnType<typeof setTimeout> | null = null;
private readonly subscriptions = new Set<string>(); private readonly subscriptions = new Set<string>();
// ========== 心跳与连接管理 ==========
// 上次收到消息的时间戳
private lastMessageTime = 0;
// 心跳检查定时器
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
// 重连次数(用于指数退避)
private reconnectAttempts = 0;
// ========== 数据过时检测与 REST 备用 ==========
// 上次收到行情数据(price/depth)的时间戳
private lastMarketDataTime = 0;
// 上次收到账户数据(position/balance)的时间戳
private lastAccountDataTime = 0;
// 数据过时检查定时器
private dataStaleCheckTimer: ReturnType<typeof setInterval> | null = null;
// REST 轮询定时器(WS 断连时启用)
private restPollTimer: ReturnType<typeof setInterval> | null = null;
// REST 轮询是否激活
private restPollActive = false;
private readonly klineTimers = new Map<string, PollTimer>(); private readonly klineTimers = new Map<string, PollTimer>();
private readonly fundingTimers = new Map<string, PollTimer>(); private readonly fundingTimers = new Map<string, PollTimer>();
@@ -525,6 +566,14 @@ export class StandxGateway {
this.connectionListeners.add(listener); this.connectionListeners.add(listener);
} }
onRestHealthEvent(listener: RestHealthListener): void {
this.restHealthListeners.add(listener);
}
offRestHealthEvent(listener: RestHealthListener): void {
this.restHealthListeners.delete(listener);
}
offConnectionEvent(listener: ConnectionEventListener): void { offConnectionEvent(listener: ConnectionEventListener): void {
this.connectionListeners.delete(listener); this.connectionListeners.delete(listener);
} }
@@ -852,7 +901,18 @@ export class StandxGateway {
const handleOpen = () => { const handleOpen = () => {
this.marketWsReady = true; this.marketWsReady = true;
this.marketWsAuthed = false; this.marketWsAuthed = false;
// 重置重连计数和时间戳
this.reconnectAttempts = 0;
this.lastMessageTime = Date.now();
this.lastMarketDataTime = Date.now();
this.lastAccountDataTime = Date.now();
this.logDebug("ws open"); this.logDebug("ws open");
// 启动心跳监控
this.startHeartbeatMonitor();
// 启动数据过时检测
this.startDataStaleCheck();
// 停止 REST 轮询(WS 恢复后不再需要)
this.stopRestPoll();
this.sendAuthIfNeeded(); this.sendAuthIfNeeded();
}; };
const handleClose = () => { const handleClose = () => {
@@ -861,6 +921,9 @@ export class StandxGateway {
this.marketWsAuthed = false; this.marketWsAuthed = false;
this.marketWsAuthRequested = false; this.marketWsAuthRequested = false;
this.marketWs = null; this.marketWs = null;
// 停止心跳监控和数据过时检测
this.stopHeartbeatMonitor();
this.stopDataStaleCheck();
this.logDebug("ws close"); this.logDebug("ws close");
// 触发断连事件,启动断连保护 // 触发断连事件,启动断连保护
if (wasReady) { if (wasReady) {
@@ -899,15 +962,23 @@ export class StandxGateway {
private scheduleReconnect(): void { private scheduleReconnect(): void {
if (this.marketReconnectTimer) return; if (this.marketReconnectTimer) return;
this.logDebug("scheduling reconnect in 2s"); // 指数退避:delay = min(base * 2^attempts, max)
const delay = Math.min(
WS_RECONNECT_DELAY_BASE * Math.pow(2, this.reconnectAttempts),
WS_RECONNECT_DELAY_MAX
);
this.reconnectAttempts += 1;
this.logDebug(`scheduling reconnect in ${delay}ms (attempt ${this.reconnectAttempts})`);
this.marketReconnectTimer = setTimeout(() => { this.marketReconnectTimer = setTimeout(() => {
this.marketReconnectTimer = null; this.marketReconnectTimer = null;
this.logDebug("attempting reconnect"); this.logDebug("attempting reconnect");
this.connectMarketWs(); this.connectMarketWs();
}, WS_RECONNECT_DELAY); }, delay);
} }
private handleMarketMessage(event: { data: any }): void { private handleMarketMessage(event: { data: any }): void {
// 更新最后收到消息的时间(心跳监控)
this.lastMessageTime = Date.now();
this.logRawPayload(event.data); this.logRawPayload(event.data);
const payloads = parseJsonPayloads(event.data); const payloads = parseJsonPayloads(event.data);
if (payloads.length === 0) return; if (payloads.length === 0) return;
@@ -938,9 +1009,11 @@ export class StandxGateway {
return; return;
} }
if (channel === "depth_book") { if (channel === "depth_book") {
// 更新行情数据时间戳
this.lastMarketDataTime = Date.now();
const data = message.data as StandxDepthBook | undefined; const data = message.data as StandxDepthBook | undefined;
const rawSymbol = data?.symbol ?? message?.symbol; const rawSymbol = data?.symbol ?? message?.symbol;
if (!rawSymbol) return; if (!rawSymbol || !data) return;
const bids = normalizeDepthLevels((data.bids ?? []).map(([price, qty]) => [String(price), String(qty)]), "bid"); const bids = normalizeDepthLevels((data.bids ?? []).map(([price, qty]) => [String(price), String(qty)]), "bid");
const asks = normalizeDepthLevels((data.asks ?? []).map(([price, qty]) => [String(price), String(qty)]), "ask"); const asks = normalizeDepthLevels((data.asks ?? []).map(([price, qty]) => [String(price), String(qty)]), "ask");
const decrossed = decrossDepthBook(bids, asks); const decrossed = decrossDepthBook(bids, asks);
@@ -969,13 +1042,15 @@ export class StandxGateway {
lastUpdateId: Number(message.seq ?? Date.now()), lastUpdateId: Number(message.seq ?? Date.now()),
bids: finalBids, bids: finalBids,
asks: finalAsks, asks: finalAsks,
eventTime: toTimestamp(data.time), eventTime: Date.now(),
symbol: rawSymbol, symbol: rawSymbol,
}; };
this.emitDepth(rawSymbol, depth); this.emitDepth(rawSymbol, depth);
return; return;
} }
if (channel === "price") { if (channel === "price") {
// 更新行情数据时间戳
this.lastMarketDataTime = Date.now();
const data = message.data as StandxPrice | undefined; const data = message.data as StandxPrice | undefined;
if (!data?.symbol) return; if (!data?.symbol) return;
const ticker = this.mapTicker(data); const ticker = this.mapTicker(data);
@@ -983,6 +1058,8 @@ export class StandxGateway {
return; return;
} }
if (channel === "order") { if (channel === "order") {
// 更新账户数据时间戳
this.lastAccountDataTime = Date.now();
const payload = message.data as StandxOrder | StandxOrder[] | undefined; const payload = message.data as StandxOrder | StandxOrder[] | undefined;
if (!payload) return; if (!payload) return;
const items = Array.isArray(payload) ? payload : [payload]; const items = Array.isArray(payload) ? payload : [payload];
@@ -994,6 +1071,8 @@ export class StandxGateway {
return; return;
} }
if (channel === "position") { if (channel === "position") {
// 更新账户数据时间戳
this.lastAccountDataTime = Date.now();
const payload = message.data as StandxPosition | StandxPosition[] | undefined; const payload = message.data as StandxPosition | StandxPosition[] | undefined;
if (!payload) return; if (!payload) return;
const items = Array.isArray(payload) ? payload : [payload]; const items = Array.isArray(payload) ? payload : [payload];
@@ -1006,6 +1085,8 @@ export class StandxGateway {
return; return;
} }
if (channel === "balance") { if (channel === "balance") {
// 更新账户数据时间戳
this.lastAccountDataTime = Date.now();
const payload = message.data as StandxBalance | StandxBalance[] | undefined; const payload = message.data as StandxBalance | StandxBalance[] | undefined;
if (!payload) return; if (!payload) return;
const items = Array.isArray(payload) ? payload : [payload]; const items = Array.isArray(payload) ? payload : [payload];
@@ -1048,6 +1129,7 @@ export class StandxGateway {
if (!this.marketWsAuthed) return; if (!this.marketWsAuthed) return;
for (const entry of this.subscriptions) { for (const entry of this.subscriptions) {
const [channel, symbol] = entry.split(":"); const [channel, symbol] = entry.split(":");
if (!channel) continue;
this.sendSubscribe({ channel, ...(symbol ? { symbol } : {}) }); this.sendSubscribe({ channel, ...(symbol ? { symbol } : {}) });
} }
} }
@@ -1057,6 +1139,194 @@ export class StandxGateway {
this.marketWs?.send(JSON.stringify({ subscribe: stream })); this.marketWs?.send(JSON.stringify({ subscribe: stream }));
} }
// ========== 心跳监控 ==========
/**
* 启动心跳监控
* 定期检查是否收到消息,如果超时则主动触发重连
*/
private startHeartbeatMonitor(): void {
this.stopHeartbeatMonitor();
this.heartbeatTimer = setInterval(() => {
const now = Date.now();
const elapsed = now - this.lastMessageTime;
if (elapsed > WS_HEARTBEAT_TIMEOUT) {
this.logDebug(`heartbeat timeout (${elapsed}ms since last message), forcing reconnect`);
this.forceReconnect("heartbeat_timeout");
}
}, WS_HEARTBEAT_CHECK_INTERVAL);
}
/**
* 停止心跳监控
*/
private stopHeartbeatMonitor(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
// ========== 数据过时检测与 REST 备用拉取 ==========
/**
* 启动数据过时检测
* 即使 WS 连接正常,如果超过 3 秒未收到行情/账户数据,也主动通过 REST 拉取
*/
private startDataStaleCheck(): void {
this.stopDataStaleCheck();
this.dataStaleCheckTimer = setInterval(() => {
const now = Date.now();
const marketStale = now - this.lastMarketDataTime > WS_DATA_STALE_THRESHOLD;
const accountStale = now - this.lastAccountDataTime > WS_DATA_STALE_THRESHOLD;
if (marketStale || accountStale) {
this.logDebug("data stale detected", {
marketStaleMs: now - this.lastMarketDataTime,
accountStaleMs: now - this.lastAccountDataTime,
marketStale,
accountStale,
});
// 主动通过 REST 拉取数据
this.fetchStaleData(marketStale, accountStale);
}
}, 1000); // 每秒检查一次
}
/**
* 停止数据过时检测
*/
private stopDataStaleCheck(): void {
if (this.dataStaleCheckTimer) {
clearInterval(this.dataStaleCheckTimer);
this.dataStaleCheckTimer = null;
}
}
/**
* 主动拉取过时的数据
*/
private fetchStaleData(marketStale: boolean, accountStale: boolean): void {
// 获取当前订阅的 symbols
const symbols = new Set<string>();
for (const key of this.subscriptions) {
const [, symbol] = key.split(":");
if (symbol) symbols.add(symbol);
}
if (marketStale) {
for (const symbol of symbols) {
void this.fetchTickerSnapshot(symbol).catch((e) => this.logger("staleTickerFetch", e));
void this.fetchDepthSnapshot(symbol).catch((e) => this.logger("staleDepthFetch", e));
}
// 更新时间戳避免重复拉取
this.lastMarketDataTime = Date.now();
}
if (accountStale) {
void this.refreshAccountSnapshot().catch((e) => this.logger("staleAccountFetch", e));
for (const symbol of symbols) {
void this.refreshOpenOrders(symbol).catch((e) => this.logger("staleOrdersFetch", e));
}
// 更新时间戳避免重复拉取
this.lastAccountDataTime = Date.now();
}
}
/**
* 启动 REST 轮询(WS 断连时使用)
* 持续通过 REST API 拉取行情和账户数据,确保止损等逻辑能正常工作
*/
private startRestPoll(): void {
if (this.restPollActive) return;
this.restPollActive = true;
this.logDebug("REST poll started (WS disconnected)");
const poll = async () => {
if (!this.restPollActive) return;
// 获取当前订阅的 symbols
const symbols = new Set<string>();
for (const key of this.subscriptions) {
const [, symbol] = key.split(":");
if (symbol) symbols.add(symbol);
}
// 拉取行情数据
for (const symbol of symbols) {
try {
await this.fetchTickerSnapshot(symbol);
this.lastMarketDataTime = Date.now();
} catch (e) {
this.logger("restPollTicker", e);
}
try {
await this.fetchDepthSnapshot(symbol);
} catch (e) {
this.logger("restPollDepth", e);
}
}
// 拉取账户数据
try {
await this.refreshAccountSnapshot();
this.lastAccountDataTime = Date.now();
} catch (e) {
this.logger("restPollAccount", e);
}
// 继续下一次轮询
if (this.restPollActive) {
this.restPollTimer = setTimeout(() => void poll(), REST_POLL_INTERVAL);
}
};
void poll();
}
/**
* 停止 REST 轮询
*/
private stopRestPoll(): void {
if (!this.restPollActive) return;
this.restPollActive = false;
if (this.restPollTimer) {
clearTimeout(this.restPollTimer);
this.restPollTimer = null;
}
this.logDebug("REST poll stopped (WS restored)");
}
/**
* 强制重连(用于心跳超时)
* 与普通断连不同,这里不增加重连计数(因为是主动行为)
*/
private forceReconnect(reason: string): void {
this.logDebug(`force reconnect: ${reason}`);
// 停止监控
this.stopHeartbeatMonitor();
this.stopDataStaleCheck();
// 关闭现有连接
if (this.marketWs) {
try {
this.marketWs.close();
} catch {
// ignore close errors
}
this.marketWs = null;
}
// 重置状态
const wasReady = this.marketWsReady;
this.marketWsReady = false;
this.marketWsAuthed = false;
this.marketWsAuthRequested = false;
// 触发断连事件
if (wasReady) {
this.onDisconnect();
}
// 立即重连(不使用指数退避,因为是主动行为)
this.reconnectAttempts = 0;
this.scheduleReconnect();
}
private logDebug(context: string, detail?: unknown): void { private logDebug(context: string, detail?: unknown): void {
if (!this.debugWs) return; if (!this.debugWs) return;
if (detail === undefined) { if (detail === undefined) {
@@ -1128,7 +1398,7 @@ export class StandxGateway {
} }
} }
private emitAccountSnapshot(): void { private emitAccountSnapshot(updateTime?: number): void {
const positions = Array.from(this.positions.values()); const positions = Array.from(this.positions.values());
const assets = Array.from(this.balances.values()); const assets = Array.from(this.balances.values());
const totalWalletBalance = assets.reduce((sum, asset) => sum + Number(asset.walletBalance ?? 0), 0); const totalWalletBalance = assets.reduce((sum, asset) => sum + Number(asset.walletBalance ?? 0), 0);
@@ -1140,7 +1410,7 @@ export class StandxGateway {
canTrade: true, canTrade: true,
canDeposit: true, canDeposit: true,
canWithdraw: true, canWithdraw: true,
updateTime: Date.now(), updateTime: typeof updateTime === "number" && Number.isFinite(updateTime) && updateTime > 0 ? updateTime : Date.now(),
totalWalletBalance: String(totalWalletBalance || 0), totalWalletBalance: String(totalWalletBalance || 0),
totalUnrealizedProfit: String(totalUnrealizedProfit || 0), totalUnrealizedProfit: String(totalUnrealizedProfit || 0),
positions, positions,
@@ -1157,16 +1427,19 @@ export class StandxGateway {
} }
} }
private async refreshAccountSnapshot(): Promise<void> { private async refreshAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
try { try {
const [balance, positions] = await Promise.all([ const [balance, positions] = await Promise.all([
this.requestJson<StandxBalanceSnapshot>("/api/query_balance", { method: "GET" }), this.requestJson<StandxBalanceSnapshot>("/api/query_balance", { method: "GET" }),
this.requestJson<StandxPosition[]>("/api/query_positions", { method: "GET" }), this.requestJson<StandxPosition[]>("/api/query_positions", { method: "GET" }),
]); ]);
let restSnapshotTime = 0;
if (Array.isArray(positions)) { if (Array.isArray(positions)) {
for (const position of positions) { for (const position of positions) {
const mapped = this.mapPosition(position); const mapped = this.mapPosition(position);
this.positions.set(mapped.symbol, mapped); this.positions.set(mapped.symbol, mapped);
const positionTime = toTimestamp(position.time ?? position.updated_at);
restSnapshotTime = Math.max(restSnapshotTime, positionTime);
} }
} }
if (balance) { if (balance) {
@@ -1175,14 +1448,44 @@ export class StandxGateway {
asset: token, asset: token,
walletBalance: String(balance.balance ?? "0"), walletBalance: String(balance.balance ?? "0"),
availableBalance: String(balance.cross_available ?? balance.balance ?? "0"), availableBalance: String(balance.cross_available ?? balance.balance ?? "0"),
updateTime: Date.now(), updateTime: restSnapshotTime > 0 ? restSnapshotTime : Date.now(),
unrealizedProfit: String(balance.upnl ?? "0"), unrealizedProfit: String(balance.upnl ?? "0"),
}; };
this.balances.set(token, asset); this.balances.set(token, asset);
} }
this.emitAccountSnapshot(); this.emitAccountSnapshot(restSnapshotTime > 0 ? restSnapshotTime : undefined);
return this.accountSnapshot;
} catch (error) { } catch (error) {
this.logger("accountSnapshot", error); this.logger("accountSnapshot", error);
return null;
}
}
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
return await this.refreshAccountSnapshot();
}
async changeMarginMode(symbol: string, marginMode: "isolated" | "cross"): Promise<void> {
if (!this.signer.hasKey()) {
throw new Error("StandX change_margin_mode requires STANDX_REQUEST_PRIVATE_KEY for signed requests");
}
const normalized = normalizeSymbol(symbol);
const response = await this.requestJson<{ code?: number; message?: string; request_id?: string }>(
"/api/change_margin_mode",
{
method: "POST",
body: {
symbol: normalized,
margin_mode: marginMode,
},
signed: true,
extraHeaders: {
"x-session-id": this.sessionId,
},
}
);
if (response && typeof response.code === "number" && response.code !== 0) {
throw new Error(response.message ?? "StandX change margin mode rejected");
} }
} }
@@ -1379,7 +1682,7 @@ export class StandxGateway {
entryPrice: String(data.entry_price ?? "0"), entryPrice: String(data.entry_price ?? "0"),
unrealizedProfit: String(data.upnl ?? "0"), unrealizedProfit: String(data.upnl ?? "0"),
positionSide: "BOTH", positionSide: "BOTH",
updateTime: toTimestamp(data.updated_at), updateTime: toTimestamp(data.time ?? data.updated_at),
leverage: data.leverage ? String(data.leverage) : undefined, leverage: data.leverage ? String(data.leverage) : undefined,
marginType: data.margin_mode, marginType: data.margin_mode,
liquidationPrice: data.liq_price ? String(data.liq_price) : undefined, liquidationPrice: data.liq_price ? String(data.liq_price) : undefined,
@@ -1454,22 +1757,70 @@ export class StandxGateway {
} }
} }
} }
const response = await fetch(url.toString(), {
method: options.method,
headers,
body: options.method === "GET" ? undefined : body,
});
const text = await response.text();
if (!response.ok) {
throw new Error(`${options.method} ${path} failed (${response.status}): ${text}`);
}
if (!text) {
return {} as T;
}
try { try {
return JSON.parse(text) as T; const response = await fetch(url.toString(), {
} catch { method: options.method,
return text as unknown as T; headers,
body: options.method === "GET" ? undefined : body,
});
const text = await response.text();
if (!response.ok) {
throw new Error(`${options.method} ${path} failed (${response.status}): ${text}`);
}
if (!text) {
this.recordRestSuccess();
return {} as T;
}
try {
const parsed = JSON.parse(text) as T;
this.recordRestSuccess();
return parsed;
} catch {
this.recordRestSuccess();
return text as unknown as T;
}
} catch (error) {
this.recordRestError({
consecutiveErrors: this.restConsecutiveErrors + 1,
method: options.method,
path,
error: error instanceof Error ? error.message : String(error),
});
throw error;
}
}
private recordRestSuccess(): void {
if (this.restConsecutiveErrors === 0 && !this.restUnhealthy) return;
this.restConsecutiveErrors = 0;
this.restLastError = null;
if (!this.restUnhealthy) return;
this.restUnhealthy = false;
this.emitRestHealth("healthy", { consecutiveErrors: 0 });
}
private recordRestError(info: RestHealthInfo): void {
this.restConsecutiveErrors = Math.max(0, Number(info.consecutiveErrors) || 0);
this.restLastError = info.error ?? this.restLastError;
if (!this.restUnhealthy && this.restConsecutiveErrors >= REST_ERROR_DEFENSE_THRESHOLD) {
this.restUnhealthy = true;
this.emitRestHealth("unhealthy", {
consecutiveErrors: this.restConsecutiveErrors,
method: info.method,
path: info.path,
error: info.error ?? this.restLastError ?? undefined,
});
}
}
private emitRestHealth(state: RestHealthState, info: RestHealthInfo): void {
for (const listener of this.restHealthListeners) {
try {
listener(state, info);
} catch (error) {
this.logger("restHealthListener", error);
}
} }
} }
@@ -1509,6 +1860,9 @@ export class StandxGateway {
if (this.lastKnownOpenOrders.length > 0 && this.disconnectedSymbol) { if (this.lastKnownOpenOrders.length > 0 && this.disconnectedSymbol) {
this.startDisconnectCancelRetry(this.disconnectedSymbol); this.startDisconnectCancelRetry(this.disconnectedSymbol);
} }
// 启动 REST 轮询,确保断连期间仍能获取行情和账户数据(用于止损等逻辑)
this.startRestPoll();
} }
/** /**
+1
View File
@@ -24,6 +24,7 @@ export interface StandxPosition {
leverage?: string; leverage?: string;
liq_price?: string; liq_price?: string;
margin_mode?: string; margin_mode?: string;
time?: string;
updated_at?: string; updated_at?: string;
} }
+53
View File
@@ -25,6 +25,11 @@ const translations: Record<string, TranslationEntry> = {
zh: "监控均线信号,自动进出场并维护止损/止盈", zh: "监控均线信号,自动进出场并维护止损/止盈",
en: "Monitors SMA signals, automates entries/exits, maintains stops.", en: "Monitors SMA signals, automates entries/exits, maintains stops.",
}, },
"app.strategy.swing.label": { zh: "Swing 策略 (RSI14/4h)", en: "Swing (RSI14/4h)" },
"app.strategy.swing.desc": {
zh: "使用 Binance ETHBTC 4h RSI 信号,主动开平仓并维护止损",
en: "Uses Binance ETHBTC 4h RSI signals to actively trade and maintain stops.",
},
"app.strategy.guardian.label": { zh: "Guardian 防守策略", en: "Guardian Protection" }, "app.strategy.guardian.label": { zh: "Guardian 防守策略", en: "Guardian Protection" },
"app.strategy.guardian.desc": { "app.strategy.guardian.desc": {
zh: "不主动开仓,只为现有仓位补挂/移动止损,防止裸奔", zh: "不主动开仓,只为现有仓位补挂/移动止损,防止裸奔",
@@ -132,6 +137,50 @@ const translations: Record<string, TranslationEntry> = {
"trend.label.long": { zh: "做多", en: "Long" }, "trend.label.long": { zh: "做多", en: "Long" },
"trend.label.short": { zh: "做空", en: "Short" }, "trend.label.short": { zh: "做空", en: "Short" },
"trend.label.none": { zh: "无信号", en: "No signal" }, "trend.label.none": { zh: "无信号", en: "No signal" },
"swing.name": { zh: "Swing 策略", en: "swing strategy" },
"swing.title": { zh: "Swing 策略仪表盘", en: "Swing Strategy Dashboard" },
"swing.readyMessage": { zh: "正在等待交易所/RSI 信号…", en: "Waiting for exchange feeds / RSI signal..." },
"swing.headerLine": {
zh: "交易所: {exchange} 交易对: {symbol} 方向: {direction} 最近价格: {lastPrice} 状态: {phase}",
en: "Exchange: {exchange} | Symbol: {symbol} | Mode: {direction} | Last: {lastPrice} | Phase: {phase}",
},
"swing.signalLine": {
zh: "信号源: Binance {binanceSymbol} 价格: {binancePrice} RSI: {rsi} ({zone}) 连接: {connection}",
en: "Signal: Binance {binanceSymbol} | Price: {binancePrice} | RSI: {rsi} ({zone}) | Conn: {connection}",
},
"swing.statusLine": {
zh: "状态: {status} 按 Esc 返回策略选择",
en: "Status: {status} | Press Esc to return to menu.",
},
"swing.zone.overbought": { zh: "超买", en: "Overbought" },
"swing.zone.oversold": { zh: "超卖", en: "Oversold" },
"swing.zone.neutral": { zh: "正常区间", en: "Neutral" },
"swing.zone.unknown": { zh: "未知", en: "Unknown" },
"swing.phase.disabled": { zh: "已禁用", en: "Disabled" },
"swing.phase.initializing": { zh: "初始化/同步中", en: "Initializing" },
"swing.phase.observing": { zh: "观察", en: "Observing" },
"swing.phase.waitingOpenShort": { zh: "等待开空", en: "Waiting to open short" },
"swing.phase.waitingCloseShort": { zh: "等待平空", en: "Waiting to close short" },
"swing.phase.waitingOpenLong": { zh: "等待开多", en: "Waiting to open long" },
"swing.phase.waitingCloseLong": { zh: "等待平多", en: "Waiting to close long" },
"swing.positionLine": {
zh: "方向: {direction} 数量: {qty} 开仓价: {entry}",
en: "Direction: {direction} | Size: {qty} | Entry: {entry}",
},
"swing.pnlLine": {
zh: "浮动盈亏: {pnl} USDT 账户未实现盈亏: {unrealized} USDT",
en: "Floating PnL: {pnl} USDT | Account Unrealized: {unrealized} USDT",
},
"swing.stopLine": {
zh: "止损目标价: {stop}",
en: "Stop target: {stop}",
},
"swing.stateTitle": { zh: "策略状态", en: "Strategy State" },
"swing.armedLine": {
zh: "Armed: SE={se} SX={sx} LE={le} LX={lx}",
en: "Armed: SE={se} SX={sx} | LE={le} LX={lx}",
},
"swing.volumeLine": { zh: "累计成交量: {volume} USDT", en: "Total volume: {volume} USDT" },
"guardian.name": { zh: "Guardian 策略", en: "Guardian strategy" }, "guardian.name": { zh: "Guardian 策略", en: "Guardian strategy" },
"guardian.title": { zh: "Guardian 策略仪表盘", en: "Guardian Strategy Dashboard" }, "guardian.title": { zh: "Guardian 策略仪表盘", en: "Guardian Strategy Dashboard" },
"guardian.readyMessage": { zh: "正在等待行情/账户推送…", en: "Waiting for market/account feeds..." }, "guardian.readyMessage": { zh: "正在等待行情/账户推送…", en: "Waiting for market/account feeds..." },
@@ -202,6 +251,10 @@ const translations: Record<string, TranslationEntry> = {
zh: "Binance 深度: 买10 {buy} 卖10 {sell} 状态: {status}", zh: "Binance 深度: 买10 {buy} 卖10 {sell} 状态: {status}",
en: "Binance depth: bid10 {buy} | ask10 {sell} | Status: {status}", en: "Binance depth: bid10 {buy} | ask10 {sell} | Status: {status}",
}, },
"makerPoints.bandDepthLine": {
zh: "StandX 档位 {band}bps 深度: 买 {buy} 卖 {sell}",
en: "StandX band {band}bps depth: buy {buy} | sell {sell}",
},
"makerPoints.mode.closeOnly": { zh: "平仓", en: "Close only" }, "makerPoints.mode.closeOnly": { zh: "平仓", en: "Close only" },
"makerPoints.mode.normal": { zh: "正常", en: "Normal" }, "makerPoints.mode.normal": { zh: "正常", en: "Normal" },
"makerPoints.feed.binance": { zh: "Binance", en: "Binance" }, "makerPoints.feed.binance": { zh: "Binance", en: "Binance" },
+5 -1
View File
@@ -41,7 +41,11 @@ function formatNotificationMessage(notification: TradeNotification, accountLabel
lines.push(``); lines.push(``);
for (const [key, value] of Object.entries(notification.details)) { for (const [key, value] of Object.entries(notification.details)) {
if (value != null) { if (value != null) {
lines.push(`${key}: ${value}`); if (Array.isArray(value)) {
lines.push(`${key}: ${value.join(", ") || "[]"}`);
} else {
lines.push(`${key}: ${value}`);
}
} }
} }
} }
+1 -1
View File
@@ -7,7 +7,7 @@ export interface TradeNotification {
title: string; title: string;
message: string; message: string;
accountLabel?: string; accountLabel?: string;
details?: Record<string, string | number | boolean | null>; details?: Record<string, string | number | boolean | null | string[]>;
timestamp?: number; timestamp?: number;
} }
+237 -25
View File
@@ -6,7 +6,24 @@ const WebSocketCtor: typeof globalThis.WebSocket =
? globalThis.WebSocket ? globalThis.WebSocket
: ((NodeWebSocket as unknown) as typeof globalThis.WebSocket); : ((NodeWebSocket as unknown) as typeof globalThis.WebSocket);
const DEFAULT_BASE_URL = "wss://fstream.binance.com/ws"; const DEFAULT_BASE_URL = "wss://stream.binance.com:9443/ws";
// ========== Binance WebSocket 连接管理常量 ==========
// Binance 会发送 ping,若长时间无消息则认为连接异常
// 我们设置 5 分钟作为心跳超时阈值(保守值)
const HEARTBEAT_TIMEOUT_MS = 5 * 60 * 1000;
// 心跳检查间隔(每 30 秒检查一次)
const HEARTBEAT_CHECK_INTERVAL_MS = 30_000;
// Binance 连接最长有效期 24 小时,我们设置 23 小时主动重连
const MAX_CONNECTION_DURATION_MS = 23 * 60 * 60 * 1000;
// 数据过时阈值(毫秒)- 超过此时间未收到数据,标记为不可用
const DATA_STALE_THRESHOLD_MS = 5_000;
// 基础重连延迟
const RECONNECT_DELAY_BASE_MS = 3000;
// 最大重连延迟
const RECONNECT_DELAY_MAX_MS = 60_000;
export type BinanceConnectionState = "connected" | "disconnected" | "stale";
export interface BinanceDepthSnapshot { export interface BinanceDepthSnapshot {
symbol: string; symbol: string;
@@ -18,13 +35,29 @@ export interface BinanceDepthSnapshot {
updatedAt: number; updatedAt: number;
} }
export type BinanceConnectionListener = (state: BinanceConnectionState) => void;
export class BinanceDepthTracker { export class BinanceDepthTracker {
private ws: WebSocket | null = null; private ws: WebSocket | null = null;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null; private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelayMs = 3000; private reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
private stopped = false; private stopped = false;
private snapshot: BinanceDepthSnapshot | null = null; private snapshot: BinanceDepthSnapshot | null = null;
private listeners = new Set<(snapshot: BinanceDepthSnapshot) => void>(); private listeners = new Set<(snapshot: BinanceDepthSnapshot) => void>();
private connectionListeners = new Set<BinanceConnectionListener>();
// ========== 心跳与连接管理 ==========
// 上次收到消息的时间戳
private lastMessageTime = 0;
// 心跳检查定时器
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
// 连接建立时间(用于日志记录)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
private connectionStartTime = 0;
// 24 小时重连定时器
private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
// 当前连接状态
private connectionState: BinanceConnectionState = "disconnected";
constructor( constructor(
private readonly symbol: string, private readonly symbol: string,
@@ -32,6 +65,7 @@ export class BinanceDepthTracker {
baseUrl?: string; baseUrl?: string;
levels?: number; levels?: number;
ratio?: number; ratio?: number;
speedMs?: number;
logger?: (context: string, error: unknown) => void; logger?: (context: string, error: unknown) => void;
} }
) {} ) {}
@@ -43,18 +77,7 @@ export class BinanceDepthTracker {
stop(): void { stop(): void {
this.stopped = true; this.stopped = true;
if (this.reconnectTimer) { this.cleanup();
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
try {
this.ws.close();
} catch {
// Ignore close errors
}
this.ws = null;
}
} }
onUpdate(handler: (snapshot: BinanceDepthSnapshot) => void): void { onUpdate(handler: (snapshot: BinanceDepthSnapshot) => void): void {
@@ -65,37 +88,122 @@ export class BinanceDepthTracker {
this.listeners.delete(handler); this.listeners.delete(handler);
} }
/**
* 监听连接状态变化
*/
onConnectionChange(handler: BinanceConnectionListener): void {
this.connectionListeners.add(handler);
}
offConnectionChange(handler: BinanceConnectionListener): void {
this.connectionListeners.delete(handler);
}
getSnapshot(): BinanceDepthSnapshot | null { getSnapshot(): BinanceDepthSnapshot | null {
return this.snapshot ? { ...this.snapshot } : null; return this.snapshot ? { ...this.snapshot } : null;
} }
/**
* 获取当前连接状态
*/
getConnectionState(): BinanceConnectionState {
return this.connectionState;
}
/**
* 检查数据是否过时
*/
isDataStale(): boolean {
if (!this.snapshot) return true;
return Date.now() - this.snapshot.updatedAt > DATA_STALE_THRESHOLD_MS;
}
private cleanup(): void {
// 停止心跳监控
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
// 停止 24 小时重连定时器
if (this.maxDurationTimer) {
clearTimeout(this.maxDurationTimer);
this.maxDurationTimer = null;
}
// 停止重连定时器
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
// 关闭 WebSocket
if (this.ws) {
try {
this.ws.close();
} catch {
// Ignore close errors
}
this.ws = null;
}
}
private connect(): void { private connect(): void {
if (this.ws || this.stopped) return; if (this.ws || this.stopped) return;
const url = this.buildUrl(); const url = this.buildUrl();
this.ws = new WebSocketCtor(url); this.ws = new WebSocketCtor(url);
const handleOpen = () => { const handleOpen = () => {
this.reconnectDelayMs = 3000; this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
this.connectionStartTime = Date.now();
this.lastMessageTime = Date.now();
this.updateConnectionState("connected");
// 启动心跳监控
this.startHeartbeatMonitor();
// 启动 24 小时自动重连定时器
this.startMaxDurationTimer();
this.options?.logger?.("binanceDepth", "WebSocket connected");
}; };
const handleClose = () => { const handleClose = () => {
this.ws = null; this.ws = null;
this.stopHeartbeatMonitor();
this.stopMaxDurationTimer();
this.updateConnectionState("disconnected");
if (!this.stopped) { if (!this.stopped) {
this.options?.logger?.("binanceDepth", "WebSocket closed, scheduling reconnect");
this.scheduleReconnect(); this.scheduleReconnect();
} }
}; };
const handleError = (error: unknown) => { const handleError = (error: unknown) => {
this.options?.logger?.("binanceDepth", error); this.options?.logger?.("binanceDepth", error);
// 如果连接从未成功建立,需要清理并重连
if (this.ws && this.connectionState === "disconnected") {
this.ws = null;
this.scheduleReconnect();
}
}; };
const handleMessage = (event: { data: unknown }) => { const handleMessage = (event: { data: unknown }) => {
this.lastMessageTime = Date.now();
// 如果之前是 stale 状态,恢复为 connected
if (this.connectionState === "stale") {
this.updateConnectionState("connected");
}
this.handlePayload(event.data); this.handlePayload(event.data);
}; };
// 处理 Binance 服务器的 ping 帧
// 根据文档:必须尽快回复 pongpayload 为 ping 的 payload 副本
const handlePing = (data: unknown) => { const handlePing = (data: unknown) => {
this.lastMessageTime = Date.now();
if (this.ws && "pong" in this.ws && typeof this.ws.pong === "function") { if (this.ws && "pong" in this.ws && typeof this.ws.pong === "function") {
this.ws.pong(data as any); try {
this.ws.pong(data as any);
} catch (error) {
this.options?.logger?.("binanceDepth pong", error);
}
} }
}; };
@@ -122,7 +230,9 @@ export class BinanceDepthTracker {
private buildUrl(): string { private buildUrl(): string {
const base = this.options?.baseUrl ?? DEFAULT_BASE_URL; const base = this.options?.baseUrl ?? DEFAULT_BASE_URL;
const stream = `${this.symbol.toLowerCase()}@depth10@100ms`; const levels = this.options?.levels ?? 10;
const speed = this.options?.speedMs ?? 100;
const stream = `${this.symbol.toLowerCase()}@depth${levels}@${speed}ms`;
return `${base}/${stream}`; return `${base}/${stream}`;
} }
@@ -130,18 +240,108 @@ export class BinanceDepthTracker {
if (this.reconnectTimer || this.stopped) return; if (this.reconnectTimer || this.stopped) return;
this.reconnectTimer = setTimeout(() => { this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null; this.reconnectTimer = null;
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, 60_000); this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, RECONNECT_DELAY_MAX_MS);
this.connect(); this.connect();
}, this.reconnectDelayMs); }, this.reconnectDelayMs);
} }
/**
* 启动心跳监控
* 根据 Binance 文档:长时间无 pong 会断连
* 我们设置 5 分钟作为心跳超时阈值
*/
private startHeartbeatMonitor(): void {
this.stopHeartbeatMonitor();
this.heartbeatTimer = setInterval(() => {
const now = Date.now();
const elapsed = now - this.lastMessageTime;
// 检查数据是否过时(5 秒无数据)
if (elapsed > DATA_STALE_THRESHOLD_MS && this.connectionState === "connected") {
this.updateConnectionState("stale");
this.options?.logger?.("binanceDepth", `Data stale: ${elapsed}ms since last message`);
}
// 检查心跳超时(5 分钟无消息)
if (elapsed > HEARTBEAT_TIMEOUT_MS) {
this.options?.logger?.("binanceDepth", `Heartbeat timeout: ${elapsed}ms, forcing reconnect`);
this.forceReconnect("heartbeat_timeout");
}
}, HEARTBEAT_CHECK_INTERVAL_MS);
}
private stopHeartbeatMonitor(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
/**
* 启动 24 小时自动重连定时器
* 根据 Binance 文档:连接最长有效期 24 小时
* 我们设置 23 小时主动重连,避免被服务器断开
*/
private startMaxDurationTimer(): void {
this.stopMaxDurationTimer();
this.maxDurationTimer = setTimeout(() => {
this.options?.logger?.("binanceDepth", "Max connection duration reached (23h), reconnecting");
this.forceReconnect("max_duration");
}, MAX_CONNECTION_DURATION_MS);
}
private stopMaxDurationTimer(): void {
if (this.maxDurationTimer) {
clearTimeout(this.maxDurationTimer);
this.maxDurationTimer = null;
}
}
/**
* 强制重连
*/
private forceReconnect(reason: string): void {
this.options?.logger?.("binanceDepth", `Force reconnect: ${reason}`);
this.stopHeartbeatMonitor();
this.stopMaxDurationTimer();
if (this.ws) {
try {
this.ws.close();
} catch {
// ignore
}
this.ws = null;
}
this.updateConnectionState("disconnected");
// 立即重连(不使用指数退避)
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
this.scheduleReconnect();
}
/**
* 更新连接状态并通知监听器
*/
private updateConnectionState(state: BinanceConnectionState): void {
if (this.connectionState === state) return;
this.connectionState = state;
for (const listener of this.connectionListeners) {
try {
listener(state);
} catch (error) {
this.options?.logger?.("binanceDepth connectionListener", error);
}
}
}
private handlePayload(data: unknown): void { private handlePayload(data: unknown): void {
const payload = this.parsePayload(data); const payload = this.parsePayload(data);
if (!payload) return; if (!payload) return;
const bids = Array.isArray(payload.b) ? payload.b : []; const bids = Array.isArray(payload.b) ? payload.b : Array.isArray(payload.bids) ? payload.bids : [];
const asks = Array.isArray(payload.a) ? payload.a : []; const asks = Array.isArray(payload.a) ? payload.a : Array.isArray(payload.asks) ? payload.asks : [];
const depth = { const depth = {
lastUpdateId: Number(payload.u ?? Date.now()), lastUpdateId: Number(payload.lastUpdateId ?? payload.u ?? Date.now()),
bids, bids,
asks, asks,
}; };
@@ -158,20 +358,32 @@ export class BinanceDepthTracker {
updatedAt: Date.now(), updatedAt: Date.now(),
}; };
for (const listener of this.listeners) { for (const listener of this.listeners) {
listener({ ...this.snapshot }); try {
listener({ ...this.snapshot });
} catch (error) {
this.options?.logger?.("binanceDepth listener", error);
}
} }
} }
private parsePayload(data: unknown): { b?: [string, string][]; a?: [string, string][]; u?: number } | null { private parsePayload(
data: unknown
): { b?: [string, string][]; a?: [string, string][]; bids?: [string, string][]; asks?: [string, string][]; u?: number; lastUpdateId?: number } | null {
try { try {
const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf-8") : null; const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf-8") : null;
if (!text) return null; if (!text) return null;
const parsed = JSON.parse(text); const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== "object") return null; if (!parsed || typeof parsed !== "object") return null;
return parsed as { b?: [string, string][]; a?: [string, string][]; u?: number }; return parsed as {
b?: [string, string][];
a?: [string, string][];
bids?: [string, string][];
asks?: [string, string][];
u?: number;
lastUpdateId?: number;
};
} catch { } catch {
return null; return null;
} }
} }
} }
+428
View File
@@ -0,0 +1,428 @@
import NodeWebSocket from "ws";
import { RSI } from "trading-signals";
const WebSocketCtor: typeof globalThis.WebSocket =
typeof globalThis.WebSocket !== "undefined"
? globalThis.WebSocket
: ((NodeWebSocket as unknown) as typeof globalThis.WebSocket);
const DEFAULT_REST_BASE_URL = "https://api.binance.com";
const DEFAULT_WS_BASE_URL = "wss://stream.binance.com:9443/ws";
// Binance sends frequent kline updates (typically 2s). We treat longer silence as stale.
const DATA_STALE_THRESHOLD_MS = 10_000;
const HEARTBEAT_TIMEOUT_MS = 5 * 60 * 1000;
const HEARTBEAT_CHECK_INTERVAL_MS = 30_000;
const MAX_CONNECTION_DURATION_MS = 23 * 60 * 60 * 1000;
const RECONNECT_DELAY_BASE_MS = 2000;
const RECONNECT_DELAY_MAX_MS = 60_000;
export type BinanceConnectionState = "connected" | "disconnected" | "stale";
export interface BinanceRsiSnapshot {
symbol: string;
interval: string;
rsiPeriod: number;
rsi: number | null;
isStable: boolean;
lastClose: number | null;
candleOpenTime: number | null;
candleClosed: boolean | null;
updatedAt: number | null;
connectionState: BinanceConnectionState;
}
type BinanceRsiListener = (snapshot: BinanceRsiSnapshot) => void;
export class BinanceRsiTracker {
private ws: WebSocket | null = null;
private stopped = false;
private reconnectTimer: ReturnType<typeof setTimeout> | null = null;
private reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
private heartbeatTimer: ReturnType<typeof setInterval> | null = null;
private maxDurationTimer: ReturnType<typeof setTimeout> | null = null;
private lastMessageTime = 0;
private connectionState: BinanceConnectionState = "disconnected";
private rsi: RSI;
private candleOpenTime: number | null = null;
private candleClosed: boolean | null = null;
private lastClose: number | null = null;
private updatedAt: number | null = null;
private listeners = new Set<BinanceRsiListener>();
constructor(
private readonly symbol: string,
private readonly interval: string,
private readonly rsiPeriod: number,
private readonly options?: {
restBaseUrl?: string;
wsBaseUrl?: string;
limit?: number;
logger?: (context: string, error: unknown) => void;
}
) {
this.rsi = new RSI(this.rsiPeriod);
}
start(): void {
this.stopped = false;
void this.seedAndConnect("startup");
}
stop(): void {
this.stopped = true;
this.cleanup();
}
onUpdate(handler: BinanceRsiListener): void {
this.listeners.add(handler);
}
offUpdate(handler: BinanceRsiListener): void {
this.listeners.delete(handler);
}
getSnapshot(): BinanceRsiSnapshot {
return this.buildSnapshot();
}
private buildSnapshot(): BinanceRsiSnapshot {
const rsiValue = this.rsi.getResult();
const rsi = typeof rsiValue === "number" && Number.isFinite(rsiValue) ? rsiValue : null;
return {
symbol: this.symbol,
interval: this.interval,
rsiPeriod: this.rsiPeriod,
rsi,
isStable: this.rsi.isStable === true,
lastClose: this.lastClose,
candleOpenTime: this.candleOpenTime,
candleClosed: this.candleClosed,
updatedAt: this.updatedAt,
connectionState: this.connectionState,
};
}
private emitUpdate(): void {
const snapshot = this.buildSnapshot();
for (const listener of this.listeners) {
try {
listener(snapshot);
} catch (error) {
this.options?.logger?.("binanceRsi listener", error);
}
}
}
private cleanup(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
if (this.maxDurationTimer) {
clearTimeout(this.maxDurationTimer);
this.maxDurationTimer = null;
}
if (this.reconnectTimer) {
clearTimeout(this.reconnectTimer);
this.reconnectTimer = null;
}
if (this.ws) {
try {
this.ws.close();
} catch {
// ignore
}
this.ws = null;
}
this.updateConnectionState("disconnected");
}
private updateConnectionState(next: BinanceConnectionState): void {
if (this.connectionState === next) return;
this.connectionState = next;
this.emitUpdate();
}
private scheduleReconnect(reason: string): void {
if (this.reconnectTimer || this.stopped) return;
this.options?.logger?.("binanceRsi", `Scheduling reconnect: ${reason}`);
this.reconnectTimer = setTimeout(() => {
this.reconnectTimer = null;
this.reconnectDelayMs = Math.min(this.reconnectDelayMs * 2, RECONNECT_DELAY_MAX_MS);
void this.seedAndConnect(`reconnect:${reason}`);
}, this.reconnectDelayMs);
}
private forceReconnect(reason: string): void {
if (this.stopped) return;
this.options?.logger?.("binanceRsi", `Force reconnect: ${reason}`);
// Stop timers and close WS; keep RSI state (we will reseed on reconnect).
this.stopHeartbeatMonitor();
this.stopMaxDurationTimer();
if (this.ws) {
try {
this.ws.close();
} catch {
// ignore
}
this.ws = null;
}
this.updateConnectionState("disconnected");
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
this.scheduleReconnect(reason);
}
private startHeartbeatMonitor(): void {
if (this.heartbeatTimer) return;
this.heartbeatTimer = setInterval(() => {
const elapsed = Date.now() - this.lastMessageTime;
if (elapsed > DATA_STALE_THRESHOLD_MS && this.connectionState === "connected") {
this.updateConnectionState("stale");
}
if (elapsed > HEARTBEAT_TIMEOUT_MS) {
this.forceReconnect(`heartbeat_timeout:${elapsed}`);
}
}, HEARTBEAT_CHECK_INTERVAL_MS);
}
private stopHeartbeatMonitor(): void {
if (this.heartbeatTimer) {
clearInterval(this.heartbeatTimer);
this.heartbeatTimer = null;
}
}
private startMaxDurationTimer(): void {
if (this.maxDurationTimer) return;
this.maxDurationTimer = setTimeout(() => {
this.forceReconnect("max_duration");
}, MAX_CONNECTION_DURATION_MS);
}
private stopMaxDurationTimer(): void {
if (this.maxDurationTimer) {
clearTimeout(this.maxDurationTimer);
this.maxDurationTimer = null;
}
}
private buildRestUrl(): string {
const base = this.options?.restBaseUrl ?? DEFAULT_REST_BASE_URL;
return base;
}
private buildWsUrl(): string {
const base = this.options?.wsBaseUrl ?? DEFAULT_WS_BASE_URL;
const stream = `${this.symbol.toLowerCase()}@kline_${this.interval}`;
return `${base}/${stream}`;
}
private async seedAndConnect(reason: string): Promise<void> {
if (this.stopped) return;
try {
await this.seedFromRest();
} catch (error) {
this.options?.logger?.(`binanceRsi seed (${reason})`, error);
this.scheduleReconnect(`seed_failed:${reason}`);
return;
}
this.connectWs(reason);
}
private async seedFromRest(): Promise<void> {
const limit = Math.max(10, Math.floor(this.options?.limit ?? 500));
const base = this.buildRestUrl();
const url = new URL("/api/v3/klines", base);
url.searchParams.set("symbol", this.symbol.toUpperCase());
url.searchParams.set("interval", this.interval);
url.searchParams.set("limit", String(limit));
const res = await fetch(url.toString(), { method: "GET" });
if (!res.ok) {
const text = await res.text().catch(() => "");
throw new Error(`Binance klines HTTP ${res.status}: ${text.slice(0, 200)}`);
}
const data = (await res.json()) as unknown;
if (!Array.isArray(data)) {
throw new Error("Binance klines response is not an array");
}
// Reset RSI from scratch for determinism.
this.rsi = new RSI(this.rsiPeriod);
this.candleOpenTime = null;
this.candleClosed = null;
this.lastClose = null;
this.updatedAt = null;
// Binance kline array format:
// [ openTime, open, high, low, close, volume, closeTime, ... ]
const rows = data
.map((row) => (Array.isArray(row) ? row : null))
.filter((row): row is any[] => Array.isArray(row) && row.length >= 7)
.map((row) => ({
openTime: Number(row[0]),
close: Number(row[4]),
closeTime: Number(row[6]),
}))
.filter((k) => Number.isFinite(k.openTime) && Number.isFinite(k.close) && Number.isFinite(k.closeTime))
.sort((a, b) => a.openTime - b.openTime);
for (const k of rows) {
this.rsi.add(k.close);
this.candleOpenTime = k.openTime;
this.candleClosed = true;
this.lastClose = k.close;
this.updatedAt = Date.now();
}
// Last bar may still be forming; we treat it as replaceable.
if (rows.length > 0) {
this.candleClosed = false;
}
this.emitUpdate();
}
private connectWs(reason: string): void {
if (this.ws || this.stopped) return;
const url = this.buildWsUrl();
this.ws = new WebSocketCtor(url);
const handleOpen = () => {
this.reconnectDelayMs = RECONNECT_DELAY_BASE_MS;
this.lastMessageTime = Date.now();
this.updateConnectionState("connected");
this.startHeartbeatMonitor();
this.startMaxDurationTimer();
this.options?.logger?.("binanceRsi", `WebSocket connected (${reason})`);
};
const handleClose = () => {
this.ws = null;
this.stopHeartbeatMonitor();
this.stopMaxDurationTimer();
if (!this.stopped) {
this.updateConnectionState("disconnected");
this.scheduleReconnect("ws_close");
}
};
const handleError = (error: unknown) => {
this.options?.logger?.("binanceRsi", error);
};
const handlePing = (data: unknown) => {
this.lastMessageTime = Date.now();
if (this.ws && "pong" in this.ws && typeof this.ws.pong === "function") {
try {
this.ws.pong(data as any);
} catch (error) {
this.options?.logger?.("binanceRsi pong", error);
}
}
};
const handleMessage = (event: { data: unknown }) => {
this.lastMessageTime = Date.now();
if (this.connectionState === "stale") {
this.updateConnectionState("connected");
}
this.handlePayload(event.data);
};
if ("addEventListener" in this.ws && typeof this.ws.addEventListener === "function") {
this.ws.addEventListener("open", handleOpen);
this.ws.addEventListener("message", handleMessage as any);
this.ws.addEventListener("close", handleClose);
this.ws.addEventListener("error", handleError as any);
this.ws.addEventListener("ping", handlePing as any);
} else if ("on" in this.ws && typeof (this.ws as any).on === "function") {
const nodeSocket = this.ws as any;
nodeSocket.on("open", handleOpen);
nodeSocket.on("message", (data: unknown) => handleMessage({ data }));
nodeSocket.on("close", handleClose);
nodeSocket.on("error", handleError);
nodeSocket.on("ping", handlePing);
} else {
(this.ws as any).onopen = handleOpen;
(this.ws as any).onmessage = handleMessage;
(this.ws as any).onclose = handleClose;
(this.ws as any).onerror = handleError;
}
}
private handlePayload(data: unknown): void {
const parsed = this.parsePayload(data);
if (!parsed) return;
const openTime = Number(parsed.openTime);
const close = Number(parsed.close);
const isClosed = Boolean(parsed.isClosed);
if (!Number.isFinite(openTime) || !Number.isFinite(close)) return;
this.applyCandleUpdate({ openTime, close, isClosed });
}
private applyCandleUpdate(params: { openTime: number; close: number; isClosed: boolean }): void {
const { openTime, close, isClosed } = params;
if (this.candleOpenTime == null) {
this.rsi.add(close);
this.candleOpenTime = openTime;
this.candleClosed = isClosed;
this.lastClose = close;
this.updatedAt = Date.now();
this.emitUpdate();
return;
}
if (openTime < this.candleOpenTime) {
// Out-of-order update; ignore.
return;
}
if (openTime === this.candleOpenTime) {
// Same candle: replace last close.
this.rsi.replace(close);
this.candleClosed = isClosed;
this.lastClose = close;
this.updatedAt = Date.now();
this.emitUpdate();
return;
}
// New candle started.
this.rsi.add(close);
this.candleOpenTime = openTime;
this.candleClosed = isClosed;
this.lastClose = close;
this.updatedAt = Date.now();
this.emitUpdate();
}
private parsePayload(
data: unknown
): { openTime?: number; close?: number; isClosed?: boolean } | null {
try {
const text = typeof data === "string" ? data : Buffer.isBuffer(data) ? data.toString("utf-8") : null;
if (!text) return null;
const parsed = JSON.parse(text);
if (!parsed || typeof parsed !== "object") return null;
// Raw stream payload shape:
// { e: "kline", s: "ETHBTC", k: { t: <openTime>, c: <close>, x: <isClosed> } }
const k = (parsed as any).k;
if (!k || typeof k !== "object") return null;
return {
openTime: Number(k.t),
close: Number(k.c),
isClosed: Boolean(k.x),
};
} catch {
return null;
}
}
}
+23 -10
View File
@@ -14,7 +14,7 @@ import { isOrderActiveStatus } from "../utils/order-status";
import { getPosition, parseSymbolParts } from "../utils/strategy"; import { getPosition, parseSymbolParts } from "../utils/strategy";
import type { PositionSnapshot } from "../utils/strategy"; import type { PositionSnapshot } from "../utils/strategy";
import { computePositionPnl } from "../utils/pnl"; import { computePositionPnl } from "../utils/pnl";
import { getTopPrices, getMidOrLast } from "../utils/price"; import { getTopPrices, getPricesAtLevel, getMidOrLast } from "../utils/price";
import { shouldStopLoss } from "../utils/risk"; import { shouldStopLoss } from "../utils/risk";
import { import {
marketClose, marketClose,
@@ -430,10 +430,18 @@ export class LiquidityMakerEngine {
// 直接使用orderbook价格,格式化为字符串避免精度问题 // 直接使用orderbook价格,格式化为字符串避免精度问题
const priceDecimals = this.getPriceDecimals(); const priceDecimals = this.getPriceDecimals();
// 平仓价格始终使用买1/卖1
const closeBidPrice = formatPriceToString(finalBid, priceDecimals); const closeBidPrice = formatPriceToString(finalBid, priceDecimals);
const closeAskPrice = formatPriceToString(finalAsk, priceDecimals); const closeAskPrice = formatPriceToString(finalAsk, priceDecimals);
const rawBidPrice = finalBid - this.config.bidOffset;
const rawAskPrice = finalAsk + this.config.askOffset; // 开仓价格根据 entryDepthLevel 使用指定档位
const entryLevel = this.config.entryDepthLevel ?? 1;
const { bidAtLevel: entryBid, askAtLevel: entryAsk } = getPricesAtLevel(latestDepth, entryLevel);
const entryBidBase = entryBid ?? finalBid;
const entryAskBase = entryAsk ?? finalAsk;
const rawBidPrice = entryBidBase - this.config.bidOffset;
const rawAskPrice = entryAskBase + this.config.askOffset;
const safeBid = this.ensureMakerPrice("BUY", rawBidPrice, finalBid, finalAsk); const safeBid = this.ensureMakerPrice("BUY", rawBidPrice, finalBid, finalAsk);
const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk); const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk);
const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null; const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null;
@@ -627,18 +635,23 @@ export class LiquidityMakerEngine {
let targetPrice: number; let targetPrice: number;
// 基于最近成交或orderbook计算目标价 // 基于最近成交或入场价计算目标价,应用 closeTickOffset
if (this.lastFill && Date.now() - this.lastFill.timestamp < 60000) { if (this.lastFill && Date.now() - this.lastFill.timestamp < 60000) {
// 最近1分钟内有成交,基于成交价计算 // 最近1分钟内有成交,基于成交价计算
if (closeSide === "SELL") { if (closeSide === "SELL") {
// 多头平仓:在成交价上方挂卖单
targetPrice = this.lastFill.price + tickOffset; targetPrice = this.lastFill.price + tickOffset;
} else { } else {
// 空头平仓:在成交价下方挂买单
targetPrice = this.lastFill.price - tickOffset; targetPrice = this.lastFill.price - tickOffset;
} }
} else if (entryPrice && Number.isFinite(entryPrice) && entryPrice > 0) {
// 没有最近成交但有入场价,基于入场价计算
if (closeSide === "SELL") {
targetPrice = entryPrice + tickOffset;
} else {
targetPrice = entryPrice - tickOffset;
}
} else { } else {
// 没有最近成交,使用orderbook价格 // 没有成交也没有入场价,使用orderbook价格
if (closeSide === "SELL") { if (closeSide === "SELL") {
targetPrice = topAsk; targetPrice = topAsk;
} else { } else {
@@ -646,18 +659,18 @@ export class LiquidityMakerEngine {
} }
} }
// 确保不亏本 // 确保不亏本(仅当目标价低于入场价时调整)
if (entryPrice && Number.isFinite(entryPrice) && entryPrice > 0) { if (entryPrice && Number.isFinite(entryPrice) && entryPrice > 0) {
if (closeSide === "SELL") { if (closeSide === "SELL") {
// 多头平仓:卖价必须 >= 入场价 // 多头平仓:卖价必须 >= 入场价
if (targetPrice < entryPrice) { if (targetPrice < entryPrice) {
targetPrice = entryPrice + this.priceTick; // 至少盈利1个tick targetPrice = entryPrice + this.priceTick;
this.tradeLog.push("info", `平仓价调整为入场价+1tick以确保不亏本: ${targetPrice.toFixed(priceDecimals)}`); this.tradeLog.push("info", `平仓价调整为入场价+1tick以确保不亏本: ${targetPrice.toFixed(priceDecimals)}`);
} }
} else { } else {
// 空头平仓:买价必须 <= 入场价 // 空头平仓:买价必须 <= 入场价
if (targetPrice > entryPrice) { if (targetPrice > entryPrice) {
targetPrice = entryPrice - this.priceTick; // 至少盈利1个tick targetPrice = entryPrice - this.priceTick;
this.tradeLog.push("info", `平仓价调整为入场价-1tick以确保不亏本: ${targetPrice.toFixed(priceDecimals)}`); this.tradeLog.push("info", `平仓价调整为入场价-1tick以确保不亏本: ${targetPrice.toFixed(priceDecimals)}`);
} }
} }
+11 -3
View File
@@ -14,7 +14,7 @@ import { isOrderActiveStatus } from "../utils/order-status";
import { getPosition } from "../utils/strategy"; import { getPosition } from "../utils/strategy";
import type { PositionSnapshot } from "../utils/strategy"; import type { PositionSnapshot } from "../utils/strategy";
import { computePositionPnl } from "../utils/pnl"; import { computePositionPnl } from "../utils/pnl";
import { getTopPrices, getMidOrLast } from "../utils/price"; import { getTopPrices, getPricesAtLevel, getMidOrLast } from "../utils/price";
import { shouldStopLoss } from "../utils/risk"; import { shouldStopLoss } from "../utils/risk";
import { import {
marketClose, marketClose,
@@ -305,10 +305,18 @@ export class MakerEngine {
// 直接使用orderbook价格,格式化为字符串避免精度问题 // 直接使用orderbook价格,格式化为字符串避免精度问题
const priceDecimals = this.getPriceDecimals(); const priceDecimals = this.getPriceDecimals();
// 平仓价格始终使用买1/卖1
const closeBidPrice = formatPriceToString(topBid, priceDecimals); const closeBidPrice = formatPriceToString(topBid, priceDecimals);
const closeAskPrice = formatPriceToString(topAsk, priceDecimals); const closeAskPrice = formatPriceToString(topAsk, priceDecimals);
const bidPrice = formatPriceToString(topBid - this.config.bidOffset, priceDecimals);
const askPrice = formatPriceToString(topAsk + this.config.askOffset, priceDecimals); // 开仓价格根据 entryDepthLevel 使用指定档位
const entryLevel = this.config.entryDepthLevel ?? 1;
const { bidAtLevel: entryBid, askAtLevel: entryAsk } = getPricesAtLevel(depth, entryLevel);
const entryBidBase = entryBid ?? topBid;
const entryAskBase = entryAsk ?? topAsk;
const bidPrice = formatPriceToString(entryBidBase - this.config.bidOffset, priceDecimals);
const askPrice = formatPriceToString(entryAskBase + this.config.askOffset, priceDecimals);
const position = getPosition(this.accountSnapshot, this.config.symbol); const position = getPosition(this.accountSnapshot, this.config.symbol);
const absPosition = Math.abs(position.positionAmt); const absPosition = Math.abs(position.positionAmt);
const desired: DesiredOrder[] = []; const desired: DesiredOrder[] = [];
File diff suppressed because it is too large Load Diff
+11 -3
View File
@@ -15,7 +15,7 @@ import { getPosition, parseSymbolParts } from "../utils/strategy";
import type { PositionSnapshot } from "../utils/strategy"; import type { PositionSnapshot } from "../utils/strategy";
import { computeDepthStats } from "../utils/depth"; import { computeDepthStats } from "../utils/depth";
import { computePositionPnl } from "../utils/pnl"; import { computePositionPnl } from "../utils/pnl";
import { getTopPrices, getMidOrLast } from "../utils/price"; import { getTopPrices, getPricesAtLevel, getMidOrLast } from "../utils/price";
import { shouldStopLoss } from "../utils/risk"; import { shouldStopLoss } from "../utils/risk";
import { import {
marketClose, marketClose,
@@ -356,10 +356,18 @@ export class OffsetMakerEngine {
// 直接使用orderbook价格,格式化为字符串避免精度问题 // 直接使用orderbook价格,格式化为字符串避免精度问题
const priceDecimals = this.getPriceDecimals(); const priceDecimals = this.getPriceDecimals();
// 平仓价格始终使用买1/卖1
const closeBidPrice = formatPriceToString(finalBid, priceDecimals); const closeBidPrice = formatPriceToString(finalBid, priceDecimals);
const closeAskPrice = formatPriceToString(finalAsk, priceDecimals); const closeAskPrice = formatPriceToString(finalAsk, priceDecimals);
const rawBidPrice = finalBid - this.config.bidOffset;
const rawAskPrice = finalAsk + this.config.askOffset; // 开仓价格根据 entryDepthLevel 使用指定档位
const entryLevel = this.config.entryDepthLevel ?? 1;
const { bidAtLevel: entryBid, askAtLevel: entryAsk } = getPricesAtLevel(latestDepth, entryLevel);
const entryBidBase = entryBid ?? finalBid;
const entryAskBase = entryAsk ?? finalAsk;
const rawBidPrice = entryBidBase - this.config.bidOffset;
const rawAskPrice = entryAskBase + this.config.askOffset;
const safeBid = this.ensureMakerPrice("BUY", rawBidPrice, finalBid, finalAsk); const safeBid = this.ensureMakerPrice("BUY", rawBidPrice, finalBid, finalAsk);
const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk); const safeAsk = this.ensureMakerPrice("SELL", rawAskPrice, finalBid, finalAsk);
const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null; const bidPrice = safeBid != null ? formatPriceToString(safeBid, priceDecimals) : null;
+624
View File
@@ -0,0 +1,624 @@
import type { ExchangeAdapter } from "../exchanges/adapter";
import type { AsterAccountSnapshot, AsterDepth, AsterOrder, AsterTicker } from "../exchanges/types";
import { createTradeLog, type TradeLogEntry } from "../logging/trade-log";
import { marketClose, placeMarketOrder, placeStopLossOrder, unlockOperating } from "../core/order-coordinator";
import type { OrderLockMap, OrderPendingMap, OrderTimerMap } from "../core/order-coordinator";
import { extractMessage, isRateLimitError, isUnknownOrderError } from "../utils/errors";
import { getPosition, type PositionSnapshot } from "../utils/strategy";
import { computePositionPnl } from "../utils/pnl";
import { getMidOrLast, getTopPrices } from "../utils/price";
import { RateLimitController } from "../core/lib/rate-limit";
import { StrategyEventEmitter } from "./common/event-emitter";
import { safeSubscribe, type LogHandler } from "./common/subscriptions";
import { SessionVolumeTracker } from "./common/session-volume";
import { t } from "../i18n";
import { BinanceRsiTracker, type BinanceRsiSnapshot } from "./common/binance-rsi";
import { createInitialSwingState, stepSwing, type SwingState } from "./swing-logic";
import { isOrderActiveStatus } from "../utils/order-status";
import type { SwingConfig } from "../config";
export type SwingRsiZone = "overbought" | "oversold" | "neutral" | "unknown";
export type SwingPhase =
| "disabled"
| "initializing"
| "observing"
| "waiting_open_short"
| "waiting_open_long"
| "waiting_close_short"
| "waiting_close_long";
export interface SwingEngineSnapshot {
ready: boolean;
disabled: boolean;
symbol: string;
direction: SwingConfig["direction"];
lastPrice: number | null;
phase: SwingPhase;
binancePrice: number | null;
rsi: number | null;
rsiStable: boolean;
rsiZone: SwingRsiZone;
binanceConnection: BinanceRsiSnapshot["connectionState"];
binanceUpdatedAt: number | null;
armed: Pick<
SwingState,
"armedShortEntry" | "armedShortExit" | "armedLongEntry" | "armedLongExit"
>;
position: PositionSnapshot;
pnl: number;
unrealized: number;
sessionVolume: number;
stopLossTarget: number | null;
stopLossKillSwitch: boolean;
openOrders: AsterOrder[];
depth: AsterDepth | null;
ticker: AsterTicker | null;
tradeLog: TradeLogEntry[];
lastUpdated: number | null;
error: string | null;
}
type SwingEvent = "update";
type SwingListener = (snapshot: SwingEngineSnapshot) => void;
const EPS = 1e-5;
export class SwingEngine {
private accountSnapshot: AsterAccountSnapshot | null = null;
private openOrders: AsterOrder[] = [];
private depthSnapshot: AsterDepth | null = null;
private tickerSnapshot: AsterTicker | null = null;
private readonly locks: OrderLockMap = {};
private readonly timers: OrderTimerMap = {};
private readonly pending: OrderPendingMap = {};
private readonly tradeLog: ReturnType<typeof createTradeLog>;
private readonly events = new StrategyEventEmitter<SwingEvent, SwingEngineSnapshot>();
private readonly sessionVolume = new SessionVolumeTracker();
private readonly rateLimit: RateLimitController;
private readonly binanceRsi: BinanceRsiTracker;
private binanceSnapshot: BinanceRsiSnapshot;
private timer: ReturnType<typeof setInterval> | null = null;
private processing = false;
private disabled = false;
private lastError: string | null = null;
private ordersSnapshotReady = false;
private precisionSync: Promise<void> | null = null;
private swingState: SwingState = createInitialSwingState();
// Stop-loss placement de-bounce
private lastStopAttempt: { side: "BUY" | "SELL" | null; price: number | null; at: number } = {
side: null,
price: null,
at: 0,
};
constructor(private readonly config: SwingConfig, private readonly exchange: ExchangeAdapter) {
this.tradeLog = createTradeLog(this.config.maxLogEntries);
this.rateLimit = new RateLimitController(this.config.pollIntervalMs, (type, detail) =>
this.tradeLog.push(type, detail)
);
this.binanceRsi = new BinanceRsiTracker(
this.config.signalSymbol,
this.config.signalInterval,
this.config.rsiPeriod,
{
limit: 500,
logger: (context, error) => {
// Keep Binance errors visible but non-fatal.
this.tradeLog.push("warn", `[Binance] ${context}: ${String(error)}`);
},
}
);
this.binanceSnapshot = this.binanceRsi.getSnapshot();
this.binanceRsi.onUpdate((snapshot) => {
this.binanceSnapshot = snapshot;
this.emitUpdate();
});
this.binanceRsi.start();
this.syncPrecision();
this.bootstrap();
}
start(): void {
if (this.timer) return;
this.timer = setInterval(() => {
void this.tick();
}, this.config.pollIntervalMs);
}
stop(): void {
if (this.timer) {
clearInterval(this.timer);
this.timer = null;
}
// Binance tracker is external IO; stop it too.
this.binanceRsi.stop();
}
on(event: SwingEvent, handler: SwingListener): void {
this.events.on(event, handler);
}
off(event: SwingEvent, handler: SwingListener): void {
this.events.off(event, handler);
}
getSnapshot(): SwingEngineSnapshot {
return this.buildSnapshot();
}
private bootstrap(): void {
const log: LogHandler = (type, detail) => this.tradeLog.push(type, detail);
safeSubscribe<AsterAccountSnapshot>(
this.exchange.watchAccount.bind(this.exchange),
(snapshot) => {
this.accountSnapshot = snapshot;
const position = getPosition(snapshot, this.config.symbol);
const reference = this.getReferencePrice();
this.sessionVolume.update(position, reference);
// Safe-by-default: refuse short mode on spot accounts.
if (
snapshot.marketType === "spot" &&
(this.config.direction === "short" || this.config.direction === "both")
) {
if (!this.disabled) {
this.disabled = true;
this.lastError = "Swing strategy requires perp/margin for shorting; spot accounts cannot short.";
this.tradeLog.push("error", this.lastError);
}
}
this.emitUpdate();
},
log,
{
subscribeFail: (error) => t("log.subscribe.accountFail", { error: String(error) }),
processFail: (error) => t("log.process.accountError", { error: extractMessage(error) }),
}
);
safeSubscribe<AsterOrder[]>(
this.exchange.watchOrders.bind(this.exchange),
(orders) => {
this.synchronizeLocks(orders);
this.openOrders = Array.isArray(orders)
? orders.filter(
(order) =>
order.type !== "MARKET" &&
order.symbol === this.config.symbol &&
isOrderActiveStatus(order.status)
)
: [];
this.ordersSnapshotReady = true;
this.emitUpdate();
},
log,
{
subscribeFail: (error) => t("log.subscribe.orderFail", { error: String(error) }),
processFail: (error) => t("log.process.orderError", { error: extractMessage(error) }),
}
);
safeSubscribe<AsterDepth>(
this.exchange.watchDepth.bind(this.exchange, this.config.symbol),
(depth) => {
this.depthSnapshot = depth;
this.emitUpdate();
},
log,
{
subscribeFail: (error) => t("log.subscribe.depthFail", { error: String(error) }),
processFail: (error) => t("log.process.depthError", { error: extractMessage(error) }),
}
);
safeSubscribe<AsterTicker>(
this.exchange.watchTicker.bind(this.exchange, this.config.symbol),
(ticker) => {
this.tickerSnapshot = ticker;
this.emitUpdate();
},
log,
{
subscribeFail: (error) => t("log.subscribe.tickerFail", { error: String(error) }),
processFail: (error) => t("log.process.tickerError", { error: extractMessage(error) }),
}
);
}
private synchronizeLocks(orders: AsterOrder[] | null | undefined): void {
const list = Array.isArray(orders) ? orders : [];
Object.keys(this.pending).forEach((type) => {
const pendingId = this.pending[type];
if (!pendingId) return;
const match = list.find((order) => String(order.orderId) === pendingId);
if (!match || (match.status && match.status !== "NEW" && match.status !== "PARTIALLY_FILLED")) {
unlockOperating(this.locks, this.timers, this.pending, type);
}
});
}
private isReady(): boolean {
return Boolean(
this.accountSnapshot &&
this.tickerSnapshot &&
this.depthSnapshot &&
this.ordersSnapshotReady &&
this.binanceSnapshot.isStable &&
this.binanceSnapshot.rsi != null
);
}
private async tick(): Promise<void> {
if (this.processing) return;
this.processing = true;
let hadRateLimit = false;
try {
const decision = this.rateLimit.beforeCycle();
if (decision === "paused") {
this.emitUpdate();
return;
}
if (decision === "skip") {
return;
}
if (this.disabled) {
this.emitUpdate();
return;
}
if (!this.isReady()) {
this.emitUpdate();
return;
}
const account = this.accountSnapshot!;
const position = getPosition(account, this.config.symbol);
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
const bid = topBid ?? Number(this.tickerSnapshot?.lastPrice);
const ask = topAsk ?? Number(this.tickerSnapshot?.lastPrice);
const pnl = computePositionPnl(position, bid, ask);
const price = this.getReferencePrice();
const decisionOut = stepSwing(
this.swingState,
{ direction: this.config.direction, rsiHigh: this.config.rsiHigh, rsiLow: this.config.rsiLow },
{ rsi: this.binanceSnapshot.rsi, positionAmt: position.positionAmt, pnl }
);
this.swingState = decisionOut.nextState;
for (const action of decisionOut.actions) {
if (action.type === "OPEN_SHORT") {
await this.tryOpen("SELL", action.reason);
} else if (action.type === "OPEN_LONG") {
await this.tryOpen("BUY", action.reason);
} else if (action.type === "CLOSE_POSITION") {
await this.tryClose(position, action.reason);
}
}
// Stop-loss management / kill-switch for any open position.
await this.handleStopLoss(position, price);
this.sessionVolume.update(position, price);
this.emitUpdate();
} catch (error) {
if (isRateLimitError(error)) {
hadRateLimit = true;
this.rateLimit.registerRateLimit("swing");
this.tradeLog.push("warn", `SwingEngine 429: ${String(error)}`);
} else {
this.lastError = extractMessage(error);
this.tradeLog.push("error", `SwingEngine error: ${this.lastError}`);
}
this.emitUpdate();
} finally {
try {
this.rateLimit.onCycleComplete(hadRateLimit);
} finally {
this.processing = false;
}
}
}
private async tryOpen(side: "BUY" | "SELL", reason: string): Promise<void> {
try {
// Ensure flat before opening.
const position = getPosition(this.accountSnapshot, this.config.symbol);
if (Math.abs(position.positionAmt) > EPS) {
return;
}
await placeMarketOrder(
this.exchange,
this.config.symbol,
this.openOrders,
this.locks,
this.timers,
this.pending,
side,
this.config.tradeAmount,
(type, detail) => this.tradeLog.push(type, detail),
false,
{
markPrice: position.markPrice,
expectedPrice: Number(this.tickerSnapshot?.lastPrice) || null,
maxPct: this.config.maxCloseSlippagePct,
},
{ qtyStep: this.config.qtyStep }
);
this.tradeLog.push("open", `${reason}: ${side} (market)`);
} catch (err) {
this.tradeLog.push("error", `Open failed: ${extractMessage(err)}`);
}
}
private async tryClose(position: PositionSnapshot, reason: string): Promise<void> {
try {
if (Math.abs(position.positionAmt) <= EPS) return;
const side: "BUY" | "SELL" = position.positionAmt > 0 ? "SELL" : "BUY";
const expected =
side === "SELL"
? Number(this.depthSnapshot?.bids?.[0]?.[0])
: Number(this.depthSnapshot?.asks?.[0]?.[0]);
await marketClose(
this.exchange,
this.config.symbol,
this.openOrders,
this.locks,
this.timers,
this.pending,
side,
Math.abs(position.positionAmt),
(type, detail) => this.tradeLog.push(type, detail),
{
markPrice: position.markPrice,
expectedPrice: Number.isFinite(expected) ? expected : Number(this.tickerSnapshot?.lastPrice) || null,
maxPct: this.config.maxCloseSlippagePct,
},
{ qtyStep: this.config.qtyStep }
);
this.tradeLog.push("close", `${reason}: ${side} (market close)`);
} catch (err) {
if (isUnknownOrderError(err)) {
this.tradeLog.push("order", "Close skipped: order missing");
} else {
this.tradeLog.push("error", `Close failed: ${extractMessage(err)}`);
}
}
}
private async handleStopLoss(position: PositionSnapshot, referencePrice: number | null): Promise<void> {
const hasPosition = Math.abs(position.positionAmt) > EPS;
if (!hasPosition) {
this.lastStopAttempt = { side: null, price: null, at: 0 };
return;
}
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
if (!hasEntryPrice) {
return;
}
const direction = position.positionAmt > 0 ? "long" : "short";
const stopSide: "BUY" | "SELL" = direction === "long" ? "SELL" : "BUY";
const stopPrice =
direction === "long"
? position.entryPrice * (1 - Math.max(0, this.config.stopLossPct))
: position.entryPrice * (1 + Math.max(0, this.config.stopLossPct));
const tick = Math.max(1e-9, this.config.priceTick);
const lastPrice = referencePrice ?? Number(this.tickerSnapshot?.lastPrice) ?? null;
// Kill-switch (always-on).
const triggerKill =
direction === "long"
? lastPrice != null && Number.isFinite(lastPrice) && lastPrice <= stopPrice + tick
: lastPrice != null && Number.isFinite(lastPrice) && lastPrice >= stopPrice - tick;
if (triggerKill) {
await this.tryClose(position, "Stop-loss kill-switch");
return;
}
// If exchange supports stop orders, keep one active.
const currentStop = this.openOrders.find((o) => {
const hasStopPrice = Number.isFinite(Number(o.stopPrice)) && Number(o.stopPrice) > 0;
return o.side === stopSide && (o.type === "STOP_MARKET" || hasStopPrice);
});
if (currentStop) return;
// De-bounce: avoid repeated submissions of same stop.
const now = Date.now();
if (
this.lastStopAttempt.side === stopSide &&
this.lastStopAttempt.price != null &&
Math.abs(stopPrice - Number(this.lastStopAttempt.price)) < tick &&
now - this.lastStopAttempt.at < 5000
) {
return;
}
try {
const qty = Math.abs(position.positionAmt);
await placeStopLossOrder(
this.exchange,
this.config.symbol,
this.openOrders,
this.locks,
this.timers,
this.pending,
stopSide,
stopPrice,
qty,
lastPrice,
(type, detail) => this.tradeLog.push(type, detail),
{
markPrice: position.markPrice,
maxPct: this.config.maxCloseSlippagePct,
},
{ priceTick: this.config.priceTick, qtyStep: this.config.qtyStep }
);
this.lastStopAttempt = { side: stopSide, price: stopPrice, at: Date.now() };
} catch (err) {
this.lastStopAttempt = { side: stopSide, price: stopPrice, at: Date.now() };
this.tradeLog.push("error", `Failed to place stop-loss order: ${extractMessage(err)}`);
}
}
private emitUpdate(): void {
try {
const snapshot = this.buildSnapshot();
this.events.emit("update", snapshot, (error) => {
this.tradeLog.push("error", `SwingEngine update handler error: ${String(error)}`);
});
} catch (err) {
this.tradeLog.push("error", `SwingEngine snapshot error: ${String(err)}`);
}
}
private buildSnapshot(): SwingEngineSnapshot {
const position = getPosition(this.accountSnapshot, this.config.symbol);
const price = this.tickerSnapshot ? Number(this.tickerSnapshot.lastPrice) : null;
const { topBid, topAsk } = getTopPrices(this.depthSnapshot);
const pnl = computePositionPnl(position, topBid ?? price, topAsk ?? price);
const reference = this.getReferencePrice();
const hasPosition = Math.abs(position.positionAmt) > EPS;
const hasEntryPrice = Number.isFinite(position.entryPrice) && Math.abs(position.entryPrice) > 1e-8;
const stopLossTarget = hasPosition && hasEntryPrice
? (position.positionAmt > 0
? position.entryPrice * (1 - Math.max(0, this.config.stopLossPct))
: position.entryPrice * (1 + Math.max(0, this.config.stopLossPct)))
: null;
const tick = Math.max(1e-9, this.config.priceTick);
const stopLossKillSwitch =
stopLossTarget != null && reference != null && Number.isFinite(reference)
? (position.positionAmt > 0 ? reference <= stopLossTarget + tick : reference >= stopLossTarget - tick)
: false;
const zone: SwingRsiZone =
this.binanceSnapshot.rsi == null || !Number.isFinite(this.binanceSnapshot.rsi)
? "unknown"
: this.binanceSnapshot.rsi > this.config.rsiHigh
? "overbought"
: this.binanceSnapshot.rsi < this.config.rsiLow
? "oversold"
: "neutral";
const posAmt = Number(position.positionAmt);
const phase: SwingPhase = this.disabled
? "disabled"
: !this.isReady()
? "initializing"
: Math.abs(posAmt) <= EPS
? this.swingState.armedShortEntry
? "waiting_open_short"
: this.swingState.armedLongEntry
? "waiting_open_long"
: "observing"
: posAmt < -EPS
? this.swingState.armedShortExit
? "waiting_close_short"
: "observing"
: this.swingState.armedLongExit
? "waiting_close_long"
: "observing";
return {
ready: this.isReady() && !this.disabled,
disabled: this.disabled,
symbol: this.config.symbol,
direction: this.config.direction,
lastPrice: reference,
phase,
binancePrice: this.binanceSnapshot.lastClose,
rsi: this.binanceSnapshot.rsi,
rsiStable: this.binanceSnapshot.isStable,
rsiZone: zone,
binanceConnection: this.binanceSnapshot.connectionState,
binanceUpdatedAt: this.binanceSnapshot.updatedAt,
armed: {
armedShortEntry: this.swingState.armedShortEntry,
armedShortExit: this.swingState.armedShortExit,
armedLongEntry: this.swingState.armedLongEntry,
armedLongExit: this.swingState.armedLongExit,
},
position,
pnl,
unrealized: position.unrealizedProfit,
sessionVolume: this.sessionVolume.value,
stopLossTarget,
stopLossKillSwitch,
openOrders: this.openOrders,
depth: this.depthSnapshot,
ticker: this.tickerSnapshot,
tradeLog: this.tradeLog.all(),
lastUpdated: Date.now(),
error: this.lastError,
};
}
private getReferencePrice(): number | null {
return (
getMidOrLast(this.depthSnapshot, this.tickerSnapshot) ??
(this.tickerSnapshot ? Number(this.tickerSnapshot.lastPrice) : null)
);
}
private syncPrecision(): void {
if (this.precisionSync) return;
const getPrecision = this.exchange.getPrecision?.bind(this.exchange);
if (!getPrecision) return;
this.precisionSync = getPrecision()
.then((precision) => {
if (!precision) return;
let updated = false;
if (Number.isFinite(precision.priceTick) && precision.priceTick > 0) {
const delta = Math.abs(precision.priceTick - this.config.priceTick);
if (delta > 1e-12) {
this.config.priceTick = precision.priceTick;
updated = true;
}
}
if (Number.isFinite(precision.qtyStep) && precision.qtyStep > 0) {
const delta = Math.abs(precision.qtyStep - this.config.qtyStep);
if (delta > 1e-12) {
this.config.qtyStep = precision.qtyStep;
updated = true;
}
}
if (updated) {
this.tradeLog.push(
"info",
`Synced precision: priceTick=${precision.priceTick} qtyStep=${precision.qtyStep}`
);
}
})
.catch((error) => {
this.tradeLog.push("error", `Precision sync failed: ${extractMessage(error)}`);
this.precisionSync = null;
setTimeout(() => this.syncPrecision(), 2000);
});
}
}
+93
View File
@@ -0,0 +1,93 @@
import { describe, expect, it } from "vitest";
import { createInitialSwingState, stepSwing, type SwingLogicConfig } from "./swing-logic";
const baseConfig: SwingLogicConfig = {
direction: "both",
rsiHigh: 70,
rsiLow: 30,
};
describe("swing logic", () => {
it("arms short entry on RSI cross up 70, then opens on cross down 70", () => {
let state = createInitialSwingState();
// First observation sets prevRsi, no cross yet.
({ nextState: state } = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 69, positionAmt: 0, pnl: 0 }));
const a1 = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 71, positionAmt: 0, pnl: 0 });
expect(a1.actions).toEqual([]);
expect(a1.nextState.armedShortEntry).toBe(true);
state = a1.nextState;
const a2 = stepSwing(state, { ...baseConfig, direction: "short" }, { rsi: 69, positionAmt: 0, pnl: 0 });
expect(a2.actions.map((a) => a.type)).toEqual(["OPEN_SHORT"]);
expect(a2.nextState.armedShortEntry).toBe(false);
});
it("arms long entry on RSI cross down 30, then opens on cross up 30", () => {
let state = createInitialSwingState();
({ nextState: state } = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 31, positionAmt: 0, pnl: 0 }));
const a1 = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 29, positionAmt: 0, pnl: 0 });
expect(a1.actions).toEqual([]);
expect(a1.nextState.armedLongEntry).toBe(true);
state = a1.nextState;
const a2 = stepSwing(state, { ...baseConfig, direction: "long" }, { rsi: 31, positionAmt: 0, pnl: 0 });
expect(a2.actions.map((a) => a.type)).toEqual(["OPEN_LONG"]);
expect(a2.nextState.armedLongEntry).toBe(false);
});
it("short exit requires profit: arms on cross down 30, closes on cross up 30 if pnl > 0", () => {
let state = createInitialSwingState();
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: -1 }));
const a1 = stepSwing(state, baseConfig, { rsi: 29, positionAmt: -1, pnl: -1 });
expect(a1.actions).toEqual([]);
expect(a1.nextState.armedShortExit).toBe(true);
state = a1.nextState;
const a2 = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0 });
expect(a2.actions).toEqual([]); // pnl not strictly positive
expect(a2.nextState.armedShortExit).toBe(true);
state = a2.nextState;
const a3 = stepSwing(state, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0.01 });
// No cross (prev=31 -> 31), still armed.
expect(a3.actions).toEqual([]);
// Cross down then up to trigger close with profit
const a4 = stepSwing(a3.nextState, baseConfig, { rsi: 29, positionAmt: -1, pnl: 0.01 });
const a5 = stepSwing(a4.nextState, baseConfig, { rsi: 31, positionAmt: -1, pnl: 0.01 });
expect(a5.actions.map((a) => a.type)).toEqual(["CLOSE_POSITION"]);
expect(a5.nextState.armedShortExit).toBe(false);
});
it("long exit requires profit: arms on cross up 70, closes on cross down 70 if pnl > 0", () => {
let state = createInitialSwingState();
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 1, pnl: 0 }));
const a1 = stepSwing(state, baseConfig, { rsi: 71, positionAmt: 1, pnl: 0 });
expect(a1.actions).toEqual([]);
expect(a1.nextState.armedLongExit).toBe(true);
state = a1.nextState;
const a2 = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 1, pnl: 0.01 });
expect(a2.actions.map((a) => a.type)).toEqual(["CLOSE_POSITION"]);
expect(a2.nextState.armedLongExit).toBe(false);
});
it("clears entry arms when a position is present", () => {
let state = createInitialSwingState();
({ nextState: state } = stepSwing(state, baseConfig, { rsi: 69, positionAmt: 0, pnl: 0 }));
// Arm short entry.
state = stepSwing(state, baseConfig, { rsi: 71, positionAmt: 0, pnl: 0 }).nextState;
expect(state.armedShortEntry).toBe(true);
// Now position appears: entry arms should be reset.
const next = stepSwing(state, baseConfig, { rsi: 71, positionAmt: -1, pnl: 0 });
expect(next.nextState.armedShortEntry).toBe(false);
expect(next.nextState.armedLongEntry).toBe(false);
});
});
+151
View File
@@ -0,0 +1,151 @@
export type SwingDirection = "long" | "short" | "both";
export interface SwingLogicConfig {
direction: SwingDirection;
rsiHigh: number; // e.g. 70
rsiLow: number; // e.g. 30
}
export interface SwingState {
prevRsi: number | null;
armedShortEntry: boolean;
armedShortExit: boolean;
armedLongEntry: boolean;
armedLongExit: boolean;
}
export type SwingAction =
| { type: "OPEN_SHORT"; reason: string }
| { type: "OPEN_LONG"; reason: string }
| { type: "CLOSE_POSITION"; reason: string };
export interface SwingStepInput {
rsi: number | null;
positionAmt: number;
pnl: number;
}
export function createInitialSwingState(): SwingState {
return {
prevRsi: null,
armedShortEntry: false,
armedShortExit: false,
armedLongEntry: false,
armedLongExit: false,
};
}
const EPS = 1e-8;
function crossUp(prev: number | null, next: number, threshold: number): boolean {
if (prev == null) return false;
return prev <= threshold && next > threshold;
}
function crossDown(prev: number | null, next: number, threshold: number): boolean {
if (prev == null) return false;
return prev >= threshold && next < threshold;
}
export function stepSwing(
state: SwingState,
config: SwingLogicConfig,
input: SwingStepInput
): { nextState: SwingState; actions: SwingAction[] } {
const nextState: SwingState = { ...state };
const actions: SwingAction[] = [];
const rsi = input.rsi;
const hasRsi = typeof rsi === "number" && Number.isFinite(rsi);
const prevRsi = nextState.prevRsi;
const direction = config.direction;
const allowLong = direction === "long" || direction === "both";
const allowShort = direction === "short" || direction === "both";
const positionAmt = Number(input.positionAmt);
const pnl = Number(input.pnl);
const isFlat = !Number.isFinite(positionAmt) || Math.abs(positionAmt) <= EPS;
const isLong = Number.isFinite(positionAmt) && positionAmt > EPS;
const isShort = Number.isFinite(positionAmt) && positionAmt < -EPS;
// If RSI is missing/invalid, avoid mutating state.
if (!hasRsi) {
return { nextState, actions };
}
// Keep prevRsi updated once we have a valid reading.
nextState.prevRsi = rsi;
if (isFlat) {
// When flat, exit arms are irrelevant.
nextState.armedShortExit = false;
nextState.armedLongExit = false;
if (!allowShort) {
nextState.armedShortEntry = false;
} else {
if (crossUp(prevRsi, rsi, config.rsiHigh)) {
nextState.armedShortEntry = true;
}
if (nextState.armedShortEntry && crossDown(prevRsi, rsi, config.rsiHigh)) {
actions.push({ type: "OPEN_SHORT", reason: "RSI armed above high, then crossed below high" });
nextState.armedShortEntry = false;
// Avoid impossible dual-entries.
nextState.armedLongEntry = false;
}
}
if (!allowLong) {
nextState.armedLongEntry = false;
} else {
if (crossDown(prevRsi, rsi, config.rsiLow)) {
nextState.armedLongEntry = true;
}
if (nextState.armedLongEntry && crossUp(prevRsi, rsi, config.rsiLow)) {
actions.push({ type: "OPEN_LONG", reason: "RSI armed below low, then crossed above low" });
nextState.armedLongEntry = false;
nextState.armedShortEntry = false;
}
}
if (actions.length > 1) {
// Defensive: avoid opening both directions in one step.
return { nextState: { ...nextState, armedShortEntry: false, armedLongEntry: false }, actions: [] };
}
return { nextState, actions };
}
// When exposed, entry arms are irrelevant (strategy does not pyramid).
nextState.armedShortEntry = false;
nextState.armedLongEntry = false;
// Exits are always allowed (even if direction config changes) to avoid trapping positions.
if (isShort) {
nextState.armedLongExit = false;
if (crossDown(prevRsi, rsi, config.rsiLow)) {
nextState.armedShortExit = true;
}
if (nextState.armedShortExit && crossUp(prevRsi, rsi, config.rsiLow) && pnl > 0) {
actions.push({ type: "CLOSE_POSITION", reason: "RSI exit armed below low, then crossed above low with profit" });
nextState.armedShortExit = false;
}
return { nextState, actions };
}
if (isLong) {
nextState.armedShortExit = false;
if (crossUp(prevRsi, rsi, config.rsiHigh)) {
nextState.armedLongExit = true;
}
if (nextState.armedLongExit && crossDown(prevRsi, rsi, config.rsiHigh) && pnl > 0) {
actions.push({ type: "CLOSE_POSITION", reason: "RSI exit armed above high, then crossed below high with profit" });
nextState.armedLongExit = false;
}
return { nextState, actions };
}
return { nextState, actions };
}
+11 -2
View File
@@ -1,6 +1,7 @@
import React, { useMemo, useState } from "react"; import React, { useMemo, useState } from "react";
import { Box, Text, useInput } from "ink"; import { Box, Text, useInput } from "ink";
import { TrendApp } from "./TrendApp"; import { TrendApp } from "./TrendApp";
import { SwingApp } from "./SwingApp";
import { GuardianApp } from "./GuardianApp"; import { GuardianApp } from "./GuardianApp";
import { MakerApp } from "./MakerApp"; import { MakerApp } from "./MakerApp";
import { MakerPointsApp } from "./MakerPointsApp"; import { MakerPointsApp } from "./MakerPointsApp";
@@ -14,7 +15,7 @@ import { resolveExchangeId } from "../exchanges/create-adapter";
import { t } from "../i18n"; import { t } from "../i18n";
interface StrategyOption { interface StrategyOption {
id: "trend" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid"; id: "trend" | "swing" | "guardian" | "maker" | "maker-points" | "offset-maker" | "liquidity-maker" | "basis" | "grid";
label: string; label: string;
description: string; description: string;
component: React.ComponentType<{ onExit: () => void }>; component: React.ComponentType<{ onExit: () => void }>;
@@ -27,6 +28,12 @@ const BASE_STRATEGIES: StrategyOption[] = [
description: t("app.strategy.trend.desc"), description: t("app.strategy.trend.desc"),
component: TrendApp, component: TrendApp,
}, },
{
id: "swing",
label: t("app.strategy.swing.label"),
description: t("app.strategy.swing.desc"),
component: SwingApp,
},
{ {
id: "guardian", id: "guardian",
label: t("app.strategy.guardian.label"), label: t("app.strategy.guardian.label"),
@@ -70,7 +77,9 @@ export function App() {
const strategies = useMemo(() => { const strategies = useMemo(() => {
const next: StrategyOption[] = [...BASE_STRATEGIES]; const next: StrategyOption[] = [...BASE_STRATEGIES];
if (exchangeId === "standx") { if (exchangeId === "standx") {
next.splice(3, 0, { const gridIndex = next.findIndex((s) => s.id === "grid");
const insertAt = gridIndex === -1 ? next.length : gridIndex;
next.splice(insertAt, 0, {
id: "maker-points" as const, id: "maker-points" as const,
label: t("app.strategy.makerPoints.label"), label: t("app.strategy.makerPoints.label"),
description: t("app.strategy.makerPoints.desc"), description: t("app.strategy.makerPoints.desc"),
+10
View File
@@ -135,6 +135,7 @@ export function MakerPointsApp({ onExit }: MakerPointsAppProps) {
? t("offset.imbalance.sell") ? t("offset.imbalance.sell")
: t("offset.imbalance.balanced"); : t("offset.imbalance.balanced");
const quoteMode = snapshot.quoteStatus.closeOnly ? t("makerPoints.mode.closeOnly") : t("makerPoints.mode.normal"); const quoteMode = snapshot.quoteStatus.closeOnly ? t("makerPoints.mode.closeOnly") : t("makerPoints.mode.normal");
const formatDepth = (value: number | null) => (value == null ? "-" : formatNumber(value, 4));
return ( return (
<Box flexDirection="column" paddingX={1}> <Box flexDirection="column" paddingX={1}>
@@ -164,6 +165,15 @@ export function MakerPointsApp({ onExit }: MakerPointsAppProps) {
status: imbalanceLabel, status: imbalanceLabel,
})} })}
</Text> </Text>
{snapshot.bandDepths.map((band) => (
<Text key={band.band} color={band.enabled ? undefined : "gray"}>
{t("makerPoints.bandDepthLine", {
band: band.band,
buy: formatDepth(band.buyDepth),
sell: formatDepth(band.sellDepth),
})}
</Text>
))}
<Text> <Text>
{t("maker.dataStatus")} {t("maker.dataStatus")}
{feedEntries.map((entry, index) => ( {feedEntries.map((entry, index) => (
+217
View File
@@ -0,0 +1,217 @@
import React, { useEffect, useMemo, useRef, useState } from "react";
import { Box, Text, useInput } from "ink";
import { swingConfig } from "../config";
import { getExchangeDisplayName, resolveExchangeId } from "../exchanges/create-adapter";
import { buildAdapterFromEnv } from "../exchanges/resolve-from-env";
import { SwingEngine, type SwingEngineSnapshot } from "../strategy/swing-engine";
import { formatNumber } from "../utils/format";
import { DataTable, type TableColumn } from "./components/DataTable";
import { t } from "../i18n";
const READY_MESSAGE = t("swing.readyMessage");
interface SwingAppProps {
onExit: () => void;
}
const inputSupported = Boolean(process.stdin && (process.stdin as any).isTTY);
export function SwingApp({ onExit }: SwingAppProps) {
const [snapshot, setSnapshot] = useState<SwingEngineSnapshot | null>(null);
const [error, setError] = useState<Error | null>(null);
const engineRef = useRef<SwingEngine | null>(null);
const exchangeId = useMemo(() => resolveExchangeId(), []);
const exchangeName = useMemo(() => getExchangeDisplayName(exchangeId), [exchangeId]);
useInput(
(_input, key) => {
if (key.escape) {
engineRef.current?.stop();
onExit();
}
},
{ isActive: inputSupported }
);
useEffect(() => {
try {
const adapter = buildAdapterFromEnv({ exchangeId, symbol: swingConfig.symbol });
const engine = new SwingEngine(swingConfig, adapter);
engineRef.current = engine;
setSnapshot(engine.getSnapshot());
const handler = (next: SwingEngineSnapshot) => {
setSnapshot({ ...next, tradeLog: [...next.tradeLog], openOrders: [...next.openOrders] });
};
engine.on("update", handler);
engine.start();
return () => {
engine.off("update", handler);
engine.stop();
};
} catch (err) {
console.error(err);
setError(err instanceof Error ? err : new Error(String(err)));
}
}, [exchangeId]);
if (error) {
return (
<Box flexDirection="column" padding={1}>
<Text color="red">{t("common.startFailed", { message: error.message })}</Text>
<Text color="gray">{t("common.checkEnv")}</Text>
</Box>
);
}
if (!snapshot) {
return (
<Box padding={1}>
<Text>{t("common.initializing", { target: t("swing.name") })}</Text>
</Box>
);
}
const zoneLabel =
snapshot.rsiZone === "overbought"
? t("swing.zone.overbought")
: snapshot.rsiZone === "oversold"
? t("swing.zone.oversold")
: snapshot.rsiZone === "neutral"
? t("swing.zone.neutral")
: t("swing.zone.unknown");
const phaseLabel =
snapshot.phase === "disabled"
? t("swing.phase.disabled")
: snapshot.phase === "initializing"
? t("swing.phase.initializing")
: snapshot.phase === "waiting_open_short"
? t("swing.phase.waitingOpenShort")
: snapshot.phase === "waiting_close_short"
? t("swing.phase.waitingCloseShort")
: snapshot.phase === "waiting_open_long"
? t("swing.phase.waitingOpenLong")
: snapshot.phase === "waiting_close_long"
? t("swing.phase.waitingCloseLong")
: t("swing.phase.observing");
const lastLogs = snapshot.tradeLog.slice(-5);
const sortedOrders = [...snapshot.openOrders].sort(
(a, b) => (Number(b.updateTime ?? 0) - Number(a.updateTime ?? 0)) || Number(b.orderId) - Number(a.orderId)
);
const orderRows = sortedOrders.slice(0, 8).map((order) => ({
id: order.orderId,
side: order.side,
type: order.type,
price: order.price,
qty: order.origQty,
filled: order.executedQty,
status: order.status,
}));
const orderColumns: TableColumn[] = [
{ key: "id", header: "ID", align: "right", minWidth: 6 },
{ key: "side", header: "Side", minWidth: 4 },
{ key: "type", header: "Type", minWidth: 10 },
{ key: "price", header: "Price", align: "right", minWidth: 10 },
{ key: "qty", header: "Qty", align: "right", minWidth: 8 },
{ key: "filled", header: "Filled", align: "right", minWidth: 8 },
{ key: "status", header: "Status", minWidth: 10 },
];
const hasPosition = Math.abs(snapshot.position.positionAmt) > 1e-5;
return (
<Box flexDirection="column" paddingX={1} paddingY={0}>
<Box flexDirection="column" marginBottom={1}>
<Text color="cyanBright">{t("swing.title")}</Text>
<Text>
{t("swing.headerLine", {
exchange: exchangeName,
symbol: snapshot.symbol,
direction: snapshot.direction,
lastPrice: formatNumber(snapshot.lastPrice, 6),
phase: phaseLabel,
})}
</Text>
<Text color="gray">
{t("swing.signalLine", {
binanceSymbol: "ETHBTC",
binancePrice: formatNumber(snapshot.binancePrice, 8),
rsi: formatNumber(snapshot.rsi, 2),
zone: zoneLabel,
connection: snapshot.binanceConnection,
})}
</Text>
<Text color={snapshot.disabled ? "red" : "gray"}>
{t("swing.statusLine", {
status: snapshot.disabled
? t("status.paused")
: snapshot.ready
? t("status.live")
: READY_MESSAGE,
})}
</Text>
{snapshot.error ? <Text color="red">{snapshot.error}</Text> : null}
</Box>
<Box flexDirection="row" marginBottom={1}>
<Box flexDirection="column" marginRight={4}>
<Text color="greenBright">{t("common.section.position")}</Text>
{hasPosition ? (
<>
<Text>
{t("swing.positionLine", {
direction: snapshot.position.positionAmt > 0 ? t("common.direction.long") : t("common.direction.short"),
qty: formatNumber(Math.abs(snapshot.position.positionAmt), 4),
entry: formatNumber(snapshot.position.entryPrice, 6),
})}
</Text>
<Text>
{t("swing.pnlLine", {
pnl: formatNumber(snapshot.pnl, 4),
unrealized: formatNumber(snapshot.unrealized, 4),
})}
</Text>
<Text color={snapshot.stopLossKillSwitch ? "red" : "gray"}>
{t("swing.stopLine", { stop: formatNumber(snapshot.stopLossTarget, 6) })}
</Text>
</>
) : (
<Text color="gray">{t("common.noPosition")}</Text>
)}
</Box>
<Box flexDirection="column">
<Text color="greenBright">{t("swing.stateTitle")}</Text>
<Text color="gray">
{t("swing.armedLine", {
se: snapshot.armed.armedShortEntry ? "Y" : "N",
sx: snapshot.armed.armedShortExit ? "Y" : "N",
le: snapshot.armed.armedLongEntry ? "Y" : "N",
lx: snapshot.armed.armedLongExit ? "Y" : "N",
})}
</Text>
<Text color="gray">{t("swing.volumeLine", { volume: formatNumber(snapshot.sessionVolume, 2) })}</Text>
</Box>
</Box>
<Box flexDirection="column" marginBottom={1}>
<Text color="yellow">{t("common.section.orders")}</Text>
{orderRows.length > 0 ? <DataTable columns={orderColumns} rows={orderRows} /> : <Text color="gray">{t("common.noOrders")}</Text>}
</Box>
<Box flexDirection="column">
<Text color="yellow">{t("common.section.recentTrades")}</Text>
{lastLogs.length > 0 ? (
lastLogs.map((item, index) => (
<Text key={`${item.time}-${index}`}>
[{item.time}] [{item.type}] {item.detail}
</Text>
))
) : (
<Text color="gray">{t("common.noLogs")}</Text>
)}
</Box>
</Box>
);
}
+20
View File
@@ -13,4 +13,24 @@ export function computePositionPnl(
: (position.entryPrice - (priceForPnl as number)) * absAmt; : (position.entryPrice - (priceForPnl as number)) * absAmt;
} }
export function computeStopLossPnl(
position: PositionSnapshot,
bestBid?: number | null,
bestAsk?: number | null
): number | null {
const absAmt = Math.abs(position.positionAmt);
if (!Number.isFinite(absAmt) || absAmt <= 0) return 0;
// If entry price is missing, prefer the exchange-provided unrealized PnL.
if (!Number.isFinite(position.entryPrice) || position.entryPrice <= 0) {
return Number.isFinite(position.unrealizedProfit) ? position.unrealizedProfit : null;
}
const priceForPnl = position.positionAmt > 0 ? bestBid : bestAsk;
if (!Number.isFinite(priceForPnl as number) || (priceForPnl as number) <= 0) {
return Number.isFinite(position.unrealizedProfit) ? position.unrealizedProfit : null;
}
return computePositionPnl(position, bestBid, bestAsk);
}
+94
View File
@@ -9,6 +9,46 @@ export function getTopPrices(depth?: AsterDepth | null): { topBid: number | null
}; };
} }
/**
*
* @param depth
* @param level 1=1/12=2/2
* @returns 退
*/
export function getPricesAtLevel(
depth?: AsterDepth | null,
level: number = 1
): { bidAtLevel: number | null; askAtLevel: number | null } {
const index = Math.max(0, level - 1);
// 尝试获取指定档位,如果不存在则回退到最近的有效档位
const bids = depth?.bids ?? [];
const asks = depth?.asks ?? [];
let bidAtLevel: number | null = null;
let askAtLevel: number | null = null;
// 从指定档位向前查找第一个有效的买价
for (let i = Math.min(index, bids.length - 1); i >= 0; i--) {
const bid = Number(bids[i]?.[0]);
if (Number.isFinite(bid)) {
bidAtLevel = bid;
break;
}
}
// 从指定档位向前查找第一个有效的卖价
for (let i = Math.min(index, asks.length - 1); i >= 0; i--) {
const ask = Number(asks[i]?.[0]);
if (Number.isFinite(ask)) {
askAtLevel = ask;
break;
}
}
return { bidAtLevel, askAtLevel };
}
export function getMidOrLast(depth?: AsterDepth | null, ticker?: AsterTicker | null): number | null { export function getMidOrLast(depth?: AsterDepth | null, ticker?: AsterTicker | null): number | null {
const { topBid, topAsk } = getTopPrices(depth); const { topBid, topAsk } = getTopPrices(depth);
if (topBid != null && topAsk != null) return (topBid + topAsk) / 2; if (topBid != null && topAsk != null) return (topBid + topAsk) / 2;
@@ -16,4 +56,58 @@ export function getMidOrLast(depth?: AsterDepth | null, ticker?: AsterTicker | n
return Number.isFinite(last) ? last : null; return Number.isFinite(last) ? last : null;
} }
/**
*
* @param depth
* @param side 挂单方向: BUY bids, SELL asks
* @param targetPrice
* @returns ()
*/
export function getDepthBetweenPrices(
depth: AsterDepth | null | undefined,
side: "BUY" | "SELL",
targetPrice: number
): number {
if (!depth) return 0;
if (!Number.isFinite(targetPrice) || targetPrice <= 0) return 0;
let total = 0;
if (side === "BUY") {
// BUY 订单挂在 bid 侧,检查从 bid1 到目标价格之间的所有 bids
// bids 按价格从高到低排序,目标价格 < bid1
const bids = depth.bids ?? [];
for (const level of bids) {
const price = Number(level[0]);
const qty = Number(level[1]);
if (!Number.isFinite(price) || !Number.isFinite(qty)) continue;
// 只计算价格 > 目标价格的档位 (目标价格以上的挂单)
if (price > targetPrice) {
total += qty;
} else {
// bids 是从高到低排序,一旦 price <= targetPrice 就停止
break;
}
}
} else {
// SELL 订单挂在 ask 侧,检查从 ask1 到目标价格之间的所有 asks
// asks 按价格从低到高排序,目标价格 > ask1
const asks = depth.asks ?? [];
for (const level of asks) {
const price = Number(level[0]);
const qty = Number(level[1]);
if (!Number.isFinite(price) || !Number.isFinite(qty)) continue;
// 只计算价格 < 目标价格的档位 (目标价格以下的挂单)
if (price < targetPrice) {
total += qty;
} else {
// asks 是从低到高排序,一旦 price >= targetPrice 就停止
break;
}
}
}
return total;
}
+41
View File
@@ -47,6 +47,47 @@ export function getPosition(snapshot: AsterAccountSnapshot | null, symbol: strin
}; };
} }
export function validateAccountSnapshotForSymbol(
snapshot: AsterAccountSnapshot | null,
symbol: string
): { ok: true } | { ok: false; issues: string[] } {
if (!snapshot) return { ok: true };
const positions = snapshot.positions?.filter((p) => p.symbol === symbol) ?? [];
if (positions.length === 0) return { ok: true };
const NON_ZERO_EPS = 1e-8;
const issues: string[] = [];
for (const position of positions) {
const amt = Number(position.positionAmt);
if (!Number.isFinite(amt)) {
issues.push("invalid_positionAmt");
continue;
}
if (Math.abs(amt) <= NON_ZERO_EPS) {
continue;
}
const entryPrice = Number(position.entryPrice);
if (!Number.isFinite(entryPrice) || entryPrice <= 0) {
issues.push("invalid_entryPrice");
}
const unrealizedProfit = Number(position.unrealizedProfit);
if (!Number.isFinite(unrealizedProfit)) {
issues.push("invalid_unrealizedProfit");
}
const rawMark = Number(position.markPrice);
if (position.markPrice != null && position.markPrice !== "" && (!Number.isFinite(rawMark) || rawMark <= 0)) {
issues.push("invalid_markPrice");
}
}
if (issues.length === 0) return { ok: true };
return { ok: false, issues: Array.from(new Set(issues)) };
}
export function getSMA(values: AsterKline[], length: number): number | null { export function getSMA(values: AsterKline[], length: number): number | null {
if (!Array.isArray(values) || values.length < length) return null; if (!Array.isArray(values) || values.length < length) return null;
const window = values.slice(-length); const window = values.slice(-length);
+87
View File
@@ -0,0 +1,87 @@
import { describe, expect, it } from "vitest";
import type { AsterAccountSnapshot } from "../src/exchanges/types";
import { validateAccountSnapshotForSymbol } from "../src/utils/strategy";
function baseSnapshot(positions: AsterAccountSnapshot["positions"]): AsterAccountSnapshot {
return {
canTrade: true,
canDeposit: true,
canWithdraw: true,
updateTime: Date.now(),
totalWalletBalance: "0",
totalUnrealizedProfit: "0",
positions,
assets: [],
marketType: "perp",
};
}
describe("validateAccountSnapshotForSymbol", () => {
it("accepts empty positions", () => {
const result = validateAccountSnapshotForSymbol(baseSnapshot([]), "BTC-USD");
expect(result.ok).toBe(true);
});
it("accepts zero-sized positions even if entry price is zero", () => {
const result = validateAccountSnapshotForSymbol(
baseSnapshot([
{
symbol: "BTC-USD",
positionAmt: "0",
entryPrice: "0",
unrealizedProfit: "0",
positionSide: "BOTH",
updateTime: Date.now(),
markPrice: "0",
},
]),
"BTC-USD"
);
expect(result.ok).toBe(true);
});
it("flags invalid numeric fields for non-zero positions", () => {
const result = validateAccountSnapshotForSymbol(
baseSnapshot([
{
symbol: "BTC-USD",
positionAmt: "1",
entryPrice: "NaN",
unrealizedProfit: "oops",
positionSide: "BOTH",
updateTime: Date.now(),
markPrice: "-1",
},
]),
"BTC-USD"
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.issues).toEqual(
expect.arrayContaining(["invalid_entryPrice", "invalid_unrealizedProfit", "invalid_markPrice"])
);
}
});
it("flags invalid positionAmt", () => {
const result = validateAccountSnapshotForSymbol(
baseSnapshot([
{
symbol: "BTC-USD",
positionAmt: "abc",
entryPrice: "100",
unrealizedProfit: "0",
positionSide: "BOTH",
updateTime: Date.now(),
markPrice: "101",
},
]),
"BTC-USD"
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.issues).toContain("invalid_positionAmt");
}
});
});
+45
View File
@@ -0,0 +1,45 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
const ORIGINAL_ENV = { ...process.env };
beforeEach(() => {
process.env = { ...ORIGINAL_ENV };
});
afterEach(() => {
process.env = { ...ORIGINAL_ENV };
});
async function loadConfig() {
vi.resetModules();
return await import("../src/config");
}
describe("config env parsing", () => {
it("strips shell-style inline comments from symbol values", async () => {
process.env.EXCHANGE = "standx";
process.env.STANDX_SYMBOL = "BTC-USD # comment";
const { resolveSymbolFromEnv } = await loadConfig();
expect(resolveSymbolFromEnv()).toBe("BTC-USD");
});
it("parses numeric maker-points env values with inline comments", async () => {
process.env.EXCHANGE = "standx";
process.env.MAKER_POINTS_STOP_LOSS_USD = "1 # comment";
process.env.MAKER_POINTS_CLOSE_THRESHOLD = "2 ; comment";
const { makerPointsConfig } = await loadConfig();
expect(makerPointsConfig.stopLossUsd).toBe(1);
expect(makerPointsConfig.closeThreshold).toBe(2);
});
it("parses boolean maker-points env values with inline comments", async () => {
process.env.EXCHANGE = "standx";
process.env.MAKER_POINTS_BAND_10_30 = "false # comment";
const { makerPointsConfig } = await loadConfig();
expect(makerPointsConfig.enableBand10To30).toBe(false);
});
});
@@ -0,0 +1,131 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ExchangeAdapter } from "../src/exchanges/adapter";
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
class StubAdapter implements ExchangeAdapter {
id = "standx";
accountSnapshot: AsterAccountSnapshot | null = null;
supportsTrailingStops(): boolean {
return false;
}
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
async createOrder(): Promise<AsterOrder> {
throw new Error("not implemented");
}
async cancelOrder(): Promise<void> {}
async cancelOrders(): Promise<void> {}
async cancelAllOrders(): Promise<void> {}
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
return this.accountSnapshot;
}
}
afterEach(() => {
vi.useRealTimers();
});
describe("MakerPointsEngine defense-mode account staleness", () => {
it("does not enter defense mode for ~21s StandX account gap (REST probe succeeds)", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-24T15:20:00.000Z"));
const adapter = new StubAdapter();
adapter.accountSnapshot = {
canTrade: true,
canDeposit: true,
canWithdraw: true,
updateTime: Date.now(),
totalWalletBalance: "0",
totalUnrealizedProfit: "0",
positions: [],
assets: [],
marketType: "perp",
};
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
const now = Date.now();
(engine as any).lastStandxDepthTime = now;
(engine as any).lastBinanceDepthTime = now;
(engine as any).lastStandxAccountTime = now - 21_000;
(engine as any).checkDataStaleAndDefense();
expect((engine as any).defenseMode).toBe(false);
await vi.runAllTimersAsync();
engine.stop();
});
it("enters defense mode if StandX account REST probe fails", async () => {
vi.useFakeTimers();
vi.setSystemTime(new Date("2026-01-24T15:20:00.000Z"));
const adapter = new StubAdapter();
adapter.accountSnapshot = null;
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
const now = Date.now();
(engine as any).lastStandxDepthTime = now;
(engine as any).lastBinanceDepthTime = now;
(engine as any).lastStandxAccountTime = now - 121_000;
(engine as any).checkDataStaleAndDefense();
expect((engine as any).defenseMode).toBe(false);
await vi.runAllTimersAsync();
vi.advanceTimersByTime(1000);
(engine as any).checkDataStaleAndDefense();
expect((engine as any).defenseMode).toBe(true);
engine.stop();
});
});
+168
View File
@@ -0,0 +1,168 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ExchangeAdapter } from "../src/exchanges/adapter";
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
class StubAdapter implements ExchangeAdapter {
id = "standx";
cancelAllCount = 0;
openOrders: AsterOrder[] | Error = [];
accountSnapshot: AsterAccountSnapshot | null = null;
supportsTrailingStops(): boolean {
return false;
}
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
async createOrder(): Promise<AsterOrder> {
throw new Error("not implemented");
}
async cancelOrder(): Promise<void> {}
async cancelOrders(): Promise<void> {}
async cancelAllOrders(): Promise<void> {
this.cancelAllCount += 1;
this.openOrders = [];
}
async queryOpenOrders(): Promise<AsterOrder[]> {
if (this.openOrders instanceof Error) throw this.openOrders;
return this.openOrders;
}
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
return this.accountSnapshot;
}
}
afterEach(() => {
vi.useRealTimers();
});
describe("MakerPointsEngine defense-mode REST polling", () => {
it("keeps trying to fetch open orders and cancel all when open orders exist", async () => {
vi.useFakeTimers();
const adapter = new StubAdapter();
adapter.openOrders = [
{
orderId: "1",
clientOrderId: "c1",
symbol: "BTC-USD",
side: "BUY",
type: "LIMIT",
status: "NEW",
price: "100",
origQty: "1",
executedQty: "0",
time: Date.now(),
updateTime: Date.now(),
reduceOnly: "false",
closePosition: "false",
},
];
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
(engine as any).enterDefenseMode({
standxDepthStale: true,
binanceStale: false,
standxAccountStale: false,
accountInvalid: false,
standxRestUnhealthy: false,
standxRestConsecutiveErrors: 0,
standxRestLastError: null,
marginModeNotIsolated: false,
marginMode: "isolated",
standxDepthAge: 6000,
binanceAge: 0,
standxAccountAge: 0,
accountIssues: [],
});
await vi.waitFor(() => {
expect(adapter.cancelAllCount).toBeGreaterThanOrEqual(1);
});
engine.stop();
});
it("attempts cancel-all even if open-order query fails", async () => {
vi.useFakeTimers();
const adapter = new StubAdapter();
adapter.openOrders = new Error("boom");
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
(engine as any).enterDefenseMode({
standxDepthStale: true,
binanceStale: false,
standxAccountStale: false,
accountInvalid: false,
standxRestUnhealthy: false,
standxRestConsecutiveErrors: 0,
standxRestLastError: null,
marginModeNotIsolated: false,
marginMode: "isolated",
standxDepthAge: 6000,
binanceAge: 0,
standxAccountAge: 0,
accountIssues: [],
});
await vi.waitFor(() => {
expect(adapter.cancelAllCount).toBeGreaterThanOrEqual(1);
});
engine.stop();
});
});
+188
View File
@@ -0,0 +1,188 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import type { ExchangeAdapter } from "../src/exchanges/adapter";
import type { AsterAccountSnapshot, AsterDepth, AsterKline, AsterOrder, AsterTicker } from "../src/exchanges/types";
import { MakerPointsEngine } from "../src/strategy/maker-points-engine";
class StandxStubAdapter implements ExchangeAdapter {
id = "standx";
marginMode: "cross" | "isolated" = "cross";
changeCalls: Array<{ symbol: string; marginMode: "isolated" | "cross" }> = [];
supportsTrailingStops(): boolean {
return false;
}
watchAccount(_cb: (snapshot: AsterAccountSnapshot) => void): void {}
watchOrders(_cb: (orders: AsterOrder[]) => void): void {}
watchDepth(_symbol: string, _cb: (depth: AsterDepth) => void): void {}
watchTicker(_symbol: string, _cb: (ticker: AsterTicker) => void): void {}
watchKlines(_symbol: string, _interval: string, _cb: (klines: AsterKline[]) => void): void {}
async createOrder(): Promise<AsterOrder> {
throw new Error("not implemented");
}
async cancelOrder(): Promise<void> {}
async cancelOrders(): Promise<void> {}
async cancelAllOrders(): Promise<void> {}
async queryAccountSnapshot(): Promise<AsterAccountSnapshot | null> {
return {
canTrade: true,
canDeposit: true,
canWithdraw: true,
updateTime: Date.now(),
totalWalletBalance: "0",
totalUnrealizedProfit: "0",
marketType: "perp",
positions: [
{
symbol: "BTC-USD",
positionAmt: "0",
entryPrice: "0",
unrealizedProfit: "0",
positionSide: "BOTH",
updateTime: Date.now(),
marginType: this.marginMode,
},
],
assets: [],
};
}
async changeMarginMode(params: { symbol: string; marginMode: "isolated" | "cross" }): Promise<void> {
this.changeCalls.push(params);
this.marginMode = params.marginMode;
}
}
afterEach(() => {
vi.useRealTimers();
});
describe("MakerPointsEngine StandX isolated margin guard", () => {
it("switches to isolated before placing orders", async () => {
vi.useFakeTimers();
const adapter = new StandxStubAdapter();
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
// Seed engine state to pass readiness checks without WS.
(engine as any).feedStatus = { account: true, depth: true, ticker: true, orders: true, binance: true };
(engine as any).initialOrderSnapshotReady = true;
(engine as any).accountSnapshot = await adapter.queryAccountSnapshot();
(engine as any).depthSnapshot = {
lastUpdateId: 1,
bids: [["100", "1"]],
asks: [["101", "1"]],
eventTime: Date.now(),
symbol: "BTC-USD",
} as AsterDepth;
(engine as any).tickerSnapshot = {
symbol: "BTC-USD",
lastPrice: "100",
openPrice: "0",
highPrice: "0",
lowPrice: "0",
volume: "0",
quoteVolume: "0",
eventTime: Date.now(),
} as AsterTicker;
const syncSpy = vi.fn().mockResolvedValue(undefined);
(engine as any).syncOrders = syncSpy;
// First tick should force margin mode to isolated and then proceed to sync orders.
await (engine as any).tick();
expect(adapter.changeCalls).toEqual([{ symbol: "BTC-USD", marginMode: "isolated" }]);
expect(syncSpy).toHaveBeenCalledTimes(1);
engine.stop();
});
it("enters defense mode if it cannot switch to isolated", async () => {
vi.useFakeTimers();
const adapter = new StandxStubAdapter();
adapter.changeMarginMode = vi.fn(async () => {
throw new Error("change failed");
}) as any;
const engine = new MakerPointsEngine(
{
symbol: "BTC-USD",
perOrderAmount: 0.01,
closeThreshold: 0,
stopLossUsd: 1,
refreshIntervalMs: 500,
maxLogEntries: 10,
maxCloseSlippagePct: 0.05,
priceTick: 0.1,
qtyStep: 0.001,
enableBand0To10: true,
enableBand10To30: false,
enableBand30To100: false,
band0To10Amount: 0.01,
band10To30Amount: 0.01,
band30To100Amount: 0.01,
minRepriceBps: 3,
enableBinanceDepthCancel: false,
filterMinDepth: 0,
},
adapter
);
(engine as any).feedStatus = { account: true, depth: true, ticker: true, orders: true, binance: true };
(engine as any).initialOrderSnapshotReady = true;
(engine as any).accountSnapshot = await adapter.queryAccountSnapshot();
(engine as any).depthSnapshot = {
lastUpdateId: 1,
bids: [["100", "1"]],
asks: [["101", "1"]],
eventTime: Date.now(),
symbol: "BTC-USD",
} as AsterDepth;
(engine as any).tickerSnapshot = {
symbol: "BTC-USD",
lastPrice: "100",
openPrice: "0",
highPrice: "0",
lowPrice: "0",
volume: "0",
quoteVolume: "0",
eventTime: Date.now(),
} as AsterTicker;
const syncSpy = vi.fn().mockResolvedValue(undefined);
(engine as any).syncOrders = syncSpy;
await (engine as any).tick();
expect(syncSpy).not.toHaveBeenCalled();
expect((engine as any).defenseMode).toBe(true);
engine.stop();
});
});
+39
View File
@@ -0,0 +1,39 @@
import { describe, expect, it } from "vitest";
import { computeStopLossPnl } from "../src/utils/pnl";
describe("computeStopLossPnl", () => {
it("falls back to exchange-provided unrealized PnL when entryPrice is missing", () => {
const pnl = computeStopLossPnl(
{ positionAmt: 1, entryPrice: 0, unrealizedProfit: -2000, markPrice: null },
40000,
40010
);
expect(pnl).toBe(-2000);
});
it("uses best bid/ask when entryPrice is available", () => {
const longPnl = computeStopLossPnl(
{ positionAmt: 1, entryPrice: 100, unrealizedProfit: -5, markPrice: null },
90,
91
);
expect(longPnl).toBe(-10);
const shortPnl = computeStopLossPnl(
{ positionAmt: -2, entryPrice: 100, unrealizedProfit: -5, markPrice: null },
95,
105
);
expect(shortPnl).toBe(-10);
});
it("falls back to exchange-provided unrealized PnL when best prices are unavailable", () => {
const pnl = computeStopLossPnl(
{ positionAmt: 1, entryPrice: 100, unrealizedProfit: -123, markPrice: null },
null,
null
);
expect(pnl).toBe(-123);
});
});
+55
View File
@@ -0,0 +1,55 @@
import { afterEach, describe, expect, it, vi } from "vitest";
import { StandxGateway } from "../src/exchanges/standx/gateway";
const ORIGINAL_FETCH = globalThis.fetch;
afterEach(() => {
globalThis.fetch = ORIGINAL_FETCH;
vi.restoreAllMocks();
});
describe("StandxGateway REST health", () => {
it("emits unhealthy after 3 consecutive REST failures, then healthy after a success", async () => {
const gateway = new StandxGateway({
token: "test-token",
symbol: "BTC-USD",
baseUrl: "https://example.com",
wsUrl: "wss://example.com/ws",
logger: () => {},
});
const events: Array<{ state: string; consecutiveErrors: number }> = [];
gateway.onRestHealthEvent((state, info) => {
events.push({ state, consecutiveErrors: info.consecutiveErrors });
});
globalThis.fetch = vi.fn(async () => {
return {
ok: false,
status: 500,
text: async () => "server error",
} as any;
}) as any;
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
await expect(gateway.queryOpenOrders("BTC-USD")).rejects.toThrow();
expect(events).toEqual([{ state: "unhealthy", consecutiveErrors: 3 }]);
globalThis.fetch = vi.fn(async () => {
return {
ok: true,
status: 200,
text: async () => "[]",
} as any;
}) as any;
await expect(gateway.queryOpenOrders("BTC-USD")).resolves.toEqual([]);
expect(events).toEqual([
{ state: "unhealthy", consecutiveErrors: 3 },
{ state: "healthy", consecutiveErrors: 0 },
]);
});
});