Building a Crypto Trading Bot from Scratch - 12: Position Tracking
Knowing Where You Stand
After placing orders through the Trade Executor, you’d think the hard part is done. But actually, that’s when a new challenge begins: tracking your positions.
How much are you up or down on each trade? Has any position hit its stop loss? Is it time to take a profit? How much total capital do you have at risk right now?
Without a Position Manager to answer these questions, you’re flying blind. You might think you’re profitable when you’re actually down. You might miss stop losses and watch small losses become big ones.
This is what the Position Manager solves. It’s your accounting system, your P&L calculator, and your exit condition monitor, all in one.
What Is a Position?
A position represents an open trade. When you buy 0.02 BTC at $50,000, you have a long position. When you sell it (hopefully at $52,000), the position closes.
Here’s what we track for each position:
@dataclass
class Position:
position_id: str
symbol: str
strategy_name: str
side: PositionSide # LONG or SHORT
entry_price: float
quantity: float
entry_time: datetime
stop_loss: Optional[float] = None
take_profit: Optional[float] = None
unrealized_pnl: float = 0.0 # Current paper profit/loss
realized_pnl: float = 0.0 # Actual profit/loss when closed
entry_fee: float = 0.0 # Fee paid on entry
Unrealized P&L: How much you’d make/lose if you closed now (paper profit) Realized P&L: Actual profit/loss from closed positions (real money)
This distinction matters. Unrealized P&L fluctuates with the market. Realized P&L only changes when you actually close positions.
The Position Manager
Here’s the core structure:



