This repository has been archived on 2025-01-08. You can view files and clone it, but cannot push or open issues or pull requests.
Files
mexc-trade/app.py
dongho 0db0405ea1
All checks were successful
SonarQube Scan / SonarQube Trigger (push) Successful in 1m44s
viewer and parser added
2024-12-20 00:00:21 +09:00

73 lines
2.0 KiB
Python

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 os
import yaml
with open("coin.yaml", "r") as file:
data = yaml.safe_load(file)
interest_coins = data["interest"]
load_dotenv()
app = FastAPI()
# Setup templates directory
templates = Jinja2Templates(directory="templates")
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"]
@app.get("/", response_class=HTMLResponse)
async def read_data(request: Request):
return templates.TemplateResponse(
request=request, name="index.html", context={"coins": interest_coins}
)
@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__":
uvicorn.run("app:app", host="0.0.0.0", port=8000, reload=True)