Position Sizing & Risk Management¶
Fixed-fractional lot sizing and a hard max-loss guardrail.
Part 15 of 20 in the ServLoci algo/options trading notebook series — full index in notebooks/README.md.
Setup¶
# Get your dedicated static IPv6 + SOCKS5 credentials free:
# https://comm.servloci.in/register (or /auth/google?free=1 for an instant trial)
# Your api_key / api_secret pair shows up in the portal after signup:
# https://comm.servloci.in/user
!pip install -q "requests[socks]"
!curl -sL https://comm.servloci.in/sdk/servloci.py -o servloci.py
import os
from servloci import ServLoci
SERVLOCI_API_KEY = os.environ.get("SERVLOCI_API_KEY", "dhan:1000000001") # broker:client_id
SERVLOCI_API_SECRET = os.environ.get("SERVLOCI_API_SECRET", "") # from the portal — leave blank to run this notebook in demo mode
sl = None
if SERVLOCI_API_SECRET:
sl = ServLoci(api_key=SERVLOCI_API_KEY, api_secret=SERVLOCI_API_SECRET)
print("ServLoci configured:", sl.host, sl.port)
else:
print("SERVLOCI_API_SECRET not set — running in demo mode (no live proxy calls).")
Fixed-fractional sizing + a hard max-loss guardrail — feed max_loss_per_lot from notebook 07/10's max_profit_loss() output for a real strategy.
def position_size(capital, risk_pct, max_loss_per_lot):
"""How many lots keep max loss within risk_pct of capital."""
if max_loss_per_lot <= 0:
return 0
return max(int((capital * risk_pct) // max_loss_per_lot), 0)
capital = 500_000
risk_pct = 0.02 # risk 2% of capital per trade
max_loss_per_lot = 4500 # from max_profit_loss()["maxLoss"] for one lot, notebooks 07/10
lots = position_size(capital, risk_pct, abs(max_loss_per_lot))
print(f"Capital Rs.{capital:,} at {risk_pct:.0%} risk -> {lots} lot(s), max loss Rs.{lots * abs(max_loss_per_lot):,}")
def guard_max_loss(strategy_max_loss, capital, hard_cap_pct=0.05):
if abs(strategy_max_loss) > capital * hard_cap_pct:
raise ValueError(f"strategy max loss {strategy_max_loss} exceeds hard cap {capital * hard_cap_pct}")
return True
guard_max_loss(lots * abs(max_loss_per_lot), capital)
« Previous: Backtest: Weekly Short Straddle
Next: Order Management System »
Try the concepts above interactively: Options Strategy Builder · Docs · Get your static IP