Files
OpenBB/openbb_terminal/cryptocurrency/onchain/whale_alert_model.py
montezdesousa 475ebb5acd [WIP] Migrate user, feature flags and configurations to dataclass (#4309)
* implement user and change is guest

* replace User methods

* move remaining functions to user

* fix bug

* portfolio test

* fix tests

* fix tests

* uncomment skip

* ruff

* start credentials model implementation

* change deault structure

* refacto quandl

* change default struct and file names

* bug

* start using global user

* add comments

* move update flair

* change cfg references in keys model

* reddit & fmp

* refactore additional keys

* remaing config keys

* remove unsude imports and fix hub keys

* ruff

* fix line too long

* unblock unittests

* fix keys model tests

* remove os patch

* fix account controller tests

* fix account controller tests

* fix account model

* account fixed

* fix user tests

* User Model

* User Model

* User Model

* Move session folder

* User Model : grouping the models

* User Model : fix bugs

* Config Plot + bug fix

* User Model : Refactoring plots

* Feature flags

* Remove dup

* clean comments a fix some vars

* fix feature flags controller

* refactor obbff from settings controller

* refactor a bunch of obbff variables

* fix bug blocking terminal

* fix integration tests

* refactor controllers with obbff

* refactor remaining ffs

* remove comments

* log not started

* mispelled variable

* set current user on local model

* User Model : moving files + updating

* User Preferences

* User : Refactor is_guest function + bug fix

* User : refactor is_guest function

* Fix conftest.py

* remove lost obbffs

* typo on fileoverwrite

* Plot config: move variables and start plot dpi

* User : tests

* refactor plot dpi references

* remove plot dpi imports

* refactor some config terminal leftover

* /account/sync : fix bug

* remove configs reload

* start path refactor

* installation paths vs user paths

* remove cfg_plot

* Tests : User Refactoring

* user prefix only for preferences

* user prefix only for preferences

* move user paths

* remove comment

* update apply remote configs

* fix tz not updating

* save some copys

* small fix

* create interface for credentials and preferences

* wrong docstrings fixed

* ruff core

* fix some pref setting

* login is better

* ruff

* ruff

* remove Literal

* add small comment

* Tests : User Refactoring

* Credentials Model : add DataBento

* Fix helper_funcs

* Fixing code

* Tests : fixing

* User Model : freezing the models

* Fixed Income + Databento

* Tests : fixing keys

* black

* ruff

* Tests : user model

* Tests : user model

* Fix linting

* Fix linting

* Linting

* Linting

* Fixing code and tests

* Fix tests

* mypy

* SDK

* Clean ruff cache

* Fix syntax issue

* Update fred_view

* Black

* Linting

* Update code

* Update tests

* Linting

* Linting

* Tests

* Black

* Linting

* Linting

* Mock os.listdir to avoid looking for file that doesnt exist

* Mock options paths

* lint

* Tests : fix

* Code : update

* Tests + Linting

* Tests

* Ruff

* Code : update

* Tests

* Code : update

* Fix workflow

* Code : update

---------

Co-authored-by: Chavithra PARANA <chavithra@gmail.com>
Co-authored-by: luqazino@gmail.com <luqazino@gmail.com>
Co-authored-by: James Maslek <jmaslek11@gmail.com>
2023-03-05 00:37:19 +01:00

178 lines
4.7 KiB
Python

"""Whale Alert model"""
__docformat__ = "numpy"
import logging
import textwrap
from typing import Any, Optional, Tuple
import numpy as np
import pandas as pd
from openbb_terminal.core.session.current_user import get_current_user
from openbb_terminal.decorators import check_api_key, log_start_end
from openbb_terminal.helper_funcs import request
from openbb_terminal.rich_config import console
logger = logging.getLogger(__name__)
FILTERS = [
"date",
"symbol",
"blockchain",
"amount",
"amount_usd",
"from",
"to",
]
class ApiKeyException(Exception):
"""Api Key Exception object"""
@log_start_end(log=logger)
def __init__(self, message: str):
super().__init__(message)
self.message = message
@log_start_end(log=logger)
def __str__(self) -> str:
return f"ApiKeyException: {self.message}"
@log_start_end(log=logger)
@check_api_key(["API_WHALE_ALERT_KEY"])
def make_request(params: Optional[dict] = None) -> Tuple[Optional[int], Any]:
"""Helper methods for requests [Source: https://docs.whale-alert.io/]
Parameters
----------
params: dict
additional param
Returns
-------
Tuple[Optional[int], Any]
status code, response from api request
"""
api_key = get_current_user().credentials.API_WHALE_ALERT_KEY or ""
url = "https://api.whale-alert.io/v1/transactions?api_key=" + api_key
try:
response = request(url, params=params)
except Exception:
return None, None
result = {}
if response.status_code == 200:
result = response.json()
elif response.status_code == 401:
console.print("[red]Invalid API Key[/red]\n")
logger.error("Invalid Authentication: %s", response.text)
elif response.status_code == 401:
console.print("[red]API Key not authorized for Premium Feature[/red]\n")
logger.error("Insufficient Authorization: %s", response.text)
elif response.status_code == 429:
console.print("[red]Exceeded number of calls per minute[/red]\n")
logger.error("Calls limit exceeded: %s", response.text)
else:
console.print(response.json()["message"])
logger.error("Error in request: %s", response.text)
return response.status_code, result
@log_start_end(log=logger)
def get_whales_transactions(
min_value: int = 800000,
limit: int = 100,
sortby: str = "date",
ascend: bool = False,
) -> pd.DataFrame:
"""Whale Alert's API allows you to retrieve live and historical transaction data from major blockchains.
Supported blockchain: Bitcoin, Ethereum, Ripple, NEO, EOS, Stellar and Tron. [Source: https://docs.whale-alert.io/]
Parameters
----------
min_value: int
Minimum value of trade to track.
limit: int
Limit of transactions. Max 100
sortby: str
Key to sort by.
ascend: str
Sort in ascending order.
Returns
-------
pd.DataFrame
Crypto wales transactions
"""
min_value = max(min_value, 800000)
limit = max(limit, 100)
params = {"limit": limit, "min_value": min_value}
status_code, response = make_request(params)
if status_code != 200:
return pd.DataFrame()
data = pd.json_normalize(response["transactions"]).sort_values(
"timestamp", ascending=False
)
data["date"] = pd.to_datetime(data["timestamp"], unit="s")
data.columns = [col.replace(".balance", "") for col in data.columns]
data["to_address"] = data["to.address"].apply(
lambda x: "\n".join(textwrap.wrap(x, width=45)) if isinstance(x, str) else x
)
data["from_address"] = data["from.address"].apply(
lambda x: "\n".join(textwrap.wrap(x, width=45)) if isinstance(x, str) else x
)
data["from"] = data.apply(
lambda x: x["from.owner"]
if x["from.owner"] not in [np.nan, None, np.NaN]
else x["from.owner_type"],
axis=1,
)
data["to"] = data.apply(
lambda x: x["to.owner"]
if x["to.owner"] not in [np.nan, None, np.NaN]
else x["to.owner_type"],
axis=1,
)
data.drop(
[
"id",
"transaction_count",
"from.owner_type",
"to.owner_type",
"to.owner",
"from.owner",
"transaction_type",
"hash",
"timestamp",
],
axis=1,
inplace=True,
)
df = data[
[
"date",
"symbol",
"blockchain",
"amount",
"amount_usd",
"from",
"to",
"from_address",
"to_address",
]
]
df = df.sort_values(by=sortby, ascending=ascend)
return df