Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added single block data from Blockchain.com #3406

Merged
merged 20 commits into from
Jan 4, 2023
Merged
Show file tree
Hide file tree
Changes from 13 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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 @@ -173,6 +173,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
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,9 @@ def test_get_btc_confirmed_transactions(recorder):
def test_get_btc_circulating_supply(recorder):
df = blockchain_model.get_btc_circulating_supply()
recorder.capture(df)


@pytest.mark.vcr
def test_get_btc_single_block(recorder):
df = blockchain_model.get_btc_single_block("")
recorder.capture(df)
Original file line number Diff line number Diff line change
Expand Up @@ -18,3 +18,11 @@ def test_display_btc_confirmed_transactions(mocker):
# MOCK VISUALIZE_OUTPUT
mocker.patch(target="openbb_terminal.helper_classes.TerminalStyle.visualize_output")
blockchain_view.display_btc_confirmed_transactions("2010-01-01", "2022-11-10", "")


@pytest.mark.vcr
@pytest.mark.record_stdout
def test_display_btc_single_block(mocker):
# MOCK VISUALIZE_OUTPUT
mocker.patch(target="openbb_terminal.helper_classes.TerminalStyle.visualize_output")
blockchain_view.display_btc_single_block("1_601_596_800", "")
15 changes: 15 additions & 0 deletions website/content/terminal/crypto/onchain/btcblockdata/_index.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
```
usage: btcblockdata [--blockhash BLOCKHASH]
[--export {csv,json,xlsx}] [-h]
```

Displays json data for a single block. [Source: https://blockchain.info/]

```
arguments:
--blockhash BLOCKHASH Hash of the block you are targeting
--export {csv,json,xlsx} Export dataframe data to csv,json,xlsx file (default: )
-h, --help Show this help message (default: False)
```

![](https://user-images.githubusercontent.com/57280701/201509706-a7c94df8-e15e-4b99-97bd-4cefa52edb02.jpg)
Empty file added website/data/menu/main.yml
Empty file.
2 changes: 1 addition & 1 deletion website/src/theme/CodeBlock/Content/String.js
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ export default function CodeBlockString({
});
const showLineNumbers =
showLineNumbersProp ?? containsLineNumbers(metastring);

const shouldWordwrapByDefault = metastring?.includes("wordwrap")

return (
Expand Down