Skip to content

Commit

Permalink
Added single block data from Blockchain.com (#3406)
Browse files Browse the repository at this point in the history
* Added single block data

* Added single block data tests to test_blockchain_model.py and test_blockchain_view.py

* Made changes requested by reviewer.

* Updating with some of the new changes.  Still have some to fix.

* Changed everything requested except a couple I need help on.

* Finished the last two changes.

* Resolving

* Added function for sdk and fixed a linter issue.

* Formatting

* Fixed tests

* tests

* Fix tests

Co-authored-by: jose-donato <[email protected]>
Co-authored-by: James Maslek <[email protected]>
  • Loading branch information
3 people authored Jan 4, 2023
1 parent 1af3ff7 commit 052c16f
Show file tree
Hide file tree
Showing 22 changed files with 91,000 additions and 2,473 deletions.
60 changes: 58 additions & 2 deletions openbb_terminal/cryptocurrency/onchain/blockchain_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,10 +28,47 @@ def _make_request(endpoint: str) -> dict:

url = f"https://api.blockchain.info/{endpoint}"
response = requests.get(
url, headers={"Accept": "application/json", "User-Agent": "GST"}
url,
headers={
"Accept": "application/json",
"User-Agent": "OBB",
"Accept-Encoding": "gzip",
},
)
if not 200 <= response.status_code < 300:
raise Exception(f"fcd terra api exception: {response.text}")
raise Exception(f"blockchain.info api exception: {response.text}")
try:
return response.json()
except Exception as e:
logger.exception("Invalid Response: %s", str(e))
raise ValueError(f"Invalid Response: {response.text}") from e


@log_start_end(log=logger)
def _blockchain_data_api_make_request(endpoint: str) -> dict:
"""Helper method handles Blockchain API requests. [Source: https://blockchain.info/]
Parameters
----------
endpoint: str
endpoint url
Returns
-------
dict:
dictionary with response data
"""

url = f"https://blockchain.info/{endpoint}"
response = requests.get(
url,
headers={
"Accept": "application/json",
"User-Agent": "OBB",
"Accept-Encoding": "gzip",
},
)
if not 200 <= response.status_code < 300:
raise Exception(f"blockchain.info api exception: {response.text}")
try:
return response.json()
except Exception as e:
Expand Down Expand Up @@ -75,3 +112,22 @@ def get_btc_confirmed_transactions() -> pd.DataFrame:
df["x"] = df["x"] * 1_000_000_000
df["x"] = pd.to_datetime(df["x"])
return df


@log_start_end(log=logger)
def get_btc_single_block(blockhash: str) -> pd.DataFrame:
"""Returns BTC block data in json format. [Source: https://blockchain.info/]
Returns
-------
pd.DataFrame
BTC single block
"""

data = _blockchain_data_api_make_request(f"rawblock/{blockhash}?format=json")

if data:

df = pd.json_normalize(data)
return df

return pd.DataFrame()
56 changes: 56 additions & 0 deletions openbb_terminal/cryptocurrency/onchain/blockchain_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
plot_autoscale,
is_valid_axes_count,
str_date_to_timestamp,
print_rich_table,
)

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -144,3 +145,58 @@ def display_btc_confirmed_transactions(
"btcct",
df,
)


@log_start_end(log=logger)
def display_btc_single_block(
blockhash: str,
export: str = "",
) -> None:
"""Returns BTC block data. [Source: https://api.blockchain.info/]
Parameters
----------
blockhash : str
Hash of the block you are looking for.
export : str
Export dataframe data to csv,json,xlsx file
"""

df = blockchain_model.get_btc_single_block(blockhash)
if not df.empty:
df.rename(index={0: "Value"}, inplace=True)
df_data = df.copy()

df_essentials = df[
[
"hash",
"ver",
"prev_block",
"mrkl_root",
"bits",
"next_block",
"fee",
"nonce",
"n_tx",
"size",
"block_index",
"main_chain",
"height",
"weight",
]
]

df_flipped = df_essentials.transpose()

print_rich_table(
df_flipped,
show_index=True,
index_name="Metric",
title=f"Block {int(df['height'])}",
)

export_data(
export,
os.path.dirname(os.path.abspath(__file__)),
"btcblockdata",
df_data,
)
36 changes: 36 additions & 0 deletions openbb_terminal/cryptocurrency/onchain/onchain_controller.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,7 @@ class OnchainController(BaseController):
"baas",
"btccp",
"btcct",
"btcblockdata",
"dt",
"ds",
"tvl",
Expand Down Expand Up @@ -115,6 +116,7 @@ def print_help(self):
mt.add_cmd("hr")
mt.add_cmd("btccp")
mt.add_cmd("btcct")
mt.add_cmd("btcblockdata")
mt.add_cmd("gwei")
mt.add_cmd("whales")
mt.add_cmd("lt")
Expand Down Expand Up @@ -1516,3 +1518,37 @@ def call_baas(self, other_args: List[str]):

else:
console.print("You didn't provide coin symbol.\n")

@log_start_end(log=logger)
def call_btcblockdata(self, other_args: List[str]):
"""Process btcblockdata command"""
parser = argparse.ArgumentParser(
add_help=False,
formatter_class=argparse.ArgumentDefaultsHelpFormatter,
prog="btcblockdata",
description="""
Display block data from Blockchain.com,
[Source: https://api.blockchain.info/]
""",
)

if other_args and "-" not in other_args[0]:
other_args.insert(0, "--blockhash")

parser.add_argument(
"--blockhash",
action="store",
help="Flag for block hash of block.",
dest="blockhash",
default=False,
)

ns_parser = self.parse_known_args_and_warn(
parser, other_args, EXPORT_ONLY_RAW_DATA_ALLOWED
)

if ns_parser:
blockchain_view.display_btc_single_block(
blockhash=ns_parser.blockhash,
export=ns_parser.export,
)
1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/data_sources_default.json
Original file line number Diff line number Diff line change
Expand Up @@ -337,6 +337,7 @@
"hr": ["Glassnode"],
"btccp": ["Blockchain"],
"btcct": ["Blockchain"],
"btcblockdata": ["Blockchain"],
"gwei": ["ETHGasStations"],
"whales": ["WhaleAlert"],
"lt": ["BitQuery"],
Expand Down
1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/i18n/en.yml
Original file line number Diff line number Diff line change
Expand Up @@ -518,6 +518,7 @@ en:
crypto/onchain/hr: check blockchain hashrate over time (BTC or ETH)
crypto/onchain/btccp: displays BTC circulating supply
crypto/onchain/btcct: displays BTC confirmed transactions
crypto/onchain/btcblockdata: displays BTC single block data
crypto/onchain/gwei: check current eth gas fees
crypto/onchain/whales: check crypto wales transactions
crypto/onchain/lt: last trades by dex or month
Expand Down
1 change: 1 addition & 0 deletions openbb_terminal/miscellaneous/library/trail_map.csv
Original file line number Diff line number Diff line change
Expand Up @@ -174,6 +174,7 @@ crypto.onchain.baas,openbb_terminal.cryptocurrency.onchain.bitquery_model.get_sp
crypto.onchain.tv,openbb_terminal.cryptocurrency.onchain.bitquery_model.get_token_volume_on_dexes,openbb_terminal.cryptocurrency.onchain.bitquery_view.display_dex_volume_for_token
crypto.onchain.query_graph,openbb_terminal.cryptocurrency.onchain.bitquery_model.query_graph,
crypto.onchain.btc_supply,openbb_terminal.cryptocurrency.onchain.blockchain_model.get_btc_circulating_supply,openbb_terminal.cryptocurrency.onchain.blockchain_view.display_btc_circulating_supply
crypto.onchain.btcsingleblock,openbb_terminal.cryptocurrency.onchain.blockchain_model.get_btc_single_block,openbb_terminal.cryptocurrency.onchain.blockchain_view.display_btc_single_block
crypto.onchain.btc_transac,openbb_terminal.cryptocurrency.onchain.blockchain_model.get_btc_confirmed_transactions,openbb_terminal.cryptocurrency.onchain.blockchain_view.display_btc_confirmed_transactions
crypto.onchain.gwei,openbb_terminal.cryptocurrency.onchain.ethgasstation_model.get_gwei_fees,openbb_terminal.cryptocurrency.onchain.ethgasstation_view.display_gwei_fees
crypto.onchain.hist,openbb_terminal.cryptocurrency.onchain.ethplorer_model.get_address_history,openbb_terminal.cryptocurrency.onchain.ethplorer_view.display_address_history
Expand Down
Loading

0 comments on commit 052c16f

Please sign in to comment.