Skip to content

Commit

Permalink
fix: improve binance service
Browse files Browse the repository at this point in the history
  • Loading branch information
adagora committed Nov 28, 2023
1 parent ee9574c commit 384d39b
Showing 1 changed file with 31 additions and 29 deletions.
60 changes: 31 additions & 29 deletions solarathon/pages/dashboard.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
# root.setLevel(logging.DEBUG)

# some app state that outlives a single page
from pydantic import BaseModel, Field, ValidationError
from pydantic import BaseModel, Field, ValidationError, RequestException


init_app_state = solara.reactive(["ada", "btc","bnb", "eth","doge", "xrp"])
Expand Down Expand Up @@ -72,27 +72,25 @@ def format_price(price):


def get_binance_ticket(symbol: str) -> TickerData:
binance_url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={symbol}"
response = requests.get(binance_url)

try:
response.raise_for_status()
data = response.json()

# Ensure that all required fields are present in the data
if all(key in data for key in ('lastPrice', 'priceChangePercent', 'highPrice', 'lowPrice')):
ticker_data = TickerData(**data)
return ticker_data
else:
return TickerData(symbol="No data", last_price=0.0, price_change_percent=0.0, high_price=0.0, low_price=0.0)
except requests.exceptions.RequestException as e:
print("Request Exception:", e)
except ValidationError as ve:
print("Validation Error:", ve)
max_retries = 5
for retry in range(max_retries):
try:
binance_url = f"https://api.binance.com/api/v3/ticker/24hr?symbol={symbol}"

response = requests.get(binance_url)
if response.status_code == 200:
return TickerData.model_validate_json(json_data=response.content)
else:
return TickerData(symbol="no data", last_price=0, price_change_percent=0, high_price=0, low_price=0)
except ConnectionError:
sleep(2 ** retry)
continue
raise Exception("Failed to fetch ticker data after maximum retries")


@solara.component
def DashboardCard(symbol: str, icon: Union[solara.Element, str] = None, market_cap: Optional[str] = None, market_cap_change_percentage: Optional[str] = None, pending: Optional[bool] = False):
print(f"Rendering {symbol}")
ticker_data, set_ticker_data = solara.use_state(
cast(Optional[TickerData], None)
)
Expand Down Expand Up @@ -162,18 +160,22 @@ def fetch_data(event: threading.Event):

return main


def get_available_symbols():
symbols_url = "https://api.binance.com/api/v3/exchangeInfo"
try:
symbols_response = requests.get(symbols_url)
symbols_data = symbols_response.json()
available_symbols = sorted(list(set([symbol['baseAsset'].lower() for symbol in symbols_data['symbols']])))
except Exception as e:
available_symbols = []

return available_symbols

max_retries = 5
for retry in range(max_retries):
try:
symbols_url = "https://api.binance.com/api/v3/exchangeInfo"
response = requests.get(symbols_url)
if response.status_code == 200:
symbols_data = response.json()
available_symbols = sorted(list(set([symbol['baseAsset'].lower() for symbol in symbols_data['symbols']])))
return available_symbols
except RequestException as e:
if retry == max_retries - 1:
raise Exception(f"Failed to fetch available symbols after maximum retries")
else:
sleep(2 ** retry)
continue

@solara.component
def Page():
Expand Down

0 comments on commit 384d39b

Please sign in to comment.