Commit Graph
52 Commits
Author SHA1 Message Date
discountry 85954461f3 feat(maker-points): enhance configuration for maker points bands
Added new configuration options for maker points bands, including target distances and maximum distance limits. Updated the logic to handle these configurations, ensuring backward compatibility with existing defaults. Enhanced documentation and tests to cover the new features and ensure correct functionality across the system.
2026-08-18 15:16:49 +08:00
discountry f3a96886ac feat(lighter): add Robinhood Chain venue support 2026-08-14 14:05:37 +08:00
discountry 0ea71503e3 refactor(exchanges): extract ReconnectScheduler from four gateways
standx, ondoperps, lighter and backpack each hand-rolled the same three pieces
around their socket: a 'one pending attempt at a time' timer guard, an attempt
counter feeding a backoff formula, and resetting that counter on open. Four
field-name conventions, four formulas, four places to forget the reset.

ReconnectScheduler owns the timer, the guard and the counter; the backoff stays
a caller-supplied policy (fixed / linear / exponential), since the venues
genuinely want different curves. Verified value-by-value that all four produce
the identical delay sequence they did before.

Scope was chosen, not maximal. The other five gateways' reconnect paths, and all
nine connect/auth/subscribe/heartbeat flows, stay where they are: those are
60-200 lines of per-venue protocol, and folding nine different auth and ping
semantics into one base class would be the wrong abstraction. I also checked the
reconnect paths for the classic defects — aster's timer that looked unclearable
is cleared at the top of connect(), and all three backoff counters do reset on
open — so there was no bug to fix here, only duplication.

12 new tests. 287 pass; tsc and oxlint clean.
2026-07-29 21:40:09 +08:00
discountry 22b9c5a39d i18n: route the remaining 300 hardcoded strings through the table
Grid, offset-maker, liquidity-maker and maker-points wrote their trade log and
Telegram alerts as Chinese literals, so LANG=en changed the menu but not a
single runtime message. src/ now holds zero user-facing Chinese literals.

Reuses rather than duplicates: the four engines' subscription boilerplate maps
onto the existing log.subscribe.* / log.process.* keys, and the spot-maker
wording shared by offset-maker and liquidity-maker became one log.spotMaker.*
set instead of two.

Exchange gateways were treated differently on purpose: aster's exception and
console.error text is developer diagnostics, not UI, and its eight sibling
gateways already used English — so those were translated to English rather than
added to the table.

Adds tests/i18n-coverage.test.ts to hold the line: it fails on any new CJK
literal in src/, on a key missing either language, and on a duplicate key.
Several existing tests asserted the Chinese literals, which is what let the gap
persist; they now assert the resolved key and hold in either language.

214 new keys (300 -> 514). 275 pass; tsc and oxlint clean.
2026-07-29 21:35:19 +08:00
discountry b9331c516a i18n(core): route order-coordinator and token/margin guards through t()
These files bypassed the i18n table entirely, so a user running LANG=en still
got Chinese order logs. Migrating them surfaced structural duplication too: the
five order paths each spelled out their own 'quantity invalid' string, now one
key parameterised by an order-kind label.

Also fixes a type that carried display text as its domain: TrendLabel was
'做多' | '做空' | '无信号', so the engine's snapshot value *was* the Chinese
string and English rendering depended on matching it. Now 'long' | 'short' |
'none', translated at the edge.

Order-coordinator tests asserted the Chinese literals, which is exactly what
made the gap invisible; they now assert the resolved key so they hold in either
language.

39 new translation keys. 271 pass; tsc and oxlint clean.
2026-07-29 21:26:57 +08:00
discountry 448a2f2615 refactor(maker-points): extract token-expiry and isolated-margin guards
Two more clusters lifted out of the engine, both defined by latches whose only
correctness property is that they move together:

- TokenExpiryGuard owns the five flags (state, logged, notified, cancelDone,
  closeOnly) that make each consequence of an expired StandX token happen once
  per episode and re-arm when a fresh token arrives. evaluate() returns a
  decision instead of a bare boolean, so the tick reads what it means.
- IsolatedMarginGuard owns the single in-flight switch promise that stops
  concurrent ticks from stacking margin-mode change requests, plus the
  poll-until-confirmed loop.

Both were previously reachable only through a live adapter; they now have 22
unit tests between them, covering the latch reset across a token renewal, the
cancel retry after a failure, unknown-order treated as success, and the
concurrent-tick sharing of one margin switch.

Confirm cadence kept at 500ms x 10 to match the engine's original constants.
271 pass; tsc and oxlint clean. Engine 1939 -> 1826 lines.
2026-07-29 21:23:26 +08:00
discountry 5aecaabb16 refactor(core): give order functions a parameter object
placeOrder took 13 positional arguments; the other five order functions took
9-13. The leading six — adapter, symbol, openOrders, locks, timers, pendings —
were the same values at all 36 call sites, and every engine spelled them out
again for each order it placed.

Introduce Parameter Object: OrderContext holds what is fixed for an engine's
lifetime (exposed once via a lazily-built this.orderContext), and each function
takes a named request. A wrong argument order is now a compile error rather than
a silently misrouted order.

The type change surfaced dead weight: placeOrder's opts.priceTick was never read
by its body, yet five engines passed it. Removed.

Also finishes the PrecisionSyncer migration — grid-engine was the ninth copy and
was missed last round, so it still carried the uncleared retry timer.

Extract Function: normalizeQuantity replaces the round-down-but-never-to-zero
block that appeared in all five order functions.

250 pass; tsc and oxlint clean.
2026-07-29 21:17:58 +08:00
discountry 9538ecf265 refactor(strategy): collapse six strategy lists into one registry
Adding a strategy meant editing six places that had to agree: the StrategyId
union and a parallel Set in args.ts, STRATEGY_LABELS and a nine-branch
STRATEGY_FACTORIES in strategy-runner.ts, plus an inline id union and
BASE_STRATEGIES in App.tsx. runEngine's type parameter was additionally bounded
by a union of all nine snapshot types.

They had already drifted: the CLI gated basis on isBasisSupportedExchangeId
while the menu checked only isBasisStrategyEnabled, so the menu offered basis
on exchanges where startStrategy would throw.

- strategy-ids.ts: the id list and alias parsing, dependency-free so CLI arg
  parsing does not pull in every engine.
- registry.ts: one definition per strategy (labels, symbol, engine factory, and
  a single unavailableReason both the menu and the runner consult), keyed by a
  total Record so a new id will not compile until it is defined.
- StrategyEngine/StrategySnapshot interfaces replace the snapshot union;
  runEngine now depends only on the contract. All nine engines already satisfied
  it — no engine changed.
- App.tsx keeps only the id -> Ink view map, also a total Record.

Menu order preserved. 8 new tests, one pinning menu/CLI availability agreement.
234 pass; tsc clean. -242 lines.
2026-07-29 20:36:55 +08:00
discountry 1e4f610c04 refactor(strategy): extract PrecisionSyncer from 8 duplicated copies
Every engine hand-rolled the same ~35-line syncPrecision: fetch getPrecision(),
compare against a 1e-12 epsilon, log, retry in 2s on failure. The copies had
drifted — three bypassed i18n with hardcoded strings, maker-points alone
supported a forced re-sync, and the maker family wrote this.qtyStep while
trend/swing/guardian wrote config.qtyStep.

Extract Class: PrecisionSyncer owns both increments plus min base/quote amounts
and writes through to config, so both read styles keep working. Engines now hold
one collaborator instead of four fields.

Fixes a leak present in all eight copies: the 2s retry timer was never cleared,
so an engine stopped mid-retry kept polling a dead adapter forever. stop() now
cancels it — in the Ink UI that leaked one retry loop per strategy switch.

Also collapses log.trend.precision*/log.guardian.precision* into log.common.*
(the three key pairs held byte-identical text).

8 new tests; 226 pass; tsc --noEmit clean. -260 lines.
2026-07-29 20:32:30 +08:00
discountry 7acb3c3b82 fix(exchanges): restore type-check safety net and repair dead balance guards
tsconfig compiled docs/ (vendored ccxt samples) and @types/react was missing,
so 269 tsc errors buried the real ones. Scoping the project and adding the
missing type packages left 42 genuine errors in src/, which exposed two bugs:

- lighter: assertSpotBalance's buy branch and createOrder's spot-sell guard
  compared the {available, wallet} object against a number, so both guards
  were dead. Introduce SpotAssetBalance with a precomputed 'effective' field
  (Extract Class) and route all three call sites through it.
- offset-maker: the below-min-sell branch logged 'skip sell' but pushed the
  SELL order anyway, and pushed a possibly-null price. Both branches now
  match their working sibling.

Also: widen LighterOrder's is_ask/reduce_only to BooleanFlag (the wire format
flags.ts already parses), extract sellableBase (Extract Function, 3 copies),
delete two scripts importing a module that does not exist, add a typecheck
script. tsc --noEmit: 269 -> 0 errors; 218 tests still pass.
2026-07-29 20:27:40 +08:00
DisneyandGitHub b7ace263b1 Feat/grid (#26)
* feat(grid): add grid shift, exchange stops, and reconcile safeguards

* docs(grid): document smart-follow shift and new grid env vars
2026-07-21 15:30:45 +08:00
discountry 1f2c2150e0 feat(exchanges): add Ondo Perps exchange adapter 2026-07-11 15:10:40 +08:00
discountry 345ad11ba3 refactor: enhance order handling and tracking in GridEngine
- Introduced a clientOrderId system for better order identification.
- Updated order creation logic to ensure unique clientOrderIds.
- Improved order cancellation methods to maintain accurate current orders.
- Added tests for new clientOrderId functionality and level state tracking.
- Ensured that desired orders have an intent field set for clarity.
- Enhanced snapshot functionality to include level states for grid lines.
2026-04-06 20:05:03 +08:00
discountry bc29b23027 refactor: restructure aster/ to match standard exchange directory layout
- Move aster-adapter.ts → aster/adapter.ts (consistent with all other exchanges)
- Rename aster/client.ts → aster/gateway.ts (consistent naming)
- Update all imports across 5 files
- Delete old aster-adapter.ts
2026-04-06 18:17:50 +08:00
discountry fda6bcad1d refactor: rename Aster-prefixed universal types to clean names
- AsterOrder → Order
- AsterAccountSnapshot → AccountSnapshot
- AsterAccountPosition → AccountPosition
- AsterAccountAsset → AccountAsset
- AsterDepthLevel → DepthLevel
- AsterDepth → Depth
- AsterTicker → Ticker
- AsterKline → Kline

These types are the platform-agnostic contract used by all 8 exchanges,
not Aster-specific. Renamed across 63 files.
2026-04-06 18:11:57 +08:00
discountry eb70bab8c5 Add Oxlint configuration and integrate linting commands
- Introduced a new `.oxlintrc.json` file to configure Oxlint for code quality checks.
- Updated `package.json` to include linting scripts (`lint` and `lint:fix`) for easier code maintenance.
- Enhanced documentation in `README` files to guide users on running Oxlint checks and applying fixes.
2026-03-12 22:40:18 +08:00
DisneyandGitHub 4014a86223 Enhance CLI command mode for ritmex-bot (#23)
- Introduced a new command mode for `ritmex-bot`, allowing agent-friendly structured trading operations without entering the Ink interactive menu.
- Updated `package.json` to include versioning and set the project as public with a new CLI entry point.
- Enhanced documentation in both English and Chinese to provide comprehensive usage instructions for the new command mode.
- Added a new executable script for `ritmex-bot` to facilitate command execution.
- Improved error handling and command parsing for better user experience and clarity in command execution.
2026-02-27 12:42:20 +08:00
DisneyandGitHub d6399b92aa Feat/support binance (#22)
* add docs

* Add Binance exchange support

- Updated the environment configuration to include Binance as a selectable exchange option.
- Enhanced the README documentation to reflect the addition of Binance.
- Implemented the Binance exchange adapter and integrated it into the existing exchange framework.
- Modified the basis arbitrage strategy to support Binance alongside existing exchanges.
- Added tests to ensure proper functionality and integration of Binance within the trading system.

* Enhance README with detailed Binance exchange configuration

- Added comprehensive instructions for setting up Binance as an exchange option.
- Included environment variable specifications for API keys, market types, and trading symbols.
- Provided examples for both perpetual and spot trading strategies.
- Clarified the use of WebSocket and REST for the Binance adapter.

* Enhance exchange support and testing framework

- Added a new test suite for exchange contracts to ensure consistency and functionality across supported exchanges.
- Refactored exchange ID handling to utilize a centralized list of supported exchanges, improving maintainability.
- Updated CLI argument parsing and help documentation to reflect the new exchange structure.
- Introduced utility functions for validating supported exchanges and their display names.
- Enhanced the BasisApp and strategy runner to leverage the new exchange validation logic.
- Added a new test command for running exchange-related tests.

* Refactor exchange contract tests and update CLI commands

- Removed the trailing supported exchanges set and simplified the logic for trailing stop support in the exchange contract tests.
- Updated the test command for exchange contracts to exclude unnecessary tests, streamlining the testing process.
- Enhanced test descriptions for clarity and improved understanding of the functionality being tested.
2026-02-27 11:37:44 +08:00
discountry 422ee6f465 update maker points config 2026-02-08 09:41:06 +08:00
discountry bee7bdd8fe update maker points 2026-02-08 09:37:39 +08:00
discountry 3f67b99291 Add immediate reprice logic to MakerPointsEngine
- Enhanced the MakerPointsEngine by introducing a new method `shouldTriggerImmediateReprice` to trigger an immediate tick when the market depth deviates beyond a specified minimum reprice basis points threshold.
- Updated the existing depth protection logic to include this new reprice condition.
- Added a comprehensive test suite to validate the immediate reprice functionality and its integration with the MakerPoints engine.
2026-02-08 00:08:38 +08:00
discountry 61e6e4cdde Add Binance depth monitoring configuration to MakerPoints
- Introduced new environment variables `MAKER_POINTS_BINANCE_DEPTH_WINDOW_BPS` and `MAKER_POINTS_BINANCE_DEPTH_IMBALANCE_RATIO` to configure Binance depth monitoring.
- Updated `MakerPointsConfig` interface and implementation to include these new parameters.
- Enhanced translations to reflect dynamic depth window information in the UI.
- Added tests to validate the new configuration options and their integration into the MakerPoints engine.
2026-02-07 23:58:01 +08:00
discountry 6998afebb1 Refactor price calculation in MakerPointsEngine for improved accuracy
- Replaced direct price calculations with a new method `normalizeDepthTargetPrice` to ensure valid target prices for buy and sell orders.
- Updated all instances of price calculations in the MakerPointsEngine to utilize the new normalization method.
- Added boundary tests for `getDepthBetweenPrices` to validate behavior when prices are exactly at the target.
2026-02-07 23:27:42 +08:00
discountry b8942c18e6 Add immediate depth protection logic to MakerPointsEngine
- Introduced a new private property `forceTickRequested` to manage immediate tick requests.
- Implemented `shouldTriggerImmediateDepthProtection` method to trigger a tick when depth falls below the configured threshold.
- Updated the tick processing logic to accommodate immediate depth protection.
- Added unit tests to validate the immediate tick triggering behavior based on depth changes.
2026-02-07 23:10:56 +08:00
DisneyandGitHub 9355ec5019 Enhance Binance depth health monitoring and defense mode logic (#21)
- Updated translations for Binance depth status messages to include depth window information.
- Modified `MakerPointsEngine` to incorporate health checks for the Binance depth tracker, including handling of unhealthy states.
- Improved defense mode activation logic to respond to Binance depth health status, ensuring appropriate logging and notifications.
- Added integration tests for defense mode behavior based on Binance depth health, validating transitions into and out of defense mode.
- Refactored `BinanceDepthTracker` to support health checks and improved connection management.
2026-02-07 22:01:49 +08:00
DisneyandGitHub fa82d45bfb fix size (#20) 2026-02-04 13:26:06 +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 93c6409688 Integrate StandX exchange support by updating configuration files, adding environment variables, and enhancing documentation. Include new API endpoints and authentication details for StandX in README and dedicated documentation files. Update CLI and adapter logic to accommodate StandX functionalities. 2025-12-21 15:37:03 +08:00
discountry 49b8f0bcf1 fix perp 2025-12-08 23:55:13 +08:00
discountry e7f6341961 feat: enhance order handling in LighterGateway and introduce order identity normalization for improved precision and consistency 2025-11-12 19:17:04 +08:00
discountry e94cf1bda2 feat: enhance toAccountSnapshot function with improved market ID and symbol matching logic, and add corresponding unit tests 2025-11-08 17:14:01 +08:00
discountry d0d1afa0ea feat: enhance quantity and price rounding functions for improved precision in trading calculations 2025-11-06 21:06:03 +08:00
discountry 1832c4c13e feat: add scaleQuantityWithMinimum function to normalize order quantities and implement corresponding tests 2025-11-03 21:30:19 +08:00
discountry ea5da20311 feat: 重构订单路由逻辑,添加订单意图类型以支持多交易所订单处理 2025-10-23 14:04:44 +08:00
discountry 66e1b3e6f5 feat: 更新网格引擎,添加现有减仓订单恢复逻辑,优化订单曝光管理和状态同步功能 2025-10-07 04:41:32 +08:00
discountry 88292c9c49 feat: 添加最大平仓滑点配置,更新网格引擎状态持久化逻辑,优化订单管理和状态恢复功能 2025-10-07 03:48:12 +08:00
discountry 5878a3dc0b feat: 更新网格引擎,重构订单管理逻辑,添加持仓水平和关闭目标管理,优化订单计算和曝光对齐处理 2025-10-07 03:24:09 +08:00
discountry ccb23ecf44 feat: 更新网格引擎,添加买卖水平索引以稳定订单侧分配,增强订单计算逻辑 2025-10-07 02:54:01 +08:00
discountry b6a6515677 feat: 增强网格引擎逻辑,添加持仓水平管理和订单书更新功能,优化订单取消和曝光对齐处理 2025-10-07 02:15:23 +08:00
discountry 5e65c7025d feat: 添加基础网格策略支持,更新环境配置示例和文档,增强 CLI 和 UI 界面 2025-10-07 01:40:06 +08:00
discountry d7a95ceb36 feat: 添加期现套利策略支持,更新相关配置和界面,增强 Aster 现货 API 客户端功能 2025-10-07 00:23:24 +08:00
discountry d829e451cd feat: 更新 BackpackGateway 适配器,增强账户快照逻辑,支持合约市场的持仓信息和资产归一化处理 2025-10-06 20:11:46 +08:00
discountry cfd5f4309d feat: 添加 Paradex 适配器支持,更新环境变量配置和适配器构建逻辑 2025-10-06 18:06:23 +08:00
discountry fcb83bd16b commit 2025-10-03 15:28:16 +08:00
discountry c8b0ab1c8e feat: 添加 Lighter 适配器及相关功能,支持 trailing stops 和新的交易逻辑 2025-09-30 22:08:05 +08:00
discountry d392f54f21 feat: 添加布林带宽度计算功能及相关配置项,优化趋势引擎以支持布林带宽度过滤 2025-09-27 22:29:56 +08:00
discountry dde7ab71a9 更新环境配置示例,添加 GRVT 相关的 API 凭证和选项,增强文档以支持新的交易所适配器,确保用户能够正确配置和使用 GRVT 交易功能。 2025-09-27 16:12:20 +08:00
discountry 5c420f8a5f 更新策略工具测试,添加 markPrice 字段以确保返回的默认位置和提取位置包含最新信息。 2025-09-25 10:20:09 +08:00