viewer and parser added
All checks were successful
SonarQube Scan / SonarQube Trigger (push) Successful in 1m44s
All checks were successful
SonarQube Scan / SonarQube Trigger (push) Successful in 1m44s
This commit is contained in:
107
app.py
107
app.py
@ -1,67 +1,72 @@
|
||||
from mexc_sdk import Spot
|
||||
from fastapi import FastAPI, Request
|
||||
from fastapi.responses import HTMLResponse
|
||||
from fastapi.templating import Jinja2Templates
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from pymongo import MongoClient
|
||||
from datetime import datetime
|
||||
import uvicorn
|
||||
from urllib.parse import quote_plus
|
||||
from dotenv import load_dotenv
|
||||
import logging
|
||||
import os
|
||||
import yaml
|
||||
|
||||
with open("coin.yaml", "r") as file:
|
||||
data = yaml.safe_load(file)
|
||||
interest_coins = data["interest"]
|
||||
|
||||
# Set up logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO, format="%(asctime)s - %(levelname)s - %(message)s"
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Load the environment variables from the .env file
|
||||
load_dotenv()
|
||||
|
||||
app = FastAPI()
|
||||
|
||||
class TradeBot(object):
|
||||
def __init__(self, api_key, api_secret):
|
||||
self.client = Spot(api_key=api_key, api_secret=api_secret)
|
||||
self.symbol = "BTCUSDT"
|
||||
|
||||
def change_symbol(self, new_symbol):
|
||||
self.symbol = new_symbol
|
||||
# Setup templates directory
|
||||
templates = Jinja2Templates(directory="templates")
|
||||
|
||||
def time(self):
|
||||
# Format is in dict
|
||||
return f"Server Time: {self.client.time()['serverTime']}"
|
||||
MONGO_URI = f'mongodb://{quote_plus(os.getenv("DB_USER"))}:{quote_plus(os.getenv("DB_PWD"))}@{os.getenv("DB_HOST")}:{os.getenv("DB_PORT")}'
|
||||
client = MongoClient(MONGO_URI)
|
||||
db = client[os.getenv("DB_NAME")] # Replace with your database name
|
||||
# collection = db["XRP"]
|
||||
|
||||
def get_market_price(self, symbol=None):
|
||||
"""Get current market price for a symbol"""
|
||||
try:
|
||||
symbol = symbol or self.symbol
|
||||
ticker = self.client.ticker_price(symbol)
|
||||
price = float(ticker["price"])
|
||||
logger.info(f"Current {symbol} price: {price}")
|
||||
return price
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting market price: {str(e)}")
|
||||
return None
|
||||
|
||||
def get_account_balance(self):
|
||||
"""Get account balance for all assets"""
|
||||
try:
|
||||
account_info = self.client.account_info()
|
||||
balances = account_info["balances"]
|
||||
@app.get("/", response_class=HTMLResponse)
|
||||
async def read_data(request: Request):
|
||||
return templates.TemplateResponse(
|
||||
request=request, name="index.html", context={"coins": interest_coins}
|
||||
)
|
||||
|
||||
logger.info("Account balances:")
|
||||
for balance in balances:
|
||||
if float(balance["free"]) > 0 or float(balance["locked"]) > 0:
|
||||
logger.info(
|
||||
f"{balance['asset']}: Free={balance['free']}, Locked={balance['locked']}"
|
||||
)
|
||||
|
||||
return balances
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting account balance: {str(e)}")
|
||||
return None
|
||||
@app.get("/coin/{coin}")
|
||||
async def view_coin_graph(request: Request, coin: str):
|
||||
if coin in interest_coins:
|
||||
return templates.TemplateResponse(
|
||||
request=request, name="coin.html", context={"coin": coin}
|
||||
)
|
||||
else:
|
||||
return {"coin": "not found"}
|
||||
|
||||
|
||||
@app.get("/data/{coin}")
|
||||
async def get_data(coin):
|
||||
collection = db[coin]
|
||||
# Get last 100 data points, sorted by time
|
||||
cursor = (
|
||||
collection.find({}, {"_id": 0, "timestamp": 1, "price": 1})
|
||||
.sort("timestamp", -1)
|
||||
.limit(100)
|
||||
)
|
||||
|
||||
data = list(cursor)
|
||||
|
||||
# Format the data for Chart.js
|
||||
times = []
|
||||
prices = []
|
||||
|
||||
for item in reversed(data): # Reverse to show oldest to newest
|
||||
times.append(str(item["timestamp"]))
|
||||
prices.append(float(item["price"]))
|
||||
|
||||
return {"times": times, "prices": prices}
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Access the variables
|
||||
api_key = os.getenv("API_KEY")
|
||||
api_secret = os.getenv("API_SECRET")
|
||||
tb = TradeBot(api_key, api_secret)
|
||||
print(tb.time())
|
||||
tb.get_market_price()
|
||||
tb.get_account_balance()
|
||||
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)
|
||||
|
Reference in New Issue
Block a user