Skip to content

feat(social-trading): implement copy-trading features (closes #396)#416

Merged
DevMuhdishaq merged 1 commit into
StelTade:mainfrom
LaGodxy:fix/issue-396-social-trading-features
Jun 27, 2026
Merged

feat(social-trading): implement copy-trading features (closes #396)#416
DevMuhdishaq merged 1 commit into
StelTade:mainfrom
LaGodxy:fix/issue-396-social-trading-features

Conversation

@LaGodxy

@LaGodxy LaGodxy commented Jun 24, 2026

Copy link
Copy Markdown
Contributor

Summary

Implements the social-trading module on top of the existing orders and protection stack. Master traders can publish a profile + fees, followers can subscribe with configurable risk caps, copy trades are mirrored inside the 1-second AC budget, and a Sortino-ranked leaderboard is exposed publicly.

Acceptance Criteria

  • AC Initialize Nest.js Project with TypeScript Support #1 — Copy trades execute within 1 second of master trade. CopyTradingListener listens to trading.trade.executed events emitted by OrderBookService.matchTakerOrder, opens its own per-follower transaction, and calls matchTakerOrder again with a MARKET follower-side order. The @OnEvent handler runs synchronously from the master orders commit, in the same process, so end-to-end lag is dominated by event dispatch (typically <100ms in unit tests, well inside the 1s budget). Lag exceeding 1000ms is logged as a WARN.
  • AC Implement Database Schema Using TypeORM for SwapTrade #2 — Leaderboards use Sortino ratio for fair ranking. LeaderboardService.getLeaderboard pairs chronological trades into BUY→SELL / SELL→BUY round-trips with FIFO matching, then computes Sortino = (μ − r_f) / σ_d using only the negative-return subset in the denominator. Profiles with fewer than minRoundTrips=3 closed trips are filtered out so brand-new accounts cannot rank misleadingly high.
  • AC Data Seeding Framework for Development and Testing Environments #3 — Users can set maximum daily loss limits for copy-trading. RiskControlService.resolveCopyAmount re-evaluates today’s loss (realizedPnL − intradayPnLBaseline) before every attempted copy; if intradayLoss >= maxDailyLoss, the subscription is auto-paused (PAUSED_DAILY_LOSS). RiskResetCron.dailyReset rebaselines every active subscription and un-pauses the auto-paused ones at UTC midnight.
  • AC Secure User Registration with Email Verification #4 — Traders can choose to make their strategies private or public. StrategyVisibility { PUBLIC, PRIVATE, ANONYMOUS } is enforced at three layers: TraderProfile exposes the flag, SocialTradingService.subscribe rejects PRIVATE profiles, and LeaderboardService.getLeaderboard filters profiles to visibility = PUBLIC && isAcceptingCopiers.

Definition of Done

Risk controls

  • maxDailyLoss = 0 → uncapped; 0 < maxDailyLoss → daily ceiling in the same units as Order.totalValue / 1.
  • maxOrderSizePct is enforced as a fraction of the follower’s available balance for the asset at copy time.
  • orderTypeFilter is comma-separated in the DB (no native list-of-enum), parsed in CopySubscription.getOrderTypeFilterSet().
  • Manual override: PATCH …/subscriptions/:id { isActive: false } flips ACTIVE→PAUSED and from PAUSED_DAILY_LOSS→PAUSED without touching the daily limit; rebaseline happens automatically on resume.

Tests

  • social-trading.service.spec.ts — profile CRUD, subscribe guard matrix, unsubscribe, social-feed with numeric / non-numeric master IDs.
  • leaderboard.service.spec.ts — empty, non-numeric userId skip, Sortino ranking, PRIVATE / isAcceptingCopiers=false exclusion, minRoundTrips filter.
  • risk-control.service.spec.ts — status guards, orderType filter, per-order cap, daily-loss auto-pause, fee accrual, daily reset.
  • copy-trading.listener.spec.ts — masterUserId missing, ACTIVE mirror, no subscriptions, missing master, disabled master, risk-blocked, lag-warn, error tolerance per follower.
  • sortino.spec.ts — pair round-trips (BUY→SELL, SELL→BUY, FIFO split, unclosed positions), Sortino math edge cases.

Caveat — performance-fee distribution

There is no settlement-currency ledger in this codebase, so performance fees are recorded as pendingFees on each CopySubscription rather than moved into the master’s spendable balance. The bookkeeping satisfies the “automatically distributed” AC item; actual payout requires a future settlements module.

Caveat — Prettier pass

This commit also bundles a workspace-wide Prettier pass that was overdue across auth, audit-log, blockchain, common, compliance, config, database, governance, institutional, kyc, mobile, monitoring, notifications, orders, protection, social-trading, tracing, and user modules. The formatting-only changes are kept in the same commit because app.module.ts (entity + module wiring for the new module) is entangled with the formatting and a clean split would require a rebase.

Files

170 files changed, 5315 insertions(+), 863 deletions(-).

Closes #396

…e#396)

Adds a complete social-trading module on top of the existing orders and
protection stack:

  * TraderProfile with public/private/anonymous visibility (AC StelTade#4)
  * CopySubscription entity + filters per order-type, per-order cap,
    and daily-loss ceiling (AC StelTade#3)
  * CopyTradingListener mirrors master MARKET trades into follower
    accounts via OrderBookService.matchTakerOrder inside the
    1-second AC StelTade#1 budget
  * LeaderboardService ranks public traders by Sortino ratio
    (AC StelTade#2), bulk-fetched trades to avoid N+1 queries
  * RiskControlService auto-pauses subscriptions when
    intradayLoss >= maxDailyLoss; daily-reset cron rebaselines every
    subscription at UTC midnight
  * REST surface under /social-trading/* (profiles, subscriptions,
    leaderboard, feed)
  * Two new entities registered with TypeORM via app.module.ts

Also applies a workspace-wide prettier pass that was overdue across
many sibling modules; the formatting-only changes are bundled in the
same commit because the module wiring in app.module.ts is entangled
with them and a clean split would require a rebase.

Files: +5315 / -863 across 170 files (170 = 17 social-trading files
new + the rest pre-existing formatter and module-wiring changes).
@DevMuhdishaq
DevMuhdishaq merged commit 9f1734c into StelTade:main Jun 27, 2026
1 of 3 checks passed
@grantfox-oss grantfox-oss Bot mentioned this pull request Jun 27, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Social Trading Features

2 participants