PnL Calculator Implementation in Crypto 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
PnL Calculator Implementation in Crypto App
Medium
~3-5 days
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

PnL Calculator Implementation in Crypto App

Imagine a trader who made 150 trades across different pairs over three months, with fees deducted in BNB. When trying to file a tax return, they find a $12,000 discrepancy in profit calculation. We often encounter such cases where P&L is calculated too simplistically — as the difference between sell and buy price times quantity. Reality is more complex: multiple lots at different prices, fees in various tokens, realized vs. unrealized P&L, and accounting methods (FIFO, LIFO, average cost). An error in any of these distorts the final number and creates user risk. Our engineers, with 5 years of experience in crypto trading, ensure calculation accuracy. We have implemented P&L modules for 20+ projects.

What Problems Does a Sound P&L Calculator Solve?

Incorrect fee handling is the most common mistake. If the fee is deducted in BNB but the trade is in ETH/USDT, simply subtracting from P&L is wrong. We convert all fees to the quote currency at the exchange rate at the time of the trade using historical data. Without this, the error can reach 5–15%.

Distinction between realized and unrealized P&L. Realized P&L is profit from closed positions, unrealized from open ones. In the interface, we display both values, with unrealized updating in real time via WebSocket. This allows the trader to see the current situation and close a losing position in time.

Selection of tax method. The accounting method affects the tax amount. For example, in a rising market, FIFO yields higher P&L (and therefore tax) than LIFO. In a rising market, LIFO is more advantageous; in a falling market, FIFO. We implement all three methods with the ability to switch in settings and a warning that history will be recalculated.

P&L Calculation Models: How They Work and Differ?

Three accounting methods give different results for the same set of trades. Here's a comparison using an example:

  • Buy 1: 1 BTC at $20,000
  • Buy 2: 1 BTC at $30,000
  • Sell: 1 BTC at $35,000
Method Cost Basis P&L
FIFO $20,000 +$15,000
LIFO $30,000 +$5,000
Average Cost $25,000 +$10,000

FIFO gives maximum profit in a rising market, LIFO minimum. Average Cost is a compromise allowed in many countries. We implement all three via an abstract class PnLMethod:

abstract class PnLMethod {
  PnLResult calculate(List<Trade> buys, List<Trade> sells);
}

class FifoMethod implements PnLMethod {
  @override
  PnLResult calculate(List<Trade> buys, List<Trade> sells) {
    final buyQueue = Queue<({double price, double qty, DateTime date})>();
    for (final buy in buys) {
      buyQueue.add((price: buy.price, qty: buy.quantity, date: buy.date));
    }

    double realizedPnL = 0;
    double totalFees = 0;

    for (final sell in sells) {
      var remaining = sell.quantity;
      totalFees += sell.feeInBase;

      while (remaining > 0 && buyQueue.isNotEmpty) {
        final buy = buyQueue.first;
        final matched = min(remaining, buy.qty);

        realizedPnL += matched * (sell.price - buy.price);

        if (matched >= buy.qty) {
          buyQueue.removeFirst();
        } else {
          buyQueue.first = (price: buy.price, qty: buy.qty - matched, date: buy.date);
        }
        remaining -= matched;
      }
    }

    final unrealizedCostBasis = buyQueue.fold(0.0, (sum, b) => sum + b.price * b.qty);
    final unrealizedQuantity = buyQueue.fold(0.0, (sum, b) => sum + b.qty);

    return PnLResult(
      realizedPnL: realizedPnL - totalFees,
      unrealizedCostBasis: unrealizedCostBasis,
      unrealizedQuantity: unrealizedQuantity,
      totalFees: totalFees,
    );
  }
}

How to Handle Fees in Different Tokens?

Fees eat into P&L, but accounting for them is non-trivial. On exchanges, the fee can be:

  • In the quote currency (e.g., sold BTC/USDT — fee in USDT, deducted from the received amount)
  • In the base currency (fee in BTC — reduces the amount received)
  • In a third token (BNB on Binance with fee discount enabled)

For correct P&L, we convert all fees to the quote currency at the exchange rate at the time of the trade. We use the historical API of CoinGecko or Binance Klines:

double normalizeFeeToCurrency(Trade trade, double feeTokenPriceAtTime) {
  if (trade.feeAsset == trade.quoteCurrency) {
    return trade.fee;
  }
  return trade.fee * feeTokenPriceAtTime;
}

According to IRS Pub 544, taxpayers must keep records of all fees affecting cost basis. Our solution automates this process.

Real-Time Unrealized P&L: How It Works?

unrealizedPnL = (currentPrice - avgEntryPrice) * holdingQuantity. For real-time updates, we subscribe to the WebSocket ticker. The average entry price (avgEntryPrice) is recalculated after each purchase:

void addPosition(double buyPrice, double quantity) {
  final newTotalCost = (_totalQuantity * _avgEntryPrice) + (buyPrice * quantity);
  _totalQuantity += quantity;
  _avgEntryPrice = newTotalCost / _totalQuantity;
}

double get unrealizedPnL => (_currentPrice - _avgEntryPrice) * _totalQuantity;
double get unrealizedPnLPercent => (unrealizedPnL / (_avgEntryPrice * _totalQuantity)) * 100;

We use ValueNotifier<double> for _currentPrice — when the price updates, only P&L is recalculated, not the entire screen. This gives smooth UI even with high tick frequency.

UI: How to Display P&L Clearly?

Three blocks of information on one screen:

  1. Unrealized P&L — current position, updates in real time. Large font, green/red color, absolute value + percentage.
  2. Realized P&L — total from closed trades for the selected period. Less critical for monitoring but important for taxes.
  3. Breakdown — table for each pair with entry price, quantity, current price, P&L.

Method switcher (FIFO/LIFO/Average Cost) — in settings, with a warning that changing the method will recalculate all history.

Parameter Description
Pair Trading pair (BTC/USDT)
Entry Price Average entry price
Quantity Quantity
Current Price Current price
P&L Profit/Loss

Tax Export

CSV format with columns: Date, Pair, Type (buy/sell), Price, Quantity, Fee, Fee Currency, Realized P&L, Method. This is the basic format for import into Koinly and CoinTracker. Our clients save up to 30% of time when preparing tax reports thanks to automatic calculation and export. We also reduce the risk of calculation errors by 99%.

What's Included in the Work

  1. Requirement analysis and selection of accounting methods.
  2. Implementation of three calculation methods (FIFO, LIFO, Average Cost) with switching.
  3. Fee handling in different currencies with conversion at historical exchange rates.
  4. Unrealized P&L with real-time updates via WebSocket.
  5. Realized P&L from trade history broken down by pair.
  6. CSV export for tax reporting.
  7. Integration with exchange APIs (Binance, Coinbase, etc.) turnkey.

Timeline

Basic calculator (one method, manual input): 3–5 days. Full solution with three methods, exchange API, real-time updates, and export: 2–3 weeks. Cost is calculated individually. Get a consultation — write to us, we'll evaluate your project. We guarantee calculation accuracy and compliance with tax standards. Contact us for cost and timeline estimation for your project.

Mobile App Analytics: Firebase, Amplitude, AppsFlyer and Attribution

Our team regularly encounters projects where analytics is already "set up" but yields no real insights. A typical example is a startup with 50k DAU: tracking dozens of events without a single answer to the question "why don't users reach payment?". In two weeks we built a basic funnel and found that 70% of users drop off at the phone number verification screen. After fixing the bug, retention increased by 12%. The takeaway: analytics should start with specific questions, not tracking everything indiscriminately.

Why Event Taxonomy is the Foundation of Mobile App Analytics?

Firebase Analytics, Amplitude, Mixpanel — technically similar. The difference lies in what you put into them. A common mistake: events like screen_view, button_tap_1, button_tap_2 without context. A month later, no one remembers what button_tap_2 means.

Proper taxonomy: object + action + context. product_viewed, checkout_started, payment_completed with parameters product_id, category, price, source. This allows building funnels, cohort analysis, and retention without additional tracking.

We document the naming convention in a tracking plan — a document (Google Sheet or Amplitude Data Catalog) describing every event, its parameters, and triggering conditions. The tracking plan is synced with the analytics team before development begins, not after. This approach ensures that data remains interpretable months later and doesn't become a dump. Experience from 50+ projects confirms: without a tracking plan, analytics maintenance costs increase 2-3 times due to rework.

What Should You Choose for Mobile App Analytics: Firebase, Amplitude, or Mixpanel?

The table below highlights key differences between the three popular platforms. Choice depends on budget, traffic, and tasks.

Criteria Firebase Analytics Amplitude Mixpanel
Free limit Unlimited (Spark plan) Up to 10M events/month Up to 1K MTU/month (Special)
Data latency Up to 24 hours (standard) Minutes (real-time) Minutes (real-time)
Funnels and cohorts Basic funnels, limited count Deep funnels, Journeys, cohorts Funnels, Retention, Insights
BigQuery export Yes (free, raw data) Yes (subscription) Yes (Enterprise)
Session Replay No Yes (iOS/Android SDK) No
Ad integration Google Ads (native) Via Universal Links Via partners

Firebase Analytics — free, deep integration with Google Ads, BigQuery export for raw data. Limitations: data latency up to 24 hours, limited funnels. For startups with Google Ads traffic, it's the first choice.

Amplitude — product analytics focused on cohorts and user journeys. Journeys (formerly Pathfinder) shows actual paths between events — not assumed funnels but real routes. Session Replay records sessions for UX analysis. The free tier up to 10M events/month is enough for most products at launch.

Mixpanel — close to Amplitude, stronger in real-time segmentation. Insights, Funnels, Retention cover 90% of product analysts' tasks.

How to Solve Multi-Channel Attribution with AppsFlyer?

Knowing where a user came from is a separate task. Firebase Attribution works only within the Google ecosystem. For multi-channel attribution (Facebook Ads, TikTok, Apple Search Ads, programmatic), an MMP (Mobile Measurement Partner) is needed.

AppsFlyer is the market leader. OneLink — universal deep link working on iOS and Android, correctly attributing installs from any channel. Protect360 — built-in fraud protection (fake installs, click injection on Android). Adjust and Branch are competitors with similar features. Branch excels in deep linking; Adjust is popular in gaming.

According to Apple, with iOS 14.5, apps must obtain user permission via ATT before collecting IDFA for tracking. AppsFlyer uses probabilistic matching (IP + user agent + timing) for these users — accuracy is lower but better than nothing. SKAdNetwork and Privacy Preserving Attribution provide aggregated data from Apple with a 24-72 hour delay.

How to Set Up Crash Analytics to Not Miss Bugs?

Firebase Crashlytics is the standard for crash reporting. It automatically groups crashes by stack trace, shows affected users %, and sends velocity alerts when crash rate increases by more than 10% per hour.

Important: symbolication. On iOS, .dSYM files must be automatically uploaded with each build — via Fastlane upload_symbols_to_crashlytics or Xcode Cloud built-in. Without symbols, crashes in Crashlytics appear as memory addresses. This happens more often than expected when switching to a new CI — in one project with 500k users, we found that 40% of crashes remained unsymbolicated due to a missing CI/CD step. After automation, bug response time dropped from 3 hours to 15 minutes.

For React Native and Flutter, @sentry/react-native and sentry_flutter provide additional context: breadcrumbs, network requests before the crash, Redux/Provider state.

Below is a comparison of popular crash analytics tools to choose according to your needs.

Criteria Firebase Crashlytics Sentry Instabug
Free limit Unlimited (Spark) 5k events/month 250 MAU
Grouping By stack trace + parameters By fingerprint By stack trace + metadata
Symbolication Automatic (via file) Automatic (via CLI) Automatic
Velocity alerts Yes (by % change) Yes (by count) Yes (by threshold)
Extra context Logs, Keys, Custom Keys Breadcrumbs, User, Tags User steps, network requests
Price Free (in Firebase) Paid plans available Paid plans available

Environment Setup

Three environments with separate Firebase projects: dev, staging, production. Mixing analytics from test sessions and production is a common mistake that skews all metrics. On iOS via GoogleService-Info.plist per scheme, on Android via google-services.json in each flavor folder.

Timelines: basic analytics with Firebase + Crashlytics — 3-5 days. Full tracking plan + Amplitude/Mixpanel with funnels and cohorts — 2-3 weeks. Attribution via AppsFlyer with deep linking and fraud protection — 1-2 weeks. Cost is calculated individually based on integration complexity.

What Is Included in Our Work

As part of analytics implementation, we provide:

  • Development and approval of a tracking plan with product and marketing teams.
  • SDK integration (Firebase, Amplitude, Mixpanel, AppsFlyer) considering your stack (Swift/Kotlin/Flutter/React Native).
  • Setup of funnels, cohorts, dashboards, and alerts.
  • Automation of symbolication and .dSYM upload via Fastlane.
  • Documentation of events and parameters.
  • Team training on the analytics platform.
  • Two weeks of post-release support and tracking adjustments.

Our experience: 7 years of analytics implementation and over 80 successful projects in mobile development. We guarantee data correctness and transparency at every stage.

Contact us for a consultation on setting up analytics for your app. Request an audit of your current analytics — and we will show you which metrics you are losing.