Created
May 12, 2025 04:29
-
-
Save koorukuroo/717cb6955ad6376d3cde192fe485b062 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import asyncio | |
import websockets | |
import json | |
import time | |
import aiohttp | |
from datetime import datetime | |
from urllib.parse import urlencode | |
API_BASE = "http://127.0.0.1:8000/items" | |
symbol = "KRW-BTC" | |
def format_number(val): | |
try: | |
return f"{val:,.2f}" if isinstance(val, float) else f"{val:,}" | |
except: | |
return "N/A" | |
async def post_data(session, key: str, value: str): | |
start = time.time() | |
query = urlencode({"value": value}) | |
url = f"{API_BASE}/{key}?{query}" | |
try: | |
async with session.post(url) as response: | |
resp_text = await response.text() | |
except Exception as e: | |
print(f"❌ POST 실패: {e}") | |
resp_text = None | |
latency = time.time() - start | |
return latency, resp_text | |
async def upbit_ws(): | |
url = "wss://api.upbit.com/websocket/v1" | |
total_requests = 0 | |
total_latency = 0 | |
max_latency = 0 | |
min_latency = float("inf") | |
start_time = time.time() | |
async with websockets.connect(url) as websocket, aiohttp.ClientSession() as session: | |
subscribe_data = [ | |
{"ticket": "test"}, | |
{"type": "ticker", "codes": [symbol]}, | |
{"format": "DEFAULT"} | |
] | |
await websocket.send(json.dumps(subscribe_data)) | |
while True: | |
raw_data = await websocket.recv() | |
parsed = json.loads(raw_data) | |
timestamp_kst = datetime.fromtimestamp(parsed.get( | |
"timestamp", 0) / 1000).strftime("%Y-%m-%d %H:%M:%S") | |
# 저장할 Key는 trade_time 기준으로 생성 (혹은 고정된 키 사용 가능) | |
key = f"{symbol}-{parsed.get('trade_time')}" | |
value = str(parsed.get("trade_price")) # Redis에는 문자열로 저장됨 | |
latency, response_text = await post_data(session, key, value) | |
total_requests += 1 | |
total_latency += latency | |
max_latency = max(max_latency, latency) | |
min_latency = min(min_latency, latency) | |
elapsed = time.time() - start_time | |
tps = total_requests / elapsed if elapsed > 0 else 0 | |
avg_latency = total_latency / total_requests if total_requests else 0 | |
print(f"\n📡 [POST] {key} = {value}") | |
print(f"⏱️ 수신 시각 : {timestamp_kst}") | |
print(f"📤 응답 내용 : {response_text}") | |
print(f"📤 전송 완료 요청 수 : {total_requests}") | |
print(f"🚀 TPS : {tps:.2f} tx/sec") | |
print(f"⏳ 최근 요청 지연 : {latency * 1000:.2f} ms") | |
print(f"📊 평균 지연 시간 : {avg_latency * 1000:.2f} ms") | |
print(f"🔼 최대 지연 : {max_latency * 1000:.2f} ms") | |
print(f"🔽 최소 지연 : {min_latency * 1000:.2f} ms") | |
print(f"⏲️ 누적 실행 시간 : {elapsed:.2f} sec") | |
print("-" * 70) | |
asyncio.run(upbit_ws()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment