DEV Community

Otto
Otto

Posted on

How I Built a Python Trading Risk Calculator in 200 Lines (No Libraries)

One of the biggest mistakes beginner traders make: entering trades without calculating their position size properly.

They risk 20% of their capital on a single trade. Then they wonder why they blow their account in 3 weeks.

So I built a simple Python script that does the math automatically. No pandas. No external libraries. Pure Python stdlib.

Here is how it works.

The Core Math of Position Sizing

Before writing a single line of code, let us understand what we are calculating:

Rule #1: Risk X% of capital per trade (professional standard: 1-2%)
Rule #2: The position size is calculated from: how far your stop loss is from entry

risk_amount = capital * (risk_pct / 100)
position_value = (risk_amount * entry_price) / stop_loss_distance
position_size_units = position_value / entry_price
Enter fullscreen mode Exit fullscreen mode

That is the core. If you only remember one thing from this article, remember this formula.

Risk/Reward Ratio

sl_distance = abs(entry - stop_loss)
tp_distance = abs(take_profit - entry)
rr_ratio = tp_distance / sl_distance
Enter fullscreen mode Exit fullscreen mode

A 1:2 R/R ratio means: for every €1 you risk, you can gain €2.

With a 50% win rate and 1:2 R/R, you are profitable long-term. The math works out.

The Full Script

def calculate_position(capital, risk_pct, entry, stop_loss, take_profit, leverage=1.0):
    risk_amount = capital * (risk_pct / 100)
    sl_distance = abs(entry - stop_loss)
    tp_distance = abs(take_profit - entry)

    rr_ratio = tp_distance / sl_distance
    position_value = (risk_amount * entry) / sl_distance
    position_size = position_value / entry
    margin_required = position_value / leverage

    potential_profit = position_size * tp_distance
    potential_loss = risk_amount

    return {
        "rr_ratio": rr_ratio,
        "position_size_units": position_size,
        "position_value_eur": position_value,
        "margin_required": margin_required,
        "potential_profit": potential_profit,
        "potential_loss": potential_loss,
    }
Enter fullscreen mode Exit fullscreen mode

CLI Support with argparse

Making it work from the command line:

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("--capital", type=float)
parser.add_argument("--risk", type=float)
parser.add_argument("--entry", type=float)
parser.add_argument("--sl", type=float)
parser.add_argument("--tp", type=float)
parser.add_argument("--leverage", type=float, default=1.0)
args = parser.parse_args()
Enter fullscreen mode Exit fullscreen mode

Now you can run:

python3 risk_calculator.py --capital 10000 --risk 1 --entry 50000 --sl 48000 --tp 56000
Enter fullscreen mode Exit fullscreen mode

Output:

📐 RISK/REWARD
   Ratio R/R        : 1:3.00
   Qualité          : 🌟 EXCELLENT

📦 TAILLE DE POSITION
   Taille (unités)  : 0.050000
   Valeur position  : €2,500.00

💹 SCÉNARIOS
   Si TP atteint    : +€300.00 (+3.00% capital)
   Si SL touché     : -€100.00 (-1.0% capital)
Enter fullscreen mode Exit fullscreen mode

Quality Rating Function

def check_rr_quality(rr_ratio):
    if rr_ratio >= 3.0:
        return "EXCELLENT", "Top tier setup"
    elif rr_ratio >= 2.0:
        return "GOOD", "Valid by professional standards"
    elif rr_ratio >= 1.5:
        return "ACCEPTABLE", "Correct but try to find better"
    elif rr_ratio >= 1.0:
        return "WEAK", "Risk too high vs reward"
    else:
        return "DANGEROUS", "Do not trade this setup"
Enter fullscreen mode Exit fullscreen mode

Simple but effective. The script refuses to let you convince yourself a bad R/R is acceptable.

What I Learned Building This

  1. The math is not the hard part — calculating position size is 5 lines of code
  2. The hard part is following it — every trader knows the math, few apply it
  3. Tools create habits — using a calculator before every trade forces you to think
  4. Zero libraries = zero friction — copy-paste the file anywhere, it just works

The Bigger Picture

This script is part of a trading toolkit I am building:

  • Risk/Reward Calculator (this one) — free
  • Trading Journal Notion Template — for tracking every trade psychologically
  • DCA Tracker for crypto investors
  • Ebook on trader psychology (why you lose even when you are right)

The calculator alone will not make you profitable. But it will stop you from making the size mistake that kills accounts.


Full script with interactive mode, leverage support, and formatted output: available on Gumroad (search "Risk Calculator").

Questions? Comments? Let me know below.

Top comments (0)