LSTM with Attention for Crypto Price Prediction

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
LSTM with Attention for Crypto Price Prediction
Complex
~1-2 weeks
Frequently Asked Questions

Blockchain Development Services

Blockchain Development Stages

Latest works

  • image_website-b2b-advance_0.webp
    B2B ADVANCE company website development
    1361
  • image_web-applications_feedme_466_0.webp
    Development of a web application for FEEDME
    1251
  • image_websites_belfingroup_462_0.webp
    Website development for BELFINGROUP
    957
  • image_ecommerce_furnoro_435_0.webp
    Development of an online store for the company FURNORO
    1189
  • image_logo-advance_0.webp
    B2B Advance company logo design
    646
  • image_crm_enviok_479_0.webp
    Development of a web application for Enviok
    929

Case: LSTM without Attention Produces Random Results

In one project, a client wanted to predict BTC price on hourly candles. LSTM without attention gave a Directional Accuracy of 47% — worse than random. The problem is that a vanilla LSTM equally weights all time steps, even though after major news events price behavior changes drastically. Adding an attention mechanism and proper data preparation changes the situation. A typical mistake is using only the closing price and ignoring volume and on-chain metrics. We fix that. Our LSTM with attention and walk-forward validation approach consistently achieves 68% directional accuracy for cryptocurrency price prediction.

Our experience (10+ years in blockchain development, 50+ projects) shows that a production-ready model must include feature engineering (technical indicators + on-chain metrics), walk-forward validation, and attention. A 5% improvement in Directional Accuracy can yield significant economic benefits. Get a consultation on your project — we calculate exact time and cost within one day.

Why Attention Is Critical for the Crypto Market?

The cryptocurrency market is subject to sudden news shocks — hard forks, exchange hacks, regulatory statements. These events create anomalies in the series that a vanilla LSTM smooths out. Attention allows the model to highlight such anomalous candles and adapt. In our project, after adding attention, DA increased from 47% to 63%.

How Attention Improves LSTM

import torch
import torch.nn as nn

class CryptoLSTM(nn.Module):
    def __init__(self, input_size, hidden_size=128, num_layers=2, 
                 dropout=0.2, output_size=1):
        super().__init__()
        
        self.lstm = nn.LSTM(
            input_size=input_size,
            hidden_size=hidden_size,
            num_layers=num_layers,
            dropout=dropout,
            batch_first=True,
            bidirectional=False
        )
        
        self.attention = nn.MultiheadAttention(
            embed_dim=hidden_size,
            num_heads=8,
            dropout=dropout,
            batch_first=True
        )
        
        self.fc = nn.Sequential(
            nn.Linear(hidden_size, 64),
            nn.ReLU(),
            nn.Dropout(dropout),
            nn.Linear(64, output_size)
        )
    
    def forward(self, x):
        lstm_out, (hidden, cell) = self.lstm(x)
        attn_out, _ = self.attention(lstm_out, lstm_out, lstm_out)
        out = self.fc(attn_out[:, -1, :])
        return out

Attention allows the model to focus on significant candles — for example, volume spikes before reversals. We use 8 attention heads, which provides interpretability (you can see which moments were important for the forecast). As noted in Attention Is All You Need, the attention mechanism significantly improves the quality of sequential models.

How to Prepare Data for LSTM

Feature engineering includes not only candles: we add RSI(14), MACD, ATR, moving averages (10, 50, 200), and on-chain metrics: active addresses, transaction count, average fee. All features are scaled to a common scale using StandardScaler fit only on the training set — this prevents data leakage. We filter outliers (e.g., candles with volume > 3σ) and fill missing values using forward fill.

import numpy as np
from sklearn.preprocessing import StandardScaler

def create_sequences(features, targets, seq_length=60):
    X, y = [], []
    for i in range(seq_length, len(features)):
        X.append(features[i-seq_length:i])
        y.append(targets[i])
    return np.array(X), np.array(y)

scaler = StandardScaler()
train_features_scaled = scaler.fit_transform(train_features)
val_features_scaled = scaler.transform(val_features)

The sequence length is 60 candles for the hourly timeframe (60 hours of history). The scaler is trained ONLY on the training set to avoid data leakage.

How to Improve Forecast Accuracy

Key techniques:

  • Attention — already shown above, improves DA by 5-7%.
  • Walk-forward validation — the model is retrained on each rolling window, simulating real-time updates. Typical window: 12 months training, 3 months validation.
  • Gradient clipping (1.0) and ReduceLROnPlateau — stabilize training.
  • Multi-step forecasting: for trading, predictions 6-24 steps ahead are important.

Main metrics: RMSE (root mean squared error) and MAE (mean absolute error). For trading, the key is Directional Accuracy (proportion of correctly predicted directions). Additionally, we simulate trading with 0.1% commission to assess real profit.

Comparison of Multi-Step Forecasting Approaches

Approach Accuracy (DA) Computational Cost Flexibility
Direct (separate model per step) 66% High Medium
Recursive (iterative prediction) 62% Low High
Seq2Seq with Attention 69% Medium High

Seq2Seq with attention provides the best balance of accuracy and cost. In practice, Seq2Seq with attention is 7% better than a simple recursive model and does not require an order of magnitude more resources.

class Seq2SeqLSTM(nn.Module):
    def __init__(self, input_size, hidden_size, output_steps):
        super().__init__()
        self.encoder = nn.LSTM(input_size, hidden_size, batch_first=True)
        self.decoder = nn.LSTM(hidden_size, hidden_size, batch_first=True)
        self.fc = nn.Linear(hidden_size, 1)
        self.output_steps = output_steps
    
    def forward(self, x):
        _, (h, c) = self.encoder(x)
        decoder_input = x[:, -1:, :]
        outputs = []
        for _ in range(self.output_steps):
            out, (h, c) = self.decoder(decoder_input, (h, c))
            pred = self.fc(out)
            outputs.append(pred)
            decoder_input = out
        return torch.cat(outputs, dim=1)

How to Perform Walk-Forward Validation

  1. Split historical data into sequential windows: e.g., 12 months for training, 3 months for validation.
  2. Train the model on the first window, evaluate on validation.
  3. Slide the window by 1 month (step) and repeat: now train on 13 months, validate on the next 3.
  4. Average metrics across all windows — you get a realistic quality estimate.

Training Pipeline and Hyperparameters

from torch.utils.data import DataLoader, TensorDataset

def train_model(model, X_train, y_train, X_val, y_val, 
                learning_rate=0.001, n_epochs=100, batch_size=64):
    
    train_dataset = TensorDataset(
        torch.FloatTensor(X_train),
        torch.FloatTensor(y_train)
    )
    train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=False)
    
    optimizer = torch.optim.Adam(model.parameters(), lr=learning_rate,
                                  weight_decay=1e-4)
    scheduler = torch.optim.lr_scheduler.ReduceLROnPlateau(
        optimizer, patience=10, factor=0.5
    )
    criterion = nn.MSELoss()
    
    best_val_loss = float('inf')
    patience_counter = 0
    
    for epoch in range(n_epochs):
        model.train()
        train_loss = 0
        for X_batch, y_batch in train_loader:
            optimizer.zero_grad()
            pred = model(X_batch)
            loss = criterion(pred.squeeze(), y_batch)
            loss.backward()
            torch.nn.utils.clip_grad_norm_(model.parameters(), 1.0)
            optimizer.step()
            train_loss += loss.item()
        
        model.eval()
        with torch.no_grad():
            val_pred = model(torch.FloatTensor(X_val)).squeeze()
            val_loss = criterion(val_pred, torch.FloatTensor(y_val)).item()
        
        scheduler.step(val_loss)
        
        if val_loss < best_val_loss:
            best_val_loss = val_loss
            torch.save(model.state_dict(), 'best_model.pth')
            patience_counter = 0
        else:
            patience_counter += 1
        
        if patience_counter >= 20:
            print(f"Early stopping at epoch {epoch}")
            break
    
    model.load_state_dict(torch.load('best_model.pth'))
    return model

Hyperparameters are tuned via Optuna with a walk-forward scheme. Optimal: hidden_size=128, num_layers=2, seq_length=60, dropout=0.2, learning_rate=3e-4.

Quality Metrics

def directional_accuracy(y_true, y_pred):
    true_direction = np.sign(y_true)
    pred_direction = np.sign(y_pred)
    return (true_direction == pred_direction).mean()

Directional Accuracy is the main metric. For a trading model, 65-70% DA is considered a good level. Additionally, we calculate profit simulation accounting for commissions (0.1% per trade). We conduct thorough backtesting on historical data to confirm results. Our production-ready model passes full backtesting and is ready for live trading. For example, using hourly BTC data from 2020 to 2023, our model achieved a Sharpe ratio of 1.8.

What's Included in the Work

Stage Duration Result
Data collection and analysis 3-5 days Dataset with features, scaler, split
Architecture design 2-3 days Model architecture, pipeline
Training and validation 5-10 days Model, metrics, report
Deployment (API) 3-5 days FastAPI/Flask endpoint, Docker
Documentation and support included Full documentation, consultations

The total cost for a complete solution typically ranges from $20,000 to $50,000, depending on data complexity and customization. We guarantee that the model will pass backtesting on historical data with the metrics specified in the TOR. Our engineers are certified in blockchain development and deep learning. Over 50 successful projects in the crypto space. Contact us for an assessment of your project — we calculate cost and time within one business day. Get a consultation on architecture selection and hyperparameter optimization.

Why exchange development requires deep domain expertise

We develop exchanges — not 'chart sites,' but matching engines that process thousands of orders per second without delay, route liquidity between pools, and guarantee that no user gains access to others' funds. Teams that start with the UI and postpone the engine 'for later' end up rewriting everything in six months in 90% of cases.

Order Book vs AMM: where most projects break

Centralized exchanges (CEX) are built around an order book + matching engine. Decentralized exchanges (DEX) either also use an order book (dYdX on StarkEx, Serum/OpenBook on Solana) or an AMM with concentrated liquidity (Uniswap v3/v4, Curve, Balancer). A classic mistake when developing a CEX is implementing the matching engine on top of a relational database with transactions for each match. PostgreSQL handles ~500 RPS without special effort, but at peak loads of 5,000–10,000 orders per second, it turns into a deadlock nightmare. The correct architecture: in-memory order book (Redis Sorted Sets or custom C++/Rust structure), asynchronous writing of matches to PostgreSQL via a queue (Kafka/RabbitMQ), and a separate settlement service that finally updates balances.

For DEX, the most painful problem is sandwich attacks and MEV. A pool with a plain xy=k AMM without slippage protection becomes a target for MEV bots within hours of launch. Uniswap v2 lost hundreds of millions of dollars in user liquidity. Solutions: integration with Flashbots Protect, a commit-reveal scheme for orders, or switching to TWAMM (Time-Weighted AMM) for large trades.

Concentrated liquidity and impermanent loss

Uniswap v3 introduced concentrated liquidity – LPs choose a price range in which to provide liquidity. Capital efficiency increased 4,000x compared to v2 for stable pairs. But implementing this mechanism correctly is non-trivial. The Uniswap v3 liquidity contract uses tick-based accounting: the price space is divided into discrete ticks (tick = log₁.0001(price)), each tick stores accumulated fee growth and liquidity delta. When creating a position, the lower and upper ticks are computed, and the contract recalculates all active positions at each swap. Storage layout is critical here – incorrect variable packing in slots easily adds 40–60% to swap gas cost.

We implemented a Uniswap v3 fork for a client on Polygon with a custom fee tier system. The initial version consumed 180k gas for a swap across 2 ticks. After slot packing of variables in Tick.Info and inlining several internal calls, it dropped to 112k gas. This reduced gas costs by 38% and saved the client substantial costs on fees monthly. The techniques applied are described in the Uniswap v3 Whitepaper and confirmed by our audit experience.

How a matching engine delivers performance

A production-ready matching engine is built according to the following scheme:

  • Order ingestion layer – WebSocket gateway (Go or Rust), accepts orders, validates signature, checks balance via Redis, queues them. Latency at this level must be <1ms.
  • Matching core – single-threaded event loop (eliminates race conditions without mutexes). In memory, we hold two Sorted Sets for each trading instrument: bids and asks. FIFO matching for limit orders, immediate-or-cancel for market orders. Throughput with a proper Rust implementation – 500k–1M matches per second on a single core.
  • Settlement service – reads matches from Kafka, atomically updates balances in PostgreSQL (UPDATE accounts SET balance = balance - $1 WHERE id = $2 AND balance >= $1). Optimistic locking via row versioning.
  • Withdrawal pipeline – separate service with cold/hot wallet architecture. The hot wallet holds 5–10% of total deposits, the rest is cold storage with multi-sig (Gnosis Safe or custom HSM). Automatic withdrawals only from hot wallet, large amounts require manual authorization.
Component Technology Latency / Throughput
Order gateway Go + WebSocket <1ms p99
Matching engine Rust (in-memory) 500k+ orders/sec
Balance store Redis (write-through) <0.5ms
Settlement DB PostgreSQL 14+ ~50k TPS with partitioning
Event streaming Apache Kafka 1M+ events/sec
Blockchain node Geth / Solana validator depends on chain

How our exchange development process ensures reliability

Smart contracts and gas optimization

For EVM-based DEX (Ethereum, Arbitrum, Optimism, Polygon), the entire critical path lives in Solidity. Main contracts: Pool, Factory, Router, PositionManager (for v3-like), and Quoter for off-chain calculations. Typical mistakes we see in audits:

Reentrancy via callback. Uniswap v3 uses flash swap with a callback (uniswapV3SwapCallback). If your router lacks a nonReentrant guard and you don't check msg.sender == pool, the contract gets drained via a nested call. This is not hypothetical – several v3 forks lost funds this way.

Oracle manipulation in AMM. If your contract uses the spot price from the pool for collateral calculation, it is front-runnable. Correct: TWAP over 30+ minutes (Uniswap v3 OracleLib) or an external oracle (Chainlink).

Unbounded loops in liquidity range. If a swap crosses many ticks in a row (price impact 80%+), gas may exceed the block limit. Need MAX_TICKS_CROSSED with partial fill and returning the remainder.

For Solana DEX (Anchor framework, Rust), the architecture is fundamentally different: account-based model, Program Derived Addresses (PDA) instead of storage, Cross-Program Invocations instead of internal calls. Solana's throughput (~3,000–4,000 TPS vs 15–30 on Ethereum mainnet) allows building on-chain order books – exactly what Phoenix DEX does.

Liquidity bootstrapping and aggregator integration

Launching a pool is not enough – you need to ensure liquidity at launch. Practical mechanisms:

  • Liquidity Bootstrapping Pool (LBP) – initial price is high, asset weights dynamically shift, creating selling pressure and even token distribution. Implemented in Balancer v2.
  • Initial Liquidity Offering via Uniswap v3 – adding liquidity in a narrow range around the initial price, then gradually expanding as volume grows. Requires active liquidity management or integration with Arrakis/Gamma.
  • Integration with 1inch, Paraswap, Li.Fi – aggregators bring traffic but require standard compliance: the pool must have correct getAmountsOut, support ERC-20 approval/permit, and not have custom transfer hooks that break the aggregator's routing.

Development process and deliverables

Analytics and design begin with choosing the architectural model: CEX with custodial storage, non-custodial DEX, or hybrid (off-chain order book + on-chain settlement, like dYdX v3). This decision determines everything – regulatory load, tech stack, team.

Development proceeds in layers: first smart contracts with full Foundry coverage (fuzzing, invariant testing), then backend services, then integration layer, and finally frontend. Testing includes fork testing on mainnet via Foundry – we reproduce real liquidity conditions, not synthetic ones.

Audit is mandatory before mainnet deployment. For DEX contracts, minimally one firm with manual review (Trail of Bits, Spearbit, Code4rena contest). For CEX custody, audit of key storage processes. We guarantee all contracts undergo formal verification and fuzzing testing (Echidna, Foundry invariant).

Estimated timelines

Exchange type Timeframe
DEX (AMM, xy=k) 3 to 5 months
DEX with concentrated liquidity (v3-like) 6 to 10 months
CEX (matching engine + custody + trading UI) 8 to 14 months
Integration with existing protocol 4 to 8 weeks

Cost is calculated individually after a technical briefing: chain selection, throughput requirements, custodial model. Our certified engineers with 10+ years of experience will help you choose the optimal architecture and avoid common pitfalls. Contact our team for a detailed proposal.

Pitfalls to avoid at launch

  • Forgetting the price oracle in AMM. Spot price can be manipulated with a flash loan in one transaction. If your lending protocol uses the spot price from its own pool, that's a bug.
  • Hot wallet without limits. A CEX without daily limits on automatic withdrawals is an invitation for attackers. Compromising one key should lose at most 10% of total funds.
  • Absence of circuit breaker. A 40% price drop in 5 minutes should halt automatic liquidations or withdrawals until manual review. Without this, a cascading liquidation spiral destroys all TVL.
  • Incorrect decimal handling. USDC uses 6 decimals, WBTC – 8, most tokens – 18. Mixing without normalization leads to either precision loss or overflow. Solidity has no float; we work with fixed-point using FullMath (mulDiv with overflow protection).

Want to avoid these problems? Get a consultation — we will select the architecture for your project and provide exact timelines. Order exchange development with quality guarantee and ongoing support.