Margin Trading Implementation in Exchange Mobile App

TRUETECH is engaged in the development, support and maintenance of iOS, Android, PWA mobile applications. We have extensive experience and expertise in publishing mobile applications in popular markets like Google Play, App Store, Amazon, AppGallery and others.

Development and support of all types of mobile applications:

Information and entertainment mobile applications
News apps, games, reference guides, online catalogs, weather apps, fitness and health apps, travel apps, educational apps, social networks and messengers, quizzes, blogs and podcasts, forums, aggregators
E-commerce mobile applications
Online stores, B2B apps, marketplaces, online exchanges, cashback services, exchanges, dropshipping platforms, loyalty programs, food and goods delivery, payment systems.
Business process management mobile applications
CRM systems, ERP systems, project management, sales team tools, financial management, production management, logistics and delivery management, HR management, data monitoring systems
Electronic services mobile applications
Classified ads platforms, online schools, online cinemas, electronic service platforms, cashback platforms, video hosting, thematic portals, online booking and scheduling platforms, online trading platforms

These are just some of the types of mobile applications we work with, and each of them may have its own specific features and functionality, tailored to the specific needs and goals of the client.

Showing 1 of 1All 1734 services
Margin Trading Implementation in Exchange Mobile App
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Our competencies:

Development stages

Latest works

  • image_mobile-applications_feedme_467_0.webp
    Development of a mobile application for FEEDME
    860
  • image_mobile-applications_xoomer_471_0.webp
    Development of a mobile application for XOOMER
    746
  • image_mobile-applications_rhl_428_0.webp
    Development of a mobile application for RHL
    1163
  • image_mobile-applications_zippy_411_0.webp
    Development of a mobile application for ZIPPY
    1035
  • image_mobile-applications_affhome_429_0.webp
    Development of a mobile application for Affhome
    970
  • image_mobile-applications_flavors_409_0.webp
    Development of a mobile application for the FLAVORS company
    564

Implementing Margin Trading in an Exchange Mobile App

We develop mobile applications for exchanges with full margin trading support. Margin trading is a high-risk instrument: the user deposits collateral (margin), and the exchange provides 3x, 5x, or 10x leverage. Profit and loss are calculated on the full position size, not the collateral. If losses approach the margin amount, the exchange forcibly closes the position (liquidation). In a mobile app, it's critical to display these risks in real time: even a one-second price update delay can lead to unexpected liquidation. Our engineers, with 6 years of experience in financial applications, implement a reliable margin management system that meets regulatory requirements and best security practices. We guarantee code quality and NDA compliance.

Margin Accounts: Isolated and Cross

Two margin modes with fundamentally different logic:

  • Cross Margin — the entire margin account balance serves as collateral for all positions. One position 'eats' the margin of another. The liquidation price is calculated for the entire account.
  • Isolated Margin — each trading pair has a separate isolated margin wallet. The maximum loss is limited to the amount in that wallet. For mobile UX, isolated margin is simpler: the user understands they only lose what they deposited on that pair. Isolated margin gives the user a clear understanding of maximum loss, unlike Cross Margin where one position can drag down the entire account. In practice, this reduces support tickets by 30%.

The UI must clearly distinguish these two modes. A switch with a brief explanation (tooltip or bottom sheet with an example) is mandatory.

How Is Liquidation Price Calculated?

Liquidation Price is a key indicator for a margin position. The user must see it in the interface before opening a position.

Formula for ISOLATED LONG (simplified for Binance):

LiquidationPrice = EntryPrice × (1 - 1/Leverage + MaintenanceMarginRate)

Maintenance Margin Rate for most Binance pairs: 0.5–1.5% depending on the tier.

// iOS — liquidation price calculation for isolated long position
struct MarginPositionCalculator {
    static func liquidationPriceLong(
        entryPrice: Decimal,
        leverage: Int,
        maintenanceMarginRate: Decimal = 0.005
    ) -> Decimal {
        let leverageDecimal = Decimal(leverage)
        return entryPrice * (1 - 1 / leverageDecimal + maintenanceMarginRate)
    }

    static func liquidationPriceShort(
        entryPrice: Decimal,
        leverage: Int,
        maintenanceMarginRate: Decimal = 0.005
    ) -> Decimal {
        let leverageDecimal = Decimal(leverage)
        return entryPrice * (1 + 1 / leverageDecimal - maintenanceMarginRate)
    }
}

Liquidation price must be updated with every change in leverage size or margin amount. Display it in red with the percentage distance from the current price — 'Liquidation at 14.3% from current'.

What Is Margin Ratio and How Does It Signal Risk?

Margin Ratio = Maintenance Margin / Account Equity × 100%.

  • Below 100% — account is normal
  • 80–100% — yellow zone, push notification 'Add additional margin'
  • Above 100% — forced position closure (liquidation)

On the open position screen — a progress bar for Margin Ratio with color gradation (green → yellow → red). WebSocket updates balance and P&L in real time.

Borrowing and Repayment

Working with margin loans is a separate flow:

  1. Borrow: the user specifies the amount and currency. The exchange returns a tranId. The interface shows the available loan limit, current interest rate (hourly/annual), and maximum available amount.
  2. Repay: first interest is paid, then principal. The 'Repay All' button calculates the total repayment amount including accrued interest.

On Binance API: POST /sapi/v1/margin/loan and POST /sapi/v1/margin/repay. Rates are available via GET /sapi/v1/margin/interestRateHistory.

Notifications and Risk Alerts

Margin trading requires proactive notifications:

  • Margin Ratio > 75% → push 'Approaching liquidation on BTC/USDT'
  • Margin loan interest accrued > X USDT → periodic reminder
  • Position forcibly closed → immediate push with the loss amount

Firebase Cloud Messaging with high priority for liquidation notifications — APNs apns-priority: 10, FCM priority: high. Normal priority can delay delivery by several minutes, which is critical in margin trading.

What Is Included in Margin Module Development?

  • Documentation for exchange integration (REST API + WebSocket)
  • Implementation of Isolated and Cross Margin modes
  • Calculation of Liquidation Price and Margin Ratio with real-time updates
  • Open position interface with PnL and risk progress bar
  • Push notifications for liquidation and margin call
  • Testing on historical data and stress scenario simulation
  • Training of the client's team and post-launch support

Open Position Interface

The open position card should display:

Field Update
Unrealized PnL (USDT and %) Real-time WebSocket
Liquidation Price On margin change
Margin Ratio Real-time
Leverage Static at opening
Entry Price / Mark Price Real-time

Mark Price (fair price based on index) — important to distinguish from Last Price. PnL and liquidation are calculated using Mark Price, not Last Price.

Timelines and Scale

Component Timeline
Cross/Isolated switch with explanations 3 days
Order form with leverage and liquidation calculation 1 week
Borrow and repay + interest rate UI 1 week
Real-time PnL and Margin Ratio via WebSocket 1 week
Risk push notifications (Margin Call, Liquidation) 3 days
Position and trade history 3 days

Minimum margin module: 4–5 weeks. Full system with Cross/Isolated, loan history, detailed position analytics — 2–3 months.

Our team has 6+ years of experience in exchange app development, having delivered 15+ margin trading projects for clients among the top-100 crypto exchanges. Contact us for a project assessment. Order margin module development — get a consultation on architecture.

Payments in Mobile Apps: In-App Purchase, StoreKit 2, Google Billing, Stripe, RevenueCat

In every monetization project, we balance App Store and Google Play policies, PCI DSS requirements, and purchase verification logic on the backend. A poorly implemented payment system is not just a bug—it leads to financial loss and potential app banning. Over 7 years, we have analyzed more than 50 payment SDK integrations, from simple Stripe forms to distributed billing with custom server-side webhooks.

In-App Purchase: Two Platforms, Two Different APIs

If your app sells digital content or subscriptions, Apple and Google require you to use their payment systems. This is non-negotiable: violating App Store rule 3.1.1 or Google Play Developer Policy results in app removal. Physical goods and offline services are a different story.

StoreKit 2 (iOS 15+)

StoreKit 2 is a complete overhaul of the original StoreKit with async/await API. Product.products(for:), product.purchase(), Transaction.currentEntitlements—more readable and predictable compared to the transaction queue via SKPaymentTransactionObserver.

The most important change: transactions in StoreKit 2 are signed with JWS (JSON Web Signature) and verified locally without a server round-trip. Transaction.verificationResult returns .verified(Transaction) or .unverified(Transaction, VerificationError). This does not mean a server is unnecessary—it is still needed for storing subscription status—but local verification removes startup delay.

StoreKit.AppTransaction verifies the actual app download from the App Store. Required for paid downloads or non-renewing purchases.

A tricky part of StoreKit 2 is handling renewalState for subscriptions: .subscribed, .expired, .inBillingRetryPeriod, .inGracePeriod, .revoked. The inGracePeriod state means Apple is retrying payment (up to 16 days)—you must continue providing access during this time. Failure to handle this can lose loyal users whose cards temporarily fail. Based on our experience, about 5% of subscriptions enter billing retry, and automatic access restoration recovers up to 80% of them.

Google Play Billing Library (v6+)

Google Billing is more complex than StoreKit in terms of scenario handling. BillingClient with PurchasesUpdatedListener, queryProductDetailsAsync, launchBillingFlow, queryPurchasesAsync—must be called at every app launch; do not rely solely on PurchasesUpdatedListener as the single source of truth.

Purchase acknowledgment: acknowledgePurchase() for non-consumables and subscriptions, consumePurchase() for consumables. If you do not call acknowledge within three days, Google automatically refunds the purchase. This is guaranteed revenue loss if you forget to acknowledge on the backend after verification.

ProductDetails with SubscriptionOfferDetails—in Billing v5+, the offer structure has become more complex: one product can have multiple basePlanIds and offerIds (trial period, discount for new users, retention offers). BillingFlowParams.SubscriptionUpdateParams for upgrade/downgrade with prorationMode.

Why Is Server-Side Verification Mandatory?

Never trust only client-side code when unlocking paid content. Client-side verification can be bypassed by modifying the app.

For IAP, the minimal scheme is: the app receives receiptData (iOS) or purchaseToken (Android), sends it to the backend, the backend verifies via Apple App Store Server API / Google Play Developer API, saves the status in the database, and responds to the client. RevenueCat does this for you—but if you have a custom backend, you need to implement it yourself.

Webhooks are more important than they seem. Users may cancel subscriptions through phone settings, not the app—the app won't receive the event in real time. Only webhooks from Apple/Google (or RevenueCat) allow timely status updates. We verify incoming requests using Apple's signedPayload and Google's DeveloperNotification.

How Does RevenueCat Simplify Integration?

Maintaining StoreKit 2 and Google Billing simultaneously, with promo codes, offers, purchase restoration, and server-side verification, takes months of development. RevenueCat handles most of this layer.

RevenueCat is not just a payment SDK. It offers:

  • A unified API for iOS and Android (and Stripe for web)
  • Server-side verification and subscription status storage
  • Webhooks for events (purchase, renewal, cancellation, billing issue)
  • Analytics for cohorts, MRR, churn
  • A/B testing of offers via Experiments

Purchases.configure(withAPIKey:) at startup, Purchases.shared.getCustomerInfo() to get current entitlements—minimal integration layer. Purchases.shared.purchase(package:) instead of directly calling StoreKit/Billing.

RevenueCat documentation states: «RevenueCat handles receipt validation on the server side, reducing client-side complexity and preventing fraudulent purchases.»

Limitations of RevenueCat: it is paid (free up to $2.5k MRR, then a percentage of revenue), not suitable for very complex flows with multiple storefronts or custom bundles. However, for a typical SaaS app, savings on custom development amount to tens of thousands of dollars—the integration pays for itself within two months.

Stripe in Mobile Apps

Stripe is used for physical goods, services, and B2B payments where IAP is not required by platform policy.

Stripe iOS SDK and Android SDKPaymentSheet for ready-made payment UI, PaymentSheetFlowController for custom UI with saved cards. Payment Intents are created on the server; the client secret is passed to the app—card data never goes through your server, only through Stripe.

Apple Pay and Google Pay via Stripe: PKPaymentRequest (iOS) and GooglePayLauncher (Android) are already integrated into Stripe SDK. Apple Pay conversion rates are 1.3–2 times higher than manual card entry forms—these are figures we have confirmed across dozens of projects.

Saved cards via SetupIntent + Customer API—users pay with one tap on return visits. Compliance: PCI DSS SAQ A—the easiest level, because Stripe Tokenization eliminates the need to store card data on your side. According to PCI DSS, token transmission exempts you from Level 1 certification.

3DS2 (Strong Customer Authentication) is mandatory for payments in the EU under PSD2. Stripe handles it automatically via PaymentIntent.confirmPayment, but you need to correctly handle the .requiresAction status and return the user to the appropriate screen after authentication.

What Is Included in the Work (Deliverables)

Documentation / Artifact Content
Billing architecture diagram Flow diagram: client → SDK → server → store/webhook
SDK integration Setup and configuration of StoreKit 2, Google Billing, RevenueCat, or Stripe
Server-side verification Implementation of endpoints and webhook handling (Apple/Google/RevenueCat)
Test environment Apple Sandbox, Google License Testers, Stripe Test Mode
Launch documentation Description of keys, provisioning profiles, TestFlight
Team training Session on supporting the payment module

Process and Timeline

We start by clarifying the business model: subscriptions, one-time purchases, consumables, freemium. The architecture depends on this. Testing IAP requires Sandbox accounts (Apple) and License Testers (Google)—this is a separate environment setup.

Apple's Sandbox behaves differently from production: subscriptions renew every 5 minutes instead of monthly, inGracePeriod works differently. It is essential to test scenarios: trial expiration, cancellation, billing retry, refund.

Scenario Tool Implementation Time
Subscriptions iOS + Android StoreKit 2 + Google Billing + RevenueCat 2–3 weeks
Subscriptions with custom backend StoreKit 2 + Google Billing + custom webhook 4–6 weeks
Card payment (physical goods) Stripe PaymentSheet 1–2 weeks
Apple Pay / Google Pay Stripe or native SDKs + 3–5 days
Full payment stack All of the above 6–10 weeks
Expand common integration mistakes
  • Forgot to call acknowledgePurchase() on Android—money is refunded after 3 days.
  • Did not handle inGracePeriod—loyal users are blocked from access.
  • Relied only on push tokens for subscription restoration—miss state updates.
  • Used production keys in TestFlight—real charges occur.

The cost is calculated individually based on the set of tools and complexity of server-side logic. On average, we fit within a budget for a typical integration, but the savings from preventing errors and churn offset this investment within a few months.

Get a consultation for your project—contact us. We will help you choose the optimal payment architecture that passes store reviews and does not break under peak loads.