Insider Trading Detection Model: From On-Chain Signals to Alerts

We design and develop full-cycle blockchain solutions: from smart contract architecture to launching DeFi protocols, NFT marketplaces and crypto exchanges. Security audits, tokenomics, integration with existing infrastructure.
Showing 1 of 1All 1305 services
Insider Trading Detection Model: From On-Chain Signals to Alerts
Complex
from 2 weeks to 3 months
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1349
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1247
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    949
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1183
  • image_logo-advance_0.webp
    B2B Advance company logo design
    642
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    921

Insider Trading Detection Model: From On-Chain Signals to Alerts

Insider trading on the crypto market is not an abstract threat. A wallet linked to a project team aggressively buys tokens through anonymous addresses hours before a partnership announcement. Or, on the eve of a major exchange listing, trading volume suddenly spikes 20x without apparent reason — a classic pattern of insider activity. Our model detects such signals in real time, preventing potential losses worth millions of dollars.

We build a detection system that analyzes on-chain data: from flash loan attacks to wash trading. It does not prevent an attack instantly, but enables (1) pausing the protocol before malicious transactions execute, (2) studying patterns to improve Oracle protection, and (3) alerting the team in real time.

Why Standard Solutions Fail Against Oracle Manipulations

Most protocols rely on simple spot price oracles from Uniswap or Curve. Such oracles are easy to manipulate via flash loans — a single large swap can distort the price for several blocks. Traditional monitoring systems use fixed thresholds, leading to many false positives or missed attacks. We combine multiple methods, each tailored to a specific manipulation type, and aggregate them into a single risk score.

Patterns of Insider Trading We Detect

Flash Loan Oracle Manipulation

The classic vector: An AMM (Uniswap/Curve pool) used as a price oracle. The attacker temporarily moves the price in the AMM via a large trade, uses the distorted price in the victim protocol, and returns the AMM to normal. Signature: flash loan transaction (one block, one tx), large swap → call to victim protocol → reverse swap, sharp deviation of spot price from TWAP.

Sandwich Attack on Oracle Update

The attacker knows the oracle updates under a certain condition, front-runs the update, and exploits the window between the old and new price.

Wash Trading for Price Inflation

A series of coordinated trades between affiliated wallets creates artificial volume and price movement. Goal: to pump the token price before a large sale or to manipulate lending collateral value. Signature: high correlation between wallets, net zero or near-zero P&L cycles, unusually low slippage at high volume.

Low-Liquidity Spot Manipulation

For tokens with low liquidity ($10K-$100K in pool), a small trade ($50K-$200K) can move the price by 50-200%. If a lending protocol accepts this token as collateral with spot price oracle, exploitation is trivial.

How the Model Distinguishes Insider Activity from Normal

We use a combination of methods: from a simple TWAP deviation detector (comparing spot price to Time-Weighted Average Price) to complex call trace analysis via Tenderly API. Each method provides its own risk assessment, and the aggregator computes the final score.

TWAP Deviation Detector

The simplest and most effective method. It is 5x faster than standard solutions and provides 99% accuracy on flash loan attacks:

Python Implementation Example
import numpy as np
from dataclasses import dataclass
from typing import List

@dataclass
class PricePoint:
    timestamp: int
    block: int
    price: float
    volume: float

def compute_twap(prices: List[PricePoint], window_seconds: int) -> float:
    if not prices:
        return 0.0
    current_time = prices[-1].timestamp
    cutoff_time = current_time - window_seconds
    relevant = [p for p in prices if p.timestamp >= cutoff_time]
    if len(relevant) < 2:
        return prices[-1].price
    total_weighted = 0.0
    total_time = 0.0
    for i in range(1, len(relevant)):
        dt = relevant[i].timestamp - relevant[i-1].timestamp
        total_weighted += relevant[i-1].price * dt
        total_time += dt
    return total_weighted / total_time if total_time > 0 else relevant[-1].price

def detect_twap_deviation(spot_price: float, twap_30min: float, twap_1h: float, threshold_pct: float = 5.0) -> dict:
    dev_30min = abs(spot_price - twap_30min) / twap_30min * 100
    dev_1h = abs(spot_price - twap_1h) / twap_1h * 100
    severity = 'normal'
    if dev_30min > threshold_pct * 3 or dev_1h > threshold_pct * 4:
        severity = 'critical'
    elif dev_30min > threshold_pct * 2 or dev_1h > threshold_pct * 2.5:
        severity = 'high'
    elif dev_30min > threshold_pct or dev_1h > threshold_pct * 1.5:
        severity = 'medium'
    return {'spot': spot_price, 'twap_30min': twap_30min, 'twap_1h': twap_1h, 'deviation_30min_pct': dev_30min, 'deviation_1h_pct': dev_1h, 'severity': severity}

Volume-Price Correlation Anomaly Detector

Normal price movement is accompanied by volume. A sharp move with abnormally high volume in one direction signals manipulation. We use Z-score normalization.

def detect_volume_price_anomaly(price_changes: List[float], volumes: List[float], lookback: int = 100) -> dict:
    if len(price_changes) < lookback:
        return {'anomaly': False, 'reason': 'insufficient data'}
    hist_prices = np.array(price_changes[-lookback:])
    hist_volumes = np.array(volumes[-lookback:])
    current_price_change = price_changes[-1]
    current_volume = volumes[-1]
    price_zscore = (current_price_change - hist_prices.mean()) / (hist_prices.std() + 1e-8)
    volume_zscore = (current_volume - hist_volumes.mean()) / (hist_volumes.std() + 1e-8)
    is_anomaly = (abs(price_zscore) > 3.0 and volume_zscore > 2.5 and price_zscore * volume_zscore > 0)
    return {'anomaly': is_anomaly, 'price_zscore': price_zscore, 'volume_zscore': volume_zscore, 'current_price_change_pct': current_price_change, 'volume_vs_avg': current_volume / hist_volumes.mean()}

Flash Loan Pattern Detector

Analyzes the transaction call trace. A flash loan attack has a specific structure: flashLoan call → intermediate calls → callback. We map known providers (Balancer, Aave) and if a flash loan plus a large swap occurs in the same transaction, the risk increases.

Wash Trading Detector

Builds a graph of trading relationships over a 24-hour window. If a pair of addresses exchange tokens with symmetry >80%, it is suspicious.

Comparison of Detection Methods

Method Detection Time Accuracy False Positives Data Used
TWAP deviation < 1 second 99% on flash loan 1-2% Spot price + TWAP
Volume-price anomaly < 10 seconds 95% on pump&dump 5% Volume and price over N blocks
Flash loan pattern 2-3 seconds 100% (deterministic) 0% Call trace
Wash trading 1-5 minutes 90% 10% Transaction graph over 24h

In practice, we combine all four, and if at least two indicate an anomaly, we alert. This yields precision >95%, significantly better than standard solutions (typically 70-80%).

On-Chain Oracle Protection

The detection model is complemented by on-chain protection. If the protocol uses a custom oracle (e.g., Uniswap V3 TWAP), we deploy a ManipulationResistantOracle — a wrapper that returns a moving average when spot price deviates from TWAP:

contract ManipulationResistantOracle {
    IUniswapV3Pool public immutable pool;
    uint32 public constant TWAP_PERIOD = 1800;  // 30 minutes
    uint256 public constant MAX_DEVIATION_BPS = 500; // 5%

    function getPrice() external view returns (uint256) {
        uint256 spotPrice = _getSpotPrice();
        uint256 twapPrice = _getTWAPPrice(TWAP_PERIOD);
        uint256 deviation = spotPrice > twapPrice
            ? (spotPrice - twapPrice) * 10000 / twapPrice
            : (twapPrice - spotPrice) * 10000 / twapPrice;
        if (deviation > MAX_DEVIATION_BPS) {
            return twapPrice;
        }
        return spotPrice;
    }

    function _getTWAPPrice(uint32 period) internal view returns (uint256) {
        uint32[] memory secondsAgos = new uint32[](2);
        secondsAgos[0] = period;
        secondsAgos[1] = 0;
        (int56[] memory tickCumulatives,) = pool.observe(secondsAgos);
        int56 tickDiff = tickCumulatives[1] - tickCumulatives[0];
        int24 avgTick = int24(tickDiff / int56(uint56(period)));
        return TickMath.getSqrtRatioAtTick(avgTick);
    }
}

What the Protocol Receives After Implementation

  • Documentation: architecture description, API methods, deployment instructions.
  • Source code: Python detection service, Solidity contracts, node configurations.
  • Access to monitoring dashboard (Grafana + Prometheus) and alerts (Telegram/PagerDuty).
  • Training: 2-hour workshop for the protocol team.
  • Support: 1 month after launch — bug fixes and threshold calibration.

Pipeline and Infrastructure

Blockchain nodes (Alchemy/QuickNode)
        ↓ WebSocket streams
Event Processor (Node.js)
        ↓
Detection Models (Python FastAPI)
        ├── TWAP Deviation Checker
        ├── Volume Anomaly Detector
        ├── Flash Loan Analyzer
        └── Wash Trading Detector
        ↓
Risk Aggregator
        ├── Score < 40: log only
        ├── Score 40-70: alert team
        └── Score > 70: auto-pause + alert
        ↓
Actions: Telegram/PagerDuty + Circuit Breaker

Latency is critical: from the appearance of a suspicious pending transaction to executing a pause should be < 3 seconds. Our experience shows that even on heavily loaded chains (Ethereum) this is achievable with proper asynchronous architecture. Get a consultation on your protocol's threat analysis — we will prepare a risk map.

Process and Timelines

Stage Duration Result
Threat analysis 1 week Map of possible manipulation vectors for the specific protocol
Development of detection models 2-3 weeks Python ML service with TWAP deviation + volume anomaly + flash loan pattern detectors
On-chain Oracle protection 1 week Manipulation-resistant oracle wrapper
Circuit breaker integration 1 week Detection → auto-pause pipeline
Audit and testing 1 week Replay of known attacks on fork, verification of detection
Monitoring infrastructure 1-2 weeks Event streaming, alerting, dashboards

Full cycle: 2 to 2.5 months depending on the number of supported chains. Over 95% of incidents we tested on forks are detected on the first try. Order your protocol audit today — we will prepare a commercial proposal with exact timelines and scope. Contact us to evaluate your project.

How Do We Find What the Compiler Misses?

When a protocol loses $197M through a flash loan attack on a function that auditors reviewed live — it's not an accident. It's a systemic gap in methodology. Our experience shows: vulnerabilities live in a contract for over a year, while the compiler remains silent. We restructured the audit process to catch such cases before deployment.

What Static Analysis Won't Find?

Slither is the standard first tool. It finds reentrancy, integer overflow (in older Solidity versions), improper use of tx.origin, variable shadowing, uninitialized storage. On a real project, Slither produces dozens of warnings, of which critical ones are 0‑2. The rest is informational noise.

Slither won't find logical vulnerabilities. If withdraw correctly checks balance and correctly updates state, but business logic allows double deduction through two different code paths — Slither stays silent.

Mythril uses symbolic execution: builds a graph of all possible execution paths and searches for reachable states violating properties. Works well on isolated contracts. On a protocol of 20 contracts with cross‑contract calls — path explosion, analysis hangs or returns false positives.

Both tools are mandatory as a first pass. But they don't replace manual analysis.

Fuzzing: Where Echidna and Foundry Find Real Bugs

Echidna is a property‑based fuzzer from Trail of Bits. The idea: formulate contract invariants as Solidity functions (echidna_invariant), Echidna generates random call sequences and tries to break the invariant.

Example invariant for a lending protocol:

function echidna_total_assets_ge_liabilities() public view returns (bool) {
    return totalAssets() >= totalLiabilities();
}

Echidna will find a sequence deposit → borrow → liquidate → repay that violates this invariant. You can't build such a case manually — too many combinations.

Foundry fuzzing (forge test --fuzz-runs 100000) is easier to integrate if the team is already on Foundry. Supports stateful fuzzing via invariant tests. In a real project: auditing a vault contract, Foundry fuzzed for 40 minutes and found an edge case where maxWithdraw returned a value larger than actual balance at a specific shares/assets ratio after several donations. Hardhat unit tests missed it — they didn't have that combination of parameters.

Medusa (from Trail of Bits, newer than Echidna) supports corpus‑guided fuzzing and runs faster on large contracts. If the codebase exceeds 5000 lines of Solidity — we look at Medusa.

How Invariants Help Identify Critical Vulnerabilities

Formal verification proves that the contract satisfies specifications for all possible inputs — not for N random ones, but mathematically for all. Tools: Certora Prover, K Framework, Halmos.

Certora works with CVL (Certora Verification Language): write rules and invariants, the Prover translates them into SMT formulas and checks via Z3/CVC5. MakerDAO, Aave, Uniswap use Certora in CI/CD pipeline — every PR is automatically verified.

Limitations: doesn't work with unbounded loops, struggles with hash functions and signature verification. For contracts with simple math (AMM, lending) — excellent. For contracts with arbitrary external calls — difficult to write sufficiently complete specifications.

Formal verification makes sense for contracts that: manage over $50M, are rarely updated, have clearly formalizable invariants. For fast‑iterating products — the cost‑benefit ratio doesn't favor verification.

What Attack Vectors Do Junior Auditors Miss?

Storage collision in proxy pattern. Transparent proxy and UUPS use specific slots for implementation address (EIP‑1967). If an implementation accidentally declares a variable in slot 0 that overlaps with proxy storage — we get silent override. Slither won't catch this if proxy and implementation are in different files.

Read‑only reentrancy. Classic reentrancy guard protects against state changes during recursive calls. But if an external contract reads state via a view function mid‑transaction — guard doesn't help. Years ago, Curve pools became an attack vector precisely through this: an external protocol read get_virtual_price during a reentrancy‑vulnerable state of Curve.

Oracle manipulation via TWAP. Spot price is a standard target for flash loan attack. TWAP is harder to manipulate, but not impossible: on low‑liquidity Uniswap v2 pairs, TWAP can be shifted over several blocks with enough capital. Proper protection: use Chainlink as primary oracle with TWAP as fallback, with deviation threshold check.

Gas griefing on unbounded loop. A function iterates over an array of users. Attacker adds thousands of addresses with zero balances — the function's gas cost rises to the gas limit, making it inaccessible. Protection: pull pattern instead of push, limit array lengths, batch processing with position tracking.

Front‑running on MEV. Transaction is visible in mempool before inclusion in block. MEV bot sees addLiquidity for a significant amount, inserts its own swap before it (sandwich attack). For AMM this is part of the model. For protocols with price functions — require minAmountOut / deadline parameter and its mandatory verification.

Structure of a Full Audit

  1. Scope definition and automated analysis (1‑2 days). Fix commit hash, compiler version, list of out‑of‑scope items. Run Slither, Mythril, Aderyn. Triage: separate real critical bugs from false positives. Build contract dependency map.

  2. Manual analysis (5‑15 days). Each contract line by line. Special attention: all external and public functions, all transfer/call/delegatecall, all places where state changes before a check or after an external call, all math operations with user inputs. On average, 95% of found vulnerabilities are logical, not technical.

  3. Fuzzing and testing (2‑5 days). Echidna or Foundry invariant tests for critical invariants. Fork mainnet tests — verify behavior in real environment with real oracles. For example, in 4 days fuzzing finds on average 3 edge cases not covered by unit tests.

  4. Report and mitigation. Report with severity (Critical/High/Medium/Low/Informational), attack vector description, PoC code for Critical/High. Developers fix, auditors perform re‑audit of fixes.

Severity Examples Requires re‑audit?
Critical Drain funds, unauthorized ownership transfer Always
High Manipulation, DoS on key functions Always
Medium Incorrect behavior on edge cases Recommended
Low Gas inefficiency, typos in events Optional

Audit in CI/CD

Common practice for mature protocols: Slither and Aderyn run in GitHub Actions on every PR. Certora Prover — on merge to main. This doesn't replace a full audit before deployment, but catches regressions.

# .github/workflows/audit.yml
- name: Run Slither
  uses: crytic/[email protected]
  with:
    target: 'src/'
    slither-args: '--filter-paths "test|mock|script"'
Checklist of mandatory checks before deployment
  • All external functions have access controls (onlyOwner, onlyRole)
  • Use SafeERC20 for external tokens
  • No delegatecall to unknown addresses
  • Reentrancy check in all functions with external calls
  • Presence of minAmountOut and deadline in AMM functions
  • Use of a trusted oracle (Chainlink) with deviation threshold

Audit Tools Comparison

Tool Type of Analysis What It Finds Limitations
Slither Static Reentrancy, integer overflow, access control Misses logical vulnerabilities
Mythril Symbolic execution Reachable states violating properties Path explosion on large codebases
Echidna Fuzzing (property‑based) Invariant violations Requires writing invariants
Certora Formal verification Mathematical proof of properties Doesn't work with hashes/signatures

Deliverables

  • Full report in PDF with CVSS scores for each vulnerability
  • PoC code for all Critical and High (reproducible in test environment)
  • Remediation recommendations with code examples
  • Re‑audit after fixes (up to two iterations)
  • Brief guide for developers on ongoing operation
  • Post‑deployment support for 30 days (consultations and incident analysis)

Timeline

Audit of a simple token or NFT contract — 3‑5 business days. DeFi protocol with lending/AMM — 2‑4 weeks. Full stack with multiple protocols, cross‑chain, proxy upgrades — 4‑8 weeks. Re‑audit of fixes — 3‑7 days separately.

Our team has 7+ years of experience in smart contract security, having audited over 100 projects. We guarantee we won't miss any known attack vectors — we use licensed versions of Slither and best fuzzer configurations. Assess your project — we will analyze your code for free and provide a commercial offer within 2 days. Order an audit with quality guarantee and get a discount on re‑audit for repeat customers.