Upload 2 files
Browse files411 unmodified lines41241341441541641741841942041942142242342442542626 unmodified lines4534544554564574584594534604614624631 unmodified line465466467461468469470471229 unmodified lines7017027037047057067071 unmodified line70971071170471271371471530 unmodified lines746747748741749750751752508 unmodified lines126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470411 unmodified lines journal = self._read_activity_journal() merged_trades = self._merge_activity(normalized_trades, journal["trades"]) merged_orders = self._merge_activity(normalized_orders, journal["orders"]) derived_positions = self._derive_positions_from_trades(merged_trades, quote_map) effective_positions = normalized_positions if self._positions_are_meaningful(normalized_positions) else derived_positions
holdings_market_value = sum(item["market_value"] or 0.0 for item in normalized_holdings) holdings_cost = sum(item["cost_value"] or 0.0 for item in normalized_holdings) holdings_pnl = sum(item["pnl"] or 0.0 for item in normalized_holdings) positions_pnl = sum(item["pnl"] or 0.0 for item in normalized_positions) positions_pnl = sum(item["pnl"] or 0.0 for item in effective_positions) positions_realized_pnl = sum(item.get("realized_pnl") or 0.0 for item in effective_positions) positions_unrealized_pnl = sum(item.get("unrealized_pnl") or 0.0 for item in effective_positions)
limits_raw = results["limits"] limits_summary = {26 unmodified lines "holdings_cost_value": holdings_cost, "holdings_pnl": holdings_pnl, "positions_pnl": positions_pnl, "positions_realized_pnl": positions_realized_pnl, "positions_unrealized_pnl": positions_unrealized_pnl, "live_pnl": holdings_pnl + positions_pnl, "positions_count": len(effective_positions), "open_positions": sum(1 for item in normalized_positions if item["net_quantity"]), "open_positions": sum(1 for item in effective_positions if item["net_quantity"]), "holdings_count": len(normalized_holdings), "orders_count": len(merged_orders), "trades_count": len(merged_trades),1 unmodified line "limits_summary": limits_summary, "limits_raw": limits_raw, "holdings": normalized_holdings, "positions": normalized_positions, "positions": effective_positions, "trade_history": merged_trades[:100], "order_book": merged_orders[:100], "activity_log": {229 unmodified lines *, timeout: int, ) -> dict[str, Any]: query_params = {"sId": context["server_id"]} if context.get("server_id") else None response = requests.get( f"{context['base_url'].rstrip('/')}/{path.lstrip('/')}", headers={1 unmodified line "Auth": context["edit_token"], "Accept": "application/json", }, params={"sId": context["server_id"]}, params=query_params, timeout=timeout, ) data = self._decode_response(response)30 unmodified lines "Accept": "application/json", "Content-Type": content_type, } query_params = {"sId": context["server_id"]} query_params = {"sId": context["server_id"]} if context.get("server_id") else None url = f"{context['base_url'].rstrip('/')}/{path.lstrip('/')}"
if content_type == "application/x-www-form-urlencoded":508 unmodified lines seen.add(key) return merged
def _positions_are_meaningful(self, positions: list[dict[str, Any]]) -> bool: for item in positions: if abs(_first_number(item.get("net_quantity")) or 0.0) > 0: return True if abs(_first_number(item.get("pnl")) or 0.0) > 0: return True if abs(_first_number(item.get("average_price")) or 0.0) > 0: return True if abs(_first_number(item.get("last_traded_price")) or 0.0) > 0: return True return False
def _activity_moment(self, item: dict[str, Any]) -> datetime | None: for field in ("trade_time", "captured_at", "order_time", "updated_at"): value = item.get(field) if not value: continue parsed = pd.to_datetime(value, errors="coerce") if pd.isna(parsed): continue if getattr(parsed, "tzinfo", None) is None: try: parsed = parsed.tz_localize(IST) except Exception: continue else: try: parsed = parsed.tz_convert(IST) except Exception: continue return parsed.to_pydatetime() return None
def _activity_day(self, item: dict[str, Any]) -> date | None: moment = self._activity_moment(item) return moment.date() if moment else None
def _trade_side_sign(self, transaction_type: Any) -> int: side = str(transaction_type or "").strip().upper() if side in {"B", "BUY"}: return 1 if side in {"S", "SELL"}: return -1 return 0
def _quote_for_symbol( self, quote_map: dict[str, dict[str, Any]], *, exchange_segment: str | None, symbol: str | None, ) -> dict[str, Any]: symbol_text = str(symbol or "").strip() if not symbol_text: return {} exchange_text = str(exchange_segment or "").strip() symbol_upper = symbol_text.upper() base_symbol_upper = symbol_upper.split("-")[0]
def matches(quote: dict[str, Any]) -> bool: quote_symbol = str(quote.get("trading_symbol") or "").strip().upper() if not quote_symbol: return False return quote_symbol == symbol_upper or quote_symbol == base_symbol_upper
if exchange_text: for quote in quote_map.values(): if str(quote.get("exchange_segment") or "").strip() != exchange_text: continue if matches(quote): return quote
for quote in quote_map.values(): if matches(quote): return quote return {}
def _derive_positions_from_trades( self, trades: list[dict[str, Any]], quote_map: dict[str, dict[str, Any]], ) -> list[dict[str, Any]]: today = datetime.now(IST).date() buckets: dict[tuple[str, str], dict[str, Any]] = {}
ordered_trades = sorted( trades, key=lambda item: self._activity_moment(item) or datetime.min.replace(tzinfo=IST), )
for trade in ordered_trades: trade_day = self._activity_day(trade) if trade_day is not None and trade_day != today: continue
side = self._trade_side_sign(trade.get("transaction_type")) quantity = abs(_first_number(trade.get("quantity")) or 0.0) price = _first_number(trade.get("price"), trade.get("average_price")) symbol = _first_text(trade.get("trading_symbol"), trade.get("symbol")) exchange = _first_text(trade.get("exchange_segment")) if not side or quantity <= 0 or price is None or not symbol: continue
key = (exchange or "", symbol.upper()) bucket = buckets.setdefault( key, { "symbol": _first_text(trade.get("symbol"), trade.get("trading_symbol")), "trading_symbol": symbol, "exchange_segment": exchange, "instrument_token": None, "product": _first_text(trade.get("product")), "transaction_type": None, "net_quantity": 0.0, "average_price": None, "last_traded_price": None, "pnl": 0.0, "realized_pnl": 0.0, "unrealized_pnl": 0.0, "multiplier": 1.0, "updated_at": None, "trade_count": 0, "_open_lots": [], "_last_fill_price": None, "_last_moment": None, }, )
bucket["trade_count"] += 1 bucket["transaction_type"] = trade.get("transaction_type") or bucket["transaction_type"] bucket["_last_fill_price"] = price moment = self._activity_moment(trade) if moment and (bucket["_last_moment"] is None or moment > bucket["_last_moment"]): bucket["_last_moment"] = moment bucket["updated_at"] = moment.isoformat()
remaining = quantity incoming_sign = side open_lots: list[dict[str, float]] = bucket["_open_lots"]
while remaining > 0 and open_lots and int(open_lots[0]["sign"]) != incoming_sign: lot = open_lots[0] matched = min(float(lot["remaining"]), remaining) bucket["realized_pnl"] += (price - float(lot["price"])) * matched * int(lot["sign"]) lot["remaining"] = float(lot["remaining"]) - matched remaining -= matched if lot["remaining"] <= 1e-12: open_lots.pop(0)
if remaining > 0: open_lots.append({ "sign": float(incoming_sign), "remaining": float(remaining), "price": float(price), })
derived_positions: list[dict[str, Any]] = [] for bucket in buckets.values(): open_lots = bucket.pop("_open_lots") open_quantity = sum(float(lot["sign"]) * float(lot["remaining"]) for lot in open_lots) open_abs_quantity = sum(float(lot["remaining"]) for lot in open_lots) average_price = None if open_abs_quantity > 0: average_price = sum(float(lot["remaining"]) * float(lot["price"]) for lot in open_lots) / open_abs_quantity
quote = self._quote_for_symbol( quote_map, exchange_segment=bucket["exchange_segment"], symbol=bucket["trading_symbol"], ) ltp = _first_number(quote.get("last_traded_price")) if ltp is None: ltp = _first_number(bucket["_last_fill_price"])
unrealized_pnl = 0.0 if open_quantity and average_price is not None and ltp is not None: unrealized_pnl = (ltp - average_price) * open_quantity
total_pnl = bucket["realized_pnl"] + unrealized_pnl if abs(open_quantity) <= 1e-12 and abs(total_pnl) <= 1e-12: continue
derived_positions.append( { "order_no": None, "symbol": bucket["symbol"], "trading_symbol": bucket["trading_symbol"], "exchange_segment": bucket["exchange_segment"], "instrument_token": _first_text(bucket["instrument_token"], quote.get("instrument_token")), "product": bucket["product"], "transaction_type": bucket["transaction_type"], "net_quantity": open_quantity, "average_price": average_price, "last_traded_price": ltp, "pnl": total_pnl, "realized_pnl": bucket["realized_pnl"], "unrealized_pnl": unrealized_pnl, "multiplier": bucket["multiplier"], "updated_at": bucket["updated_at"], } )
derived_positions.sort(key=lambda item: str(item.get("updated_at") or ""), reverse=True) return derived_positions
kotak_neo_manager = KotakNeoManager()kotak_neo.py+218-5