Skip to content

feat(margin): implement leveraged margin trading with risk management (closes #383)#418

Merged
DevMuhdishaq merged 1 commit into
StelTade:mainfrom
ciynthia:fix/issue-383-margin-trading
Jun 28, 2026
Merged

feat(margin): implement leveraged margin trading with risk management (closes #383)#418
DevMuhdishaq merged 1 commit into
StelTade:mainfrom
ciynthia:fix/issue-383-margin-trading

Conversation

@ciynthia

Copy link
Copy Markdown
Contributor

Overview

This PR implements leveraged/margin trading with comprehensive risk management in SwapTrade-Backend. It adds per-asset-pair margin configuration, leveraged position management, maintenance margin enforcement, automatic liquidation for undercollateralized positions, volatility-based leverage caps, margin call notifications (email/SMS via queue), and daily interest accrual on borrowed funds.

Related Issue

Closes #383

Changes

⚙️ Margin Trading Core

  • [ADD] src/margin/services/margin-calculator.service.ts

  • Added equity, margin ratio, liquidation price, and volatility-adjusted max leverage calculations.

  • Enforces maintenance margin requirements and margin-call threshold detection.

  • [ADD] src/margin/services/margin-position.service.ts

  • Added open/close position flows with collateral locking against UserBalance.

  • Rejects positions when available margin is insufficient or leverage exceeds pair limits.

  • Integrates with the insurance fund via shortfall coverage on liquidation.

  • [ADD] src/margin/services/margin-pair-config.service.ts

  • Added CRUD for per-pair margin parameters (max leverage, initial/maintenance margin, interest rate, volatility caps).

  • [ADD] src/margin/services/liquidation-engine.service.ts

  • Added cron-based monitor (every 5s) that liquidates positions before equity goes negative.

  • Emits margin call events when positions approach the liquidation threshold.

  • [ADD] src/margin/services/margin-interest.service.ts

  • Added daily interest accrual on borrowed funds with auditable records.

🗄️ Entities & Migration

  • [ADD] src/margin/entities/margin-pair-config.entity.ts — per-pair configurable margin parameters
  • [ADD] src/margin/entities/margin-position.entity.ts — leveraged positions with margin, leverage, collateral, and borrowed amount fields
  • [ADD] src/margin/entities/margin-interest-accrual.entity.ts — auditable daily interest records
  • [ADD] src/database/migrations/1750200000000-CreateMarginTradingTables.ts — database migration for all margin tables

🌐 API Surface

  • [ADD] src/margin/margin.controller.ts

  • Added REST endpoints for pair config management and position open/close/query.

  • Added effective leverage lookup with volatility adjustment.

  • [ADD] src/margin/margin.module.ts

  • Added dedicated NestJS module wiring entities, services, controller, and listener.

  • [MODIFY] src/app.module.ts

  • Registered MarginModule and margin entities in TypeORM configuration.

🔔 Notifications & Events

  • [ADD] src/margin/listeners/margin.listener.ts

  • Dispatches email, SMS (via queue), and in-app notifications on margin calls and liquidations.

  • [MODIFY] src/infrastructure/events/domain.events.ts

  • Added PositionOpenedEvent, MarginCallEvent, and PositionLiquidatedEvent.

  • [MODIFY] src/common/enums/notification-event-type.enum.ts

  • Added MARGIN_CALL and POSITION_LIQUIDATED notification types.

🧪 Tests

  • [ADD] src/margin/services/margin-calculator.service.spec.ts
  • [ADD] src/margin/services/margin-position.service.spec.ts
  • [ADD] src/margin/services/liquidation-engine.service.spec.ts
  • [ADD] src/margin/services/margin-interest.service.spec.ts

Verification Results

npm run lint ✅ completed (existing repo warnings only)
npm test -- --testPathPatterns="src/margin" --no-coverage --runInBand ✅ passed (16/16)
npm run build ✅ passed
Acceptance Criteria Status
Users cannot open positions exceeding their available margin
Liquidations occur before positions go negative
All margin parameters are configurable per asset pair
Users receive email/SMS notifications for margin calls
Interest calculations are accurate and auditable
Users can open leveraged positions up to 10x (configurable)
Maintenance margin requirements are strictly enforced
Underwater positions are automatically liquidated
Margin calls sent when approaching liquidation threshold
Interest on borrowed funds calculated and charged daily

…closes StelTade#383)

Add margin pair configuration, position management, automatic liquidation engine,
daily interest accrual, and margin call notifications integrated with the
existing insurance fund and queue infrastructure.
@DevMuhdishaq
DevMuhdishaq merged commit a3d385f into StelTade:main Jun 28, 2026
2 of 3 checks passed
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.

Margin Trading with Risk Management

2 participants