Conceptualizing a Solution
\n\n
I'm zeroing in on the core components. I'll need modules for data retrieval (mining pool APIs), data processing (calculating hash rates, earnings, etc.), and data presentation (user interface, logging). The focus is on a modular, extendable design; it should easily accommodate new mining pools or currencies. The architecture will emphasize asynchronous operations to prevent blocking the UI.
Mapping Out Implementation Steps
\n\n
My current thinking is focused on breaking down the implementation. First, the 2Miners API calls need to be handled, which I can do using the requests library. Next, the JSON response must be parsed to extract the necessary metrics. After that, I will design a function to calculate hashrate, earnings, etc. Finally, I will write the code to present the data in the console. Error handling and logging will also be important.
Outlining Code Modules
\n\n
My current thinking is focused on turning the architecture into code modules. I will start by building the data fetcher, focusing on making API requests to 2Miners. Then, I'll build the parser to extract and format the required data, like hashrate and balance, from the JSON responses. Next, I will design a console display function that neatly presents the formatted data and incorporates error handling to manage potential issues with network requests or invalid data. The main program loop will call these modules sequentially with a timed interval.
Designing The Program Logic
\n\n
My current thinking revolves around the core program logic. I will draft a MiningMonitor class with methods for data fetching and display. The API will need to be specified by the user. I'll need to define a class that takes the address and pool API as arguments. Inside the class, I will use try-except blocks for error handling, particularly when dealing with network requests. I'm focusing on clean, modular code.
Designing the Core Code
\n\n
My current thinking is focused on shaping the core of the code. I am leaning toward a MiningMonitor class, which will encapsulate data fetching, parsing, and display functionality. API selection and configuration will be key. I am starting with the example of 2Miners (Ethereum Classic), where I will define the API endpoint and the necessary fields to be extracted, such as hashrate and unpaid balance.
Designing for Extensibility
\n\n
My current thinking centers on designing for expansion. I'm focusing on a class structure with methods to fetch, parse, and display the data. Adapting the program for different mining pools and currencies requires a modular approach, where individual "adapters" can be added. These would manage API interactions and data parsing, making the core code agnostic. This will minimize changes to the main logic when adding new functionality.
This is a Python project that interacts with a mining pool API to fetch real-time data.
Since every mining pool changes its API format (e.g., 2Miners, HiveOn, Nanopool, NiceHash), I have built a modular program. The default configuration below is set up for 2Miners (Ethereum Classic) because their API is open, free, and easy to test.
Prerequisites
You will need the requests library to handle API calls.
pip install requests
The Python Code
Save this file as miner_monitor.py.
import requests
import time
import sys
from datetime import datetime
# Configuration
# ---------------------------------------------------------
# Example: 2Miners Pool (Ethereum Classic)
# Replace 'YOUR_WALLET_ADDRESS' with a real ETC address to see real data.
# If you don't have one, we use a top miner address found publicly just for demo purposes.
POOL_API_URL = "https://etc.2miners.com/api/accounts/{}"
WALLET_ADDRESS = "0x00192Fb10df37c9FB26829eb2CC623cd1BF599E8" # Replace this with yours!
REFRESH_RATE_SEC = 60
# ---------------------------------------------------------
class MiningMonitor:
def __init__(self, wallet, api_url):
self.wallet = wallet
self.api_url = api_url.format(wallet)
self.stats = {}
def fetch_data(self):
"""Fetches JSON data from the mining pool API."""
try:
# Set a timeout so the program doesn't hang if the internet is down
response = requests.get(self.api_url, timeout=10)
if response.status_code == 200:
return response.json()
else:
print(f"[!] Error: API returned status code {response.status_code}")
return None
except requests.exceptions.RequestException as e:
print(f"[!] Connection Error: {e}")
return None
def format_hashrate(self, hashes):
"""Converts raw hashes/s to readable MH/s or GH/s."""
if hashes is None: return "0 H/s"
h = float(hashes)
if h >= 1_000_000_000:
return f"{h/1_000_000_000:.2f} GH/s"
elif h >= 1_000_000:
return f"{h/1_000_000:.2f} MH/s"
else:
return f"{h:.2f} H/s"
def parse_data(self, raw_data):
"""
Extracts relevant data.
NOTE: If you change pools (e.g. from 2Miners to HiveOn),
address the JSON keys changes here.
"""
if not raw_data:
return False
# 2Miners API Structure
current_hashrate = raw_data.get('currentHashrate', 0)
avg_hashrate = raw_data.get('hashrate', 0) # 24h avg
# Balance is usually in atomic units (wei). For ETC, divide by 1e18 for 2Miners,
# but pools vary (sometimes 1e9). 2Miners usually sends Shannons or Wei.
# We assume 1e9 for the sake of standard output in this specific API version
stats = raw_data.get('stats', {})
balance = stats.get('balance', 0)
unpaid = float(balance) / 1_000_000_000 # Adjust divisor based on specific coin
workers = raw_data.get('workersTotal', 0)
last_seen = raw_data.get('updated', 0)
self.stats = {
"current_hr": current_hashrate,
"avg_hr": avg_hashrate,
"workers": workers,
"unpaid_balance": unpaid,
"last_seen": last_seen
}
return True
def display_dashboard(self):
"""Clears console and prints the stats table."""
# Calculate formatted strings
curr_fmt = self.format_hashrate(self.stats['current_hr'])
avg_fmt = self.format_hashrate(self.stats['avg_hr'])
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
# Simple UI layout
print("\033c", end="") # ANSI escape code to clear terminal (works on Linux/Mac/Win10+)
print("="*50)
print(f" CRYTPO MINING MONITOR - {now}")
print("="*50)
print(f" Wallet: {self.WALLET_DISPLAY_SHORT()}")
print(f" Workers: {self.stats['workers']}")
print("-" * 50)
print(f" Current Hashrate : {curr_fmt}")
print(f" Average Hashrate : {avg_fmt}")
print("-" * 50)
print(f" Unpaid Balance : {self.stats['unpaid_balance']:.6f} Coins")
print("="*50)
print(f" Press Ctrl+C to exit. Refreshing in {REFRESH_RATE_SEC}s...")
def WALLET_DISPLAY_SHORT(self):
return f"{self.wallet[:6]}...{self.wallet[-4:]}"
def run(self):
print("Starting monitor...")
while True:
raw_data = self.fetch_data()
if self.parse_data(raw_data):
self.display_dashboard()
try:
time.sleep(REFRESH_RATE_SEC)
except KeyboardInterrupt:
print("\n\n[!] Monitor stopped by user.")
sys.exit(0)
if __name__ == "__main__":
app = MiningMonitor(WALLET_ADDRESS, POOL_API_URL)
app.run()
How to customize this for your pool
Every mining pool uses a different JSON structure. To adapt this code to a different pool (e.g., HiveOn or Ethermine), follow these steps:
- Find the API Endpoint: Google "HiveOn API" or "Nanopool API".
- Example (Nanopool):
https://api.nanopool.org/v1/eth/user/{address}
- Update
POOL_API_URL: Change the URL in the variable at the top.
- Update
parse_data: This is the most important part. You need to run the code once, print raw_data, and see what the keys are.
- 2Miners uses:
data['currentHashrate']
- Nanopool might use:
data['data']['hashrate']
Enhancements you can add
-
Email/Discord Alerts:
Add a check in the parse_data function. If workers == 0 or current_hashrate == 0, send a request to a Discord Webhook URL or an SMTP email alert.
-
Profit Calculator:
Fetch the current price of the coin (e.g., from CoinGecko API) and multiply it by your unpaid_balance to see your earnings in USD.
-
Logging:
Instead of just printing to the screen, append the hashrate and timestamp to a .csv file so you can open it in Excel and graph your performance over time.