vortex-api 2.1.8b4__tar.gz → 2.1.8b5__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (21) hide show
  1. {vortex_api-2.1.8b4/vortex_api.egg-info → vortex_api-2.1.8b5}/PKG-INFO +1 -1
  2. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/pyproject.toml +1 -1
  3. vortex_api-2.1.8b5/vortex_api/__version__.py +1 -0
  4. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/instruments.py +25 -0
  5. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/vortex_feed.py +195 -36
  6. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5/vortex_api.egg-info}/PKG-INFO +1 -1
  7. vortex_api-2.1.8b4/vortex_api/__version__.py +0 -1
  8. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/LICENSE +0 -0
  9. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/README.md +0 -0
  10. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/setup.cfg +0 -0
  11. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/__init__.py +0 -0
  12. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/api.py +0 -0
  13. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/backtest/__init__.py +0 -0
  14. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/backtest/_backtestingpy.py +0 -0
  15. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/backtest/_backtrader.py +0 -0
  16. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/backtest/_common.py +0 -0
  17. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api/backtest/_vectorbt.py +0 -0
  18. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api.egg-info/SOURCES.txt +0 -0
  19. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api.egg-info/dependency_links.txt +0 -0
  20. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api.egg-info/requires.txt +0 -0
  21. {vortex_api-2.1.8b4 → vortex_api-2.1.8b5}/vortex_api.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vortex_api
3
- Version: 2.1.8b4
3
+ Version: 2.1.8b5
4
4
  Summary: Vortex APIs to place orders in Rupeezy application
5
5
  Author-email: "Astha Credit & Securities Pvt Ltd." <tech@rupeezy.in>
6
6
  License: MIT
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "vortex_api"
7
- version = "2.1.8b4"
7
+ version = "2.1.8b5"
8
8
  description = "Vortex APIs to place orders in Rupeezy application"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -0,0 +1 @@
1
+ __version__ = "2.1.8b5"
@@ -319,6 +319,31 @@ class InstrumentManager:
319
319
  with self._lock:
320
320
  return len(self._by_exchange_token)
321
321
 
322
+ @property
323
+ def is_loaded(self) -> bool:
324
+ """``True`` once instruments have been loaded into memory.
325
+
326
+ Useful in hot paths (e.g. the WebSocket tick parser) where a blocking
327
+ lazy-load would be unacceptable: check this first and skip enrichment
328
+ until a background ``.load()`` has populated the cache.
329
+ """
330
+ return self._loaded
331
+
332
+ def get_ticker_or_none(self, exchange: str, token: int) -> Optional[str]:
333
+ """Non-blocking variant of ``token_to_ticker``.
334
+
335
+ Returns the ticker if the manager is already loaded *and* the lookup
336
+ succeeds. Returns ``None`` if the manager hasn't loaded yet, or if the
337
+ instrument isn't known. Never raises, never triggers a network fetch.
338
+ Designed for the WebSocket tick parser.
339
+ """
340
+ if not self._loaded:
341
+ return None
342
+ key = _exchange_token_key(exchange, token)
343
+ with self._lock:
344
+ inst = self._by_exchange_token.get(key)
345
+ return inst.ticker if inst is not None else None
346
+
322
347
  # ------------------------------------------------------------- Lookups
323
348
 
324
349
  def get_by_ticker(self, ticker: str) -> Instrument:
@@ -6,6 +6,7 @@ import struct
6
6
  import logging
7
7
  import threading
8
8
  import os
9
+ import warnings
9
10
  from twisted.internet import reactor, ssl
10
11
  from twisted.python import log as twisted_log
11
12
  from twisted.internet.protocol import ReconnectingClientFactory
@@ -16,6 +17,16 @@ from .__version__ import __version__, __name__
16
17
 
17
18
  log = logging.getLogger(__name__)
18
19
 
20
+
21
+ def _warn_token_exchange_deprecated(method_name: str) -> None:
22
+ """Emit a FutureWarning when callers pass ``token``/``exchange`` instead of ``ticker``."""
23
+ warnings.warn(
24
+ f"Passing 'exchange' and 'token' to {method_name}() is deprecated and will be "
25
+ "removed in a future release. Use 'ticker' instead (e.g. ticker=\"NSE:RELIANCE\").",
26
+ FutureWarning,
27
+ stacklevel=3,
28
+ )
29
+
19
30
  class ClientProtocol(WebSocketClientProtocol):
20
31
  """
21
32
  A WebSocket client protocol that implements ping-pong keepalive.
@@ -236,7 +247,23 @@ class VortexFeed:
236
247
  _message_unsubscribe = "unsubscribe"
237
248
 
238
249
  def __init__(self, access_token: str=None, websocket_endpoint="wss://wire.rupeezy.in/ws",reconnect=True, reconnect_max_tries=RECONNECT_MAX_TRIES, reconnect_max_delay=RECONNECT_MAX_DELAY,
239
- connect_timeout=CONNECT_TIMEOUT, debug = False) -> None:
250
+ connect_timeout=CONNECT_TIMEOUT, debug = False, instruments=None) -> None:
251
+ """
252
+ Args:
253
+ instruments: Optional ``InstrumentManager``. If you don't pass one,
254
+ ``VortexFeed`` creates its own automatically — every tick
255
+ parsed from the binary feed will be tagged with a ``ticker``
256
+ field (e.g. ``"NSE:RELIANCE"``) alongside the existing
257
+ ``exchange``/``token`` fields. Pass an existing manager (e.g.
258
+ ``client.instruments``) if you want to share one cache across
259
+ the REST client and the feed.
260
+
261
+ ``connect()`` blocks until the instrument master is loaded so
262
+ every tick — including the very first one — is guaranteed to
263
+ carry a ``ticker`` field. The load is cached on disk and only
264
+ hits the network once per IST trading day, so this overhead is
265
+ near-zero on every connect after the first of the day.
266
+ """
240
267
  self._maximum_reconnect_max_tries = self.RECONNECT_MAX_TRIES
241
268
  self._minimum_reconnect_max_delay = 0
242
269
  if reconnect == False:
@@ -281,6 +308,24 @@ class VortexFeed:
281
308
  self.on_reconnect = None
282
309
  self.on_noreconnect = None
283
310
  self.on_order_update = None
311
+ if instruments is None:
312
+ # Default: every feed gets its own InstrumentManager so ticker
313
+ # enrichment "just works" without any wiring from the user. The
314
+ # underlying disk cache is process-wide, so multiple managers in
315
+ # the same process share the same master.csv on disk.
316
+ try:
317
+ from .instruments import InstrumentManager
318
+ instruments = InstrumentManager()
319
+ except Exception as exc:
320
+ # Never let an instruments-import problem break the feed.
321
+ log.debug("Could not auto-construct InstrumentManager: %s", exc)
322
+ instruments = None
323
+ self.instruments = instruments
324
+ # Flat dict of active subscriptions, keyed by the canonical identifier
325
+ # (the ``ticker`` string, or ``"<exchange>:<token>"`` for the legacy form).
326
+ # Each value is a dict carrying the original args plus the mode so that
327
+ # ``resubscribe()`` can replay each subscription exactly as the user
328
+ # originally requested it.
284
329
  self.subscribed_tokens = {}
285
330
  pass
286
331
 
@@ -311,6 +356,12 @@ class VortexFeed:
311
356
  Establish a websocket connection.
312
357
  - `disable_ssl_verification` disables building ssl context
313
358
  """
359
+ # Load the instrument master *before* opening the websocket so the
360
+ # very first tick is already eligible for ticker enrichment. The
361
+ # InstrumentManager caches on disk (1× per IST day across processes),
362
+ # so this is near-instant on every connect after the day's first.
363
+ self._preload_instruments()
364
+
314
365
  # Init WebSocket client factory
315
366
  self._create_connection(self.socket_url,
316
367
  useragent=self._user_agent())
@@ -371,50 +422,112 @@ class VortexFeed:
371
422
  if self.factory:
372
423
  self.factory.stopTrying()
373
424
 
374
- def subscribe(self, exchange: str,token: int,mode: str)->bool:
425
+ def subscribe(self, exchange: str = None, token: int = None, mode: str = None, ticker: str = None) -> bool:
375
426
  """
376
- Subscribe to a list of instrument_tokens.
377
- - `instrument_tokens` is list of instrument instrument_tokens to subscribe
378
- """
379
- try:
380
- self.ws.sendMessage(six.b(json.dumps({"message_type": self._message_subscribe, "exchange": exchange,"token": token,"mode": mode})))
427
+ Subscribe to live updates for an instrument.
381
428
 
382
- try:
383
- self.subscribed_tokens[exchange][token] = mode
384
- except KeyError:
385
- self.subscribed_tokens[exchange] = {}
386
- self.subscribed_tokens[exchange][token] = mode
429
+ Pass either ``ticker`` (e.g. ``"NSE:RELIANCE"``) or both ``exchange`` and
430
+ ``token``. The ``(exchange, token)`` form is supported for backward
431
+ compatibility but is deprecated — prefer ``ticker``.
387
432
 
433
+ Args:
434
+ exchange (str, optional): Exchange code (e.g. ``"NSE_EQ"``).
435
+ Required together with ``token`` when ``ticker`` is not supplied.
436
+ token (int, optional): Security token. Required together with
437
+ ``exchange`` when ``ticker`` is not supplied.
438
+ mode (str): Quote mode — ``"ltp"``, ``"ohlcv"``, or ``"full"``.
439
+ ticker (str, optional): Instrument ticker in the form
440
+ ``<EXCHANGE>:<SYMBOL>`` (e.g. ``"NSE:RELIANCE"``).
441
+
442
+ Raises:
443
+ ValueError: If neither ``ticker`` nor (``exchange`` and ``token``) is provided.
444
+ TypeError: If ``mode`` is missing.
445
+ """
446
+ if ticker is None and (exchange is None or token is None):
447
+ raise ValueError("Either 'ticker' or both 'exchange' and 'token' must be provided")
448
+ if mode is None:
449
+ raise TypeError("missing required argument: 'mode'")
450
+
451
+ if ticker is None:
452
+ _warn_token_exchange_deprecated("subscribe")
453
+
454
+ payload = {"message_type": self._message_subscribe, "mode": mode}
455
+ if ticker is not None:
456
+ payload["ticker"] = ticker
457
+ sub_key = ticker
458
+ record = {"ticker": ticker, "mode": mode}
459
+ else:
460
+ payload["exchange"] = exchange
461
+ payload["token"] = token
462
+ sub_key = f"{exchange}:{token}"
463
+ record = {"exchange": exchange, "token": token, "mode": mode}
464
+
465
+ try:
466
+ self.ws.sendMessage(six.b(json.dumps(payload)))
467
+ self.subscribed_tokens[sub_key] = record
388
468
  return True
389
469
  except Exception as e:
390
470
  self._close(reason="Error while subscribe: {}".format(str(e)))
391
471
  raise
392
472
 
393
- def unsubscribe(self, exchange: str,token: int)->bool:
473
+ def unsubscribe(self, exchange: str = None, token: int = None, ticker: str = None) -> bool:
394
474
  """
395
- Unsubscribe the given list of instrument_tokens.
396
- - `instrument_tokens` is list of instrument_tokens to unsubscribe.
475
+ Unsubscribe from live updates for an instrument.
476
+
477
+ Pass either ``ticker`` or both ``exchange`` and ``token`` — must match
478
+ the form originally used in ``subscribe()`` for the local subscription
479
+ record to be cleared (the server unsubscribes either way).
480
+
481
+ Args:
482
+ exchange (str, optional): Exchange code. Required together with
483
+ ``token`` when ``ticker`` is not supplied.
484
+ token (int, optional): Security token. Required together with
485
+ ``exchange`` when ``ticker`` is not supplied.
486
+ ticker (str, optional): Instrument ticker in the form
487
+ ``<EXCHANGE>:<SYMBOL>`` (e.g. ``"NSE:RELIANCE"``).
488
+
489
+ Raises:
490
+ ValueError: If neither ``ticker`` nor (``exchange`` and ``token``) is provided.
397
491
  """
398
- try:
399
- self.ws.sendMessage(six.b(json.dumps({"message_type": self._message_unsubscribe, "exchange": exchange,"token": token})))
492
+ if ticker is None and (exchange is None or token is None):
493
+ raise ValueError("Either 'ticker' or both 'exchange' and 'token' must be provided")
400
494
 
401
- try:
402
- del(self.subscribed_tokens[exchange][token])
403
- except KeyError:
404
- pass
495
+ if ticker is None:
496
+ _warn_token_exchange_deprecated("unsubscribe")
497
+
498
+ payload = {"message_type": self._message_unsubscribe}
499
+ if ticker is not None:
500
+ payload["ticker"] = ticker
501
+ sub_key = ticker
502
+ else:
503
+ payload["exchange"] = exchange
504
+ payload["token"] = token
505
+ sub_key = f"{exchange}:{token}"
405
506
 
507
+ try:
508
+ self.ws.sendMessage(six.b(json.dumps(payload)))
509
+ self.subscribed_tokens.pop(sub_key, None)
406
510
  return True
407
511
  except Exception as e:
408
512
  self._close(reason="Error while unsubscribe: {}".format(str(e)))
409
513
  raise
410
514
 
411
515
  def resubscribe(self):
412
- """Resubscribe to all current subscribed tokens."""
413
- modes = {}
516
+ """Resubscribe to all currently-tracked instruments.
414
517
 
415
- for exchange in self.subscribed_tokens:
416
- for token in self.subscribed_tokens[exchange]:
417
- self.subscribe(exchange=exchange, token=token,mode=self.subscribed_tokens[exchange][token])
518
+ Each subscription is replayed in the exact form (ticker or
519
+ exchange/token) the user originally used.
520
+ """
521
+ # Snapshot first because subscribe() mutates the dict.
522
+ for record in list(self.subscribed_tokens.values()):
523
+ if "ticker" in record:
524
+ self.subscribe(ticker=record["ticker"], mode=record["mode"])
525
+ else:
526
+ self.subscribe(
527
+ exchange=record["exchange"],
528
+ token=record["token"],
529
+ mode=record["mode"],
530
+ )
418
531
 
419
532
  def _on_connect(self, ws, response):
420
533
  self.ws = ws
@@ -482,6 +595,52 @@ class VortexFeed:
482
595
  if self.on_order_update and data.get("type") and data.get("data"):
483
596
  self.on_order_update(self, data)
484
597
 
598
+ def _preload_instruments(self) -> None:
599
+ """Load the InstrumentManager synchronously before the WS connects.
600
+
601
+ This is what guarantees that ticker enrichment is available on the
602
+ very first tick. The InstrumentManager has an in-memory + disk cache,
603
+ so this call returns instantly on every connect after the day's first.
604
+
605
+ Failure modes (network down, read-only filesystem, etc.) are logged
606
+ but do not block the websocket — the feed will simply emit ticks
607
+ with ``exchange``/``token`` only until a future ``load()`` succeeds.
608
+ """
609
+ mgr = self.instruments
610
+ if mgr is None or mgr.is_loaded:
611
+ return
612
+ try:
613
+ mgr.load()
614
+ except Exception as exc:
615
+ log.warning(
616
+ "Instrument preload failed; tick ticker enrichment will be "
617
+ "skipped until a subsequent successful load. Error: %s",
618
+ exc,
619
+ )
620
+
621
+ def _enrich_with_ticker(self, record: dict) -> dict:
622
+ """Add a ``ticker`` field to a tick record.
623
+
624
+ The binary tick wire format carries only ``exchange`` + ``token`` — the
625
+ server never sends a ticker string. This method resolves the ticker
626
+ client-side via the attached ``InstrumentManager``, so users who
627
+ subscribed by ticker get tick callbacks tagged with the same ticker
628
+ without any wire-format change.
629
+
630
+ Non-blocking and silent on failure — a missing instrument or unloaded
631
+ manager just leaves the record alone (no exception, no lazy-load).
632
+ """
633
+ mgr = self.instruments
634
+ if mgr is None:
635
+ return record
636
+ try:
637
+ ticker = mgr.get_ticker_or_none(record["exchange"], record["token"])
638
+ except Exception:
639
+ return record
640
+ if ticker:
641
+ record["ticker"] = ticker
642
+ return record
643
+
485
644
  def _parse_binary(self, bin):
486
645
  """Parse binary data to a (list of) ticks structure."""
487
646
  packets = self._split_packets(bin) # split data to individual ticks packet
@@ -492,17 +651,17 @@ class VortexFeed:
492
651
  format_string = "<10sid"
493
652
  exchange, token, last_trade_price = struct.unpack(format_string, packet)
494
653
  exchange = exchange.decode("utf-8").rstrip('\x00')
495
- data.append({
496
- "exchange" : exchange,
654
+ data.append(self._enrich_with_ticker({
655
+ "exchange" : exchange,
497
656
  "token": token,
498
657
  "last_trade_price": last_trade_price
499
- })
500
- elif len(packet) == 62:
658
+ }))
659
+ elif len(packet) == 62:
501
660
  format_string = "<10sididdddi"
502
661
  exchange, token, last_trade_price, last_trade_time, open_price, high_price, low_price, close_price, volume = struct.unpack(format_string, packet)
503
662
  exchange = exchange.decode("utf-8").rstrip('\x00')
504
- data.append({
505
- "exchange" : exchange,
663
+ data.append(self._enrich_with_ticker({
664
+ "exchange" : exchange,
506
665
  "token": token,
507
666
  "last_trade_price": last_trade_price,
508
667
  "last_trade_time": last_trade_time,
@@ -511,13 +670,13 @@ class VortexFeed:
511
670
  "low_price": low_price,
512
671
  "close_price": close_price,
513
672
  "volume": volume
514
- })
673
+ }))
515
674
  elif len(packet) == 266:
516
675
  format_string = "<10sididdddiiidqqidiidiidiidiidiidiidiidiidiidiiii"
517
676
  unpacked_data = struct.unpack(format_string, packet)
518
677
  exchange = unpacked_data[0].decode("utf-8").rstrip('\x00')
519
- data.append({
520
- "exchange" : exchange,
678
+ data.append(self._enrich_with_ticker({
679
+ "exchange" : exchange,
521
680
  "token": unpacked_data[1],
522
681
  "last_trade_price": unpacked_data[2],
523
682
  "last_trade_time": unpacked_data[3],
@@ -579,7 +738,7 @@ class VortexFeed:
579
738
  },
580
739
  "dpr_high": unpacked_data[45],
581
740
  "dpr_low": unpacked_data[46],
582
- })
741
+ }))
583
742
  return data
584
743
 
585
744
  def _unpack_int(self, bin, start, end, byte_format="H"):
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vortex_api
3
- Version: 2.1.8b4
3
+ Version: 2.1.8b5
4
4
  Summary: Vortex APIs to place orders in Rupeezy application
5
5
  Author-email: "Astha Credit & Securities Pvt Ltd." <tech@rupeezy.in>
6
6
  License: MIT
@@ -1 +0,0 @@
1
- __version__ = "2.1.8b4"
File without changes
File without changes
File without changes