vortex-api 2.1.7__tar.gz → 2.1.8b2__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.7/vortex_api.egg-info → vortex_api-2.1.8b2}/PKG-INFO +1 -1
  2. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/pyproject.toml +1 -1
  3. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/__init__.py +2 -1
  4. vortex_api-2.1.8b2/vortex_api/__version__.py +1 -0
  5. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/api.py +139 -51
  6. vortex_api-2.1.8b2/vortex_api/instruments.py +478 -0
  7. {vortex_api-2.1.7 → vortex_api-2.1.8b2/vortex_api.egg-info}/PKG-INFO +1 -1
  8. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api.egg-info/SOURCES.txt +1 -0
  9. vortex_api-2.1.7/vortex_api/__version__.py +0 -1
  10. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/LICENSE +0 -0
  11. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/README.md +0 -0
  12. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/setup.cfg +0 -0
  13. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/backtest/__init__.py +0 -0
  14. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/backtest/_backtestingpy.py +0 -0
  15. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/backtest/_backtrader.py +0 -0
  16. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/backtest/_common.py +0 -0
  17. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/backtest/_vectorbt.py +0 -0
  18. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api/vortex_feed.py +0 -0
  19. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api.egg-info/dependency_links.txt +0 -0
  20. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/vortex_api.egg-info/requires.txt +0 -0
  21. {vortex_api-2.1.7 → vortex_api-2.1.8b2}/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.7
3
+ Version: 2.1.8b2
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.7"
7
+ version = "2.1.8b2"
8
8
  description = "Vortex APIs to place orders in Rupeezy application"
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
@@ -35,4 +35,5 @@ Getting started
35
35
  from __future__ import unicode_literals, absolute_import
36
36
  from vortex_api.api import VortexAPI,Constants
37
37
  from vortex_api.vortex_feed import VortexFeed
38
- __all__ = [VortexAPI,Constants,VortexFeed]
38
+ from vortex_api.instruments import InstrumentManager, Instrument, InstrumentNotFound
39
+ __all__ = [VortexAPI,Constants,VortexFeed,InstrumentManager,Instrument,InstrumentNotFound]
@@ -0,0 +1 @@
1
+ __version__ = "2.1.8b2"
@@ -2,11 +2,22 @@ import requests
2
2
  import csv
3
3
  import datetime
4
4
  import logging
5
+ import warnings
5
6
  from enum import Enum
6
7
  import inspect
7
8
  import wrapt
8
9
  import hashlib
9
10
  import os
11
+
12
+
13
+ def _warn_token_exchange_deprecated(method_name: str) -> None:
14
+ """Emit a FutureWarning when callers pass ``token``/``exchange`` instead of ``ticker``."""
15
+ warnings.warn(
16
+ f"Passing 'exchange' and 'token' to {method_name}() is deprecated and will be "
17
+ "removed in a future release. Use 'ticker' instead (e.g. ticker=\"NSE:RELIANCE\").",
18
+ FutureWarning,
19
+ stacklevel=3,
20
+ )
10
21
  class Constants:
11
22
  """
12
23
  Constants used in the API
@@ -194,6 +205,22 @@ class VortexAPI:
194
205
  self.enable_logging = enable_logging
195
206
  if self.enable_logging:
196
207
  logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
208
+
209
+ self._instruments = None # lazily constructed InstrumentManager
210
+
211
+ @property
212
+ def instruments(self):
213
+ """Lazy ``InstrumentManager`` for this client.
214
+
215
+ The first access constructs the manager but does **not** download
216
+ ``master.csv``; the download happens on the first lookup (or on an
217
+ explicit ``.load()`` call) and is cached in memory and on disk so
218
+ subsequent script runs hit the network at most once per IST trading day.
219
+ """
220
+ if self._instruments is None:
221
+ from vortex_api.instruments import InstrumentManager
222
+ self._instruments = InstrumentManager()
223
+ return self._instruments
197
224
 
198
225
  def _make_api_request(self, method: str, endpoint: str, data: dict = None, params=None) -> dict:
199
226
  """
@@ -298,8 +325,8 @@ class VortexAPI:
298
325
  my_list = list(cr)
299
326
  return my_list
300
327
 
301
- def place_order(self,exchange: Constants.ExchangeTypes, token: int, transaction_type: Constants.TransactionSides, product: Constants.ProductTypes, variety: Constants.VarietyTypes,
302
- quantity: int, price: float, trigger_price: float, disclosed_quantity: int, validity: Constants.ValidityTypes) -> dict:
328
+ def place_order(self, exchange: Constants.ExchangeTypes = None, token: int = None, transaction_type: Constants.TransactionSides = None, product: Constants.ProductTypes = None, variety: Constants.VarietyTypes = None,
329
+ quantity: int = None, price: float = None, trigger_price: float = None, disclosed_quantity: int = None, validity: Constants.ValidityTypes = None, ticker: str = None) -> dict:
303
330
  """
304
331
  Place an order for a specific security
305
332
 
@@ -307,44 +334,62 @@ class VortexAPI:
307
334
  https://vortex.rupeezy.in/docs/latest/order/#placing-an-order
308
335
 
309
336
  Args:
310
- exchange (Constants.ExchangeTypes): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO]
311
- token (int): Security token of the scrip. It can be found in the scripmaster file
337
+ exchange (Constants.ExchangeTypes, optional): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO].
338
+ Required together with ``token`` when ``ticker`` is not supplied.
339
+ token (int, optional): Security token of the scrip. It can be found in the scripmaster file.
340
+ Required together with ``exchange`` when ``ticker`` is not supplied.
312
341
  transaction_type (Constants.TransactionSides): Possible values: [BUY, SELL]
313
342
  product (Constants.ProductTypes): Possible values: [INTRADAY, DELIVERY, MTF]. MTF product can only be used in NSE_EQ exchange.
314
- variety (Constants.VarietyTypes): Possible values: [RL, RL-MKT, SL, SL-MKT]. RL means regular orders, SL means Stop Loss order.
343
+ variety (Constants.VarietyTypes): Possible values: [RL, RL-MKT, SL, SL-MKT]. RL means regular orders, SL means Stop Loss order.
315
344
  MKT means that the trade will happen at market price
316
- quantity (int): For exchange NSE_FO, if you want to trade in 2 lots and lot size is 50, you should pass 100.
317
- In all other exchanges, you should pass just the number of lots. For example, in MCX_FO,
345
+ quantity (int): For exchange NSE_FO, if you want to trade in 2 lots and lot size is 50, you should pass 100.
346
+ In all other exchanges, you should pass just the number of lots. For example, in MCX_FO,
318
347
  if you want to trade 5 lots, you should pass just 5.
319
- price (float): Price should be an integer multiple of Tick Size. For example, IDEA's tick size is 0.05.
320
- So the price entered can be 9.5 or 9.65. It cannot be 9.67.
348
+ price (float): Price should be an integer multiple of Tick Size. For example, IDEA's tick size is 0.05.
349
+ So the price entered can be 9.5 or 9.65. It cannot be 9.67.
321
350
  In case of market orders, you should send the Last Trade Price received from the Quote API or Websocket API
322
- trigger_price (float): To be used for Stop loss orders. For BUY side SL orders, trigger_price should be
351
+ trigger_price (float): To be used for Stop loss orders. For BUY side SL orders, trigger_price should be
323
352
  lesser than price. for SELL side SL orders, trigger_price should be greater than price.
324
353
  disclosed_quantity (int): Can be any number lesser than or equal to quantity, including 0
325
- validity (Constants.ValidityTypes): Can be DAY for orders which are valid throughout the day, or IOC.
354
+ validity (Constants.ValidityTypes): Can be DAY for orders which are valid throughout the day, or IOC.
326
355
  IOC order will be cancelled if it is not traded immediately
356
+ ticker (str, optional): Instrument ticker in the form ``<EXCHANGE>:<SYMBOL>`` (e.g. "NSE:RELIANCE").
357
+ Pass this as an alternative to ``exchange`` and ``token``.
358
+ Either ``ticker`` or (``exchange`` and ``token``) must be provided.
327
359
  Returns:
328
360
  dict: JSON response containing the details of the placed order
329
361
 
330
362
  Raises:
331
363
  HTTPError: If any HTTP error occurs during the API call
364
+ ValueError: If neither ``ticker`` nor (``exchange`` and ``token``) is provided.
332
365
  """
333
366
 
367
+ if ticker is None and (exchange is None or token is None):
368
+ raise ValueError("Either 'ticker' or both 'exchange' and 'token' must be provided")
369
+
370
+ if ticker is None:
371
+ _warn_token_exchange_deprecated("place_order")
372
+
373
+ for required_name, required_value in (
374
+ ("transaction_type", transaction_type), ("product", product), ("variety", variety),
375
+ ("quantity", quantity), ("price", price), ("trigger_price", trigger_price),
376
+ ("disclosed_quantity", disclosed_quantity), ("validity", validity),
377
+ ):
378
+ if required_value is None:
379
+ raise TypeError(f"missing required argument: '{required_name}'")
380
+
334
381
  endpoint = "/trading/orders/regular"
335
- if validity == Constants.ValidityTypes.FULL_DAY:
336
- validity_days = 1
382
+ if validity == Constants.ValidityTypes.FULL_DAY:
383
+ validity_days = 1
337
384
  is_amo = False
338
- elif validity == Constants.ValidityTypes.IMMEDIATE_OR_CANCEL:
339
- validity_days = 0
385
+ elif validity == Constants.ValidityTypes.IMMEDIATE_OR_CANCEL:
386
+ validity_days = 0
340
387
  is_amo = False
341
- else:
342
- validity_days = 1
343
- is_amo = True
388
+ else:
389
+ validity_days = 1
390
+ is_amo = True
344
391
 
345
392
  data = {
346
- "exchange": exchange,
347
- "token": token,
348
393
  "transaction_type": transaction_type,
349
394
  "product": product,
350
395
  "variety": variety,
@@ -356,7 +401,13 @@ class VortexAPI:
356
401
  "validity_days": validity_days,
357
402
  "is_amo": is_amo
358
403
  }
359
-
404
+
405
+ if ticker is not None:
406
+ data["ticker"] = ticker
407
+ else:
408
+ data["exchange"] = exchange
409
+ data["token"] = token
410
+
360
411
  return self._make_api_request("POST", endpoint, data=data)
361
412
 
362
413
  def modify_order(self, order_id: str, variety: Constants.VarietyTypes, quantity: int, traded_quantity: int, price: float, trigger_price: float, disclosed_quantity: int, validity: Constants.ValidityTypes) -> dict:
@@ -505,43 +556,60 @@ class VortexAPI:
505
556
  endpoint = "/user/funds"
506
557
  return self._make_api_request("GET", endpoint)
507
558
 
508
- def get_order_margin(self, exchange: Constants.ExchangeTypes, token: int, transaction_type: Constants.TransactionSides, product: Constants.ProductTypes, variety: Constants.VarietyTypes,
509
- quantity: int, price: float,mode: Constants.OrderMarginModes, old_quantity: int = 0 , old_price: float = 0 ) -> dict:
559
+ def get_order_margin(self, exchange: Constants.ExchangeTypes = None, token: int = None, transaction_type: Constants.TransactionSides = None, product: Constants.ProductTypes = None, variety: Constants.VarietyTypes = None,
560
+ quantity: int = None, price: float = None, mode: Constants.OrderMarginModes = None, old_quantity: int = 0, old_price: float = 0, ticker: str = None) -> dict:
510
561
  """
511
562
  Get the margin required for placing an order for a specific security.
512
563
 
513
- Documentation:
564
+ Documentation:
514
565
  https://vortex.rupeezy.in/docs/latest/margin/#order-margin
515
566
 
516
567
  Args:
517
- exchange (Constants.ExchangeTypes): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO]
518
- token (int): Security token of the scrip. It can be found in the scripmaster file
568
+ exchange (Constants.ExchangeTypes, optional): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO].
569
+ Required together with ``token`` when ``ticker`` is not supplied.
570
+ token (int, optional): Security token of the scrip. It can be found in the scripmaster file.
571
+ Required together with ``exchange`` when ``ticker`` is not supplied.
519
572
  transaction_type (Constants.TransactionSides): Possible values: [BUY, SELL]
520
573
  product (Constants.ProductTypes): Possible values: [INTRADAY, DELIVERY, MTF]. MTF product can only be used in NSE_EQ exchange.
521
- variety (Constants.VarietyTypes): Possible values: [RL, RL-MKT, SL, SL-MKT]. RL means regular orders, SL means Stop Loss order.
574
+ variety (Constants.VarietyTypes): Possible values: [RL, RL-MKT, SL, SL-MKT]. RL means regular orders, SL means Stop Loss order.
522
575
  MKT means that the trade will happen at market price
523
- quantity (int): For exchange NSE_FO, if you want to trade in 2 lots and lot size is 50, you should pass 100.
524
- In all other exchanges, you should pass just the number of lots. For example, in MCX_FO,
576
+ quantity (int): For exchange NSE_FO, if you want to trade in 2 lots and lot size is 50, you should pass 100.
577
+ In all other exchanges, you should pass just the number of lots. For example, in MCX_FO,
525
578
  if you want to trade 5 lots, you should pass just 5.
526
- price (float): Price should be an integer multiple of Tick Size. For example, IDEA's tick size is 0.05.
527
- So the price entered can be 9.5 or 9.65. It cannot be 9.67.
579
+ price (float): Price should be an integer multiple of Tick Size. For example, IDEA's tick size is 0.05.
580
+ So the price entered can be 9.5 or 9.65. It cannot be 9.67.
528
581
  In case of market orders, you should send the Last Trade Price received from the Quote API or Websocket API
529
- mode (Constants.OrderMarginModes): Possible values: [NEW, MODIFY] , Whether you are trying to modify an existing order or placing a new order.
582
+ mode (Constants.OrderMarginModes): Possible values: [NEW, MODIFY] , Whether you are trying to modify an existing order or placing a new order.
530
583
  old_quantity (int): For NSE_FO segments, old_quantity is lots * lot_size. For all others, enter just the number of lots. Required if mode is MODIFY
531
584
  old_price (float): Old Price in INR. Required if mode is MODIFY
585
+ ticker (str, optional): Instrument ticker in the form ``<EXCHANGE>:<SYMBOL>`` (e.g. "NSE:RELIANCE").
586
+ Pass this as an alternative to ``exchange`` and ``token``.
587
+ Either ``ticker`` or (``exchange`` and ``token``) must be provided.
532
588
 
533
589
  Returns:
534
590
  dict: JSON response containing the details of the margin required to place the order
535
591
 
536
592
  Raises:
537
593
  HTTPError: If any HTTP error occurs during the API call
594
+ ValueError: If neither ``ticker`` nor (``exchange`` and ``token``) is provided.
538
595
  """
539
-
596
+
597
+ if ticker is None and (exchange is None or token is None):
598
+ raise ValueError("Either 'ticker' or both 'exchange' and 'token' must be provided")
599
+
600
+ if ticker is None:
601
+ _warn_token_exchange_deprecated("get_order_margin")
602
+
603
+ for required_name, required_value in (
604
+ ("transaction_type", transaction_type), ("product", product), ("variety", variety),
605
+ ("quantity", quantity), ("price", price), ("mode", mode),
606
+ ):
607
+ if required_value is None:
608
+ raise TypeError(f"missing required argument: '{required_name}'")
609
+
540
610
  endpoint = "/margins/order"
541
-
611
+
542
612
  data = {
543
- "exchange": exchange,
544
- "token": token,
545
613
  "transaction_type": transaction_type,
546
614
  "product": product,
547
615
  "variety": variety,
@@ -551,6 +619,13 @@ class VortexAPI:
551
619
  "old_price": old_price,
552
620
  "mode": mode,
553
621
  }
622
+
623
+ if ticker is not None:
624
+ data["ticker"] = ticker
625
+ else:
626
+ data["exchange"] = exchange
627
+ data["token"] = token
628
+
554
629
  return self._make_api_request("POST", endpoint, data=data)
555
630
 
556
631
  def brokerage_plan(self)-> dict:
@@ -585,35 +660,48 @@ class VortexAPI:
585
660
  params = {"q": instruments,"mode": mode}
586
661
  return self._make_api_request("GET", endpoint, data=None,params=params)
587
662
 
588
- def historical_candles(self, exchange: Constants.ExchangeTypes, token: int, to: datetime.datetime , start: datetime.datetime, resolution: Constants.Resolutions):
663
+ def historical_candles(self, exchange: Constants.ExchangeTypes = None, token: int = None, to: datetime.datetime = None, start: datetime.datetime = None, resolution: Constants.Resolutions = None, ticker: str = None):
589
664
  """
590
- Gets historical candle data of a particular instrument.
665
+ Gets historical candle data of a particular instrument.
591
666
 
592
- Documentation:
667
+ Documentation:
593
668
  https://vortex.rupeezy.in/docs/latest/historical/#fetch-historical-candle-data
594
669
 
595
670
  Args:
596
- exchange (Constants.ExchangeTypes): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO]
597
- token (int): Security token of the scrip. It can be found in the instruments master file:
598
- to (datetime): datetime up till when you want to receive candles
599
- start (datetime): datetime from when you want to receive candles
671
+ exchange (Constants.ExchangeTypes, optional): Possible values: [NSE_EQ, NSE_FO, BSE_EQ, BSE_FO, NSE_CD or MCX_FO].
672
+ Required together with ``token`` when ``ticker`` is not supplied.
673
+ token (int, optional): Security token of the scrip. It can be found in the instruments master file.
674
+ Required together with ``exchange`` when ``ticker`` is not supplied.
675
+ to (datetime): datetime up till when you want to receive candles
676
+ start (datetime): datetime from when you want to receive candles
600
677
  resolution (Constants.Resolutions): resoulution of the candle. can be "1", "2", "3", "4", "5", "10", "15", "30", "45", "60", "120", "180", "240", "1D", "1W", "1M"
601
-
678
+ ticker (str, optional): Instrument ticker in the form ``<EXCHANGE>:<SYMBOL>`` (e.g. "NSE:RELIANCE").
679
+ Pass this as an alternative to ``exchange`` and ``token``.
680
+ Either ``ticker`` or (``exchange`` and ``token``) must be provided.
681
+
602
682
  Returns:
603
683
  dict: JSON response containing the historical candles
604
684
  """
605
685
 
606
- if not isinstance(token, int):
607
- raise TypeError("token must be an integer")
608
- if not isinstance(to,datetime.datetime):
686
+ if ticker is None and (exchange is None or token is None):
687
+ raise ValueError("Either 'ticker' or both 'exchange' and 'token' must be provided")
688
+ if ticker is None:
689
+ _warn_token_exchange_deprecated("historical_candles")
690
+ if not isinstance(token, int):
691
+ raise TypeError("token must be an integer")
692
+ if not isinstance(to, datetime.datetime):
609
693
  raise TypeError("to must be a datetime")
610
- if not isinstance(start,datetime.datetime):
694
+ if not isinstance(start, datetime.datetime):
611
695
  raise TypeError("start must be a datetime")
612
696
 
613
-
614
697
  endpoint = "/data/history"
615
- params = {"exchange": exchange,"token": token , "to": int(to.timestamp()), "from": int(start.timestamp()), "resolution": resolution}
616
- return self._make_api_request("GET", endpoint, data=None,params=params)
698
+ params = {"to": int(to.timestamp()), "from": int(start.timestamp()), "resolution": resolution}
699
+ if ticker is not None:
700
+ params["ticker"] = ticker
701
+ else:
702
+ params["exchange"] = exchange
703
+ params["token"] = token
704
+ return self._make_api_request("GET", endpoint, data=None, params=params)
617
705
 
618
706
  def login_url(self, callback_param: str) -> str:
619
707
  """
@@ -0,0 +1,478 @@
1
+ """
2
+ Instrument manager for the Vortex SDK.
3
+
4
+ Downloads the Vortex instruments master (``master.csv``) and exposes fast
5
+ lookups by ticker, ``(exchange, token)``, or ISIN. The master file is cached
6
+ both in memory and on disk so that ``master.csv`` is fetched at most once per
7
+ trading day, even across process restarts.
8
+
9
+ Typical use::
10
+
11
+ from vortex_api import VortexAPI
12
+
13
+ client = VortexAPI(...)
14
+
15
+ inst = client.instruments.get_by_ticker("NSE:RELIANCE")
16
+ print(inst.token, inst.exchange, inst.lot_size)
17
+
18
+ # Reverse lookup
19
+ inst = client.instruments.get_by_exchange_token("NSE_EQ", 2885)
20
+
21
+ # All option contracts under NIFTY
22
+ chain = client.instruments.all_by_underlying("NSE_FO", "NIFTY")
23
+ """
24
+
25
+ from __future__ import annotations
26
+
27
+ import csv
28
+ import datetime
29
+ import gzip
30
+ import io
31
+ import json
32
+ import logging
33
+ import os
34
+ import tempfile
35
+ import threading
36
+ from dataclasses import dataclass, field
37
+ from typing import Callable, Dict, List, Optional
38
+
39
+ import requests
40
+
41
+ DEFAULT_MASTER_URL = "https://static.rupeezy.in/master.csv"
42
+ DEFAULT_REVALIDATE_AFTER_SECONDS = 15 * 60 # how long to trust disk before conditional GET
43
+ _IST_OFFSET = datetime.timedelta(hours=5, minutes=30)
44
+
45
+ logger = logging.getLogger(__name__)
46
+
47
+
48
+ class InstrumentNotFound(Exception):
49
+ """Raised when a lookup cannot find the requested instrument."""
50
+
51
+
52
+ @dataclass
53
+ class Instrument:
54
+ """A single tradable instrument row from ``master.csv``.
55
+
56
+ Fields mirror the columns produced by the Vortex master file. Missing or
57
+ empty columns produce default values rather than raising.
58
+ """
59
+
60
+ ticker: str = "" # e.g. "NSE:RELIANCE"
61
+ token: int = 0
62
+ exchange: str = "" # e.g. "NSE_EQ", "NSE_FO"
63
+ instrument_name: str = ""
64
+ symbol: str = ""
65
+ series: str = ""
66
+ expiry_date: str = ""
67
+ isin: str = ""
68
+ option_type: str = ""
69
+ strike_price: float = 0.0
70
+ tick: float = 0.0
71
+ lot_size: int = 0
72
+ eligibility: bool = False
73
+ name: str = ""
74
+ last_trading_date: Optional[datetime.datetime] = None
75
+ asm_gsm_stage: str = ""
76
+ extras: Dict[str, str] = field(default_factory=dict)
77
+
78
+ @property
79
+ def exchange_token_key(self) -> str:
80
+ """Composite key used internally for ``(exchange, token)`` lookups.
81
+
82
+ Matches the Go package's ``TokenIdentifier`` format: first three
83
+ characters of the exchange (NSE/BSE/MCX) joined with the token.
84
+ """
85
+ return _exchange_token_key(self.exchange, self.token)
86
+
87
+
88
+ def _exchange_token_key(exchange: str, token: int) -> str:
89
+ short = (exchange or "")[:3]
90
+ return f"{short}:{int(token)}"
91
+
92
+
93
+ def _now_ist() -> datetime.datetime:
94
+ return datetime.datetime.now(datetime.timezone.utc).astimezone(
95
+ datetime.timezone(_IST_OFFSET)
96
+ )
97
+
98
+
99
+ def _default_cache_path() -> str:
100
+ base = os.environ.get("XDG_CACHE_HOME") or os.path.join(
101
+ os.path.expanduser("~"), ".cache"
102
+ )
103
+ return os.path.join(base, "pyvortex", "master.csv")
104
+
105
+
106
+ class InstrumentManager:
107
+ """Thread-safe, lazily-loaded instruments cache.
108
+
109
+ Args:
110
+ master_url: Override the master CSV URL (mostly for testing).
111
+ cache_path: Where to persist the downloaded master file. Defaults to
112
+ ``~/.cache/pyvortex/master.csv`` (or ``$XDG_CACHE_HOME``).
113
+ enable_disk_cache: If ``False``, every load re-downloads. Default ``True``.
114
+ request_timeout: HTTP request timeout in seconds.
115
+ revalidate_after_seconds: How long to trust the disk cache without
116
+ re-checking the server. After this interval, the next ``load()``
117
+ issues a conditional GET using ``If-None-Match`` / ``If-Modified-Since``.
118
+ A ``304`` response keeps the disk cache; a ``200`` swaps it in.
119
+ Default 900 (15 minutes). Set to 0 to revalidate on every load.
120
+ """
121
+
122
+ def __init__(
123
+ self,
124
+ master_url: str = DEFAULT_MASTER_URL,
125
+ cache_path: Optional[str] = None,
126
+ enable_disk_cache: bool = True,
127
+ request_timeout: float = 30.0,
128
+ revalidate_after_seconds: int = DEFAULT_REVALIDATE_AFTER_SECONDS,
129
+ ) -> None:
130
+ self._master_url = master_url
131
+ self._cache_path = cache_path or _default_cache_path()
132
+ self._meta_path = self._cache_path + ".meta.json"
133
+ self._enable_disk_cache = enable_disk_cache
134
+ self._request_timeout = request_timeout
135
+ self._revalidate_after_seconds = max(0, int(revalidate_after_seconds))
136
+
137
+ self._lock = threading.RLock()
138
+ self._by_ticker: Dict[str, Instrument] = {}
139
+ self._by_exchange_token: Dict[str, Instrument] = {}
140
+ self._by_isin: Dict[str, List[Instrument]] = {}
141
+ self._last_loaded_at: Optional[datetime.datetime] = None
142
+ self._loaded = False
143
+
144
+ # ------------------------------------------------------------------ Public
145
+
146
+ def load(self, force: bool = False) -> int:
147
+ """Ensure instruments are loaded. Returns the instrument count.
148
+
149
+ Freshness strategy (in order, cheapest first):
150
+
151
+ 1. In-memory cache: already populated this process → no I/O at all.
152
+ 2. Disk cache + revalidation cooldown: if we validated less than
153
+ ``revalidate_after_seconds`` ago, trust the disk cache without
154
+ touching the network.
155
+ 3. Conditional GET: send ``If-None-Match`` / ``If-Modified-Since`` from
156
+ the cached metadata. A ``304`` response confirms the cache is
157
+ current (a few hundred bytes on the wire). A ``200`` brings the new
158
+ master and we re-index.
159
+ 4. Unconditional GET: only when there is no usable disk cache.
160
+
161
+ Set ``force=True`` to bypass every cache and re-download.
162
+ """
163
+ with self._lock:
164
+ if not force and self._loaded:
165
+ return len(self._by_exchange_token)
166
+
167
+ csv_text: Optional[str] = None
168
+ meta = self._read_meta() if self._enable_disk_cache else None
169
+
170
+ if not force and meta is not None and self._has_disk_cache():
171
+ # (2) Recent revalidation → skip the network entirely.
172
+ if self._within_revalidation_cooldown(meta):
173
+ csv_text = self._read_disk_cache()
174
+ if csv_text is not None:
175
+ logger.debug("Using disk cache (within cooldown): %s", self._cache_path)
176
+
177
+ # (3) Otherwise issue a conditional GET.
178
+ if csv_text is None:
179
+ csv_text, new_meta = self._conditional_download(meta)
180
+ if csv_text is None:
181
+ # 304 path — disk is still current.
182
+ csv_text = self._read_disk_cache()
183
+ self._touch_meta(meta, new_meta)
184
+ else:
185
+ # 200 path — write through.
186
+ self._write_disk_cache(csv_text)
187
+ self._write_meta(new_meta)
188
+
189
+ if csv_text is None:
190
+ # (4) No usable disk cache, or force=True.
191
+ csv_text, new_meta = self._unconditional_download()
192
+ if self._enable_disk_cache:
193
+ self._write_disk_cache(csv_text)
194
+ self._write_meta(new_meta)
195
+
196
+ self._parse_and_index(csv_text)
197
+ self._last_loaded_at = _now_ist()
198
+ self._loaded = True
199
+ return len(self._by_exchange_token)
200
+
201
+ def refresh(self) -> int:
202
+ """Force a network refresh, bypassing both caches."""
203
+ return self.load(force=True)
204
+
205
+ def count(self) -> int:
206
+ with self._lock:
207
+ return len(self._by_exchange_token)
208
+
209
+ # ------------------------------------------------------------- Lookups
210
+
211
+ def get_by_ticker(self, ticker: str) -> Instrument:
212
+ self._ensure_loaded()
213
+ with self._lock:
214
+ try:
215
+ return self._by_ticker[ticker]
216
+ except KeyError:
217
+ raise InstrumentNotFound(f"ticker not found: {ticker!r}")
218
+
219
+ def get_by_exchange_token(self, exchange: str, token: int) -> Instrument:
220
+ self._ensure_loaded()
221
+ key = _exchange_token_key(exchange, token)
222
+ with self._lock:
223
+ try:
224
+ return self._by_exchange_token[key]
225
+ except KeyError:
226
+ raise InstrumentNotFound(
227
+ f"instrument not found for exchange={exchange!r}, token={token}"
228
+ )
229
+
230
+ def get_by_isin(self, isin: str) -> List[Instrument]:
231
+ self._ensure_loaded()
232
+ with self._lock:
233
+ insts = self._by_isin.get(isin)
234
+ if not insts:
235
+ raise InstrumentNotFound(f"ISIN not found: {isin!r}")
236
+ return list(insts)
237
+
238
+ def ticker_to_token(self, ticker: str) -> "tuple[str, int]":
239
+ inst = self.get_by_ticker(ticker)
240
+ return inst.exchange, inst.token
241
+
242
+ def token_to_ticker(self, exchange: str, token: int) -> str:
243
+ return self.get_by_exchange_token(exchange, token).ticker
244
+
245
+ def all_by_underlying(self, exchange: str, underlying: str) -> List[Instrument]:
246
+ """Return all instruments on ``exchange`` whose ``symbol`` matches
247
+ ``underlying`` (typically used to fetch an option chain)."""
248
+ self._ensure_loaded()
249
+ with self._lock:
250
+ return [
251
+ i for i in self._by_exchange_token.values()
252
+ if i.exchange == exchange and i.symbol == underlying
253
+ ]
254
+
255
+ def filter(self, predicate: Callable[[Instrument], bool]) -> List[Instrument]:
256
+ self._ensure_loaded()
257
+ with self._lock:
258
+ return [i for i in self._by_exchange_token.values() if predicate(i)]
259
+
260
+ # --------------------------------------------------------- Internals
261
+
262
+ def _ensure_loaded(self) -> None:
263
+ if not self._loaded:
264
+ self.load()
265
+
266
+ # ---- cache I/O ----
267
+
268
+ def _has_disk_cache(self) -> bool:
269
+ return os.path.exists(self._cache_path)
270
+
271
+ def _read_disk_cache(self) -> Optional[str]:
272
+ try:
273
+ with open(self._cache_path, "r", encoding="utf-8") as fh:
274
+ return fh.read()
275
+ except OSError as exc:
276
+ logger.warning("Failed to read instruments cache %s: %s", self._cache_path, exc)
277
+ return None
278
+
279
+ def _write_disk_cache(self, csv_text: str) -> None:
280
+ self._atomic_write(self._cache_path, csv_text)
281
+
282
+ def _read_meta(self) -> Optional[Dict[str, str]]:
283
+ if not os.path.exists(self._meta_path):
284
+ return None
285
+ try:
286
+ with open(self._meta_path, "r", encoding="utf-8") as fh:
287
+ data = json.load(fh)
288
+ if isinstance(data, dict):
289
+ return data
290
+ except (OSError, ValueError) as exc:
291
+ logger.warning("Failed to read instruments meta %s: %s", self._meta_path, exc)
292
+ return None
293
+
294
+ def _write_meta(self, meta: Dict[str, str]) -> None:
295
+ try:
296
+ self._atomic_write(self._meta_path, json.dumps(meta))
297
+ except OSError as exc:
298
+ logger.warning("Failed to write instruments meta %s: %s", self._meta_path, exc)
299
+
300
+ def _touch_meta(self, old: Dict[str, str], new: Dict[str, str]) -> None:
301
+ """Merge ``new`` validation timestamp / headers into ``old`` and persist."""
302
+ merged = dict(old)
303
+ merged.update(new)
304
+ self._write_meta(merged)
305
+
306
+ def _atomic_write(self, path: str, text: str) -> None:
307
+ os.makedirs(os.path.dirname(path), exist_ok=True)
308
+ fd, tmp_path = tempfile.mkstemp(
309
+ prefix=".master-", suffix=".tmp", dir=os.path.dirname(path)
310
+ )
311
+ try:
312
+ with os.fdopen(fd, "w", encoding="utf-8") as fh:
313
+ fh.write(text)
314
+ os.replace(tmp_path, path)
315
+ except Exception:
316
+ try:
317
+ os.unlink(tmp_path)
318
+ except OSError:
319
+ pass
320
+ raise
321
+
322
+ # ---- freshness ----
323
+
324
+ def _within_revalidation_cooldown(self, meta: Dict[str, str]) -> bool:
325
+ if self._revalidate_after_seconds <= 0:
326
+ return False
327
+ fetched_at = meta.get("fetched_at")
328
+ if not fetched_at:
329
+ return False
330
+ try:
331
+ ts = datetime.datetime.fromisoformat(fetched_at)
332
+ except ValueError:
333
+ return False
334
+ if ts.tzinfo is None:
335
+ ts = ts.replace(tzinfo=datetime.timezone.utc)
336
+ age = datetime.datetime.now(datetime.timezone.utc) - ts
337
+ return age.total_seconds() < self._revalidate_after_seconds
338
+
339
+ # ---- network ----
340
+
341
+ def _conditional_download(
342
+ self, meta: Dict[str, str]
343
+ ) -> "tuple[Optional[str], Dict[str, str]]":
344
+ """Issue a conditional GET. Returns ``(csv_text_or_None, new_meta)``.
345
+
346
+ ``csv_text`` is ``None`` iff the server returned ``304 Not Modified``
347
+ (in which case ``new_meta`` only carries an updated ``fetched_at``).
348
+ """
349
+ headers = {"Accept-Encoding": "gzip"}
350
+ if meta.get("etag"):
351
+ headers["If-None-Match"] = meta["etag"]
352
+ if meta.get("last_modified"):
353
+ headers["If-Modified-Since"] = meta["last_modified"]
354
+
355
+ logger.debug("Conditional GET master.csv (etag=%s)", meta.get("etag"))
356
+ resp = requests.get(self._master_url, headers=headers, timeout=self._request_timeout)
357
+
358
+ if resp.status_code == 304:
359
+ logger.debug("master.csv unchanged (304); reusing disk cache")
360
+ return None, {"fetched_at": _utc_now_iso()}
361
+
362
+ resp.raise_for_status()
363
+ return _decode_body(resp.content), _meta_from_response(resp)
364
+
365
+ def _unconditional_download(self) -> "tuple[str, Dict[str, str]]":
366
+ logger.debug("Downloading master.csv from %s", self._master_url)
367
+ resp = requests.get(
368
+ self._master_url,
369
+ headers={"Accept-Encoding": "gzip"},
370
+ timeout=self._request_timeout,
371
+ )
372
+ resp.raise_for_status()
373
+ return _decode_body(resp.content), _meta_from_response(resp)
374
+
375
+ def _parse_and_index(self, csv_text: str) -> None:
376
+ reader = csv.DictReader(io.StringIO(csv_text))
377
+ by_ticker: Dict[str, Instrument] = {}
378
+ by_exchange_token: Dict[str, Instrument] = {}
379
+ by_isin: Dict[str, List[Instrument]] = {}
380
+
381
+ for row in reader:
382
+ inst = _row_to_instrument(row)
383
+ if inst.ticker:
384
+ by_ticker[inst.ticker] = inst
385
+ if inst.exchange and inst.token:
386
+ by_exchange_token[inst.exchange_token_key] = inst
387
+ if inst.isin:
388
+ by_isin.setdefault(inst.isin, []).append(inst)
389
+
390
+ # Atomic swap
391
+ self._by_ticker = by_ticker
392
+ self._by_exchange_token = by_exchange_token
393
+ self._by_isin = by_isin
394
+ logger.debug("Indexed %d instruments", len(by_exchange_token))
395
+
396
+
397
+ def _utc_now_iso() -> str:
398
+ return datetime.datetime.now(datetime.timezone.utc).isoformat()
399
+
400
+
401
+ def _decode_body(content: bytes) -> str:
402
+ """Decode a response body that may be gzipped at the application layer.
403
+
404
+ ``requests`` already strips ``Content-Encoding: gzip`` transparently, but
405
+ the static asset is sometimes served as ``application/octet-stream`` with
406
+ the gzip magic bytes intact — handle both.
407
+ """
408
+ if content[:2] == b"\x1f\x8b":
409
+ content = gzip.decompress(content)
410
+ return content.decode("utf-8")
411
+
412
+
413
+ def _meta_from_response(resp: requests.Response) -> Dict[str, str]:
414
+ meta: Dict[str, str] = {"fetched_at": _utc_now_iso()}
415
+ etag = resp.headers.get("ETag")
416
+ if etag:
417
+ meta["etag"] = etag
418
+ last_modified = resp.headers.get("Last-Modified")
419
+ if last_modified:
420
+ meta["last_modified"] = last_modified
421
+ return meta
422
+
423
+
424
+ def _safe_int(v: str) -> int:
425
+ try:
426
+ return int(v)
427
+ except (TypeError, ValueError):
428
+ return 0
429
+
430
+
431
+ def _safe_float(v: str) -> float:
432
+ try:
433
+ return float(v)
434
+ except (TypeError, ValueError):
435
+ return 0.0
436
+
437
+
438
+ def _row_to_instrument(row: Dict[str, str]) -> Instrument:
439
+ last_trading_date: Optional[datetime.datetime] = None
440
+ raw_ltd = row.get("last_trading_date") or ""
441
+ if raw_ltd:
442
+ try:
443
+ # Master file stores epoch seconds shifted by IST offset
444
+ # (see Go parser: `time.Unix(int64(t)-19800, 0)`).
445
+ secs = float(raw_ltd) - 19800
446
+ last_trading_date = datetime.datetime.fromtimestamp(
447
+ secs, tz=datetime.timezone(_IST_OFFSET)
448
+ )
449
+ except (TypeError, ValueError):
450
+ last_trading_date = None
451
+
452
+ known = {
453
+ "ticker", "symbol", "token", "exchange", "instrument_name", "series",
454
+ "expiry_date", "isin_code", "option_type", "strike_price", "tick",
455
+ "lot_size", "eligibility", "security_desc", "last_trading_date",
456
+ "asm_gsm_stage",
457
+ }
458
+ extras = {k: v for k, v in row.items() if k not in known and v}
459
+
460
+ return Instrument(
461
+ ticker=row.get("ticker", "") or "",
462
+ token=_safe_int(row.get("token", "")),
463
+ exchange=row.get("exchange", "") or "",
464
+ instrument_name=row.get("instrument_name", "") or "",
465
+ symbol=row.get("symbol", "") or "",
466
+ series=row.get("series", "") or "",
467
+ expiry_date=row.get("expiry_date", "") or "",
468
+ isin=row.get("isin_code", "") or "",
469
+ option_type=row.get("option_type", "") or "",
470
+ strike_price=_safe_float(row.get("strike_price", "")),
471
+ tick=_safe_float(row.get("tick", "")),
472
+ lot_size=_safe_int(row.get("lot_size", "")),
473
+ eligibility=_safe_int(row.get("eligibility", "")) > 0,
474
+ name=row.get("security_desc", "") or "",
475
+ last_trading_date=last_trading_date,
476
+ asm_gsm_stage=row.get("asm_gsm_stage", "") or "",
477
+ extras=extras,
478
+ )
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: vortex_api
3
- Version: 2.1.7
3
+ Version: 2.1.8b2
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,6 +4,7 @@ pyproject.toml
4
4
  vortex_api/__init__.py
5
5
  vortex_api/__version__.py
6
6
  vortex_api/api.py
7
+ vortex_api/instruments.py
7
8
  vortex_api/vortex_feed.py
8
9
  vortex_api.egg-info/PKG-INFO
9
10
  vortex_api.egg-info/SOURCES.txt
@@ -1 +0,0 @@
1
- __version__ = "2.1.7"
File without changes
File without changes
File without changes