feat: scrape BCV directly, all currencies, P2P filter 10 USDT
Browse files- main.py +85 -31
- requirements.txt +2 -0
main.py
CHANGED
|
@@ -1,8 +1,10 @@
|
|
| 1 |
from fastapi import FastAPI, Depends, HTTPException, Header
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
|
| 3 |
import httpx
|
| 4 |
import asyncio
|
| 5 |
import time
|
|
|
|
| 6 |
import jwt
|
| 7 |
from jwt import PyJWKClient
|
| 8 |
|
|
@@ -45,7 +47,7 @@ def verify_app_check(x_firebase_appcheck: str = Header(...)):
|
|
| 45 |
# Cache simple en memoria
|
| 46 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 47 |
_cache: dict = {}
|
| 48 |
-
BCV_TTL = 60 * 60 * 4 # 4 horas
|
| 49 |
P2P_TTL = 60 * 20 # 20 minutos
|
| 50 |
|
| 51 |
|
|
@@ -60,6 +62,17 @@ def _store(key: str, data: dict):
|
|
| 60 |
_cache[key] = {"ts": time.time(), "data": data}
|
| 61 |
|
| 62 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 64 |
# Fetchers
|
| 65 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
@@ -68,26 +81,38 @@ async def fetch_bcv() -> dict:
|
|
| 68 |
if cached:
|
| 69 |
return cached
|
| 70 |
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
)
|
| 76 |
-
cotizaciones_res.raise_for_status()
|
| 77 |
-
paralelo_res.raise_for_status()
|
| 78 |
|
| 79 |
-
|
| 80 |
-
|
|
|
|
| 81 |
|
| 82 |
-
|
| 83 |
-
bcv_eur = next((x["promedio"] for x in cotizaciones if x.get("moneda") == "EUR" and x.get("fuente") == "oficial"), None)
|
| 84 |
|
| 85 |
-
|
| 86 |
-
"
|
| 87 |
-
"
|
| 88 |
-
"
|
| 89 |
-
"
|
|
|
|
| 90 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 91 |
_store("bcv", data)
|
| 92 |
return data
|
| 93 |
|
|
@@ -97,32 +122,61 @@ async def fetch_p2p() -> dict:
|
|
| 97 |
if cached:
|
| 98 |
return cached
|
| 99 |
|
|
|
|
|
|
|
| 100 |
headers = {
|
| 101 |
"User-Agent": "Mozilla/5.0",
|
| 102 |
"Content-Type": "application/json",
|
| 103 |
}
|
| 104 |
-
|
| 105 |
-
"fiat": "VES",
|
| 106 |
-
"
|
| 107 |
-
"
|
| 108 |
-
"
|
| 109 |
-
"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 110 |
}
|
| 111 |
-
body_sell = {**body_buy, "tradeType": "SELL"}
|
| 112 |
|
| 113 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 114 |
buy_res, sell_res = await asyncio.gather(
|
| 115 |
-
client.post(
|
| 116 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 117 |
)
|
| 118 |
buy_res.raise_for_status()
|
| 119 |
sell_res.raise_for_status()
|
| 120 |
|
| 121 |
-
|
| 122 |
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 126 |
|
| 127 |
data = {"p2pBuyMax": buy_max, "p2pSellMax": sell_max}
|
| 128 |
_store("p2p", data)
|
|
|
|
| 1 |
from fastapi import FastAPI, Depends, HTTPException, Header
|
| 2 |
from fastapi.middleware.cors import CORSMiddleware
|
| 3 |
+
from bs4 import BeautifulSoup
|
| 4 |
import httpx
|
| 5 |
import asyncio
|
| 6 |
import time
|
| 7 |
+
import re
|
| 8 |
import jwt
|
| 9 |
from jwt import PyJWKClient
|
| 10 |
|
|
|
|
| 47 |
# Cache simple en memoria
|
| 48 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 49 |
_cache: dict = {}
|
| 50 |
+
BCV_TTL = 60 * 60 * 4 # 4 horas (BCV actualiza una vez al dΓa)
|
| 51 |
P2P_TTL = 60 * 20 # 20 minutos
|
| 52 |
|
| 53 |
|
|
|
|
| 62 |
_cache[key] = {"ts": time.time(), "data": data}
|
| 63 |
|
| 64 |
|
| 65 |
+
def _parse_bcv_rate(text: str) -> float | None:
|
| 66 |
+
"""Convierte '36,85' o '36.853,12' a float."""
|
| 67 |
+
cleaned = text.strip().replace("Bs.", "").replace("S", "").strip()
|
| 68 |
+
# Formato venezolano: punto como separador de miles, coma como decimal
|
| 69 |
+
cleaned = cleaned.replace(".", "").replace(",", ".")
|
| 70 |
+
try:
|
| 71 |
+
return float(cleaned)
|
| 72 |
+
except ValueError:
|
| 73 |
+
return None
|
| 74 |
+
|
| 75 |
+
|
| 76 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
| 77 |
# Fetchers
|
| 78 |
# ββββββββββββββββββββββββββββββββββββββββββββββ
|
|
|
|
| 81 |
if cached:
|
| 82 |
return cached
|
| 83 |
|
| 84 |
+
headers = {
|
| 85 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
| 86 |
+
"Accept-Language": "es-VE,es;q=0.9",
|
| 87 |
+
}
|
|
|
|
|
|
|
|
|
|
| 88 |
|
| 89 |
+
async with httpx.AsyncClient(timeout=15, follow_redirects=True) as client:
|
| 90 |
+
response = await client.get("https://www.bcv.org.ve/", headers=headers)
|
| 91 |
+
response.raise_for_status()
|
| 92 |
|
| 93 |
+
soup = BeautifulSoup(response.text, "lxml")
|
|
|
|
| 94 |
|
| 95 |
+
currency_ids = {
|
| 96 |
+
"usd": "dolar",
|
| 97 |
+
"eur": "euro",
|
| 98 |
+
"cny": "yuan",
|
| 99 |
+
"try": "lira",
|
| 100 |
+
"rub": "rublo",
|
| 101 |
}
|
| 102 |
+
|
| 103 |
+
rates = {}
|
| 104 |
+
for code, div_id in currency_ids.items():
|
| 105 |
+
div = soup.find(id=div_id)
|
| 106 |
+
tag = div.find("strong") if div else None
|
| 107 |
+
rates[f"bcv{code.upper()}"] = _parse_bcv_rate(tag.text) if tag else None
|
| 108 |
+
|
| 109 |
+
if all(v is None for v in rates.values()):
|
| 110 |
+
raise HTTPException(status_code=503, detail="No se pudo obtener las tasas BCV")
|
| 111 |
+
|
| 112 |
+
updated_tag = soup.find("span", {"class": re.compile(r"date-display")})
|
| 113 |
+
updated_at = updated_tag.text.strip() if updated_tag else None
|
| 114 |
+
|
| 115 |
+
data = {**rates, "updatedAt": updated_at}
|
| 116 |
_store("bcv", data)
|
| 117 |
return data
|
| 118 |
|
|
|
|
| 122 |
if cached:
|
| 123 |
return cached
|
| 124 |
|
| 125 |
+
target_usdt = 10.0
|
| 126 |
+
|
| 127 |
headers = {
|
| 128 |
"User-Agent": "Mozilla/5.0",
|
| 129 |
"Content-Type": "application/json",
|
| 130 |
}
|
| 131 |
+
body_base = {
|
| 132 |
+
"fiat": "VES",
|
| 133 |
+
"page": 1,
|
| 134 |
+
"rows": 20,
|
| 135 |
+
"asset": "USDT",
|
| 136 |
+
"countries": [],
|
| 137 |
+
"proMerchantAds": False,
|
| 138 |
+
"shieldMerchantAds": False,
|
| 139 |
+
"publisherType": None,
|
| 140 |
+
"payTypes": [],
|
| 141 |
+
"classifies": ["mass", "profession"],
|
| 142 |
}
|
|
|
|
| 143 |
|
| 144 |
async with httpx.AsyncClient(timeout=10) as client:
|
| 145 |
buy_res, sell_res = await asyncio.gather(
|
| 146 |
+
client.post(
|
| 147 |
+
"https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
|
| 148 |
+
json={**body_base, "tradeType": "BUY"},
|
| 149 |
+
headers=headers,
|
| 150 |
+
),
|
| 151 |
+
client.post(
|
| 152 |
+
"https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search",
|
| 153 |
+
json={**body_base, "tradeType": "SELL"},
|
| 154 |
+
headers=headers,
|
| 155 |
+
),
|
| 156 |
)
|
| 157 |
buy_res.raise_for_status()
|
| 158 |
sell_res.raise_for_status()
|
| 159 |
|
| 160 |
+
def best_price_for(ads: list, target: float) -> float | None:
|
| 161 |
+
"""Retorna el precio mΓ‘s alto entre anuncios que aceptan `target` USDT."""
|
| 162 |
+
eligible = []
|
| 163 |
+
for item in ads:
|
| 164 |
+
adv = item.get("adv", {})
|
| 165 |
+
try:
|
| 166 |
+
price = float(adv["price"])
|
| 167 |
+
surplus = float(adv.get("surplusAmount", 0))
|
| 168 |
+
min_fiat = float(adv.get("minSingleTransAmount", 0))
|
| 169 |
+
max_fiat = float(adv.get("maxSingleTransAmount", float("inf")))
|
| 170 |
+
# Verifica que el anuncio tenga suficiente stock y acepte 10 USDT
|
| 171 |
+
fiat_needed = price * target
|
| 172 |
+
if surplus >= target and min_fiat <= fiat_needed <= max_fiat:
|
| 173 |
+
eligible.append(price)
|
| 174 |
+
except (KeyError, ValueError, TypeError):
|
| 175 |
+
continue
|
| 176 |
+
return max(eligible) if eligible else None
|
| 177 |
+
|
| 178 |
+
buy_max = best_price_for(buy_res.json().get("data", []), target_usdt)
|
| 179 |
+
sell_max = best_price_for(sell_res.json().get("data", []), target_usdt)
|
| 180 |
|
| 181 |
data = {"p2pBuyMax": buy_max, "p2pSellMax": sell_max}
|
| 182 |
_store("p2p", data)
|
requirements.txt
CHANGED
|
@@ -2,3 +2,5 @@ fastapi==0.115.6
|
|
| 2 |
uvicorn==0.34.0
|
| 3 |
httpx==0.28.1
|
| 4 |
PyJWT[crypto]==2.10.1
|
|
|
|
|
|
|
|
|
| 2 |
uvicorn==0.34.0
|
| 3 |
httpx==0.28.1
|
| 4 |
PyJWT[crypto]==2.10.1
|
| 5 |
+
beautifulsoup4==4.12.3
|
| 6 |
+
lxml==5.3.0
|