-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcurrent-fees.py
More file actions
192 lines (156 loc) · 6.52 KB
/
Copy pathcurrent-fees.py
File metadata and controls
192 lines (156 loc) · 6.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
#!/usr/bin/env python3
"""
BTCBench Python Current Fees Example
https://www.btcbench.com/
Fetches current Bitcoin fee estimates from the public BTCBench API
and displays them with approximate USD transaction cost.
# ─────────────────────────────────────────────
# BTCBench Bitcoin Fee Example
# Source : https://www.btcbench.com
# API : https://www.btcbench.com/api-docs.html
# GitHub : https://github.com/btcbench-com/btcbench-api-examples
# Please keep this credit if you use or share this code.
# ─────────────────────────────────────────────
"""
import json
import urllib.request
from datetime import datetime, timezone
# ─────────────────────────────────────────────
# Config
# ─────────────────────────────────────────────
API_URL = "https://www.btcbench.com/api/v1/fees.json"
DEFAULT_TX_VBYTES = 140
# ─────────────────────────────────────────────
# Helpers
# ─────────────────────────────────────────────
def fee_to_usd(fee_rate_sat_per_vb, btc_usd_price):
"""
Convert a sat/vB fee rate to an approximate USD cost
based on a default transaction size.
"""
try:
fee = float(fee_rate_sat_per_vb)
price = float(btc_usd_price)
sats = fee * DEFAULT_TX_VBYTES
usd = (sats / 100_000_000) * price
return f"~${usd:.2f}"
except (TypeError, ValueError):
return "~$—"
def parse_date(data):
"""
Extract and parse the timestamp from the API response.
Tries multiple known field names.
"""
raw = (
data.get("datetime")
or data.get("btc_price_fetched_at")
or data.get("updated_at")
or data.get("timestamp")
)
if raw is None:
return None
# Unix timestamp (integer)
if isinstance(raw, (int, float)):
return datetime.fromtimestamp(raw, tz=timezone.utc)
# String timestamp
raw_str = str(raw).strip()
# Normalise space-separated datetimes to ISO format
if "T" not in raw_str:
raw_str = raw_str.replace(" ", "T")
if not raw_str.endswith("Z"):
raw_str += "Z"
try:
# Python 3.11+ supports Z suffix natively
return datetime.fromisoformat(raw_str.replace("Z", "+00:00"))
except ValueError:
return None
def format_utc_date(date):
"""
Format a datetime object as a readable UTC string.
"""
if not date:
return "Latest BTCBench snapshot"
return date.strftime("%d %b %Y %H:%M UTC")
def minutes_ago(date):
"""
Return a human-readable 'Updated X min ago' string.
"""
if not date:
return "Updated recently"
diff_seconds = (datetime.now(tz=timezone.utc) - date).total_seconds()
diff_min = max(0, round(diff_seconds / 60))
if diff_min < 1:
return "Updated just now"
if diff_min == 1:
return "Updated 1 min ago"
if diff_min < 60:
return f"Updated {diff_min} min ago"
diff_hours = round(diff_min / 60)
if diff_hours == 1:
return "Updated 1 hour ago"
return f"Updated {diff_hours} hours ago"
# ─────────────────────────────────────────────
# Fetch
# ─────────────────────────────────────────────
def fetch_fees():
"""
Fetch fee data from the BTCBench public API.
Returns parsed JSON dict or raises on failure.
"""
req = urllib.request.Request(
API_URL,
headers={"User-Agent": "BTCBench-Python-Example/1.0"}
)
with urllib.request.urlopen(req, timeout=10) as response:
if response.status != 200:
raise RuntimeError(f"HTTP {response.status}")
raw = response.read().decode("utf-8")
return json.loads(raw)
# ─────────────────────────────────────────────
# Render
# ─────────────────────────────────────────────
def render(data):
"""
Validate and display the fee data in the terminal.
"""
if not data or "fees" not in data:
raise ValueError("Invalid BTCBench API response")
fees = data["fees"]
fastest = fees.get("fastest", "N/A")
normal = fees.get("halfHour", "N/A")
economy = fees.get("economy", "N/A")
btc_price_usd = data.get("btc_price_usd")
date = parse_date(data)
# ── Output ──────────────────────────────
print()
print("=" * 44)
print(" BTCBench — Current Bitcoin Fee Estimates")
print("=" * 44)
print(f" {'Tier':<12} {'sat/vB':>8} {'USD ~140 vB':>12}")
print("-" * 44)
print(f" {'Fastest':<12} {str(fastest):>8} {fee_to_usd(fastest, btc_price_usd):>12}")
print(f" {'Normal':<12} {str(normal):>8} {fee_to_usd(normal, btc_price_usd):>12}")
print(f" {'Economy':<12} {str(economy):>8} {fee_to_usd(economy, btc_price_usd):>12}")
print("-" * 44)
print(f" {minutes_ago(date)}")
print(f" {format_utc_date(date)}")
print("=" * 44)
print(" Powered by BTCBench · https://www.btcbench.com")
print(" USD estimate assumes 140 vbyte transaction.")
print(" Always verify fees in your own wallet.")
print("=" * 44)
print()
# ─────────────────────────────────────────────
# Main
# ─────────────────────────────────────────────
def main():
print("\n Fetching BTCBench fee data…")
try:
data = fetch_fees()
render(data)
except Exception as error:
print(f"\n [ERROR] Could not load BTCBench fee data: {error}")
print(" Please check the BTCBench API or status page.")
print(" https://www.btcbench.com\n")
if __name__ == "__main__":
main()