Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files411 unmodified lines41241341441541641741841942042142226 unmodified lines4494504514524534544554561 unmodified line458459460461462463464229 unmodified lines6946956966976986991 unmodified line70170270370470570670730 unmodified lines738739740741742743744508 unmodified lines12531254125512561257411 unmodified linesjournal = self._read_activity_journal()merged_trades = self._merge_activity(normalized_trades, journal["trades"])merged_orders = self._merge_activity(normalized_orders, journal["orders"])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)limits_raw = results["limits"]limits_summary = {26 unmodified lines"holdings_cost_value": holdings_cost,"holdings_pnl": holdings_pnl,"positions_pnl": positions_pnl,"live_pnl": holdings_pnl + positions_pnl,"open_positions": sum(1 for item in normalized_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,"trade_history": merged_trades[:100],"order_book": merged_orders[:100],"activity_log": {229 unmodified lines*,timeout: int,) -> dict[str, Any]: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"]},timeout=timeout,)data = self._decode_response(response)30 unmodified lines"Accept": "application/json","Content-Type": content_type,}query_params = {"sId": context["server_id"]}url = f"{context['base_url'].rstrip('/')}/{path.lstrip('/')}"if content_type == "application/x-www-form-urlencoded":508 unmodified linesseen.add(key)return mergedkotak_neo_manager = KotakNeoManager()411 unmodified lines41241341441541641741841942042142242342442542626 unmodified lines4534544554564574584594604614624631 unmodified line465466467468469470471229 unmodified lines7017027037047057067071 unmodified line70971071171271371471530 unmodified lines746747748749750751752508 unmodified lines126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470411 unmodified linesjournal = 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_positionsholdings_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 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 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": 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 Noneresponse = requests.get(f"{context['base_url'].rstrip('/')}/{path.lstrip('/')}",headers={1 unmodified line"Auth": context["edit_token"],"Accept": "application/json",},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"]} if context.get("server_id") else Noneurl = f"{context['base_url'].rstrip('/')}/{path.lstrip('/')}"if content_type == "application/x-www-form-urlencoded":508 unmodified linesseen.add(key)return mergeddef _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 Trueif abs(_first_number(item.get("pnl")) or 0.0) > 0:return Trueif abs(_first_number(item.get("average_price")) or 0.0) > 0:return Trueif abs(_first_number(item.get("last_traded_price")) or 0.0) > 0:return Truereturn Falsedef _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:continueparsed = pd.to_datetime(value, errors="coerce")if pd.isna(parsed):continueif getattr(parsed, "tzinfo", None) is None:try:parsed = parsed.tz_localize(IST)except Exception:continueelse:try:parsed = parsed.tz_convert(IST)except Exception:continuereturn parsed.to_pydatetime()return Nonedef _activity_day(self, item: dict[str, Any]) -> date | None:moment = self._activity_moment(item)return moment.date() if moment else Nonedef _trade_side_sign(self, transaction_type: Any) -> int:side = str(transaction_type or "").strip().upper()if side in {"B", "BUY"}:return 1if side in {"S", "SELL"}:return -1return 0def _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 Falsereturn quote_symbol == symbol_upper or quote_symbol == base_symbol_upperif exchange_text:for quote in quote_map.values():if str(quote.get("exchange_segment") or "").strip() != exchange_text:continueif matches(quote):return quotefor quote in quote_map.values():if matches(quote):return quotereturn {}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:continueside = 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:continuekey = (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"] += 1bucket["transaction_type"] = trade.get("transaction_type") or bucket["transaction_type"]bucket["_last_fill_price"] = pricemoment = self._activity_moment(trade)if moment and (bucket["_last_moment"] is None or moment > bucket["_last_moment"]):bucket["_last_moment"] = momentbucket["updated_at"] = moment.isoformat()remaining = quantityincoming_sign = sideopen_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"]) - matchedremaining -= matchedif 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 = Noneif open_abs_quantity > 0:average_price = sum(float(lot["remaining"]) * float(lot["price"]) for lot in open_lots) / open_abs_quantityquote = 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.0if open_quantity and average_price is not None and ltp is not None:unrealized_pnl = (ltp - average_price) * open_quantitytotal_pnl = bucket["realized_pnl"] + unrealized_pnlif abs(open_quantity) <= 1e-12 and abs(total_pnl) <= 1e-12:continuederived_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_positionskotak_neo_manager = KotakNeoManager()
kotak_neo.py+218-5