Back
Learning Hub / Python for Algo Trading / Lesson 1 Phase 1 of 6
Python for Algo Trading · Phase 1

Variables & Data Types

Every trading system starts with data. Learn how Python stores prices, quantities, symbols and signals — and write your first real P&L calculator for NIFTY futures.

Lesson 1 of 9 ~30 min Beginner NSE / BSE examples
Lesson 1 of 9 — Variables & Data Types 11% complete
LESSON 01 · SECTION 1
What is a Variable?
beginner

Think of a variable as a labelled box that holds a value. In trading, every number you work with — a stock price, a trade quantity, a P&L figure — needs to be stored somewhere so your program can use it. Python lets you create a variable with a simple name = value assignment.

📦
Variable = labelled box
A name pointing to a value in memory. Write it as name = value — no type declaration needed.
🔄
Values can change
That's why they're called "variables". Your ltp updates every second; your variable can too.
📜
Rules for names
Use letters, numbers (not first), underscores. Lowercase with underscores is the Python convention: entry_price.
🚫
Reserved keywords
Cannot use Python keywords as names: for, if, return, True, class, etc.
your_first_variables.py python
# ── Creating variables ──────────────────────────
symbol      = "NIFTY25MAYFUT"   # str  – stock / contract symbol
entry_price = 24350.50           # float – entry price in ₹
quantity    = 50                 # int  – lot size
is_long     = True               # bool – direction of trade

print("Symbol  :", symbol)
print("Entry   :", entry_price)
print("Qty     :", quantity)
print("Long?   :", is_long)
Output
Symbol  : NIFTY25MAYFUT
Entry   : 24350.5
Qty     : 50
Long?   : True
💡 Trading Pro Tip
Use descriptive names. p is bad; entry_price is perfect. When debugging at midnight, you'll thank yourself.

Section 2
The 5 Core Data Types

Python automatically detects the type of a variable from the value you assign. As a trader-programmer, you'll use these five constantly:

intInteger50, -10, 0
floatDecimal24350.50, 0.01
strString"NIFTY", "BUY"
boolBooleanTrue, False
NoneNo valueNone
TypeTrading UseExampleCheck with
intQuantity, lot size, candle indexquantity = 50type(quantity) → int
floatPrice, P&L, percentageprice = 24350.50type(price) → float
strSymbol, signal text, broker namesym = "RELIANCE"type(sym) → str
boolSignal on/off, kill switch, position activeis_long = Truetype(is_long) → bool
NoneUnset stop loss, missing datastop_loss = Nonestop_loss is None
🎯 Why This Matters for Trading
When you fetch live data from a broker API, prices often come back as str instead of float. If you don't convert them, your P&L calculation will crash. Always check types when working with external data!

Section 3
Type Conversion (Critical for API Data)

When your broker API returns "24350.50" instead of 24350.50, you need to convert it before doing any maths.

int(x)
Converts to integer. Use for quantity, index numbers.
float(x)
Converts to decimal. Use for prices, P&L.
str(x)
Converts to text. Use when building log messages or API payloads.
bool(x)
Converts to True/False. 0 → False, any non-zero → True.
type_conversion.pypython
# ── Broker API returns everything as strings ──
api_ltp    = "24380.25"
api_qty    = "50"
api_signal = "1"

# ── Convert before using ──────────────────────
ltp    = float(api_ltp)
qty    = int(api_qty)
signal = bool(int(api_signal))

entry  = 24350.50
pnl    = (ltp - entry) * qty

print(f"LTP     : {ltp}")
print(f"Qty     : {qty}")
print(f"Signal  : {signal}")
print(f"P&L     : ₹{pnl}")
Output
LTP     : 24380.25
Qty     : 50
Signal  : True
P&L     : ₹1487.5
What happens if you skip conversion
TypeError: unsupported operand type(s) for -: 'str' and 'float'
# ltp is still "24380.25" (string) — Python can't do maths on text!
⚠️ Common Mistake
Never skip type conversion on API data. Most order placement bugs for Indian traders happen because price or quantity values are strings from JSON and haven't been converted to float / int.

Section 4
Arithmetic with Prices — NIFTY P&L Calculator
+ Add
target = entry + pts
- Subtract
pnl = exit - entry
* Multiply
total = pts * qty
/ Divide
pct = pnl / capital * 100
// Floor div
lots = capital // margin
% Modulo
Remainder; candle numbering
nifty_pnl_calculator.pypython
# ══ NIFTY FUTURES — P&L CALCULATOR ═══════════════════
symbol        = "NIFTY25MAYFUT"
entry_price   = 24350.50
exit_price    = 24420.75
quantity      = 50
brokerage     = 20.0
capital       = 500000.0

pnl_per_unit  = exit_price - entry_price
gross_pnl     = pnl_per_unit * quantity
net_pnl       = gross_pnl - (brokerage * 2)
return_pct    = (net_pnl / capital) * 100
stop_loss     = entry_price - 40
target_price  = entry_price + 80
risk_reward   = 80 / 40

print(f"Gross P&L : ₹{gross_pnl}")
print(f"Net P&L   : ₹{net_pnl}")
print(f"Return    : {return_pct:.2f}%")
print(f"Stop Loss : ₹{stop_loss}")
print(f"Target    : ₹{target_price}")
print(f"R:R Ratio : 1 : {risk_reward}")
Output
Gross P&L : ₹3512.5
Net P&L   : ₹3472.5
Return    : 0.69%
Stop Loss : ₹24310.5
Target    : ₹24430.5
R:R Ratio : 1 : 2.0
💡 The :.2f Format Trick
Inside f-strings, :.2f rounds to 2 decimal places. Use :, for comma-separated thousands like ₹3,472.50.

Section 5
F-Strings — Your Best Friend for Trade Logging
fstring_examples.pypython
# ── F-string formatting examples ───────────────────
symbol  = "BANKNIFTY25MAYFUT"
price   = 52145.50
qty     = 15
pnl     = -3250.75
capital = 1000000

print(f"Order: BUY {qty} lots of {symbol} @ ₹{price}")
print(f"P&L: ₹{pnl:.2f}")
print(f"Capital: ₹{capital:,}")
print(f"Result: {'PROFIT ✓' if pnl > 0 else 'LOSS ✗'}")
Output
Order: BUY 15 lots of BANKNIFTY25MAYFUT @ ₹52145.5
P&L: ₹-3250.75
Capital: ₹1,000,000
Result: LOSS ✗

Section 6 · Practical
Building a Real Trade Journal Entry
trade_journal_entry.pypython
# ══ TRADE JOURNAL ENTRY — RELIANCE ════════════════════
trade_id      = "TXN-20250404-001"
symbol        = "RELIANCE"
side          = "BUY"
entry_price   = 2985.50
exit_price    = 3034.75
quantity      = 100
brokerage     = 40.0
stt           = 0.025

gross_pnl     = (exit_price - entry_price) * quantity
stt_amount    = (exit_price * quantity * stt) / 100
net_pnl       = gross_pnl - brokerage - stt_amount
result_tag    = "WIN" if net_pnl > 0 else "LOSS"

print(f"Trade ID  : {trade_id}")
print(f"Symbol    : {symbol}")
print(f"Side      : {side}")
print(f"Entry     : ₹{entry_price}")
print(f"Exit      : ₹{exit_price}")
print("─" * 36)
print(f"Gross P&L : ₹{gross_pnl:,.2f}")
print(f"Net P&L   : ₹{net_pnl:,.2f}")
print(f"Result    : [{result_tag}]")
Output
Trade ID  : TXN-20250404-001
Symbol    : RELIANCE
Side      : BUY
Entry     : ₹2985.5
Exit      : ₹3034.75
────────────────────────────────────
Gross P&L : ₹4,925.00
Net P&L   : ₹4,884.24
Result    : [WIN]

Section 7 · Quiz
Test Your Understanding
QUIZ 1 of 3
What data type should you use to store the price 24350.50?
A int
B float
C str
D bool
QUIZ 2 of 3
A broker API returns qty = "50" as a string. What converts it to an integer?
A float(qty)
B int(qty)
C str(qty)
D bool(qty)
QUIZ 3 of 3
Which f-string formats pnl = 3472.5 as ₹3,472.50?
A f"₹{pnl:.2}"
B f"₹{pnl:2f}"
C f"₹{pnl:,.2f}"
D f"₹{pnl:,2}"

Section 8 · Exercises
Practise These Yourself
EXERCISE 1 — Easy
Basic Trade Setup
Create variables for: broker name, capital (₹5,00,000), risk per trade (1%). Calculate max loss per trade. Print a formatted summary.
Hint: max_loss = capital × (risk_pct / 100)
EXERCISE 2 — Medium
BankNifty P&L Calculator
Build a P&L calculator for BankNifty: entry (51,200), exit (51,850), lot size (15), brokerage (₹40). Calculate gross P&L, net P&L, stop loss (−100 pts), target (200 pts), and R:R ratio.
EXERCISE 3 — Challenge
Multi-Stock Watchlist
Create variables for 3 NSE stocks. For each store: symbol, ltp, prev_close. Calculate change_pct = ((ltp - prev_close) / prev_close) * 100. Print a formatted table with all 3 using f-string padding.

Lesson Summary
What You Covered in Lesson 1
  • Variables — how to store and name trading data in Python
  • 5 data typesint, float, str, bool, None and when to use each
  • Type conversion — critical for broker API data (int(), float(), str())
  • Arithmetic operators+ - * / // % for P&L calculations
  • F-strings — embed variables, format decimals, add comma separators
  • Real application — NIFTY P&L calculator + RELIANCE trade journal entry
🚀 Up Next — Lesson 2
In Lesson 2 you'll learn If / Else Conditions — the logic engine of every trading strategy. You'll build a signal generator checking VWAP, RSI and stop-loss conditions, just like a real algo.
← Back to Hub