API Reference
This section provides detailed documentation for the pymempool Python API.
MempoolAPI Class
- class pymempool.api.MempoolAPI(api_base_url: list | str = ['https://mempool.space/api/', 'https://mempool.emzy.de/api/', 'https://mempool.bitcoin-21.org/api/'], retries: int = 3, request_verify: bool = True, proxies: dict | None = None)[source]
Bases:
object- get_address_transactions(address)[source]
Get transaction history for the specified address/scripthash, sorted with newest first.
- get_address_transactions_chain(address, last_seen_txid=None)[source]
Get confirmed transaction history for the specified address/scripthash, sorted with newest first.
- get_address_transactions_mempool(address)[source]
Get unconfirmed transaction history for the specified address/scripthash.
- get_address_utxo(address)[source]
Get the list of unspent transaction outputs associated with the address/scripthash.
- get_block_feerates(time_period)[source]
Returns average feerate percentiles for blocks in the specified.
:timePeriod, ordered oldest to newest. :timePeriod can be any of the following: 24h, 3d, 1w, 1m, 3m, 6m, 1y, 2y, 3y.
- get_block_fees(time_period)[source]
Returns average total fees for blocks in the specified :timePeriod, ordered oldest to newest.
- TimePeriod can be any of the following:
24h, 3d, 1w, 1m, 3m,
6m, 1y, 2y, 3y.
- get_block_rewards(time_period)[source]
Returns average block rewards for blocks in the specified :timePeriod, ordered oldest to newest.
- TimePeriod can be any of the following:
24h, 3d, 1w, 1m, 3m,
6m, 1y, 2y, 3y.
- get_block_sizes_and_weights(time_period)[source]
Returns average size (bytes) and average weight (weight units) for blocks in the specified :timePeriod, ordered oldest to newest.
- TimePeriod can be any of the following:
24h, 3d, 1w, 1m, 3m,
6m, 1y, 2y, 3y.
- get_block_transaction_id(hash_value, index)[source]
Returns the transaction at index index within the specified block.
- get_block_transactions(hash_value, start_index=None)[source]
Returns a list of transactions in the block (up to 25 transactions beginning at start_index).
- get_blocks(start_height=None)[source]
Returns the 10 newest blocks starting at the tip or at :start_height if specified.
- get_blocks_bulk(min_height, max_height=None)[source]
Returns details on the range of blocks between :min_height and :max_height, inclusive, up to 10 blocks.
If :max_height is not specified, it defaults to the current tip.
- get_blocks_v1(start_height=None)[source]
Returns the 10 newest blocks starting at the tip or at :start_height if specified.
- get_channel_from_txid(txids: str | list) Any[source]
Returns info about Lightning channels with the given transaction IDs.
- Parameters:
txids – Transaction ID string (comma-separated) or list of transaction IDs
- Returns:
Information about the channels
- get_channel_geodata_for_node(pubkey)[source]
Returns a list of channels with corresponding geodata for a node with the given :pubKey.
- get_channels_from_node_pubkey(pubkey, channel_status, index=None)[source]
Returns a list of a node’s channels given its :pubKey.
Ten channels are returned at a time. Use :index for paging. :channelStatus can be open, active, or closed.
- get_children_pay_for_parents(txid)[source]
Returns the ancestors and the best descendant fees for a transaction.
- get_hashrate(time_period=None)[source]
Returns network-wide hashrate and difficulty figures over the specified trailing :timePeriod:
- get_historical_price(currency=None, timestamp=None)[source]
Returns bitcoin historical price denominated in main currencies.
Available query parameters: currency, timestamp. If no parameter is provided, the full price history for all currencies is returned.
- get_isp_nodes(isp)[source]
Returns a list of nodes hosted by a specified isp, where isp is an ISP’s ASN.
- get_mining_pool_block(slug, block_height=None)[source]
Returns past 10 blocks mined by the specified mining pool (slug) before the specified block_height.
If no block_height is specified, the mining pool’s 10 most recent blocks are returned.
- get_mining_pool_hashrate(slug)[source]
Returns all known hashrate data for the mining pool specified by slug.
Hashrate values are weekly averages.
- get_mining_pool_hashrates(time_period)[source]
Returns average hashrates (and share of total hashrate) of mining pools active in the specified trailing time_period, in descending order of hashrate.
- get_mining_pools(time_period)[source]
Returns a list of all known mining pools ordered by blocks found over the specified trailing time_period.
- get_network_stats(interval)[source]
Returns network-wide stats such as total number of channels and nodes, total capacity, and average/median fee figures.
Pass one of the following for interval: latest, 24h, 3d, 1w, 1m, 3m, 6m, 1y, 2y, 3y.
- get_node_stat_per_country()[source]
Returns aggregate capacity and number of clearnet nodes per country.
Capacity figures are in satoshis.
- get_node_stat_per_isp()[source]
Returns aggregate capacity, number of nodes, and number of channels per ISP.
Capacity figures are in satoshis.
- get_nodes_channels(query)[source]
Returns Lightning nodes and channels that match a full-text, case-insensitive search :query across node aliases, node pubkeys, channel IDs, and short channel IDs.
- get_nodes_in_country(country)[source]
Returns a list of Lightning nodes running on clearnet in the requested country, where :country is an ISO Alpha-2 country code.
- get_reward_stats(block_count)[source]
Returns block reward and total transactions confirmed for the past.
:blockCount blocks.
- get_top_100_nodes()[source]
Returns two lists of the top 100 nodes: one ordered by liquidity (aggregate channel capacity) and the other ordered by connectivity (number of open channels).
- get_top_100_nodes_by_connectivity()[source]
Returns a list of the top 100 nodes by connectivity (number of open channels).
- get_top_100_nodes_by_liquidity()[source]
Returns a list of the top 100 nodes by liquidity (aggregate channel capacity).
- get_transaction_merkle_proof(txid)[source]
Returns a merkle inclusion proof for the transaction using Electrum’s blockchain.transaction.get_merkle format.
- exception pymempool.api.MempoolAPIError[source]
Bases:
ExceptionBase exception for Mempool API errors.
- exception pymempool.api.MempoolNetworkError[source]
Bases:
MempoolAPIErrorException raised for network connectivity issues.
- exception pymempool.api.MempoolResponseError[source]
Bases:
MempoolAPIErrorException raised for API response errors.
Utility Functions
Block Parser
Mempool Block Parser
Difficulty Adjustment
- class pymempool.difficulty_adjustment.DifficultyAdjustment(lastblocknum: int, difficulty_adjustment: dict[Any, Any])[source]
Bases:
objectBitcoin difficulty adjustment calculation and information.
This class processes and calculates information related to Bitcoin’s difficulty adjustment mechanism, which occurs every 2016 blocks.
- difficulty_adjustment
Raw difficulty adjustment data from mempool API
- Type:
Optional[Dict]
- estimated_retarget_date
Datetime of the next difficulty adjustment
- Type:
Optional[datetime]
- update_difficulty_adjustment(lastblocknum: int, difficulty_adjustment: dict[Any, Any]) bool[source]
Update difficulty adjustment calculations with new blockchain data.
This method processes the difficulty adjustment data from the mempool API and calculates various metrics related to the difficulty adjustment.
- Parameters:
lastblocknum – Current blockchain height
difficulty_adjustment – Difficulty adjustment data from mempool API
- Returns:
True if the update was successful
Note
The difficulty_adjustment dict is expected to contain the following keys: - remainingBlocks: Number of blocks until next adjustment - estimatedRetargetDate: Timestamp of estimated next adjustment - expectedBlocks: Number of blocks expected to be found since last retarget - timeAvg: Average time between blocks in milliseconds
Halving
Recommended Fees
This module provides the RecommendedFees class for calculating and updating Bitcoin transaction fee recommendations based on mempool and block data.
- class pymempool.recommended_fees.RecommendedFees(recommended_fees: dict | None = None, mempool_blocks_fee: list | None = None)[source]
Bases:
objectHandles recommended Bitcoin transaction fees based on mempool and block data.
This class provides methods to update and calculate recommended fees for different confirmation times (fastest, half-hour, hour, economy) using mempool statistics and block fee data.
- build_fee_array() tuple[list[float], list[float], list[float]][source]
Build arrays of minimum, median, and maximum fees for the next n blocks.
- Returns:
(minFee, medianFee, maxFee) lists for the next n fee blocks.
- Return type:
- optimize_median_fee(p_block: dict, next_block: dict | None = None, previous_fee: float | None = None) float[source]
Calculate an optimized median fee for a mempool block.
- Parameters:
- Returns:
Optimized median fee for the block.
- Return type:
- update_mempool_blocks(mempool_blocks_fee: list | None) bool[source]
Update mempool block statistics and recalculate recommended fees.
- update_recommended_fees(recommended_fees: dict | None) None[source]
Update the recommended fee values from a provided dictionary.
- Parameters:
recommended_fees (dict) – Dictionary containing fee recommendations. Keys may include ‘hourFee’, ‘halfHourFee’, ‘fastestFee’, ‘economy_fee’, and ‘minimumFee’.
WebSocket
- class pymempool.websocket.MempoolWebSocketClient(uri='wss://mempool.space/api/v1/ws', max_retries=5, max_backoff=60, want_data=None, track_address=None, track_addresses=None, track_mempool=False, track_mempool_txids=False, track_mempool_block_index=None, track_rbf=None, enable_logging=True)[source]
Bases:
object