Commit Graph
309 Commits
Author SHA1 Message Date
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 6f64dd5a0a refactor(maker-points): extract defense-mode decision into pure logic
checkDataStaleAndDefense mixed the question (are these feeds trustworthy?) with
the answer (probe over REST, cancel everything, start polling), inside a 2063-line
class, so the rule could only be exercised through a live adapter.

Separate Query from Modifier: maker-points-defense.ts takes feed ages and health
flags and returns a verdict; the engine keeps every action. Follows the existing
maker-points-logic.ts / grid-logic.ts convention.

Three other enterDefenseMode call sites each spelled out the same 14-field stale
info, 11 fields of which were false/0/null padding. defenseReasonsFor() states
only the known cause.

16 new unit tests cover what previously had none — the age-0 startup case, the
threshold boundary, and the probe-then-defend sequence for a quiet account feed.

250 pass; tsc and oxlint clean. Engine 2063 -> 1939 lines.
2026-07-29 20:43:06 +08:00
discountry 2c98664412 refactor(ui): extract useStrategyEngine from 9 duplicated screens
Every screen repeated the same block: resolve the exchange, build an adapter,
construct an engine, hold it in a ref, subscribe, clone the snapshot into state,
stop on unmount, and stop again on Escape. Roughly 45 lines each, differing only
in which engine they built and which arrays they cloned.

Two of them also carried their own copy of an availability rule — MakerPointsApp
re-checked 'standx' and BasisApp re-checked isBasisSupportedExchangeId — a third
and fourth statement of what the registry now owns. The hook reads
strategyUnavailableReason instead, so a screen cannot drift from the menu.

Screens now declare a strategy id and, when they render engine-owned arrays
beyond tradeLog, a cloneSnapshot. Engine construction leaves the view layer
entirely.

234 pass; tsc and oxlint clean; menu renders unchanged. -338 lines.
2026-07-29 20:39:16 +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
discountry 9f3e50045a docs: update Lighter referral link in README files
- Replaced the Lighter referral link in both English and Chinese README files to ensure accuracy and consistency across language versions.
2026-07-29 19:01:53 +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 7efd64ef29 docs: update referral links in README files
- Replaced the Hyperliquid invite link with a referral link in both English and Chinese README files.
- Ensured consistency in the referral links section across both language versions.
2026-07-12 12:05:12 +08:00
discountry a6394191d8 docs: update README and add bilingual configuration guides for exchanges
- Changed installation command from `npx` to `bunx` for consistency.
- Added bilingual configuration guides for Aster and Backpack exchanges.
- Updated exchange details in the README to reflect new market types and required settings.
- Enhanced clarity in the supported exchanges section with updated variable names and descriptions.
2026-07-12 11:51:45 +08:00
discountry 35653c8beb docs: add Hyperliquid invite link to README files 2026-07-12 11:15:29 +08:00
discountry 1f2c2150e0 feat(exchanges): add Ondo Perps exchange adapter 2026-07-11 15:10:40 +08:00
discountry 6b5f2542a4 docs: update repository guidelines and project structure details 2026-04-06 20:18:54 +08:00
discountry 4e69b81da2 docs: update testing instructions for Bun in CLAUDE.md 2026-04-06 20:08:52 +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 d925fd93ee refactor: update import paths for AsterSpotBookTicker type
- Moved AsterSpotBookTicker import to the correct module path from "../exchanges/aster/types".
- Cleaned up imports in basis-arb-engine.ts for better organization and clarity.
2026-04-06 18:54:56 +08:00
discountry e81d1396a2 Implement feature X to enhance user experience and fix bug Y in module Z 2026-04-06 18:40:12 +08:00
discountry 20855c2d1d refactor: extract shared adapter utilities (safeInvoke + initManager)
Created src/exchanges/adapter-utils.ts with createSafeInvoke() and
createInitManager() factories. Converted 7/8 adapters to use shared
utilities, eliminating ~350 lines of duplicated retry/init/error-handling
boilerplate. Lighter adapter kept as-is (no retry logic by design).
Also translated Chinese comments in adapter.ts and order-schema.ts.
2026-04-06 18:36:56 +08:00
discountry d799cf79c2 refactor: extract shared order handler factory, deduplicate 8 order.ts files
Created src/exchanges/order-handlers.ts with createOrderHandlers() factory.
All 8 exchange order.ts files now use config-driven delegation instead of
duplicated ~80-line implementations. Shared applyCommonFields() logic
consolidated into the factory module.
2026-04-06 18:24:42 +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 fb906be27c refactor: split types.ts into per-exchange type modules
- Extract GRVT-specific types to grvt/types.ts
- Extract Aster-spot/futures types to aster/types.ts
- types.ts now contains only universal/platform-agnostic types
- Reduced from 632 to ~135 lines
2026-04-06 18:16:25 +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 230c0d5e18 Add .factory to .gitignore and ensure proper newline at end of file 2026-04-06 17:58: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
discountry 055bb445a9 fix denpendence 2026-03-01 23:47:52 +08:00
discountry 74d0a0a98b Update package.json and README files to include repository information and enhance CLI command mode documentation
- Added repository details to package.json for better project visibility.
- Revised README files in both English and Chinese to improve the clarity and accessibility of the `ritmex-bot` CLI command mode instructions.
- Included installation instructions for adding the project as a skill, enhancing user onboarding experience.
2026-02-27 12:55:28 +08:00
discountry 674a6fe0da Add CLI user guides and .npmignore file
- Introduced English and Chinese user guides for the `ritmex-bot` CLI, detailing command usage and options.
- Created a new `.npmignore` file to exclude documentation directories from npm package distribution.
- Updated README files to link to the new user guides directly, ensuring easy access for users.
2026-02-27 12:47:32 +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 858b2f304b Update imbalance ratio in MakerPointsEngine and binance-depth.ts for improved trading strategy
- Adjusted the `ratio` in `MakerPointsEngine` from 8 to 2 to better align with current market conditions.
- Updated `DEFAULT_IMBALANCE_RATIO` in `binance-depth.ts` from 8 to 2 to maintain consistency across the trading strategy.
2026-02-07 23:35:22 +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
discountry 6f85e609f8 Update minimum depth threshold and imbalance ratio for improved trading performance
- Changed `filterMinDepth` in `MakerPointsConfig` from 5 to 10 to enhance trading strategy.
- Adjusted `ratio` in `MakerPointsEngine` and `DEFAULT_IMBALANCE_RATIO` in `binance-depth.ts` from 9 to 8 for better alignment with market conditions.
2026-02-07 22:46:48 +08:00
discountry a851257149 Update minimum depth threshold in MakerPointsConfig from 50 to 5 for improved trading performance 2026-02-07 22:19:39 +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 d0154e5721 fix den 2026-02-03 18:48:06 +08:00
discountry 52b6a8a076 Add invitation links for Nado registration in trading tutorial 2026-02-03 12:04:36 +08:00
discountry db6a9cfc68 Add Nado trading tutorial for ritmex-bot 2026-02-03 12:02:55 +08:00
DisneyandGitHub 03b8e53d30 Merge pull request #19 from discountry/feat/arb
Feat/arb
2026-02-01 11:15:42 +08:00
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