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(address)[source]

Returns details about an address.

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_api_base_url(index: int = 0) str[source]
get_block(hash_value)[source]

Returns details about a block.

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_header(hash_value)[source]

Returns the hex-encoded block header.

get_block_height(height)[source]

Returns the hash of the block currently at height.

get_block_raw(hash_value)[source]

Returns the raw block representation in binary.

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_status(hash_value)[source]

Returns the confirmation status of a block.

get_block_tip_hash()[source]

Returns the hash of the last block.

get_block_tip_height()[source]

Returns the height of the last block.

get_block_transaction_id(hash_value, index)[source]

Returns the transaction at index index within the specified block.

get_block_transaction_ids(hash_value)[source]

Returns a list of all txids in the 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_block_v1(hash_value)[source]

Returns details about a block.

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(channelid)[source]

Returns info about a Lightning channel with the given :channelId.

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()[source]

Returns a list of channels with corresponding node geodata.

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_difficulty_adjustment()[source]

Returns details about difficulty adjustment.

get_hashrate(time_period=None)[source]

Returns network-wide hashrate and difficulty figures over the specified trailing :timePeriod:

get_historical_node_stats(pubkey)[source]

Returns details about a node with the given pubKey.

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_mempool()[source]

Returns current mempool backlog statistics.

get_mempool_blocks_fee()[source]

Returns current mempool as projected blocks.

get_mempool_recent()[source]

Get a list of the last 10 transactions to enter the mempool.

get_mempool_transactions_ids()[source]

Get the full list of txids in the mempool as an array.

get_mining_pool(slug)[source]

Returns details about the mining pool specified by slug.

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_node_stats(pubkey)[source]

Returns details about a node with the given pubKey.

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_price()[source]

Returns bitcoin latest price denominated in main currencies.

Returns our currently suggested fees for new transactions.

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_top_100_oldest_nodes()[source]

Returns a list of the top 100 oldest nodes.

get_transaction(txid)[source]

Returns details about a transaction.

get_transaction_hex(txid)[source]

Returns a transaction serialized as hex.

get_transaction_merkle_proof(txid)[source]

Returns a merkle inclusion proof for the transaction using Electrum’s blockchain.transaction.get_merkle format.

get_transaction_merkleblock_proof(txid)[source]

Returns a merkle inclusion proof for the transaction using bitcoind’s merkleblock format.

get_transaction_outspend(txid, vout)[source]

Returns the spending status of a transaction output.

get_transaction_outspends(txid)[source]

Returns the spending status of all transaction outputs.

get_transaction_raw(txid)[source]

Returns a transaction as binary data.

get_transaction_status(txid)[source]

Returns the confirmation status of a transaction.

post_transaction(txHex)[source]

Broadcast a raw transaction to the network.

set_api_base_url(api_base_url: list | str) None[source]
exception pymempool.api.MempoolAPIError[source]

Bases: Exception

Base exception for Mempool API errors.

exception pymempool.api.MempoolNetworkError[source]

Bases: MempoolAPIError

Exception raised for network connectivity issues.

exception pymempool.api.MempoolResponseError[source]

Bases: MempoolAPIError

Exception raised for API response errors.

Utility Functions

pymempool.utils.median(a)[source]
pymempool.utils.time_until(target_datetime: datetime, short: bool = False) str[source]

Block Parser

class pymempool.block_parser.BlockParser(api_json)[source]

Bases: object

Parses the output from mempool.space blocks API and exposes a list of blocks with helper methods.

all_formatted_lines()[source]

Returns a list of formatted lines for all blocks.

formatted_lines(idx)[source]

Returns a list of lines suitable for AsciiBlock for block at idx.

Mempool Block Parser

class pymempool.mempool_block_parser.MempoolBlockParser(api_json)[source]

Bases: object

Parses the mempool-blocks API output and exposes a list of blocks and helper methods.

all_formatted_lines()[source]

Returns a list of formatted lines for all blocks.

formatted_lines(idx)[source]

Returns a list of lines suitable for AsciiBlock for block at idx.

Difficulty Adjustment

class pymempool.difficulty_adjustment.DifficultyAdjustment(lastblocknum: int, difficulty_adjustment: dict[Any, Any])[source]

Bases: object

Bitcoin difficulty adjustment calculation and information.

This class processes and calculates information related to Bitcoin’s difficulty adjustment mechanism, which occurs every 2016 blocks.

lastblocknum

Current blockchain height

Type:

int

difficulty_adjustment

Raw difficulty adjustment data from mempool API

Type:

Optional[Dict]

last_retarget

Block height of the last difficulty adjustment

Type:

int

minutes_between_blocks

Average time between blocks in minutes

Type:

float

found_blocks

Number of blocks found since last retarget

Type:

int

blocks_behind

Difference between expected and found blocks

Type:

int

estimated_retarget_date

Datetime of the next difficulty adjustment

Type:

Optional[datetime]

estimated_retarget_period

Human-readable time until next adjustment

Type:

str

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

class pymempool.halving.Halving(current_height: int, difficulty_adjustment: dict[Any, Any] | None = None)[source]

Bases: object

Bitcoin halving calculation and information.

HALVING_INTERVAL = 210000
INITIAL_REWARD = 50.0
update(current_height: int, difficulty_adjustment: dict[Any, Any] | None = None) None[source]

Update halving calculations with new data.

Parameters:
  • current_height – Current blockchain height

  • difficulty_adjustment – Difficulty adjustment data from mempool API

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: object

Handles 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:

tuple

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:
  • p_block (dict) – Block data containing ‘medianFee’ and ‘blockVSize’.

  • next_block (dict, optional) – Next block’s data for context (default: None).

  • previous_fee (float, optional) – Previous block’s optimized fee (default: None).

Returns:

Optimized median fee for the block.

Return type:

float

update_mempool_blocks(mempool_blocks_fee: list | None) bool[source]

Update mempool block statistics and recalculate recommended fees.

Parameters:

mempool_blocks_fee (list) – List of mempool block fee data dicts.

Returns:

True if update was successful, False otherwise.

Return type:

bool

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

async connect(use_queue=False, consumer=None)[source]
async default_handler(data)[source]
async receive_data()[source]
run(handler=None, stream_to_queue=False, queue_consumer=None)[source]
async subscribe_all()[source]