5 Python Scripts Every Crypto Investor Should Have in 2026
I've been coding for investors for a while now, and one thing is clear: most retail crypto investors are flying blind.
They check prices manually. They have no idea what their actual ROI is. They panic-sell at the worst moments.
Here are 5 Python scripts that genuinely changed how I (and dozens of others) approach crypto investing. All under 50 lines each. Zero paid libraries required.
1. Portfolio P&L Tracker
Stop using exchange apps that obscure your real gains. Build your own.
import json
from datetime import datetime
def calculate_pnl(holdings: list) -> None:
"""holdings = [{"symbol": "BTC", "bought_at": 30000, "quantity": 0.1, "current_price": 65000}]"""
total_invested = 0
total_current = 0
print(f"\n{'Symbol':<8} {'Qty':<10} {'Buy €':<10} {'Now €':<10} {'P&L €':<12} {'%':<8}")
print("-" * 60)
for h in holdings:
invested = h["bought_at"] * h["quantity"]
current = h["current_price"] * h["quantity"]
pnl = current - invested
pct = (pnl / invested) * 100
total_invested += invested
total_current += current
emoji = "🟢" if pnl > 0 else "🔴"
print(f"{h['symbol']:<8} {h['quantity']:<10.4f} {invested:<10.2f} {current:<10.2f} {emoji}{pnl:<11.2f} {pct:+.1f}%")
total_pnl = total_current - total_invested
print("-" * 60)
print(f"{'TOTAL':<8} {'':<10} {total_invested:<10.2f} {total_current:<10.2f} {'🟢' if total_pnl > 0 else '🔴'}{total_pnl:<11.2f} {(total_pnl/total_invested)*100:+.1f}%")
# Example
holdings = [
{"symbol": "BTC", "bought_at": 32000, "quantity": 0.15, "current_price": 65000},
{"symbol": "ETH", "bought_at": 1800, "quantity": 2.0, "current_price": 3200},
{"symbol": "SOL", "bought_at": 90, "quantity": 10, "current_price": 145},
]
calculate_pnl(holdings)
Output:
Symbol Qty Buy € Now € P&L € %
------------------------------------------------------------
BTC 0.1500 4800.00 9750.00 🟢4950.00 103.1%
ETH 2.0000 3600.00 6400.00 🟢2800.00 77.8%
SOL 10.0000 900.00 1450.00 🟢550.00 61.1%
------------------------------------------------------------
TOTAL 9300.00 17600.00 🟢8300.00 89.2%
2. DCA Simulator — "What If I Had Started Earlier?"
This is the script that removes regret and builds discipline.
def simulate_dca(monthly_amount: float, start_price: float,
current_price: float, months: int) -> None:
"""Simulate DCA returns over time."""
coins_total = 0
total_invested = 0
# Simulate gradual price increase
import math
price_multiplier = (current_price / start_price) ** (1 / months)
print(f"\nDCA Simulation: €{monthly_amount}/month for {months} months")
print(f"Start price: €{start_price:,.0f} → Current: €{current_price:,.0f}\n")
for month in range(1, months + 1):
price_this_month = start_price * (price_multiplier ** month)
coins_bought = monthly_amount / price_this_month
coins_total += coins_bought
total_invested += monthly_amount
if month % 6 == 0 or month == months:
current_value = coins_total * current_price
roi = ((current_value - total_invested) / total_invested) * 100
print(f"Month {month:3d}: invested €{total_invested:,.0f} → worth €{current_value:,.0f} ({roi:+.1f}% ROI)")
print(f"\n✅ Final: €{total_invested:,.0f} invested → €{coins_total * current_price:,.0f} value")
print(f" Coins accumulated: {coins_total:.6f} BTC")
simulate_dca(monthly_amount=200, start_price=28000, current_price=65000, months=24)
This script alone is worth bookmarking. Run it with your actual numbers and watch your conviction grow.
3. Crypto Price Alert (No API Key Needed)
Check prices every N minutes and get console alerts when targets are hit.
import urllib.request
import json
import time
def check_price_alert(coin_id: str, target_low: float, target_high: float,
interval_seconds: int = 300) -> None:
"""Monitor price and alert when thresholds are crossed."""
url = f"https://api.coingecko.com/api/v3/simple/price?ids={coin_id}&vs_currencies=eur"
print(f"🔔 Monitoring {coin_id.upper()} | Low: €{target_low:,} | High: €{target_high:,}")
print(f" Checking every {interval_seconds//60} minutes...\n")
while True:
try:
with urllib.request.urlopen(url, timeout=10) as response:
data = json.loads(response.read())
price = data[coin_id]["eur"]
timestamp = time.strftime("%H:%M:%S")
if price <= target_low:
print(f"🟢 [{timestamp}] BUY ALERT! {coin_id.upper()} = €{price:,.2f} (below €{target_low:,})")
elif price >= target_high:
print(f"🔴 [{timestamp}] SELL ALERT! {coin_id.upper()} = €{price:,.2f} (above €{target_high:,})")
else:
print(f" [{timestamp}] {coin_id.upper()} = €{price:,.2f} (watching...)")
except Exception as e:
print(f" Error: {e}")
time.sleep(interval_seconds)
check_price_alert("bitcoin", target_low=55000, target_high=72000, interval_seconds=300)
4. Risk/Reward Calculator
Before every trade: know your numbers. This is non-negotiable.
def calculate_risk_reward(entry: float, stop_loss: float, take_profit: float,
capital: float, risk_percent: float = 1.0) -> dict:
"""Calculate position size and R:R for any trade."""
risk_per_unit = abs(entry - stop_loss)
reward_per_unit = abs(take_profit - entry)
rr_ratio = reward_per_unit / risk_per_unit
max_risk_amount = capital * (risk_percent / 100)
position_size = max_risk_amount / risk_per_unit
position_value = position_size * entry
result = {
"entry": entry,
"stop_loss": stop_loss,
"take_profit": take_profit,
"risk_reward_ratio": rr_ratio,
"position_size": position_size,
"max_loss": max_risk_amount,
"max_profit": position_size * reward_per_unit,
}
print(f"\n📊 Trade Analysis")
print(f" Entry: €{entry:,.2f} | SL: €{stop_loss:,.2f} | TP: €{take_profit:,.2f}")
print(f" R:R Ratio: 1:{rr_ratio:.2f} {'✅ Good' if rr_ratio >= 2 else '⚠️ Consider skipping'}")
print(f" Position size: {position_size:.4f} units (€{position_value:,.2f})")
print(f" Max loss: €{max_risk_amount:.2f} | Max profit: €{result['max_profit']:.2f}")
return result
calculate_risk_reward(entry=65000, stop_loss=62000, take_profit=72000,
capital=10000, risk_percent=1.0)
Rule of thumb: Skip trades with R:R below 1:2. This one rule will save your account.
5. Monthly Performance Report Generator
Track every month. Spot patterns. Improve.
def monthly_report(trades: list) -> None:
"""trades = [{"date": "2026-01", "pnl": 450, "trades": 8, "wins": 5}]"""
print(f"\n📈 Monthly Trading Report")
print(f"{'Month':<12} {'P&L €':<12} {'Trades':<10} {'Win%':<10} {'Avg/Trade':<12}")
print("-" * 56)
total_pnl = 0
for m in trades:
win_rate = (m["wins"] / m["trades"]) * 100
avg_per_trade = m["pnl"] / m["trades"]
total_pnl += m["pnl"]
emoji = "🟢" if m["pnl"] > 0 else "🔴"
print(f"{m['date']:<12} {emoji}{m['pnl']:+.0f}€{'':<7} {m['trades']:<10} {win_rate:.0f}%{'':<6} {avg_per_trade:+.0f}€")
print("-" * 56)
print(f"{'TOTAL':<12} {'🟢' if total_pnl > 0 else '🔴'}{total_pnl:+.0f}€")
trades = [
{"date": "2026-01", "pnl": 320, "trades": 12, "wins": 8},
{"date": "2026-02", "pnl": -180, "trades": 10, "wins": 4},
{"date": "2026-03", "pnl": 650, "trades": 9, "wins": 7},
]
monthly_report(trades)
Want the Full Toolkit?
If you want a complete DCA automation system (auto-tracker, portfolio rebalancer, price alerts, and monthly PDF reports), I packaged everything into a ready-to-use Python toolkit:
👉 DCA Crypto Bot Python — Full Toolkit (€14.99)
Also check out the Trading Journal Pro in Notion (€19.99) — because code is useless without tracking your psychology too.
TL;DR
| Script | Use Case |
|---|---|
| P&L Tracker | Know your real gains |
| DCA Simulator | Build conviction with data |
| Price Alert | Never miss a target price |
| Risk/Reward Calc | Size positions correctly |
| Monthly Report | Track patterns over time |
Save this. Run these. Trade better.
Built with Python 3.10+. Zero paid dependencies. CoinGecko free API.
Top comments (0)