2. **Code**:
python
from ib_insync import IB
# Connect to TWS or IBKR Gateway
ib = IB()
ib.connect('127.0.0.1', 7497, clientId=1) # Adjust port if using IBKR Gateway
# Fetch Positions
positions = ib.positions()
# Calculate MTM
total_mtm = 0
for pos in positions:
contract = pos.contract
avg_cost = pos.avgCost
quantity = pos.position
# Fetch Market Price
market_data = ib.reqMktData(contract, '', False, False)
ib.sleep(2) # Wait for market data to be retrieved
current_price = market_data.last if market_data.last else market_data.close
# Calculate MTM
mtm = (current_price - avg_cost) * quantity
total_mtm += mtm
print(f"Symbol: {contract.localSymbol}, MTM: {mtm:.2f}")
print(f"Total MTM: {total_mtm:.2f}")
# Disconnect
ib.disconnect()
---
### Key Points:
1. **Port & Client ID**:
- TWS default port:
7497 (for live) or
7496 (for paper trading).
- Use unique
clientId if running multiple connections.
2. **API Access**:
- Enable API settings in TWS under *File > Global Configuration > API > Settings*.
- Set trusted IPs and ensure the API is active.
3. **Handling Market Data**:
- The example uses
ib.reqMktData()` for the latest price. Adjust based on your subscription or latency requirements.
4. **Error Handling**:
- Add error handling for network issues, invalid symbols, or missing market data.
---
This code will calculate MTM for all open positions.