├── intriniorealtime ├── __init__.py ├── equities_replay_client.py ├── equities_client.py └── options_client.py ├── setup.cfg ├── MANIFEST.in ├── publish.sh ├── docker-compose.yml ├── ExampleApp.cmd ├── Dockerfile ├── setup.py ├── .github └── workflows │ ├── python-publish.yml │ └── pr.yml ├── .gitignore ├── example_app_equities.py ├── example_app_options.py ├── LICENSE └── README.md /intriniorealtime/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /setup.cfg: -------------------------------------------------------------------------------- 1 | [metadata] 2 | description-file = README.md 3 | -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include setup.py README.md MANIFEST.in LICENSE 2 | global-exclude *~ 3 | -------------------------------------------------------------------------------- /publish.sh: -------------------------------------------------------------------------------- 1 | twine upload dist/$(la dist | grep "intriniorealtime.*\.tar\.gz$" | tail -n 1) 2 | -------------------------------------------------------------------------------- /docker-compose.yml: -------------------------------------------------------------------------------- 1 | version: "3.9" 2 | services: 3 | client: 4 | build: . 5 | volumes: 6 | - .:/intrinio -------------------------------------------------------------------------------- /ExampleApp.cmd: -------------------------------------------------------------------------------- 1 | pip uninstall intriniorealtime -y 2 | pip install -e intriniorealtime 3 | python example_app_equities.py 4 | # python example_app_options.py -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.10 2 | 3 | RUN mkdir /intrinio 4 | 5 | WORKDIR /intrinio 6 | 7 | COPY . /intrinio 8 | 9 | RUN pip uninstall 'websocket' 10 | RUN pip install 'websocket-client' 11 | RUN pip install 'requests' 12 | RUN pip install 'wsaccel' 13 | 14 | RUN pip install 'intrinio_sdk' 15 | 16 | CMD python example_app_equities.py 17 | #CMD python example_app_options.py -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup 2 | 3 | def readme(): 4 | with open('README.md') as f: 5 | return f.read() 6 | 7 | setup( 8 | name = 'intriniorealtime', 9 | packages = ['intriniorealtime'], 10 | version = '6.2.0', 11 | author = 'Intrinio Python SDK for Real-Time Stock Prices', 12 | author_email = 'success@intrinio.com', 13 | url = 'https://intrinio.com', 14 | description = 'Intrinio Python SDK for Real-Time Stock Prices', 15 | long_description = readme(), 16 | long_description_content_type = 'text/markdown', 17 | install_requires = ['requests>=2.26.0','websocket-client>=1.2.1','wsaccel>=0.6.3', 'intrinio-sdk>=6.26.0'], 18 | python_requires = '~=3.10', 19 | download_url = 'https://github.com/intrinio/intrinio-realtime-python-sdk/archive/v6.2.0.tar.gz', 20 | keywords = ['realtime','stock prices','intrinio','stock market','stock data','financial'], 21 | classifiers = [ 22 | 'Intended Audience :: Financial and Insurance Industry', 23 | 'Topic :: Office/Business :: Financial :: Investment' 24 | ] 25 | ) -------------------------------------------------------------------------------- /.github/workflows/python-publish.yml: -------------------------------------------------------------------------------- 1 | # This workflow will upload a Python Package using Twine when a release is created 2 | # For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python#publishing-to-package-registries 3 | 4 | # This workflow uses actions that are not certified by GitHub. 5 | # They are provided by a third-party and are governed by 6 | # separate terms of service, privacy policy, and support 7 | # documentation. 8 | 9 | name: Upload Python Package 10 | 11 | on: 12 | release: 13 | types: [published] 14 | 15 | permissions: 16 | contents: read 17 | 18 | jobs: 19 | deploy: 20 | 21 | runs-on: ubuntu-latest 22 | 23 | steps: 24 | - uses: actions/checkout@v3 25 | - name: Set up Python 26 | uses: actions/setup-python@v3 27 | with: 28 | python-version: '3.x' 29 | - name: Install dependencies 30 | run: | 31 | python -m pip install --upgrade pip 32 | pip install build 33 | - name: Build package 34 | run: python -m build 35 | - name: Publish package 36 | uses: pypa/gh-action-pypi-publish@27b31702a0e7fc50959f5ad993c78deac1bdfc29 37 | with: 38 | user: __token__ 39 | password: ${{ secrets.PYPI_API_TOKEN }} 40 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .DS_Store 2 | # Byte-compiled / optimized / DLL files 3 | __pycache__/ 4 | *.py[cod] 5 | *$py.class 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | wheels/ 24 | *.egg-info/ 25 | .installed.cfg 26 | *.egg 27 | 28 | # PyInstaller 29 | # Usually these files are written by a python script from a template 30 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 31 | *.manifest 32 | *.spec 33 | 34 | # Installer logs 35 | pip-log.txt 36 | pip-delete-this-directory.txt 37 | 38 | # Unit test / coverage reports 39 | htmlcov/ 40 | .tox/ 41 | .coverage 42 | .coverage.* 43 | .cache 44 | nosetests.xml 45 | coverage.xml 46 | *.cover 47 | .hypothesis/ 48 | 49 | # Translations 50 | *.mo 51 | *.pot 52 | 53 | # Django stuff: 54 | *.log 55 | local_settings.py 56 | 57 | # Flask stuff: 58 | instance/ 59 | .webassets-cache 60 | 61 | # Scrapy stuff: 62 | .scrapy 63 | 64 | # Sphinx documentation 65 | docs/_build/ 66 | 67 | # PyBuilder 68 | target/ 69 | 70 | # Jupyter Notebook 71 | .ipynb_checkpoints 72 | 73 | # pyenv 74 | .python-version 75 | 76 | # celery beat schedule file 77 | celerybeat-schedule 78 | 79 | # SageMath parsed files 80 | *.sage.py 81 | 82 | # Environments 83 | .env 84 | .venv 85 | env/ 86 | venv/ 87 | ENV/ 88 | 89 | # Spyder project settings 90 | .spyderproject 91 | .spyproject 92 | 93 | # Rope project settings 94 | .ropeproject 95 | 96 | # mkdocs documentation 97 | /site 98 | 99 | # mypy 100 | .mypy_cache/ 101 | 102 | test.py 103 | test1.py 104 | 105 | .pypirc 106 | 107 | .vs/ 108 | 109 | .idea/ 110 | -------------------------------------------------------------------------------- /.github/workflows/pr.yml: -------------------------------------------------------------------------------- 1 | name: PR Merge 2 | 3 | on: 4 | pull_request: 5 | types: [ closed ] 6 | 7 | jobs: 8 | notify: 9 | if: github.event.pull_request.merged == true && github.ref == 'refs/heads/production' 10 | 11 | runs-on: ubuntu-latest 12 | steps: 13 | - name: Git checkout 14 | uses: actions/checkout@v2 15 | 16 | - name: Prepare Slack Message 17 | id: slack-body-formatter 18 | run: | 19 | SLACK_MESSAGE="${{github.event.pull_request.body}}" 20 | 21 | echo "::set-output name=slack-message::${SLACK_MESSAGE//$'\r\n'/'\n'}" 22 | 23 | - name: Send GitHub Action trigger data to Slack workflow 24 | id: slack 25 | uses: slackapi/slack-github-action@v1.24.0 26 | with: 27 | # This data can be any valid JSON from a previous step in the GitHub Action 28 | payload: | 29 | { 30 | "text": "${{ github.event.repository.name }} deployed by ${{ github.event.pull_request.user.login }}", 31 | "blocks": [ 32 | { 33 | "type": "header", 34 | "text": { 35 | "type": "plain_text", 36 | "text": "----------------------\n${{ github.event.repository.name }} Deployed\n----------------------\n${{ github.event.pull_request.title }}" 37 | } 38 | }, 39 | { 40 | "type": "section", 41 | "text": { 42 | "type": "mrkdwn", 43 | "text": "*Pull request created by ${{ github.event.pull_request.user.login }}*" 44 | } 45 | }, 46 | { 47 | "type": "section", 48 | "text": { 49 | "type": "mrkdwn", 50 | "text": "${{ steps.slack-body-formatter.outputs.slack-message }}" 51 | } 52 | } 53 | ] 54 | } 55 | env: 56 | SLACK_WEBHOOK_URL: ${{ secrets.SLACK_WEBHOOK_URL }} 57 | SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK -------------------------------------------------------------------------------- /example_app_equities.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import signal 3 | import time 4 | import sys 5 | import datetime 6 | from threading import Timer,Thread,Event,Lock 7 | 8 | from intriniorealtime.equities_client import IntrinioRealtimeEquitiesClient 9 | from intriniorealtime.equities_replay_client import IntrinioReplayEquitiesClient 10 | from intriniorealtime.equities_client import EquitiesQuote 11 | from intriniorealtime.equities_client import EquitiesTrade 12 | 13 | trade_count = 0 14 | ask_count = 0 15 | bid_count = 0 16 | backlog_count = 0 17 | 18 | def on_quote(quote, backlog): 19 | global ask_count 20 | global bid_count 21 | global backlog_count 22 | backlog_count = backlog 23 | if isinstance(quote, EquitiesQuote) and 'type' in quote.__dict__: 24 | if quote.type == "ask": ask_count += 1 25 | else: bid_count += 1 26 | 27 | def on_trade(trade, backlog): 28 | global trade_count 29 | global backlog_count 30 | backlog_count = backlog 31 | trade_count += 1 32 | 33 | class Summarize(threading.Thread): 34 | def __init__(self, stop_flag): 35 | threading.Thread.__init__(self, group=None, args=(), kwargs={}) 36 | self.daemon = True 37 | self.stop_flag = stop_flag 38 | 39 | def run(self): 40 | global trade_count 41 | global bid_count 42 | global ask_count 43 | global backlog_count 44 | while not self.stop_flag.wait(5): 45 | print("trades: " + str(trade_count) + "; asks: " + str(ask_count) + "; bids: " + str(bid_count) + "; backlog: " + str(backlog_count)) 46 | 47 | 48 | configuration = { 49 | 'api_key': 'API_KEY_HERE', 50 | 'provider': 'IEX' # 'REALTIME' (IEX), or 'IEX', or 'DELAYED_SIP', or 'NASDAQ_BASIC', or 'CBOE_ONE', or 'EQUITIES_EDGE' 51 | # ,'delayed': True # Add this if you have realtime (nondelayed) access and want to force delayed mode. If you only have delayed mode access, this is redundant. 52 | # ,'replay_date': datetime.date.today() - datetime.timedelta(days=1) # needed for ReplayClient. The date to replay. 53 | # ,'with_simulated_delay': False # needed for ReplayClient. This plays back the events at the same rate they happened in market. 54 | # ,'delete_file_when_done': True # needed for ReplayClient 55 | # ,'write_to_csv': False # needed for ReplayClient 56 | # ,'csv_file_path': 'data.csv' # needed for ReplayClient 57 | # ,'bypass_parsing': True # if you want to handle parsing yourself, set this to True. Otherwise, leave it alone. 58 | # ,'debug': True 59 | # ,'max_queue_size': 250000 60 | } 61 | 62 | 63 | client = IntrinioRealtimeEquitiesClient(configuration, on_trade, on_quote) 64 | # client = IntrinioReplayClient(options, on_trade, on_quote) 65 | stop_event = Event() 66 | 67 | 68 | def on_kill_process(sig, frame): 69 | print("Stopping") 70 | stop_event.set() 71 | client.disconnect() 72 | sys.exit(0) 73 | 74 | 75 | signal.signal(signal.SIGINT, on_kill_process) 76 | 77 | 78 | client.join(['AAPL','GE','MSFT']) 79 | # client.join(['lobby']) 80 | client.connect() 81 | 82 | summarize_thread = Summarize(stop_event) 83 | summarize_thread.start() 84 | 85 | time.sleep(60 * 60 * 24) 86 | 87 | # sigint, or ctrl+c, during the thread wait will also perform the same below code. 88 | print("Stopping") 89 | stop_event.set() 90 | client.disconnect() 91 | sys.exit(0) 92 | -------------------------------------------------------------------------------- /example_app_options.py: -------------------------------------------------------------------------------- 1 | import threading 2 | import signal 3 | import time 4 | import sys 5 | import logging 6 | from threading import Event, Lock 7 | 8 | from intriniorealtime.options_client import IntrinioRealtimeOptionsClient 9 | from intriniorealtime.options_client import OptionsQuote 10 | from intriniorealtime.options_client import OptionsTrade 11 | from intriniorealtime.options_client import OptionsRefresh 12 | from intriniorealtime.options_client import OptionsUnusualActivity 13 | from intriniorealtime.options_client import OptionsUnusualActivityType 14 | from intriniorealtime.options_client import OptionsUnusualActivitySentiment 15 | from intriniorealtime.options_client import log 16 | from intriniorealtime.options_client import Config 17 | from intriniorealtime.options_client import Providers 18 | from intriniorealtime.options_client import LogLevel 19 | 20 | options_trade_count = 0 21 | options_trade_count_lock = Lock() 22 | options_quote_count = 0 23 | options_quote_count_lock = Lock() 24 | options_refresh_count = 0 25 | options_refresh_count_lock = Lock() 26 | options_ua_block_count = 0 27 | options_ua_block_count_lock = Lock() 28 | options_ua_sweep_count = 0 29 | options_ua_sweep_count_lock = Lock() 30 | options_ua_large_trade_count = 0 31 | options_ua_large_trade_count_lock = Lock() 32 | options_ua_unusual_sweep_count = 0 33 | options_ua_unusual_sweep_count_lock = Lock() 34 | 35 | 36 | def on_quote(quote: OptionsQuote): 37 | global options_quote_count 38 | global options_quote_count_lock 39 | with options_quote_count_lock: 40 | options_quote_count += 1 41 | 42 | 43 | def on_trade(trade: OptionsTrade): 44 | global options_trade_count 45 | global options_trade_count_lock 46 | with options_trade_count_lock: 47 | options_trade_count += 1 48 | 49 | 50 | def on_refresh(refresh: OptionsRefresh): 51 | global options_refresh_count 52 | global options_refresh_count_lock 53 | with options_refresh_count_lock: 54 | options_refresh_count += 1 55 | 56 | 57 | def on_unusual_activity(ua: OptionsUnusualActivity): 58 | global options_ua_block_count 59 | global options_ua_block_count_lock 60 | global options_ua_sweep_count 61 | global options_ua_sweep_count_lock 62 | global options_ua_large_trade_count 63 | global options_ua_large_trade_count_lock 64 | global options_ua_unusual_sweep_count 65 | global options_ua_unusual_sweep_count_lock 66 | if ua.activity_type == OptionsUnusualActivityType.BLOCK: 67 | with options_ua_block_count_lock: 68 | options_ua_block_count += 1 69 | elif ua.activity_type == OptionsUnusualActivityType.SWEEP: 70 | with options_ua_sweep_count_lock: 71 | options_ua_sweep_count += 1 72 | elif ua.activity_type == OptionsUnusualActivityType.LARGE: 73 | with options_ua_large_trade_count_lock: 74 | options_ua_large_trade_count += 1 75 | elif ua.activity_type == OptionsUnusualActivityType.UNUSUAL_SWEEP: 76 | with options_ua_unusual_sweep_count_lock: 77 | options_ua_unusual_sweep_count += 1 78 | else: 79 | log("on_unusual_activity - Unknown activity_type {0}", ua.activity_type) 80 | 81 | 82 | class Summarize(threading.Thread): 83 | def __init__(self, stop_flag: threading.Event, intrinio_client: IntrinioRealtimeOptionsClient): 84 | threading.Thread.__init__(self, group=None, args=(), kwargs={}, daemon=True) 85 | self.__stop_flag: threading.Event = stop_flag 86 | self.__client = intrinio_client 87 | 88 | def run(self): 89 | while not self.__stop_flag.is_set(): 90 | time.sleep(30.0) 91 | (dataMsgs, txtMsgs, queueDepth) = self.__client.get_stats() 92 | log("Client Stats - Data Messages: {0}, Text Messages: {1}, Queue Depth: {2}".format(dataMsgs, txtMsgs, queueDepth)) 93 | log( 94 | "App Stats - Trades: {0}, Quotes: {1}, Refreshes: {2}, Blocks: {3}, Sweeps: {4}, Large Trades: {5}, Unusual Sweeps: {6}" 95 | .format( 96 | options_trade_count, 97 | options_quote_count, 98 | options_refresh_count, 99 | options_ua_block_count, 100 | options_ua_sweep_count, 101 | options_ua_large_trade_count, 102 | options_ua_unusual_sweep_count)) 103 | 104 | 105 | # Your config object MUST include the 'api_key' and 'provider', at a minimum 106 | config: Config = Config( 107 | api_key="API_KEY_HERE", 108 | provider=Providers.OPRA, # or Providers.OPTIONS_EDGE 109 | num_threads=8, 110 | symbols=["AAPL", "BRKB__230217C00300000"], # this is a static list of symbols (options contracts or option chains) that will automatically be subscribed to when the client starts 111 | log_level=LogLevel.INFO, 112 | delayed=False) #set delayed parameter to true if you have realtime access but want the data delayed 15 minutes anyway 113 | 114 | # Register only the callbacks that you want. 115 | # Take special care when registering the 'on_quote' handler as it will increase throughput by ~10x 116 | intrinioRealtimeOptionsClient: IntrinioRealtimeOptionsClient = IntrinioRealtimeOptionsClient(config, on_trade=on_trade, on_quote=on_quote, on_refresh=on_refresh, on_unusual_activity=on_unusual_activity) 117 | 118 | stop_event = Event() 119 | 120 | 121 | def on_kill_process(sig, frame): 122 | log("Sample Application - Stopping") 123 | stop_event.set() 124 | intrinioRealtimeOptionsClient.stop() 125 | sys.exit(0) 126 | 127 | 128 | signal.signal(signal.SIGINT, on_kill_process) 129 | 130 | summarize_thread = Summarize(stop_event, intrinioRealtimeOptionsClient) 131 | summarize_thread.start() 132 | 133 | intrinioRealtimeOptionsClient.start() 134 | 135 | #use this to join the channels already declared in your config 136 | intrinioRealtimeOptionsClient.join() 137 | 138 | # Use this to subscribe to the entire universe of symbols (option contracts). This requires special permission. 139 | # intrinioRealtimeOptionsClient.join_firehose() 140 | 141 | # Use this to subscribe, dynamically, to an option chain (all option contracts for a given underlying contract). 142 | # intrinioRealtimeOptionsClient.join("AAPL") 143 | 144 | # Use this to subscribe, dynamically, to a specific option contract. 145 | # intrinioRealtimeOptionsClient.join("AAP___230616P00250000") 146 | 147 | # Use this to subscribe, dynamically, a list of specific option contracts or option chains. 148 | # intrinioRealtimeOptionsClient.join("GOOG__220408C02870000", "MSFT__220408C00315000", "AAPL__220414C00180000", "TSLA", "GE") 149 | 150 | time.sleep(60 * 60 * 24) 151 | # sigint, or ctrl+c, during the thread wait will also perform the same below code. 152 | on_kill_process(None, None) 153 | -------------------------------------------------------------------------------- /intriniorealtime/equities_replay_client.py: -------------------------------------------------------------------------------- 1 | import time 2 | import datetime 3 | import requests 4 | import threading 5 | import logging 6 | import queue 7 | import struct 8 | import sys 9 | import intrinio_sdk as intrinio 10 | import tempfile 11 | import os 12 | import urllib.request 13 | from typing import Optional, Dict, Any 14 | 15 | DEBUGGING = not (sys.gettrace() is None) 16 | 17 | 18 | class IntrinioRealtimeConstants: 19 | REALTIME = "REALTIME" 20 | DELAYED_SIP = "DELAYED_SIP" 21 | NASDAQ_BASIC = "NASDAQ_BASIC" 22 | MANUAL = "MANUAL" 23 | NO_PROVIDER = "NO_PROVIDER" 24 | NO_SUBPROVIDER = "NO_SUBPROVIDER" 25 | CTA_A = "CTA_A" 26 | CTA_B = "CTA_B" 27 | UTP = "UTP" 28 | OTC = "OTC" 29 | NASDAQ_BASIC = "NASDAQ_BASIC" 30 | IEX = "IEX" 31 | CBOE_ONE = "CBOE_ONE" 32 | EQUITIES_EDGE = "EQUITIES_EDGE" 33 | PROVIDERS = [REALTIME, MANUAL, DELAYED_SIP, NASDAQ_BASIC, IEX, CBOE_ONE, EQUITIES_EDGE] 34 | SUB_PROVIDERS = [NO_SUBPROVIDER, CTA_A, CTA_B, UTP, OTC, NASDAQ_BASIC, IEX, CBOE_ONE, EQUITIES_EDGE] 35 | MAX_QUEUE_SIZE = 1000000 36 | EVENT_BUFFER_SIZE = 100 37 | 38 | 39 | class Quote: 40 | def __init__(self, symbol, type, price, size, timestamp, subprovider, market_center, condition): 41 | self.symbol = symbol 42 | self.type = type 43 | self.price = price 44 | self.size = size 45 | self.timestamp = timestamp 46 | self.subprovider = subprovider 47 | self.market_center = market_center 48 | self.condition = condition 49 | 50 | def __str__(self): 51 | return self.symbol + ", " + self.type + ", price: " + str(self.price) + ", size: " + str(self.size) + ", timestamp: " + str(self.timestamp) + ", subprovider: " + str(self.subprovider) + ", market_center: " + str(self.market_center) + ", condition: " + str(self.condition) 52 | 53 | 54 | class Trade: 55 | def __init__(self, symbol, price, size, total_volume, timestamp, subprovider, market_center, condition): 56 | self.symbol = symbol 57 | self.price = price 58 | self.size = size 59 | self.total_volume = total_volume 60 | self.timestamp = timestamp 61 | self.subprovider = subprovider 62 | self.market_center = market_center 63 | self.condition = condition 64 | 65 | def __str__(self): 66 | return self.symbol + ", trade, price: " + str(self.price) + ", size: " + str(self.size) + ", timestamp: " + str(self.timestamp) + ", subprovider: " + str(self.subprovider) + ", market_center: " + str(self.market_center) + ", condition: " + str(self.condition) 67 | 68 | 69 | class Tick: 70 | def __init__(self, time_received, data): 71 | self.time_received = time_received 72 | self.data = data 73 | 74 | 75 | class IntrinioReplayEquitiesClient: 76 | def __init__(self, options: Dict[str, Any], on_trade: callable, on_quote: callable): 77 | if options is None: 78 | raise ValueError("Options parameter is required") 79 | 80 | self.options = options 81 | self.api_key = options.get('api_key') 82 | self.provider = options.get('provider') 83 | self.tradesonly = options.get('tradesonly') 84 | self.replay_date = options.get('replay_date') 85 | self.with_simulated_delay = options.get('with_simulated_delay') 86 | self.delete_file_when_done = options.get('delete_file_when_done') 87 | self.worker_thread_count = options.get('worker_thread_count') 88 | self.write_to_csv = options.get('write_to_csv') 89 | self.csv_file_path = options.get('csv_file_path') 90 | 91 | if (self.worker_thread_count is None) or (type(self.worker_thread_count) is not int) or self.worker_thread_count < 1: 92 | self.worker_thread_count = 4 93 | 94 | if 'channels' in options: 95 | self.channels = set(options['channels']) 96 | else: 97 | self.channels = set() 98 | 99 | if 'logger' in options: 100 | self.logger = options['logger'] 101 | else: 102 | log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 103 | log_handler = logging.StreamHandler() 104 | log_handler.setFormatter(log_formatter) 105 | self.logger = logging.getLogger('intrinio_realtime') 106 | if 'debug' in options and options['debug'] is True: 107 | self.logger.setLevel(logging.DEBUG) 108 | else: 109 | self.logger.setLevel(logging.INFO) 110 | self.logger.addHandler(log_handler) 111 | 112 | if 'max_queue_size' in options: 113 | self.events = queue.Queue(maxsize=options['max_queue_size']) 114 | else: 115 | self.events = queue.Queue(maxsize=IntrinioRealtimeConstants.MAX_QUEUE_SIZE) 116 | 117 | if self.api_key: 118 | if not self.valid_api_key(self.api_key): 119 | raise ValueError("API Key was formatted invalidly") 120 | else: 121 | raise ValueError("API key is required") 122 | 123 | if not callable(on_quote): 124 | self.on_quote = None 125 | raise ValueError("Parameter 'on_quote' must be a function") 126 | else: 127 | self.on_quote = on_quote 128 | 129 | if not callable(on_trade): 130 | self.on_trade = None 131 | raise ValueError("Parameter 'on_trade' must be a function") 132 | else: 133 | self.on_trade = on_trade 134 | 135 | if self.provider not in IntrinioRealtimeConstants.PROVIDERS: 136 | raise ValueError(f"Parameter 'provider' is invalid, use one of {IntrinioRealtimeConstants.PROVIDERS}") 137 | 138 | if ('replay_date' not in options) or (type(self.replay_date) is not datetime.date): 139 | raise ValueError(f"Parameter 'replay_date' is invalid, use a datetime.date.") 140 | 141 | if ('with_simulated_delay' not in options) or (type(self.with_simulated_delay) is not bool): 142 | raise ValueError(f"Parameter 'with_simulated_delay' is invalid, use a bool.") 143 | 144 | if ('delete_file_when_done' not in options) or (type(self.delete_file_when_done) is not bool): 145 | raise ValueError(f"Parameter 'delete_file_when_done' is invalid, use a bool.") 146 | 147 | if ('write_to_csv' not in options) or (type(self.write_to_csv) is not bool): 148 | raise ValueError(f"Parameter 'write_to_csv' is invalid, use a bool.") 149 | 150 | if self.write_to_csv and (('csv_file_path' not in options) or (type(self.csv_file_path) is not str)): 151 | raise ValueError(f"Parameter 'csv_file_path' is invalid, use a string path.") 152 | 153 | self.file_parsing_thread = None 154 | self.quote_handling_threads = [] 155 | self.joined_channels = set() 156 | self.last_queue_warning_time = 0 157 | 158 | @staticmethod 159 | def valid_api_key(api_key): 160 | if not isinstance(api_key, str): 161 | return False 162 | 163 | if api_key == "": 164 | return False 165 | 166 | return True 167 | 168 | def connect(self): 169 | try: 170 | self.logger.info("Connecting...") 171 | self.joined_channels = set() 172 | self.refresh_channels() 173 | self.file_parsing_thread = FileParsingThread(self) 174 | self.file_parsing_thread.start() 175 | self.quote_handling_threads = [None] * self.worker_thread_count 176 | for i in range(len(self.quote_handling_threads)): 177 | self.quote_handling_threads[i] = QuoteHandlingThread(self) 178 | self.quote_handling_threads[i].start() 179 | except Exception as e: 180 | self.logger.error(f"Cannot connect: {repr(e)}") 181 | 182 | def disconnect(self): 183 | self.joined_channels = set() 184 | if self.file_parsing_thread: 185 | self.file_parsing_thread.join() 186 | for thread in self.quote_handling_threads: 187 | thread.join() 188 | self.quote_handling_threads = [] 189 | 190 | def on_queue_full(self): 191 | if time.time() - self.last_queue_warning_time > 1: 192 | self.logger.error("Quote queue is full! Dropped some new events") 193 | self.last_queue_warning_time = time.time() 194 | 195 | def join(self, channels): 196 | if isinstance(channels, str): 197 | channels = [channels] 198 | 199 | self.channels = self.channels | set(channels) 200 | self.refresh_channels() 201 | 202 | def leave(self, channels): 203 | if isinstance(channels, str): 204 | channels = [channels] 205 | 206 | self.channels = self.channels - set(channels) 207 | self.refresh_channels() 208 | 209 | def leave_all(self): 210 | self.channels = set() 211 | self.refresh_channels() 212 | 213 | def refresh_channels(self): 214 | # Join new channels 215 | new_channels = self.channels - self.joined_channels 216 | self.logger.debug(f"New channels: {new_channels}") 217 | for channel in new_channels: 218 | self.logger.info(f"Joined channel {channel}") 219 | 220 | # Leave old channels 221 | old_channels = self.joined_channels - self.channels 222 | self.logger.debug(f"Old channels: {old_channels}") 223 | for channel in old_channels: 224 | self.logger.info(f"Left channel {channel}") 225 | 226 | self.joined_channels = self.channels.copy() 227 | self.logger.debug(f"Current channels: {self.joined_channels}") 228 | 229 | 230 | class FileParsingThread(threading.Thread): 231 | def __init__(self, client): 232 | threading.Thread.__init__(self, group=None, args=(), kwargs={}) 233 | self.daemon = True 234 | self.client = client 235 | self.enabled = True 236 | 237 | def run(self): 238 | self.client.logger.debug("FileParsingThread ready") 239 | file_paths = self.get_all_files() 240 | ticks_group = [None] * len(file_paths) 241 | for i in range(len(file_paths)): 242 | ticks_group[i] = self.replay_tick_file_without_delay(file_paths[i]) 243 | 244 | aggregated_ticks = [] 245 | if self.client.with_simulated_delay: 246 | aggregated_ticks = self.replay_file_group_with_delay(ticks_group) 247 | else: 248 | aggregated_ticks = self.replay_file_group_without_delay(ticks_group) 249 | 250 | if self.client.write_to_csv: 251 | csv_writer = open(self.client.csv_file_path, "w") 252 | self.write_header_to_csv(csv_writer) 253 | csv_writer.close() 254 | 255 | for tick in aggregated_ticks: 256 | self.client.events.put_nowait(tick.data) 257 | 258 | if self.client.delete_file_when_done: 259 | for file_path in file_paths: 260 | if os.path.exists(file_path): 261 | self.client.logger.info("Deleting file " + file_path) 262 | os.remove(file_path) 263 | self.client.logger.debug("FileParsingThread exiting") 264 | 265 | @staticmethod 266 | def map_subprovider_to_api_value(sub_provider): 267 | match sub_provider: 268 | case IntrinioRealtimeConstants.IEX: 269 | return "iex" 270 | case IntrinioRealtimeConstants.UTP: 271 | return "utp_delayed" 272 | case IntrinioRealtimeConstants.CTA_A: 273 | return "cta_a_delayed" 274 | case IntrinioRealtimeConstants.CTA_B: 275 | return "cta_b_delayed" 276 | case IntrinioRealtimeConstants.OTC: 277 | return "otc_delayed" 278 | case IntrinioRealtimeConstants.NASDAQ_BASIC: 279 | return "nasdaq_basic" 280 | case IntrinioRealtimeConstants.CBOE_ONE: 281 | return "cboe_one" 282 | case IntrinioRealtimeConstants.EQUITIES_EDGE: 283 | return "equities_edge" 284 | case _: 285 | return "iex" 286 | 287 | @staticmethod 288 | def map_provider_to_subproviders(provider): 289 | match provider: 290 | case IntrinioRealtimeConstants.NO_PROVIDER: 291 | return [] 292 | case IntrinioRealtimeConstants.MANUAL: 293 | return [] 294 | case IntrinioRealtimeConstants.REALTIME: 295 | return [IntrinioRealtimeConstants.IEX] 296 | case IntrinioRealtimeConstants.IEX: 297 | return [IntrinioRealtimeConstants.IEX] 298 | case IntrinioRealtimeConstants.DELAYED_SIP: 299 | return [IntrinioRealtimeConstants.UTP, IntrinioRealtimeConstants.CTA_A, IntrinioRealtimeConstants.CTA_B, IntrinioRealtimeConstants.OTC] 300 | case IntrinioRealtimeConstants.NASDAQ_BASIC: 301 | return [IntrinioRealtimeConstants.NASDAQ_BASIC] 302 | case IntrinioRealtimeConstants.CBOE_ONE: 303 | return [IntrinioRealtimeConstants.CBOE_ONE] 304 | case IntrinioRealtimeConstants.EQUITIES_EDGE: 305 | return [IntrinioRealtimeConstants.EQUITIES_EDGE] 306 | case _: 307 | return [] 308 | 309 | @staticmethod 310 | def write_header_to_csv(csv_writer): 311 | csv_writer.write("\"Type\",\"Symbol\",\"Price\",\"Size\",\"Timestamp\",\"SubProvider\",\"MarketCenter\",\"Condition\",\"TotalVolume\"\r\n") 312 | 313 | def get_file(self, subprovider): 314 | intrinio.ApiClient().configuration.api_key['api_key'] = self.client.api_key 315 | intrinio.ApiClient().allow_retries(True) 316 | security_api = intrinio.SecurityApi() 317 | api_response = security_api.get_security_replay_file(self.map_subprovider_to_api_value(subprovider), self.client.replay_date) 318 | decoded_url = api_response.url.replace("\u0026", "&") 319 | temp_dir = tempfile.gettempdir() 320 | file_path = os.path.join(temp_dir, api_response.name) 321 | self.client.logger.info("Downloading file to " + file_path) 322 | urllib.request.urlretrieve(decoded_url, file_path) 323 | return file_path 324 | 325 | def get_all_files(self): 326 | subproviders = self.map_provider_to_subproviders(self.client.provider) 327 | file_names = [] 328 | for subprovider in subproviders: 329 | try: 330 | file_names.append(self.get_file(subprovider)) 331 | except Exception as e: 332 | self.client.logger.info("Could not retrieve file for " + subprovider) 333 | return file_names 334 | 335 | @staticmethod 336 | def read_file_chunk(file_obj, chunk_size): 337 | data = file_obj.read(chunk_size) 338 | if not data: 339 | return None 340 | return data 341 | 342 | @staticmethod 343 | def copy_into(source, destination, destination_start_index): 344 | for i in range(0, len(source)): 345 | destination[destination_start_index + i] = source[i] 346 | 347 | def replay_tick_file_without_delay(self, file_path): 348 | if os.path.exists(file_path): 349 | file = open(file_path, "rb") 350 | read_result = self.read_file_chunk(file, 1) 351 | while read_result is not None: 352 | event_bytes = [0] * IntrinioRealtimeConstants.EVENT_BUFFER_SIZE 353 | event_bytes[0] = 1 # This is the number of messages in the group 354 | event_bytes[1] = int.from_bytes(read_result, "big") # This is message type 355 | event_bytes[2] = int.from_bytes(self.read_file_chunk(file, 1), "big") # This is message length, including this and the previous byte. 356 | self.copy_into(self.read_file_chunk(file, event_bytes[2] - 2), event_bytes, 3) # read the rest of the message 357 | time_received_bytes = self.read_file_chunk(file, 8) 358 | time_received = struct.unpack_from(' 0: 468 | condition = buffer[(start_index + 23 + symbol_length):(start_index + 23 + symbol_length + condition_length)].tobytes().decode("ascii") 469 | 470 | subprovider = self.subprovider_codes.get(buffer[3 + symbol_length + start_index], IntrinioRealtimeConstants.IEX) # default IEX for backward behavior consistency. 471 | market_center = buffer[(start_index + 4 + symbol_length):(start_index + 6 + symbol_length)].tobytes().decode("utf-16") 472 | 473 | return Quote(symbol, quote_type, price, size, timestamp, subprovider, market_center, condition) 474 | 475 | def parse_trade(self, trade_bytes, start_index=0): 476 | buffer = memoryview(trade_bytes) 477 | symbol_length = buffer[start_index + 2] 478 | symbol = buffer[(start_index + 3):(start_index + 3 + symbol_length)].tobytes().decode("ascii") 479 | price, size, timestamp, total_volume = struct.unpack_from(' 0: 484 | condition = buffer[(start_index + 27 + symbol_length):(start_index + 27 + symbol_length + condition_length)].tobytes().decode("ascii") 485 | 486 | subprovider = self.subprovider_codes.get(buffer[3 + symbol_length + start_index], IntrinioRealtimeConstants.IEX) # default IEX for backward behavior consistency. 487 | market_center = buffer[(start_index + 4 + symbol_length):(start_index + 6 + symbol_length)].tobytes().decode("utf-16") 488 | 489 | return Trade(symbol, price, size, total_volume, timestamp, subprovider, market_center, condition) 490 | 491 | def subscribed(self, ticker): 492 | return 'lobby' in self.client.joined_channels or ticker in self.client.joined_channels 493 | 494 | def write_quote_to_csv(self, quote): 495 | if self.client.write_to_csv: 496 | with self._csv_lock: 497 | csv_writer = open(self.client.csv_file_path, "a") 498 | csv_writer.write(f"\"{quote.type}\",\"{quote.symbol}\",\"{quote.price}\",\"{quote.size}\",\"{quote.timestamp}\",\"{quote.subprovider}\",\"{quote.market_center}\",\"{quote.condition}\",\"\"\r\n") 499 | csv_writer.close() 500 | 501 | def write_trade_to_csv(self, trade): 502 | if self.client.write_to_csv: 503 | with self._csv_lock: 504 | csv_writer = open(self.client.csv_file_path, "a") 505 | csv_writer.write(f"\"trade\",\"{trade.symbol}\",\"{trade.price}\",\"{trade.size}\",\"{trade.timestamp}\",\"{trade.subprovider}\",\"{trade.market_center}\",\"{trade.condition}\",\"{trade.total_volume}\"\r\n") 506 | csv_writer.close() 507 | 508 | def parse_message(self, bytes, start_index, backlog_len): 509 | message_type = bytes[start_index] 510 | message_length = bytes[start_index + 1] 511 | new_start_index = start_index + message_length 512 | item = None 513 | if message_type == 0: # this is a trade 514 | item = self.parse_trade(bytes, start_index) 515 | if callable(self.client.on_trade) and self.subscribed(item.symbol): 516 | try: 517 | self.client.on_trade(item, backlog_len) 518 | self.write_trade_to_csv(item) 519 | except Exception as e: 520 | self.client.logger.error(repr(e)) 521 | else: # message_type is ask or bid (quote) 522 | if not self.client.tradesonly: 523 | item = self.parse_quote(bytes, start_index) 524 | if callable(self.client.on_quote) and self.subscribed(item.symbol): 525 | try: 526 | self.client.on_quote(item, backlog_len) 527 | self.write_quote_to_csv(item) 528 | except Exception as e: 529 | self.client.logger.error(repr(e)) 530 | return new_start_index 531 | 532 | def run(self): 533 | self.client.logger.debug("QuoteHandlingThread ready") 534 | while True: 535 | message = self.client.events.get() 536 | backlog_len = self.client.events.qsize() 537 | items_in_message = message[0] 538 | start_index = 1 539 | for i in range(0, items_in_message): 540 | start_index = self.parse_message(message, start_index, backlog_len) 541 | -------------------------------------------------------------------------------- /intriniorealtime/equities_client.py: -------------------------------------------------------------------------------- 1 | import time 2 | import requests 3 | import threading 4 | import websocket 5 | import logging 6 | import queue 7 | import struct 8 | import sys 9 | import wsaccel 10 | from enum import IntEnum, unique 11 | from typing import Optional, Dict, Any 12 | 13 | SELF_HEAL_BACKOFFS = [10, 30, 60, 300, 600] 14 | _EMPTY_STRING = "" 15 | _NAN = float("NAN") 16 | REALTIME = "REALTIME" 17 | DELAYED_SIP = "DELAYED_SIP" 18 | NASDAQ_BASIC = "NASDAQ_BASIC" 19 | MANUAL = "MANUAL" 20 | NO_PROVIDER = "NO_PROVIDER" 21 | NO_SUBPROVIDER = "NO_SUBPROVIDER" 22 | CTA_A = "CTA_A" 23 | CTA_B = "CTA_B" 24 | UTP = "UTP" 25 | OTC = "OTC" 26 | IEX = "IEX" 27 | CBOE_ONE = "CBOE_ONE" 28 | EQUITIES_EDGE = "EQUITIES_EDGE" 29 | PROVIDERS = [REALTIME, MANUAL, DELAYED_SIP, NASDAQ_BASIC, IEX, CBOE_ONE, EQUITIES_EDGE] 30 | SUB_PROVIDERS = [NO_SUBPROVIDER, CTA_A, CTA_B, UTP, OTC, NASDAQ_BASIC, IEX, CBOE_ONE, EQUITIES_EDGE] 31 | MAX_QUEUE_SIZE = 250000 32 | DEBUGGING = not (sys.gettrace() is None) 33 | HEADER_MESSAGE_FORMAT_KEY = "UseNewEquitiesFormat" 34 | HEADER_MESSAGE_FORMAT_VALUE = "v2" 35 | HEADER_CLIENT_INFORMATION_KEY = "Client-Information" 36 | HEADER_CLIENT_INFORMATION_VALUE = "IntrinioPythonSDKv6.2.0" 37 | 38 | 39 | class EquitiesQuote: 40 | def __init__(self, symbol, type, price, size, timestamp, subprovider, market_center, condition): 41 | self.symbol = symbol 42 | self.type = type 43 | self.price = price 44 | self.size = size 45 | self.timestamp = timestamp 46 | self.subprovider = subprovider 47 | self.market_center = market_center 48 | self.condition = condition 49 | 50 | @staticmethod 51 | def json_keys(): 52 | return ["symbol","type","price","size","timestamp","subprovider","market_center","condition"] 53 | 54 | @classmethod 55 | def to_json_array(self): 56 | return f'["{self.symbol}","{self.type}",{self.price},{self.size},{self.timestamp},"{self.subprovider}","{self.market_center}","{self.condition}"]' 57 | 58 | @classmethod 59 | def to_json(self): 60 | return f'{{"symbol":"{self.symbol}","type":"{self.type}","price":{self.price},"size":{self.size},"timestamp":{self.timestamp},"subprovider":"{self.subprovider}","market_center":"{self.market_center}","condition":"{self.condition}"}}' 61 | 62 | @classmethod 63 | def __str__(self): 64 | return self.symbol + ", " + self.type + ", price: " + str(self.price) + ", size: " + str(self.size) + ", timestamp: " + str(self.timestamp) + ", subprovider: " + str(self.subprovider) + ", market_center: " + str(self.market_center) + ", condition: " + str(self.condition) 65 | 66 | 67 | class EquitiesTrade: 68 | def __init__(self, symbol, price, size, total_volume, timestamp, subprovider, market_center, condition): 69 | self.symbol = symbol 70 | self.price = price 71 | self.size = size 72 | self.total_volume = total_volume 73 | self.timestamp = timestamp 74 | self.subprovider = subprovider 75 | self.market_center = market_center 76 | self.condition = condition 77 | 78 | def json_keys(self): 79 | return ["symbol","price","size","total_volume","timestamp","subprovider","market_center","condition"] 80 | 81 | def to_json_array(self): 82 | return f'["{self.symbol}",{self.price},{self.size},{self.total_volume},{self.timestamp},"{self.subprovider}","{self.market_center}","{self.condition}"]' 83 | 84 | def to_json(self): 85 | return f'{{"symbol":"{self.symbol}","price":{self.price},"size":{self.size},"total_volume":{self.total_volume},"timestamp":{self.timestamp},"subprovider":"{self.subprovider}","market_center":"{self.market_center}","condition":"{self.condition}"}}' 86 | 87 | def __str__(self): 88 | return self.symbol + ", trade, price: " + str(self.price) + ", size: " + str(self.size) + ", timestamp: " + str(self.timestamp) + ", subprovider: " + str(self.subprovider) + ", market_center: " + str(self.market_center) + ", condition: " + str(self.condition) 89 | 90 | def is_darkpool(self): 91 | if self.subprovider in [CTA_A, CTA_B, OTC, UTP, DELAYED_SIP]: 92 | return (not self.market_center) or self.market_center == 'D' or self.market_center == 'E' or self.market_center == '\0' or self.market_center.strip() == '' 93 | elif self.subprovider == NASDAQ_BASIC: 94 | return (not self.market_center) or self.market_center == 'L' or self.market_center == '2' or self.market_center == '\0' or self.market_center.strip() == '' 95 | else: 96 | return False 97 | 98 | 99 | class IntrinioRealtimeEquitiesClient: 100 | def __init__(self, configuration: Dict[str, Any], on_trade: Optional[callable], on_quote: Optional[callable]): 101 | if configuration is None: 102 | raise ValueError("Options parameter is required") 103 | 104 | self.options = configuration 105 | self.api_key = configuration.get('api_key') 106 | self.username = configuration.get('username') 107 | self.password = configuration.get('password') 108 | self.provider = configuration.get('provider') 109 | self.ipaddress = configuration.get('ipaddress') 110 | self.tradesonly = configuration.get('tradesonly') 111 | self.bypass_parsing = configuration.get('bypass_parsing', False) 112 | self.delayed = configuration.get('delayed', False) 113 | 114 | if 'channels' in configuration: 115 | self.channels = set(configuration['channels']) 116 | else: 117 | self.channels = set() 118 | 119 | if 'logger' in configuration: 120 | self.logger = configuration['logger'] 121 | else: 122 | log_formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 123 | log_handler = logging.StreamHandler() 124 | log_handler.setFormatter(log_formatter) 125 | self.logger = logging.getLogger('intrinio_realtime') 126 | if 'debug' in configuration and configuration['debug'] == True: 127 | self.logger.setLevel(logging.DEBUG) 128 | else: 129 | self.logger.setLevel(logging.INFO) 130 | self.logger.addHandler(log_handler) 131 | 132 | if 'max_queue_size' in configuration: 133 | self.quotes = queue.Queue(maxsize=configuration['max_queue_size']) 134 | else: 135 | self.quotes = queue.Queue(maxsize=MAX_QUEUE_SIZE) 136 | 137 | if self.api_key: 138 | if not self.valid_api_key(self.api_key): 139 | raise ValueError("API Key was formatted invalidly") 140 | else: 141 | if not self.username and not self.password: 142 | raise ValueError("API key or username and password are required") 143 | 144 | if not self.username: 145 | raise ValueError("Parameter 'username' must be specified") 146 | 147 | if not self.password: 148 | raise ValueError("Parameter 'password' must be specified") 149 | 150 | if not callable(on_quote): 151 | self.on_quote = None 152 | raise ValueError("Parameter 'on_quote' must be a function") 153 | else: 154 | self.on_quote = on_quote 155 | 156 | if not callable(on_trade): 157 | self.on_trade = None 158 | raise ValueError("Parameter 'on_trade' must be a function") 159 | else: 160 | self.on_trade = on_trade 161 | 162 | if self.provider not in PROVIDERS: 163 | raise ValueError(f"Parameter 'provider' is invalid, use one of {PROVIDERS}") 164 | 165 | self.ready = False 166 | self.token = None 167 | self.ws = None 168 | self.quote_receiver = None 169 | self.quote_handler = EquitiesQuoteHandler(self, self.bypass_parsing) 170 | self.joined_channels = set() 171 | self.last_queue_warning_time = 0 172 | self.last_self_heal_backoff = -1 173 | self.quote_handler.start() 174 | 175 | def auth_url(self) -> str: 176 | auth_url = "" 177 | 178 | if self.provider == REALTIME: 179 | auth_url = "https://realtime-mx.intrinio.com/auth" 180 | elif self.provider == IEX: 181 | auth_url = "https://realtime-mx.intrinio.com/auth" 182 | elif self.provider == DELAYED_SIP: 183 | auth_url = "https://realtime-delayed-sip.intrinio.com/auth" 184 | elif self.provider == NASDAQ_BASIC: 185 | auth_url = "https://realtime-nasdaq-basic.intrinio.com/auth" 186 | elif self.provider == CBOE_ONE: 187 | auth_url = "https://cboe-one.intrinio.com/auth" 188 | elif self.provider == EQUITIES_EDGE: 189 | auth_url = "https://equities-edge.intrinio.com/auth" 190 | elif self.provider == MANUAL: 191 | auth_url = "http://" + self.ipaddress + "/auth" 192 | 193 | if self.api_key: 194 | auth_url = self.api_auth_url(auth_url) 195 | 196 | return auth_url 197 | 198 | def api_auth_url(self, auth_url: str) -> str: 199 | if "?" in auth_url: 200 | auth_url = auth_url + "&" 201 | else: 202 | auth_url = auth_url + "?" 203 | 204 | return auth_url + "api_key=" + self.api_key 205 | 206 | def websocket_url(self) -> str: 207 | delayed_part = "&delayed=true" if self.delayed else "" 208 | 209 | if self.provider == REALTIME: 210 | return "wss://realtime-mx.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 211 | elif self.provider == IEX: 212 | return "wss://realtime-mx.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 213 | elif self.provider == DELAYED_SIP: 214 | return "wss://realtime-delayed-sip.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 215 | elif self.provider == NASDAQ_BASIC: 216 | return "wss://realtime-nasdaq-basic.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 217 | elif self.provider == CBOE_ONE: 218 | return "wss://cboe-one.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 219 | elif self.provider == EQUITIES_EDGE: 220 | return "wss://equities-edge.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 221 | elif self.provider == MANUAL: 222 | return "ws://" + self.ipaddress + "/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 223 | else: 224 | return "wss://realtime-mx.intrinio.com/socket/websocket?vsn=1.0.0&token=" + self.token + delayed_part 225 | 226 | def do_backoff(self): 227 | self.last_self_heal_backoff += 1 228 | i = min(self.last_self_heal_backoff, len(SELF_HEAL_BACKOFFS) - 1) 229 | backoff = SELF_HEAL_BACKOFFS[i] 230 | time.sleep(backoff) 231 | 232 | def connect(self): 233 | connected = False 234 | while not connected: 235 | try: 236 | self.logger.info("Connecting...") 237 | self.ready = False 238 | self.joined_channels = set() 239 | 240 | if self.ws: 241 | self.ws.close() 242 | time.sleep(3) 243 | 244 | self.refresh_token() 245 | self.refresh_websocket() 246 | connected = True 247 | except Exception as e: 248 | self.logger.error(f"Cannot connect: {repr(e)}") 249 | self.do_backoff() 250 | 251 | def disconnect(self): 252 | self.ready = False 253 | self.joined_channels = set() 254 | 255 | if self.ws: 256 | self.ws.close() 257 | time.sleep(1) 258 | 259 | def refresh_token(self): 260 | headers = {HEADER_CLIENT_INFORMATION_KEY: HEADER_CLIENT_INFORMATION_VALUE} 261 | if self.api_key: 262 | response = requests.get(self.auth_url(), headers=headers) 263 | else: 264 | response = requests.get(self.auth_url(), auth=(self.username, self.password), headers=headers) 265 | 266 | if response.status_code != 200: 267 | raise RuntimeError("Auth failed") 268 | 269 | self.token = response.text 270 | self.logger.info("Authentication successful!") 271 | 272 | def refresh_websocket(self): 273 | self.quote_receiver = EquitiesQuoteReceiver(self) 274 | self.quote_receiver.start() 275 | 276 | def on_connect(self): 277 | self.ready = True 278 | self.last_self_heal_backoff = -1 279 | self.refresh_channels() 280 | 281 | def on_queue_full(self): 282 | if time.time() - self.last_queue_warning_time > 1: 283 | self.logger.error("Quote queue is full! Dropped some new quotes") 284 | self.last_queue_warning_time = time.time() 285 | 286 | def join(self, channels: list[str]): 287 | if isinstance(channels, str): 288 | channels = [channels] 289 | 290 | self.channels = self.channels | set(channels) 291 | self.refresh_channels() 292 | 293 | def leave(self, channels: list[str]): 294 | if isinstance(channels, str): 295 | channels = [channels] 296 | 297 | self.channels = self.channels - set(channels) 298 | self.refresh_channels() 299 | 300 | def leave_all(self): 301 | self.channels = set() 302 | self.refresh_channels() 303 | 304 | def refresh_channels(self): 305 | if self.ready != True: 306 | return 307 | 308 | # Join new channels 309 | new_channels = self.channels - self.joined_channels 310 | self.logger.debug(f"New channels: {new_channels}") 311 | for channel in new_channels: 312 | msg = self.join_binary_message(channel) 313 | self.ws.send(msg, websocket.ABNF.OPCODE_BINARY) 314 | self.logger.info(f"Joined channel {channel}") 315 | 316 | # Leave old channels 317 | old_channels = self.joined_channels - self.channels 318 | self.logger.debug(f"Old channels: {old_channels}") 319 | for channel in old_channels: 320 | msg = self.leave_binary_message(channel) 321 | self.ws.send(msg, websocket.ABNF.OPCODE_BINARY) 322 | self.logger.info(f"Left channel {channel}") 323 | 324 | self.joined_channels = self.channels.copy() 325 | self.logger.debug(f"Current channels: {self.joined_channels}") 326 | 327 | def join_binary_message(self, channel: str): 328 | if channel == "lobby": 329 | message = bytearray([74, 1 if self.tradesonly else 0]) 330 | channel_bytes = bytes("$FIREHOSE", 'ascii') 331 | message.extend(channel_bytes) 332 | return message 333 | else: 334 | message = bytearray([74, 1 if self.tradesonly else 0]) 335 | channel_bytes = bytes(channel, 'ascii') 336 | message.extend(channel_bytes) 337 | return message 338 | 339 | def leave_binary_message(self, channel: str): 340 | if channel == "lobby": 341 | message = bytearray([76]) 342 | channel_bytes = bytes("$FIREHOSE", 'ascii') 343 | message.extend(channel_bytes) 344 | return message 345 | else: 346 | message = bytearray([76]) 347 | channel_bytes = bytes(channel, 'ascii') 348 | message.extend(channel_bytes) 349 | return message 350 | 351 | def valid_api_key(self, api_key: str): 352 | if not isinstance(api_key, str): 353 | return False 354 | 355 | if api_key == "": 356 | return False 357 | 358 | return True 359 | 360 | 361 | class EquitiesQuoteReceiver(threading.Thread): 362 | def __init__(self, client): 363 | threading.Thread.__init__(self, group=None, args=(), kwargs={}) 364 | self.daemon = True 365 | self.client = client 366 | self.enabled = True 367 | self.continuation_queue = queue.Queue(100) 368 | self.continuation_lock: threading.Lock = threading.Lock() 369 | 370 | def run(self): 371 | self.client.ws = websocket.WebSocketApp( 372 | self.client.websocket_url(), 373 | header={HEADER_MESSAGE_FORMAT_KEY: HEADER_MESSAGE_FORMAT_VALUE, HEADER_CLIENT_INFORMATION_KEY: HEADER_CLIENT_INFORMATION_VALUE}, 374 | on_open=self.on_open, 375 | on_close=self.on_close, 376 | on_message=self.on_message, 377 | on_cont_message=self.on_cont_message, 378 | on_error=self.on_error 379 | ) 380 | 381 | self.client.logger.debug("QuoteReceiver ready") 382 | self.client.ws.run_forever(skip_utf8_validation=True) # skip_utf8_validation for more performance 383 | self.client.logger.debug("QuoteReceiver exiting") 384 | 385 | def on_open(self, ws): 386 | self.client.logger.info("Websocket opened!") 387 | self.client.on_connect() 388 | 389 | def on_close(self, ws, code, message): 390 | self.client.logger.info("Websocket closed!") 391 | 392 | def on_error(self, ws, error, *args): 393 | try: 394 | self.client.logger.error(f"Websocket ERROR: {error}") 395 | self.client.connect() 396 | except Exception as e: 397 | self.client.logger.error(f"Error in on_error handler: {repr(e)}; {repr(error)}") 398 | raise e 399 | 400 | def stitch(self): 401 | full = None 402 | while not self.continuation_queue.empty(): 403 | partial = self.continuation_queue.get(True, 1) 404 | if full is None: 405 | full = partial 406 | else: 407 | full = full.join(partial) 408 | return full 409 | 410 | def on_cont_message(self, partial_message, is_last): # The 3rd argument is continue flag. if 0, the data continue 411 | try: 412 | if DEBUGGING: # This is here for performance reasons so we don't use slow reflection on every message. 413 | if isinstance(partial_message, str): 414 | self.client.logger.debug(f"Received partial message (str): {partial_message.encode('utf-8').hex()}") 415 | else: 416 | if isinstance(partial_message, bytes): 417 | self.client.logger.debug(f"Received partial message (hex): {partial_message.hex()}") 418 | #self.client.logger.debug(f"Received partial message (hex): {partial_message.hex()}") 419 | 420 | self.continuation_lock.acquire() 421 | try: 422 | if is_last == 0: 423 | self.continuation_queue.put(partial_message) 424 | else: 425 | self.continuation_queue.put(partial_message) 426 | full_message = self.stitch() 427 | self.on_message(self.client.ws, full_message) 428 | finally: 429 | self.continuation_lock.release() 430 | except queue.Full: 431 | self.client.on_queue_full() 432 | except Exception as e: 433 | hex_message = "" 434 | if isinstance(partial_message, str): 435 | hex_message = partial_message.encode('utf-8').hex() 436 | else: 437 | if isinstance(partial_message, bytes): 438 | hex_message = partial_message.hex() 439 | self.client.logger.error(f"Websocket on_message ERROR. Message as hex: {hex_message}; error: {repr(e)}") 440 | raise e 441 | 442 | def on_message(self, ws, message): 443 | try: 444 | if DEBUGGING: # This is here for performance reasons so we don't use slow reflection on every message. 445 | if isinstance(message, str): 446 | self.client.logger.debug(f"Received message (str): {message.encode('utf-8').hex()}") 447 | else: 448 | if isinstance(message, bytes): 449 | self.client.logger.debug(f"Received message (hex): {message.hex()}") 450 | self.client.quotes.put_nowait(message) 451 | except queue.Full: 452 | self.client.on_queue_full() 453 | except Exception as e: 454 | hex_message = "" 455 | if isinstance(message, str): 456 | hex_message = message.encode('utf-8').hex() 457 | else: 458 | if isinstance(message, bytes): 459 | hex_message = message.hex() 460 | self.client.logger.error(f"Websocket on_message ERROR. Message as hex: {hex_message}; error: {repr(e)}") 461 | raise e 462 | 463 | 464 | class EquitiesQuoteHandler(threading.Thread): 465 | def __init__(self, client, bypass_parsing: bool): 466 | threading.Thread.__init__(self, group=None, args=(), kwargs={}) 467 | self.daemon = True 468 | self.client = client 469 | self.bypass_parsing = bypass_parsing 470 | self.subprovider_codes = { 471 | 0: NO_SUBPROVIDER, 472 | 1: CTA_A, 473 | 2: CTA_B, 474 | 3: UTP, 475 | 4: OTC, 476 | 5: NASDAQ_BASIC, 477 | 6: IEX, 478 | 7: CBOE_ONE, 479 | 8: EQUITIES_EDGE 480 | } 481 | 482 | def parse_quote(self, quote_bytes: bytes, start_index: int = 0) -> EquitiesQuote: 483 | buffer = memoryview(quote_bytes) 484 | symbol_length = buffer[start_index + 2] 485 | symbol = buffer[(start_index + 3):(start_index + 3 + symbol_length)].tobytes().decode("ascii") 486 | quote_type = "ask" if buffer[start_index] == 1 else "bid" 487 | price, size, timestamp = struct.unpack_from(' 0: 492 | condition = buffer[(start_index + 23 + symbol_length):(start_index + 23 + symbol_length + condition_length)].tobytes().decode("ascii") 493 | 494 | subprovider = self.subprovider_codes.get(buffer[3 + symbol_length + start_index], IEX) # default IEX for backward behavior consistency. 495 | market_center = buffer[(start_index + 4 + symbol_length):(start_index + 6 + symbol_length)].tobytes().decode("utf-16") 496 | 497 | return EquitiesQuote(symbol, quote_type, price, size, timestamp, subprovider, market_center, condition) 498 | 499 | 500 | def parse_trade(self, trade_bytes: bytes, start_index: int = 0) -> EquitiesTrade: 501 | buffer = memoryview(trade_bytes) 502 | symbol_length = buffer[start_index + 2] 503 | symbol = buffer[(start_index + 3):(start_index + 3 + symbol_length)].tobytes().decode("ascii") 504 | price, size, timestamp, total_volume = struct.unpack_from(' 0: 509 | condition = buffer[(start_index + 27 + symbol_length):(start_index + 27 + symbol_length + condition_length)].tobytes().decode("ascii") 510 | 511 | subprovider = self.subprovider_codes.get(buffer[3 + symbol_length + start_index], IEX) # default IEX for backward behavior consistency. 512 | market_center = buffer[(start_index + 4 + symbol_length):(start_index + 6 + symbol_length)].tobytes().decode("utf-16") 513 | 514 | return EquitiesTrade(symbol, price, size, total_volume, timestamp, subprovider, market_center, condition) 515 | 516 | 517 | def parse_message(self, message_bytes: bytes, start_index: int, backlog_len: int) -> int: 518 | message_type = message_bytes[start_index] 519 | message_length = message_bytes[start_index + 1] 520 | new_start_index = start_index + message_length 521 | item = None 522 | if message_type == 0: # this is a trade 523 | if callable(self.client.on_trade): 524 | try: 525 | if self.bypass_parsing: 526 | item = message_bytes[start_index:new_start_index - 1] 527 | else: 528 | item = self.parse_trade(message_bytes, start_index) 529 | self.client.on_trade(item, backlog_len) 530 | except Exception as e: 531 | self.client.logger.error(repr(e)) 532 | else: # message_type is ask or bid (quote) 533 | if callable(self.client.on_quote): 534 | try: 535 | if self.bypass_parsing: 536 | item = message_bytes[start_index:new_start_index - 1] 537 | else: 538 | item = self.parse_quote(message_bytes, start_index) 539 | self.client.on_quote(item, backlog_len) 540 | except Exception as e: 541 | self.client.logger.error(repr(e)) 542 | 543 | return new_start_index 544 | 545 | def run(self): 546 | self.client.logger.debug("QuoteHandler ready") 547 | while True: 548 | message = self.client.quotes.get() 549 | backlog_len = self.client.quotes.qsize() 550 | if message is not None and len(message) > 0 and len(message) >= message[0] * 24: #sanity check on length. Should be at least as long as the smallest message times the number of messages it says it has. 551 | items_in_message = message[0] 552 | start_index = 1 553 | for i in range(0, items_in_message): 554 | start_index = self.parse_message(message, start_index, backlog_len) -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | {one line to give the program's name and a brief idea of what it does.} 635 | Copyright (C) {year} {name of author} 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | {project} Copyright (C) {year} {fullname} 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /intriniorealtime/options_client.py: -------------------------------------------------------------------------------- 1 | from distutils.command.config import config 2 | import queue 3 | import time 4 | import threading 5 | import requests 6 | import websocket 7 | import logging 8 | import struct 9 | from collections.abc import Callable 10 | from enum import IntEnum, unique 11 | 12 | _SELF_HEAL_BACKOFFS = [10, 30, 60, 300, 600] 13 | _EMPTY_STRING = "" 14 | _OPTIONS_TRADE_MESSAGE_SIZE = 72 # 61 used + 11 pad 15 | _OPTIONS_QUOTE_MESSAGE_SIZE = 52 # 48 used + 4 pad 16 | _OPTIONS_REFRESH_MESSAGE_SIZE = 52 # 44 used + 8 pad 17 | _OPTIONS_UNUSUAL_ACTIVITY_MESSAGE_SIZE = 74 # 62 used + 12 pad 18 | _NAN = float("NAN") 19 | 20 | _stopFlag: threading.Event = threading.Event() 21 | _dataMsgLock: threading.Lock = threading.Lock() 22 | _dataMsgCount: int = 0 23 | _txtMsgLock: threading.Lock = threading.Lock() 24 | _txtMsgCount: int = 0 25 | _logHandler: logging.Logger = logging.StreamHandler() 26 | _logHandler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')) 27 | _log: logging.Logger = logging.getLogger('intrinio_realtime_options') 28 | _log.setLevel(logging.INFO) 29 | _log.addHandler(_logHandler) 30 | 31 | def log(message: str): 32 | _log.info(message) 33 | 34 | def do_backoff(fn: Callable[[None], bool]): 35 | i: int = 0 36 | backoff: int = _SELF_HEAL_BACKOFFS[i] 37 | success: bool = fn() 38 | while (not success): 39 | time.sleep(backoff) 40 | i = min(i + 1, len(_SELF_HEAL_BACKOFFS) - 1) 41 | backoff = _SELF_HEAL_BACKOFFS[i] 42 | success = fn() 43 | 44 | @unique 45 | class Providers(IntEnum): 46 | OPRA = 1 47 | MANUAL = 2 48 | OPTIONS_EDGE = 3 49 | 50 | @unique 51 | class LogLevel(IntEnum): 52 | DEBUG = logging.DEBUG 53 | INFO = logging.INFO 54 | 55 | class OptionsQuote: 56 | def __init__(self, contract: str, ask_price: float, ask_size: int, bid_price: float, bid_size: int, timestamp: float): 57 | self.contract: str = contract 58 | self.ask_price: float = ask_price 59 | self.bid_price: float = bid_price 60 | self.ask_size: int = ask_size 61 | self.bid_size: int = bid_size 62 | self.timestamp: float = timestamp 63 | 64 | def __str__(self) -> str: 65 | return "Quote (Contract: {0}, AskPrice: {1:.2f}, AskSize: {2}, BidPrice: {3:.2f}, BidSize: {4}, Timestamp: {5})"\ 66 | .format(self.contract, 67 | self.ask_price, 68 | self.ask_size, 69 | self.bid_price, 70 | self.bid_size, 71 | self.timestamp) 72 | 73 | def get_strike_price(self) -> float: 74 | whole: int = (ord(self.contract[13]) - ord('0')) * 10000 + (ord(self.contract[14]) - ord('0')) * 1000 + (ord(self.contract[15]) - ord('0')) * 100 + (ord(self.contract[16]) - ord('0')) * 10 + (ord(self.contract[17]) - ord('0')) 75 | part: float = float(ord(self.contract[18]) - ord('0')) * 0.1 + float(ord(self.contract[19]) - ord('0')) * 0.01 + float(ord(self.contract[20]) - ord('0')) * 0.001 76 | return float(whole) + part 77 | 78 | def is_put(self) -> bool: 79 | return self.contract[12] == 'P' 80 | 81 | def is_call(self) -> bool: 82 | return self.contract[12] == 'C' 83 | 84 | def get_expiration_date(self) -> time.struct_time: 85 | return time.strptime(self.contract[6:12], "%y%m%d") 86 | 87 | def get_underlying_symbol(self) -> str: 88 | return self.contract[0:6].rstrip('_') 89 | 90 | @unique 91 | class Exchange(IntEnum): 92 | NYSE_AMERICAN = ord('A') 93 | BOSTON = ord('B') 94 | CBOE = ord('C') 95 | MIAMI_EMERALD = ord('D') 96 | BATS_EDGX = ord('E') 97 | ISE_GEMINI = ord('H') 98 | ISE = ord('I') 99 | MERCURY = ord('J') 100 | MIAMI = ord('M') 101 | NYSE_ARCA = ord('N') 102 | MIAMI_PEARL = ord('O') 103 | NYSE_ARCA_DEPRECIATED = ord('P') 104 | NASDAQ = ord('Q') 105 | MIAX_SAPPHIRE = ord('S') 106 | NASDAQ_BX = ord('T') 107 | MEMX = ord('U') 108 | CBOE_C2 = ord('W') 109 | PHLX = ord('X') 110 | BATS_BZX = ord('Z') 111 | UNKNOWN = ord('?') 112 | 113 | @classmethod 114 | def _missing_(cls, value): 115 | return cls.UNKNOWN 116 | 117 | class OptionsTrade: 118 | def __init__(self, contract: str, exchange: Exchange, price: float, size: int, timestamp: float, total_volume: int, qualifiers: tuple, ask_price_at_execution: float, bid_price_at_execution: float, underlying_price_at_execution: float): 119 | self.contract: str = contract 120 | self.exchange: Exchange = exchange 121 | self.price: float = price 122 | self.size: int = size 123 | self.timestamp: float = timestamp 124 | self.total_volume: int = total_volume 125 | self.qualifiers: tuple = qualifiers 126 | self.ask_price_at_execution = ask_price_at_execution 127 | self.bid_price_at_execution = bid_price_at_execution 128 | self.underlying_price_at_execution = underlying_price_at_execution 129 | 130 | def __str__(self) -> str: 131 | return "Trade (Contract: {0}, Exchange: {1}, Price: {2:.2f}, Size: {3}, Timestamp: {4}, TotalVolume: {5}, Qualifiers: {6}, AskPriceAtExecution: {7:.2f}, BidPriceAtExecution: {8:.2f}, UnderlyingPriceAtExecution: {9:.2f})"\ 132 | .format(self.contract, 133 | self.exchange.name, 134 | self.price, 135 | self.size, 136 | self.timestamp, 137 | self.total_volume, 138 | self.qualifiers, 139 | self.ask_price_at_execution, 140 | self.bid_price_at_execution, 141 | self.underlying_price_at_execution) 142 | 143 | def get_strike_price(self) -> float: 144 | whole: int = (ord(self.contract[13]) - ord('0')) * 10000 + (ord(self.contract[14]) - ord('0')) * 1000 + (ord(self.contract[15]) - ord('0')) * 100 + (ord(self.contract[16]) - ord('0')) * 10 + (ord(self.contract[17]) - ord('0')) 145 | part: float = float(ord(self.contract[18]) - ord('0')) * 0.1 + float(ord(self.contract[19]) - ord('0')) * 0.01 + float(ord(self.contract[20]) - ord('0')) * 0.001 146 | return float(whole) + part 147 | 148 | def is_put(self) -> bool: 149 | return self.contract[12] == 'P' 150 | 151 | def is_call(self) -> bool: 152 | return self.contract[12] == 'C' 153 | 154 | def get_expiration_date(self) -> time.struct_time: 155 | return time.strptime(self.contract[6:12], "%y%m%d") 156 | 157 | def get_underlying_symbol(self) -> str: 158 | return self.contract[0:6].rstrip('_') 159 | 160 | @unique 161 | class OptionsUnusualActivitySentiment(IntEnum): 162 | NEUTRAL = 0 163 | BULLISH = 1 164 | BEARISH = 2 165 | 166 | @unique 167 | class OptionsUnusualActivityType(IntEnum): 168 | BLOCK = 3 169 | SWEEP = 4 170 | LARGE = 5 171 | UNUSUAL_SWEEP = 6 172 | 173 | class OptionsRefresh: 174 | def __init__(self, contract: str, open_interest: int, open_price: float, close_price: float, high_price: float, low_price: float): 175 | self.contract: str = contract 176 | self.open_interest: int = open_interest 177 | self.open_price: float = open_price 178 | self.close_price: float = close_price 179 | self.high_price: float = high_price 180 | self.low_price: float = low_price 181 | 182 | def __str__(self) -> str: 183 | return "Refresh (Contract: {0}, OpenInterest: {1}, OpenPrice: {2:.2f}, ClosePrice: {3:.2f}, HighPrice: {4:.2f}, LowPrice: {5:.2f})"\ 184 | .format(self.contract, 185 | self.open_interest, 186 | self.open_price, 187 | self.close_price, 188 | self.high_price, 189 | self.low_price) 190 | 191 | def get_strike_price(self) -> float: 192 | whole: int = (ord(self.contract[13]) - ord('0')) * 10000 + (ord(self.contract[14]) - ord('0')) * 1000 + (ord(self.contract[15]) - ord('0')) * 100 + (ord(self.contract[16]) - ord('0')) * 10 + (ord(self.contract[17]) - ord('0')) 193 | part: float = float(ord(self.contract[18]) - ord('0')) * 0.1 + float(ord(self.contract[19]) - ord('0')) * 0.01 + float(ord(self.contract[20]) - ord('0')) * 0.001 194 | return float(whole) + part 195 | 196 | def is_put(self) -> bool: 197 | return self.contract[12] == 'P' 198 | 199 | def is_call(self) -> bool: 200 | return self.contract[12] == 'C' 201 | 202 | def get_expiration_date(self) -> time.struct_time: 203 | return time.strptime(self.contract[6:12], "%y%m%d") 204 | 205 | def get_underlying_symbol(self) -> str: 206 | return self.contract[0:6].rstrip('_') 207 | 208 | class OptionsUnusualActivity: 209 | def __init__(self, 210 | contract: str, 211 | activity_type: OptionsUnusualActivityType, 212 | sentiment: OptionsUnusualActivitySentiment, 213 | total_value: float, 214 | total_size: int, 215 | average_price: float, 216 | ask_price_at_execution: float, 217 | bid_price_at_execution: float, 218 | underlying_price_at_execution: float, 219 | timestamp: float): 220 | self.contract: str = contract 221 | self.activity_type: OptionsUnusualActivityType = activity_type 222 | self.sentiment: OptionsUnusualActivitySentiment = sentiment 223 | self.total_value: float = total_value 224 | self.total_size: int = total_size 225 | self.average_price: float = average_price 226 | self.ask_price_at_execution: float = ask_price_at_execution 227 | self.bid_price_at_execution: float = bid_price_at_execution 228 | self.underlying_price_at_execution: float = underlying_price_at_execution 229 | self.timestamp: float = timestamp 230 | 231 | def __str__(self) -> str: 232 | return "Unusual Activity (Contract: {0}, Type: {1}, Sentiment: {2}, Total Value: {3:.2f}, Total Size: {4}, Average Price: {5:.2f}, Ask at Execution: {6:.2f}, Bid at Execution: {7:.2f}, Underlying Price at Execution: {8:.2f}, Timestamp: {9})"\ 233 | .format(self.contract, 234 | self.activity_type, 235 | self.sentiment, 236 | self.total_value, 237 | self.total_size, 238 | self.average_price, 239 | self.ask_price_at_execution, 240 | self.bid_price_at_execution, 241 | self.underlying_price_at_execution, 242 | self.timestamp) 243 | 244 | def get_strike_price(self) -> float: 245 | whole: int = (ord(self.contract[13]) - ord('0')) * 10000 + (ord(self.contract[14]) - ord('0')) * 1000 + (ord(self.contract[15]) - ord('0')) * 100 + (ord(self.contract[16]) - ord('0')) * 10 + (ord(self.contract[17]) - ord('0')) 246 | part: float = float(ord(self.contract[18]) - ord('0')) * 0.1 + float(ord(self.contract[19]) - ord('0')) * 0.01 + float(ord(self.contract[20]) - ord('0')) * 0.001 247 | return float(whole) + part 248 | 249 | def is_put(self) -> bool: 250 | return self.contract[12] == 'P' 251 | 252 | def is_call(self) -> bool: 253 | return self.contract[12] == 'C' 254 | 255 | def get_expiration_date(self) -> time.struct_time: 256 | return time.strptime(self.contract[6:12], "%y%m%d") 257 | 258 | def get_underlying_symbol(self) -> str: 259 | return self.contract[0:6].rstrip('_') 260 | 261 | def _get_option_mask(use_on_trade: bool, use_on_quote: bool, use_on_refresh: bool, use_on_unusual_activity: bool) -> int: 262 | mask: int = 0 263 | if use_on_trade: 264 | mask |= 0b0001 265 | if use_on_quote: 266 | mask |= 0b0010 267 | if use_on_refresh: 268 | mask |= 0b0100 269 | if use_on_unusual_activity: 270 | mask |= 0b1000 271 | return mask 272 | 273 | class _WebSocket(websocket.WebSocketApp): 274 | def __init__(self, 275 | ws_url: str, 276 | ws_lock: threading.Lock, 277 | worker_threads: list[threading.Thread], 278 | get_channels: Callable[[None], set[tuple[str, bool]]], 279 | get_token: Callable[[None], str], 280 | get_url: Callable[[str], str], 281 | use_on_trade: bool, 282 | use_on_quote: bool, 283 | use_on_refresh: bool, 284 | use_on_ua: bool, 285 | data_queue: queue.Queue): 286 | super().__init__(ws_url, on_open=self.__on_open, on_close=self.__on_close, on_data=self.__on_data, on_error=self.__on_error) 287 | self.__wsLock: threading.Lock = ws_lock 288 | self.__continuation_queue = queue.Queue(100) 289 | self.__continuation_lock: threading.Lock = threading.Lock() 290 | self.__currently_continuing: bool = False 291 | self.__worker_threads: list[threading.Thread] = worker_threads 292 | self.__get_channels: Callable[[None], set[tuple[str, bool]]] = get_channels 293 | self.__get_token: Callable[[None], str] = get_token 294 | self.__get_url: Callable[[str], str] = get_url 295 | self.__use_on_trade: bool = use_on_trade 296 | self.__use_on_quote: bool = use_on_quote 297 | self.__use_on_refresh: bool = use_on_refresh 298 | self.__use_on_ua: bool = use_on_ua 299 | self.__data_queue: queue.Queue = data_queue 300 | self.__is_reconnecting: bool = False 301 | self.__last_reset: float = time.time() 302 | self.isReady: bool = False 303 | 304 | def __on_open(self, ws): 305 | _log.info("Websocket - Connected") 306 | self.__wsLock.acquire() 307 | try: 308 | self.isReady = True 309 | self.__is_reconnecting = False 310 | for worker in self.__worker_threads: 311 | if not worker.is_alive(): 312 | worker.start() 313 | finally: 314 | self.__wsLock.release() 315 | if self.__get_channels and callable(self.__get_channels): 316 | channels: set[str] = self.__get_channels() 317 | if channels and (len(channels) > 0): 318 | for symbol in channels: 319 | symbol_bytes = bytes(symbol, 'utf-8') 320 | message: bytes = bytearray(len(symbol_bytes) + 2) 321 | message[0] = 74 # join code 322 | message[1] = _get_option_mask(self.__use_on_trade, self.__use_on_quote, self.__use_on_refresh, self.__use_on_ua) 323 | message[2:] = symbol_bytes 324 | if self.isReady: 325 | _log.info("Websocket - Joining channel: {0}".format(symbol)) 326 | self.send_binary(message) 327 | 328 | def __try_reconnect(self) -> bool: 329 | _log.info("Websocket - Reconnecting...") 330 | if self.isReady: 331 | return True 332 | else: 333 | with self.__wsLock: 334 | self.__is_reconnecting = True 335 | token: str = self.__get_token(None) 336 | super().url = self.__get_url(token) 337 | self.start() 338 | return False 339 | 340 | def __on_close(self, ws, closeStatusCode, closeMsg): 341 | self.__wsLock.acquire() 342 | try: 343 | if (not self.__is_reconnecting): 344 | _log.info("Websocket - Closed - {0}: {1}".format(closeStatusCode, closeMsg)) 345 | self.isReady = False 346 | if (not _stopFlag.is_set()): 347 | do_backoff(self.__try_reconnect) 348 | finally: 349 | self.__wsLock.release() 350 | 351 | def __on_error(self, ws, error): 352 | _log.error("Websocket - Error - {0}".format(error)) 353 | 354 | def __stitch(self): 355 | full = None 356 | while not self.__continuation_queue.empty(): 357 | partial = self.__continuation_queue.get(True, 1) 358 | if full is None: 359 | full = partial 360 | else: 361 | full = full.join(partial) 362 | return full 363 | 364 | def __on_data(self, ws, data, code, is_last): #continueFlag - If 0, the data continues 365 | if code == websocket.ABNF.OPCODE_BINARY: 366 | with _dataMsgLock: 367 | global _dataMsgCount 368 | _dataMsgCount += 1 369 | 370 | if self.__currently_continuing or is_last == 0: # we're either in the middle of a continue, or we're starting a continue 371 | with self.__continuation_lock: 372 | if self.__currently_continuing or is_last == 0: #check lock check 373 | #_log.info(f"Received partial message (hex): {data.hex()}") 374 | self.__continuation_queue.put(data) 375 | if is_last != 0: 376 | full_message = self.__stitch() 377 | self.__data_queue.put(full_message) 378 | self.__currently_continuing = True if is_last == 0 else False # we're in the middle of a continue, but this is the last message, so remove flag 379 | else: # We're not in the middle of a continue, and this isn't marked as multi-part, so this is a full message by itself. 380 | self.__data_queue.put(data) 381 | else: # We're not in the middle of a continue, and this isn't marked as multi-part, so this is a full message by itself. 382 | self.__data_queue.put(data) 383 | else: 384 | _log.debug("Websocket - Message received") 385 | with _txtMsgLock: 386 | global _txtMsgCount 387 | _txtMsgCount += 1 388 | _log.error("Error received: {0}".format(data)) 389 | 390 | def start(self): 391 | super().run_forever(skip_utf8_validation=True) 392 | # super().run_forever(ping_interval = 5, ping_timeout = 2, skip_utf8_validation = True) 393 | 394 | def stop(self): 395 | super().close() 396 | 397 | def send(self, message: str): 398 | super().send(message, websocket.ABNF.OPCODE_TEXT) 399 | 400 | def send_binary(self, message: bytes): 401 | super().send(message, websocket.ABNF.OPCODE_BINARY) 402 | 403 | def reset(self): 404 | self.__last_reset = time.time() 405 | 406 | class Config: 407 | def __init__(self, api_key: str, provider: Providers, num_threads: int = 4, log_level: LogLevel = LogLevel.INFO, 408 | manual_ip_address: str = None, symbols: set[str] = None, delayed: bool = False): 409 | self.api_key: str = api_key 410 | self.provider: Providers = provider 411 | self.num_threads: int = num_threads 412 | self.manual_ip_address: str = manual_ip_address 413 | self.symbols: list[str] = symbols 414 | self.log_level: LogLevel = log_level 415 | self.delayed: bool = delayed 416 | 417 | def _transform_contract_to_new(contract: str) -> str: 418 | if (len(contract) <= 9) or (contract.find('.') >= 9): 419 | return contract 420 | else: # this is of the old format and we need to translate it. ex: AAPL__220101C00140000, TSLA__221111P00195000 421 | symbol: str = contract[0:6].rstrip('_') 422 | date: str = contract[6:12] 423 | call_put: str = contract[12] 424 | whole_price: str = contract[13:18].lstrip('0') 425 | if whole_price == '': 426 | whole_price = '0' 427 | decimal_price: str = contract[18:] 428 | if decimal_price[2] == '0': 429 | decimal_price = decimal_price[0:2] 430 | return "{symbol}_{date}{call_put}{whole_price}.{decimal_price}".format( 431 | symbol=symbol, 432 | date=date, 433 | call_put=call_put, 434 | whole_price=whole_price, 435 | decimal_price=decimal_price) 436 | 437 | def _copy_to(src: list, dest: list, dest_index: int): 438 | for i in range(0, len(src)): 439 | dest[i + dest_index] = src[i] 440 | 441 | def _transform_contract_to_old(alternate_formatted_contract: bytes) -> str: 442 | # Transform from server format to normal format 443 | # From this: AAPL_201016C100.00 or ABC_201016C100.003 444 | # To this: AAPL__201016C00100000 or ABC___201016C00100003 445 | contract_chars: list = [ord('_'), ord('_'), ord('_'), ord('_'), ord('_'), ord('_'), ord('2'), ord('2'), ord('0'), ord('1'), ord('0'), ord('1'), ord('C'), ord('0'), ord('0'), ord('0'), ord('0'), ord('0'), ord('0'), ord('0'), ord('0')] 446 | underscore_index: int = alternate_formatted_contract.find(ord('_')) 447 | decimal_index: int = alternate_formatted_contract[9:].find(ord('.')) + 9 # ignore decimals in tickersymbol 448 | _copy_to(alternate_formatted_contract[0:underscore_index], contract_chars, 0) # copy symbol 449 | _copy_to(alternate_formatted_contract[underscore_index+1:underscore_index+7], contract_chars, 6) # copy date 450 | _copy_to(alternate_formatted_contract[underscore_index+7:underscore_index+8], contract_chars, 12) # copy put / call 451 | _copy_to(alternate_formatted_contract[underscore_index+8:decimal_index], contract_chars, 18 - (decimal_index - underscore_index - 8)) # whole number copy 452 | _copy_to(alternate_formatted_contract[decimal_index+1:], contract_chars, 18) # decimal number copy 453 | return bytes(contract_chars).decode('ascii') 454 | 455 | def _get_seconds_from_epoch_from_ticks(ticks: int) -> float: 456 | return float(ticks) / 1_000_000_000.0 457 | 458 | def _scale_value(value: int, scale_type: int) -> float: 459 | match scale_type: 460 | case 0x00: 461 | return float(value) # divided by 1 462 | case 0x01: 463 | return float(value) / 10.0 464 | case 0x02: 465 | return float(value) / 100.0 466 | case 0x03: 467 | return float(value) / 1_000.0 468 | case 0x04: 469 | return float(value) / 10_000.0 470 | case 0x05: 471 | return float(value) / 100_000.0 472 | case 0x06: 473 | return float(value) / 1_000_000.0 474 | case 0x07: 475 | return float(value) / 10_000_000.0 476 | case 0x08: 477 | return float(value) / 100_000_000.0 478 | case 0x09: 479 | return float(value) / 1_000_000_000.0 480 | case 0x0A: 481 | return float(value) / 512.0 482 | case 0x0F: 483 | return 0.0 484 | case _: 485 | return float(value) # divided by 1 486 | 487 | def _scale_uint64(value: int, scale_type: int) -> float: 488 | if value == 18446744073709551615: 489 | return _NAN 490 | else: 491 | return _scale_value(value, scale_type) 492 | 493 | def _scale_int32(value: int, scale_type: int) -> float: 494 | if value == 2147483647 or value == -2147483648: 495 | return _NAN 496 | else: 497 | return _scale_value(value, scale_type) 498 | 499 | def _thread_fn(index: int, data: queue.Queue, 500 | on_trade: Callable[[OptionsTrade], None], 501 | on_quote: Callable[[OptionsQuote], None] = None, 502 | on_refresh: Callable[[OptionsRefresh], None] = None, 503 | on_unusual_activity: Callable[[OptionsUnusualActivity], None] = None): 504 | _log.debug("Starting worker thread {0}".format(index)) 505 | datum: bytes = None 506 | count: int = 0 507 | start_index: int = 1 508 | msg_type: int = 0 509 | message: bytes = None 510 | while not _stopFlag.is_set(): 511 | try: 512 | datum = data.get(True, 1.0) 513 | count = datum[0] 514 | start_index = 1 515 | for _ in range(count): 516 | msg_type = datum[start_index + 22] 517 | if msg_type == 1: # Quote 518 | message: bytes = datum[start_index:(start_index + _OPTIONS_QUOTE_MESSAGE_SIZE)] 519 | # byte structure: 520 | # contract length [0] 521 | # contract [1-21] utf-8 string 522 | # event type [22] uint8 523 | # price type [23] uint8 524 | # ask price [24-27] int32 525 | # ask size [28-31] uint32 526 | # bid price [32-35] int32 527 | # bid size [36-39] uint32 528 | # timestamp [40-47] uint64 529 | contract: str = _transform_contract_to_old(message[1:message[0]+1]) 530 | ask_price: float = _scale_int32(struct.unpack_from(' 2: # Unusual Activity 569 | message: bytes = datum[start_index:(start_index + _OPTIONS_UNUSUAL_ACTIVITY_MESSAGE_SIZE)] 570 | # byte structure: 571 | # contract length [0] uint8 572 | # contract [1-21] utf-8 string 573 | # event type [22] uint8 574 | # sentiment type [23] uint8 575 | # price type [24] uint8 576 | # underlying price type [25] uint8 577 | # total value [26-33] uint64 578 | # total size [34-37] uint32 579 | # average price [38-41] int32 580 | # ask price at execution [42-45] int32 581 | # bid price at execution [46-49] int32 582 | # underlying price at execution [50-53] int32 583 | # timestamp [54-61] uint64 584 | contract: str = _transform_contract_to_old(message[1:message[0]+1]) 585 | activity_type: OptionsUnusualActivityType = message[22] 586 | sentiment: OptionsUnusualActivitySentiment = message[23] 587 | total_value: float = _scale_uint64(struct.unpack_from(' 0): 679 | self.__channels: set[str] = set((_transform_contract_to_new(symbol)) for symbol in config.symbols) 680 | else: 681 | self.__channels: set[str] = set() 682 | self.__data: queue.Queue = queue.Queue() 683 | self.__t_lock: threading.Lock = threading.Lock() 684 | self.__ws_lock: threading.Lock = threading.Lock() 685 | self.__worker_threads: list[threading.Thread] = [threading.Thread(None, 686 | _thread_fn, 687 | args=[i, self.__data, on_trade, on_quote, on_refresh, on_unusual_activity], 688 | daemon=True) for i in range(config.num_threads)] 689 | self.__socket_thread: threading.Thread = None 690 | self.__is_started: bool = False 691 | _log.setLevel(config.log_level) 692 | 693 | def __all_ready(self) -> bool: 694 | self.__ws_lock.acquire() 695 | ready: bool = True 696 | try: 697 | ready = (self.__webSocket is not None) and (self.__webSocket.isReady) 698 | finally: 699 | self.__ws_lock.release() 700 | return ready 701 | 702 | def __get_websocket(self) -> _WebSocket: 703 | return self.__webSocket 704 | 705 | def __get_auth_url(self) -> str: 706 | if self.__provider == Providers.OPRA: 707 | return "https://realtime-options.intrinio.com/auth?api_key=" + self.__apiKey 708 | elif self.__provider == Providers.OPTIONS_EDGE: 709 | return "https://options-edge.intrinio.com/auth?api_key=" + self.__apiKey 710 | elif self.__provider == Providers.MANUAL: 711 | return "http://" + self.__manualIP + "/auth?api_key=" + self.__apiKey 712 | else: 713 | raise ValueError("Provider not specified") 714 | 715 | def __get_web_socket_url(self, token: str) -> str: 716 | delay: str = "&delayed=true" if self.__delayed else "" 717 | if self.__provider == Providers.OPRA: 718 | return "wss://realtime-options.intrinio.com/socket/websocket?vsn=1.0.0&token=" + token + delay 719 | elif self.__provider == Providers.OPTIONS_EDGE: 720 | return "wss://options-edge.intrinio.com/socket/websocket?vsn=1.0.0&token=" + token + delay 721 | elif self.__provider == Providers.MANUAL: 722 | return "ws://" + self.__manualIP + "/socket/websocket?vsn=1.0.0&token=" + token + delay 723 | else: 724 | raise ValueError("Provider not specified") 725 | 726 | def __try_set_token(self) -> bool: 727 | _log.info("Authorizing...") 728 | headers = {"Client-Information": "IntrinioOptionsPythonSDKv2.5"} 729 | try: 730 | response: requests.Response = requests.get(self.__get_auth_url(), headers=headers, timeout=1) 731 | if response.status_code != 200: 732 | _log.error( 733 | "Authorization Failure (status code = {0}): The authorization key you provided is likely incorrect.".format( 734 | response.status_code)) 735 | return False 736 | self.__token = (response.text, time.time()) 737 | _log.info("Authorization successful.") 738 | return True 739 | except requests.exceptions.Timeout: 740 | _log.error("Authorization Failure: The request timed out.") 741 | return False 742 | except requests.exceptions.ConnectionError as err: 743 | _log.error("Authorization Failure: {0}".format(err)) 744 | return False 745 | 746 | def __get_token(self) -> str: 747 | self.__t_lock.acquire() 748 | try: 749 | if ((time.time() - self.__token[1]) > (60 * 60 * 24)): # 60sec/min * 60min/hr * 24hrs = 1 day 750 | do_backoff(self.__try_set_token) 751 | return self.__token[0] 752 | finally: 753 | self.__t_lock.release() 754 | 755 | def __get_channels(self) -> set[str]: 756 | return self.__channels 757 | 758 | def __join(self, symbol: str): 759 | transformed_symbol: str = _transform_contract_to_new(symbol) 760 | if transformed_symbol not in self.__channels: 761 | self.__channels.add(transformed_symbol) 762 | symbol_bytes = bytes(transformed_symbol, 'utf-8') 763 | message: bytes = bytearray(len(symbol_bytes)+2) 764 | message[0] = 74 # join code 765 | message[1] = _get_option_mask(self.__use_on_trade, self.__use_on_quote, self.__use_on_refresh, self.__use_on_unusual_activity) 766 | message[2:] = symbol_bytes 767 | if self.__webSocket.isReady: 768 | _log.info("Websocket - Joining channel: {0}".format(transformed_symbol)) 769 | self.__webSocket.send_binary(message) 770 | 771 | def __leave(self, symbol: str): 772 | transformed_symbol: str = _transform_contract_to_new(symbol) 773 | if transformed_symbol in self.__channels: 774 | self.__channels.remove(transformed_symbol) 775 | symbol_bytes = bytes(transformed_symbol, 'utf-8') 776 | message: bytes = bytearray(len(symbol_bytes) + 2) 777 | message[0] = 76 # leave code 778 | message[1] = _get_option_mask(self.__use_on_trade, self.__use_on_quote, self.__use_on_refresh, self.__use_on_unusual_activity) 779 | message[2:] = symbol_bytes 780 | if self.__webSocket.isReady: 781 | _log.info("Websocket - Leaving channel: {0}".format(transformed_symbol)) 782 | self.__webSocket.send_binary(message) 783 | 784 | def join(self, *symbols): 785 | if self.__is_started: 786 | while not self.__all_ready(): 787 | time.sleep(1.0) 788 | for (symbol) in symbols: 789 | self.__join(symbol) 790 | 791 | def join_firehose(self): 792 | if "$FIREHOSE" in self.__channels: 793 | _log.warn("This client has already joined the firehose channel") 794 | else: 795 | if self.__is_started: 796 | while not self.__all_ready(): 797 | time.sleep(1.0) 798 | self.__join("$FIREHOSE") 799 | 800 | def leave(self, *symbols): 801 | if not symbols: 802 | _log.info("Leaving all channels") 803 | channels: set[str] = self.__channels.copy() 804 | for (symbol) in channels: 805 | self.__leave(symbol) 806 | symbol_set: set[str] = set(symbols) 807 | for sym in symbol_set: 808 | self.__leave(sym) 809 | 810 | def leave_firehose(self): 811 | if "$FIREHOSE" in self.__channels: 812 | self.__leave("$FIREHOSE") 813 | 814 | def __socket_start_fn(self, token: str): 815 | _log.info("Websocket - Connecting...") 816 | ws_url: str = self.__get_web_socket_url(token) 817 | self.__webSocket = _WebSocket(ws_url, 818 | self.__ws_lock, 819 | self.__worker_threads, 820 | self.__get_channels, 821 | self.__get_token, 822 | self.__get_web_socket_url, 823 | self.__use_on_trade, 824 | self.__use_on_quote, 825 | self.__use_on_refresh, 826 | self.__use_on_unusual_activity, 827 | self.__data) 828 | self.__webSocket.start() 829 | 830 | def start(self): 831 | if (not (self.__use_on_trade or self.__use_on_quote or self.__use_on_refresh or self.__use_on_unusual_activity)): 832 | raise ValueError("You must set at least one callback method before starting client") 833 | token: str = self.__get_token() 834 | self.__ws_lock.acquire() 835 | try: 836 | self.__socket_thread = threading.Thread = threading.Thread(None, self.__socket_start_fn, args=[token], daemon=True) 837 | finally: 838 | self.__ws_lock.release() 839 | self.__socket_thread.start() 840 | self.__is_started = True 841 | 842 | def stop(self): 843 | _log.info("Stopping...") 844 | if len(self.__channels) > 0: 845 | self.leave() 846 | time.sleep(1.0) 847 | self.__ws_lock.acquire() 848 | try: 849 | self.__webSocket.isReady = False 850 | finally: 851 | self.__ws_lock.release() 852 | _stopFlag.set() 853 | self.__webSocket.stop() 854 | for i in range(len(self.__worker_threads)): 855 | self.__worker_threads[i].join() 856 | _log.debug("Worker thread {0} joined".format(i)) 857 | self.__socket_thread.join() 858 | _log.debug("Socket thread joined") 859 | _log.info("Stopped") 860 | 861 | def get_stats(self) -> tuple[int, int, int]: 862 | return _dataMsgCount, _txtMsgCount, self.__data.qsize() 863 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # intrinio realtime python sdk 2 | SDK for working with Intrinio's realtime OPRA, Options Edge, IEX, delayed SIP, CBOE One, Equities Edge, or NASDAQ Basic prices feeds. Get a comprehensive view with increased market volume and enjoy minimized exchange and per user fees. 3 | 4 | [Intrinio](https://intrinio.com/) provides real-time stock and option prices via a two-way WebSocket connection. To get started, [subscribe to a real-time equity feed](https://intrinio.com/real-time-multi-exchange), or [subscribe to a real-time options feed](https://intrinio.com/financial-market-data/options-data) and follow the instructions below. 5 | 6 | ## Requirements 7 | 8 | - Python 3.10 9 | - NOTE: You need https://pypi.org/project/websocket-client/, not https://pypi.org/project/websocket/. 10 | 11 | ## Docker 12 | Add your API key to the example_app_equities.py or example_app_options.py file, comment the correct line (16 or 17) in Dockerfile, then 13 | ``` 14 | docker compose build 15 | docker compose run client 16 | ``` 17 | 18 | ## Features 19 | 20 | ### Equities 21 | 22 | * Receive streaming, real-time pricing (trades, NBBO bid, ask) 23 | * Subscribe to updates from individual securities, individual contracts, or 24 | * Subscribe to updates for all securities (Lobby/Firehose mode) 25 | * Replay a specific day (at actual pace or as fast as it loads) while the servers are down, either for testing or fetching missed data. 26 | 27 | ### Options 28 | 29 | * Receive streaming, real-time option price updates: 30 | * every trade 31 | * conflated bid and ask 32 | * open interest, open, close, high, low 33 | * unusual activity(block trades, sweeps, whale trades, unusual sweeps) 34 | * Subscribe to updates from individual options contracts (or option chains) 35 | * Subscribe to updates for the entire universe of option contracts (~1.5M option contracts) 36 | 37 | ## Installation 38 | ``` 39 | pip install intriniorealtime 40 | ``` 41 | 42 | ## Handling Quotes and the Queue 43 | 44 | There are thousands of securities (and millions of options contracts), each with their own feed of activity. We highly encourage you to make your on-event handlers as short as possible and follow a queue pattern so your app can handle the volume of activity. 45 | Note that quotes (ask and bid updates) comprise 99% of the volume of the entire feed. Be cautious when deciding to receive quote updates. 46 | 47 | ## Example Equities Usage 48 | 49 | ```python 50 | import threading 51 | import signal 52 | import time 53 | import sys 54 | import datetime 55 | from threading import Timer,Thread,Event,Lock 56 | 57 | from intriniorealtime.equities_client import IntrinioRealtimeEquitiesClient 58 | from intriniorealtime.equities_replay_client import IntrinioReplayEquitiesClient 59 | from intriniorealtime.equities_client import EquitiesQuote 60 | from intriniorealtime.equities_client import EquitiesTrade 61 | 62 | trade_count = 0 63 | ask_count = 0 64 | bid_count = 0 65 | backlog_count = 0 66 | 67 | def on_quote(quote, backlog): 68 | global ask_count 69 | global bid_count 70 | global backlog_count 71 | backlog_count = backlog 72 | if isinstance(quote, EquitiesQuote) and 'type' in quote.__dict__: 73 | if quote.type == "ask": ask_count += 1 74 | else: bid_count += 1 75 | 76 | def on_trade(trade, backlog): 77 | global trade_count 78 | global backlog_count 79 | backlog_count = backlog 80 | trade_count += 1 81 | 82 | class Summarize(threading.Thread): 83 | def __init__(self, stop_flag): 84 | threading.Thread.__init__(self, group=None, args=(), kwargs={}) 85 | self.daemon = True 86 | self.stop_flag = stop_flag 87 | 88 | def run(self): 89 | global trade_count 90 | global bid_count 91 | global ask_count 92 | global backlog_count 93 | while not self.stop_flag.wait(5): 94 | print("trades: " + str(trade_count) + "; asks: " + str(ask_count) + "; bids: " + str(bid_count) + "; backlog: " + str(backlog_count)) 95 | 96 | 97 | configuration = { 98 | 'api_key': 'API_KEY_HERE', 99 | 'provider': 'IEX' # 'REALTIME' (IEX), or 'IEX', or 'DELAYED_SIP', or 'NASDAQ_BASIC', or 'CBOE_ONE' or 'EQUITIES_EDGE' 100 | # ,'delayed': True # Add this if you have realtime (nondelayed) access and want to force delayed mode. If you only have delayed mode access, this is redundant. 101 | # ,'replay_date': datetime.date.today() - datetime.timedelta(days=1) # needed for ReplayClient. The date to replay. 102 | # ,'with_simulated_delay': False # needed for ReplayClient. This plays back the events at the same rate they happened in market. 103 | # ,'delete_file_when_done': True # needed for ReplayClient 104 | # ,'write_to_csv': False # needed for ReplayClient 105 | # ,'csv_file_path': 'data.csv' # needed for ReplayClient 106 | # ,'bypass_parsing': True # if you want to handle parsing yourself, set this to True. Otherwise, leave it alone. 107 | # ,'debug': True 108 | # ,'max_queue_size': 250000 109 | } 110 | 111 | 112 | client = IntrinioRealtimeEquitiesClient(configuration, on_trade, on_quote) 113 | # client = IntrinioReplayClient(options, on_trade, on_quote) 114 | stop_event = Event() 115 | 116 | 117 | def on_kill_process(sig, frame): 118 | print("Stopping") 119 | stop_event.set() 120 | client.disconnect() 121 | sys.exit(0) 122 | 123 | 124 | signal.signal(signal.SIGINT, on_kill_process) 125 | 126 | 127 | client.join(['AAPL','GE','MSFT']) 128 | # client.join(['lobby']) 129 | client.connect() 130 | 131 | summarize_thread = Summarize(stop_event) 132 | summarize_thread.start() 133 | 134 | time.sleep(120) 135 | 136 | # sigint, or ctrl+c, during the thread wait will also perform the same below code. 137 | print("Stopping") 138 | stop_event.set() 139 | client.disconnect() 140 | sys.exit(0) 141 | ``` 142 | 143 | ## Equities Data Format 144 | 145 | ### Quote Message 146 | 147 | ```python 148 | { 'symbol': 'AAPL', 149 | 'type': 'ask', 150 | 'price': '102.3', 151 | 'size': 100, 152 | 'timestamp': 1636395583000000000, 153 | 'subprovider': 'UTP', 154 | 'market_center': '', 155 | 'condition': '' } 156 | ``` 157 | 158 | * **symbol** - the ticker of the security 159 | * **type** - the quote type 160 | * **`ask`** - represents the top-of-book ask price 161 | * **`bid`** - represents the top-of-book bid price 162 | * **price** - the price in USD 163 | * **size** - the size of the `last` trade, or total volume of orders at the top-of-book `bid` or `ask` price 164 | * **timestamp** - a Unix timestamp (nanoseconds since unix epoch) 165 | * **subprovider** - Denotes the detailed source within grouped sources. 166 | * **`NO_SUBPROVIDER`** - No subtype specified. 167 | * **`CTA_A`** - CTA_A in the DELAYED_SIP provider. 168 | * **`CTA_B`** - CTA_B in the DELAYED_SIP provider. 169 | * **`UTP`** - UTP in the DELAYED_SIP provider. 170 | * **`OTC`** - OTC in the DELAYED_SIP provider. 171 | * **`NASDAQ_BASIC`** - NASDAQ Basic in the NASDAQ_BASIC provider. 172 | * **`IEX`** - From the IEX exchange in the REALTIME provider. 173 | * **`CBOE_ONE`** - From the CBOE One exchanges provider. 174 | * **`EQUITIES_EDGE`** - From the Equities Edge provider. 175 | * **market_center** - Provides the market center 176 | * **condition** - Provides the condition 177 | 178 | ### Trade Message 179 | 180 | ```python 181 | { 'symbol': 'AAPL', 182 | 'total_volume': '106812', 183 | 'price': '102.3', 184 | 'size': 100, 185 | 'timestamp': 1636395583000000000, 186 | 'subprovider': 'IEX', 187 | 'market_center': '', 188 | 'condition': '' } 189 | ``` 190 | 191 | * **symbol** - the ticker of the security 192 | * **total_volume** - the total volume of trades for the security so far today. 193 | * **price** - the price in USD 194 | * **size** - the size of the `last` trade, or total volume of orders at the top-of-book `bid` or `ask` price 195 | * **timestamp** - a Unix timestamp (nanoseconds since unix epoch) 196 | * **subprovider** - Denotes the detailed source within grouped sources. 197 | * **`NO_SUBPROVIDER`** - No subtype specified. 198 | * **`CTA_A`** - CTA_A in the DELAYED_SIP provider. 199 | * **`CTA_B`** - CTA_B in the DELAYED_SIP provider. 200 | * **`UTP`** - UTP in the DELAYED_SIP provider. 201 | * **`OTC`** - OTC in the DELAYED_SIP provider. 202 | * **`NASDAQ_BASIC`** - NASDAQ Basic in the NASDAQ_BASIC provider. 203 | * **`IEX`** - From the IEX exchange in the REALTIME provider. 204 | * **`CBOE_ONE`** - From the CBOE One exchanges provider. 205 | * **`EQUITIES_EDGE`** - From the Equities Edge provider. 206 | * **market_center** - Provides the market center 207 | * **condition** - Provides the condition 208 | 209 | ### Equities Trade Conditions 210 | 211 | | Value | Description | 212 | |-------|---------------------------------------------------| 213 | | @ | Regular Sale | 214 | | A | Acquisition | 215 | | B | Bunched Trade | 216 | | C | Cash Sale | 217 | | D | Distribution | 218 | | E | Placeholder | 219 | | F | Intermarket Sweep | 220 | | G | Bunched Sold Trade | 221 | | H | Priced Variation Trade | 222 | | I | Odd Lot Trade | 223 | | K | Rule 155 Trade (AMEX) | 224 | | L | Sold Last | 225 | | M | Market Center Official Close | 226 | | N | Next Day | 227 | | O | Opening Prints | 228 | | P | Prior Reference Price | 229 | | Q | Market Center Official Open | 230 | | R | Seller | 231 | | S | Split Trade | 232 | | T | Form T | 233 | | U | Extended Trading Hours (Sold Out of Sequence) | 234 | | V | Contingent Trade | 235 | | W | Average Price Trade | 236 | | X | Cross/Periodic Auction Trade | 237 | | Y | Yellow Flag Regular Trade | 238 | | Z | Sold (Out of Sequence) | 239 | | 1 | Stopped Stock (Regular Trade) | 240 | | 4 | Derivatively Priced | 241 | | 5 | Re-Opening Prints | 242 | | 6 | Closing Prints | 243 | | 7 | Qualified Contingent Trade (QCT) | 244 | | 8 | Placeholder for 611 Exempt | 245 | | 9 | Corrected Consolidated Close (Per Listing Market) | 246 | 247 | 248 | ### Equities Trade Conditions (CBOE One) 249 | Trade conditions for CBOE One are represented as the integer representation of a bit flag. 250 | 251 | None = 0, 252 | UpdateHighLowConsolidated = 1, 253 | UpdateLastConsolidated = 2, 254 | UpdateHighLowMarketCenter = 4, 255 | UpdateLastMarketCenter = 8, 256 | UpdateVolumeConsolidated = 16, 257 | OpenConsolidated = 32, 258 | OpenMarketCenter = 64, 259 | CloseConsolidated = 128, 260 | CloseMarketCenter = 256, 261 | UpdateVolumeMarketCenter = 512 262 | 263 | 264 | ### Equities Quote Conditions 265 | 266 | | Value | Description | 267 | |-------|---------------------------------------------| 268 | | R | Regular | 269 | | A | Slow on Ask | 270 | | B | Slow on Bid | 271 | | C | Closing | 272 | | D | News Dissemination | 273 | | E | Slow on Bid (LRP or Gap Quote) | 274 | | F | Fast Trading | 275 | | G | Trading Range Indication | 276 | | H | Slow on Bid and Ask | 277 | | I | Order Imbalance | 278 | | J | Due to Related - News Dissemination | 279 | | K | Due to Related - News Pending | 280 | | O | Open | 281 | | L | Closed | 282 | | M | Volatility Trading Pause | 283 | | N | Non-Firm Quote | 284 | | O | Opening | 285 | | P | News Pending | 286 | | S | Due to Related | 287 | | T | Resume | 288 | | U | Slow on Bid and Ask (LRP or Gap Quote) | 289 | | V | In View of Common | 290 | | W | Slow on Bid and Ask (Non-Firm) | 291 | | X | Equipment Changeover | 292 | | Y | Sub-Penny Trading | 293 | | Z | No Open / No Resume | 294 | | 1 | Market Wide Circuit Breaker Level 1 | 295 | | 2 | Market Wide Circuit Breaker Level 2 | 296 | | 3 | Market Wide Circuit Breaker Level 3 | 297 | | 4 | On Demand Intraday Auction | 298 | | 45 | Additional Information Required (CTS) | 299 | | 46 | Regulatory Concern (CTS) | 300 | | 47 | Merger Effective | 301 | | 49 | Corporate Action (CTS) | 302 | | 50 | New Security Offering (CTS) | 303 | | 51 | Intraday Indicative Value Unavailable (CTS) | 304 | 305 | 306 | ## Example Options Usage 307 | ```python 308 | import threading 309 | import signal 310 | import time 311 | import sys 312 | import logging 313 | from threading import Event, Lock 314 | 315 | from intriniorealtime.options_client import IntrinioRealtimeOptionsClient 316 | from intriniorealtime.options_client import OptionsQuote 317 | from intriniorealtime.options_client import OptionsTrade 318 | from intriniorealtime.options_client import OptionsRefresh 319 | from intriniorealtime.options_client import OptionsUnusualActivity 320 | from intriniorealtime.options_client import OptionsUnusualActivityType 321 | from intriniorealtime.options_client import OptionsUnusualActivitySentiment 322 | from intriniorealtime.options_client import log 323 | from intriniorealtime.options_client import Config 324 | from intriniorealtime.options_client import Providers 325 | from intriniorealtime.options_client import LogLevel 326 | 327 | options_trade_count = 0 328 | options_trade_count_lock = Lock() 329 | options_quote_count = 0 330 | options_quote_count_lock = Lock() 331 | options_refresh_count = 0 332 | options_refresh_count_lock = Lock() 333 | options_ua_block_count = 0 334 | options_ua_block_count_lock = Lock() 335 | options_ua_sweep_count = 0 336 | options_ua_sweep_count_lock = Lock() 337 | options_ua_large_trade_count = 0 338 | options_ua_large_trade_count_lock = Lock() 339 | options_ua_unusual_sweep_count = 0 340 | options_ua_unusual_sweep_count_lock = Lock() 341 | 342 | 343 | def on_quote(quote: OptionsQuote): 344 | global options_quote_count 345 | global options_quote_count_lock 346 | with options_quote_count_lock: 347 | options_quote_count += 1 348 | 349 | 350 | def on_trade(trade: OptionsTrade): 351 | global options_trade_count 352 | global options_trade_count_lock 353 | with options_trade_count_lock: 354 | options_trade_count += 1 355 | 356 | 357 | def on_refresh(refresh: OptionsRefresh): 358 | global options_refresh_count 359 | global options_refresh_count_lock 360 | with options_refresh_count_lock: 361 | options_refresh_count += 1 362 | 363 | 364 | def on_unusual_activity(ua: OptionsUnusualActivity): 365 | global options_ua_block_count 366 | global options_ua_block_count_lock 367 | global options_ua_sweep_count 368 | global options_ua_sweep_count_lock 369 | global options_ua_large_trade_count 370 | global options_ua_large_trade_count_lock 371 | global options_ua_unusual_sweep_count 372 | global options_ua_unusual_sweep_count_lock 373 | if ua.activity_type == OptionsUnusualActivityType.BLOCK: 374 | with options_ua_block_count_lock: 375 | options_ua_block_count += 1 376 | elif ua.activity_type == OptionsUnusualActivityType.SWEEP: 377 | with options_ua_sweep_count_lock: 378 | options_ua_sweep_count += 1 379 | elif ua.activity_type == OptionsUnusualActivityType.LARGE: 380 | with options_ua_large_trade_count_lock: 381 | options_ua_large_trade_count += 1 382 | elif ua.activity_type == OptionsUnusualActivityType.UNUSUAL_SWEEP: 383 | with options_ua_unusual_sweep_count_lock: 384 | options_ua_unusual_sweep_count += 1 385 | else: 386 | log("on_unusual_activity - Unknown activity_type {0}", ua.activity_type) 387 | 388 | 389 | class Summarize(threading.Thread): 390 | def __init__(self, stop_flag: threading.Event, intrinio_client: IntrinioRealtimeOptionsClient): 391 | threading.Thread.__init__(self, group=None, args=(), kwargs={}, daemon=True) 392 | self.__stop_flag: threading.Event = stop_flag 393 | self.__client = intrinio_client 394 | 395 | def run(self): 396 | while not self.__stop_flag.is_set(): 397 | time.sleep(30.0) 398 | (dataMsgs, txtMsgs, queueDepth) = self.__client.get_stats() 399 | log("Client Stats - Data Messages: {0}, Text Messages: {1}, Queue Depth: {2}".format(dataMsgs, txtMsgs, queueDepth)) 400 | log( 401 | "App Stats - Trades: {0}, Quotes: {1}, Refreshes: {2}, Blocks: {3}, Sweeps: {4}, Large Trades: {5}, Unusual Sweeps: {6}" 402 | .format( 403 | options_trade_count, 404 | options_quote_count, 405 | options_refresh_count, 406 | options_ua_block_count, 407 | options_ua_sweep_count, 408 | options_ua_large_trade_count, 409 | options_ua_unusual_sweep_count)) 410 | 411 | 412 | # Your config object MUST include the 'api_key' and 'provider', at a minimum 413 | config: Config = Config( 414 | api_key="API_KEY_HERE", 415 | provider=Providers.OPRA, # or Providers.OPTIONS_EDGE 416 | num_threads=8, 417 | symbols=["AAPL", "BRKB__230217C00300000"], # this is a static list of symbols (options contracts or option chains) that will automatically be subscribed to when the client starts 418 | log_level=LogLevel.INFO, 419 | delayed=False) #set delayed parameter to true if you have realtime access but want the data delayed 15 minutes anyway 420 | 421 | # Register only the callbacks that you want. 422 | # Take special care when registering the 'on_quote' handler as it will increase throughput by ~10x 423 | intrinioRealtimeOptionsClient: IntrinioRealtimeOptionsClient = IntrinioRealtimeOptionsClient(config, on_trade=on_trade, on_quote=on_quote, on_refresh=on_refresh, on_unusual_activity=on_unusual_activity) 424 | 425 | stop_event = Event() 426 | 427 | 428 | def on_kill_process(sig, frame): 429 | log("Sample Application - Stopping") 430 | stop_event.set() 431 | intrinioRealtimeOptionsClient.stop() 432 | sys.exit(0) 433 | 434 | 435 | signal.signal(signal.SIGINT, on_kill_process) 436 | 437 | summarize_thread = Summarize(stop_event, intrinioRealtimeOptionsClient) 438 | summarize_thread.start() 439 | 440 | intrinioRealtimeOptionsClient.start() 441 | 442 | #use this to join the channels already declared in your config 443 | intrinioRealtimeOptionsClient.join() 444 | 445 | # Use this to subscribe to the entire universe of symbols (option contracts). This requires special permission. 446 | # intrinioRealtimeOptionsClient.join_firehose() 447 | 448 | # Use this to subscribe, dynamically, to an option chain (all option contracts for a given underlying contract). 449 | # intrinioRealtimeOptionsClient.join("AAPL") 450 | 451 | # Use this to subscribe, dynamically, to a specific option contract. 452 | # intrinioRealtimeOptionsClient.join("AAP___230616P00250000") 453 | 454 | # Use this to subscribe, dynamically, a list of specific option contracts or option chains. 455 | # intrinioRealtimeOptionsClient.join("GOOG__220408C02870000", "MSFT__220408C00315000", "AAPL__220414C00180000", "TSLA", "GE") 456 | 457 | time.sleep(60 * 60) 458 | # sigint, or ctrl+c, during the thread wait will also perform the same below code. 459 | on_kill_process(None, None) 460 | 461 | ``` 462 | 463 | ## Options Data Format 464 | ### Trade Message 465 | 466 | ```python 467 | class Trade: 468 | def __init__(self, contract: str, exchange: Exchange, price: float, size: int, timestamp: float, total_volume: int, qualifiers: tuple, ask_price_at_execution: float, bid_price_at_execution: float, underlying_price_at_execution: float): 469 | self.contract: str = contract 470 | self.exchange: Exchange = exchange 471 | self.price: float = price 472 | self.size: int = size 473 | self.timestamp: float = timestamp 474 | self.total_volume: int = total_volume 475 | self.qualifiers: tuple = qualifiers 476 | self.ask_price_at_execution = ask_price_at_execution 477 | self.bid_price_at_execution = bid_price_at_execution 478 | self.underlying_price_at_execution = underlying_price_at_execution 479 | ``` 480 | 481 | * **contract** - Identifier for the options contract. This includes the ticker symbol, put/call, expiry, and strike price. 482 | * **exchange** - Exchange(IntEnum): the specific exchange through which the trade occurred 483 | * **price** - the price in USD 484 | * **size** - the size of the last trade in hundreds (each contract is for 100 shares). 485 | * **total_volume** - The number of contracts traded so far today. 486 | * **timestamp** - a Unix timestamp (with microsecond precision) 487 | * **qualifiers** - a tuple containing 4 ints: each item represents one trade qualifier. see list of possible [Trade Qualifiers](#trade-qualifiers), below. 488 | * **ask_price_at_execution** - the contract ask price in USD at the time of execution. 489 | * **bid_price_at_execution** - the contract bid price in USD at the time of execution. 490 | * **underlying_price_at_execution** - the contract's underlying security price in USD at the time of execution. 491 | 492 | ### Trade Qualifiers 493 | 494 | ### Option Trade Qualifiers 495 | 496 | | Value | Description | 497 | |-------|----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 498 | | 0 | Transaction is a regular trade | 499 | | 1 | Out-of-sequence cancellation | 500 | | 2 | Transaction is being reported late and is out-of-sequence | 501 | | 3 | In-sequence cancellation | 502 | | 4 | Transaction is being reported late, but is in correct sequence. | 503 | | 5 | Cancel the first trade of the day | 504 | | 6 | Late report of the opening trade and is out -of-sequence. Send an open price. | 505 | | 7 | Transaction was the only one reported this day for the particular option contract and is now to be cancelled. | 506 | | 8 | Late report of an opening trade and is in correct sequence. Process as regular trade. | 507 | | 9 | Transaction was executed electronically. Process as regular trade. | 508 | | 10 | Re-opening of a contract which was halted earlier. Process as regular trade. | 509 | | 11 | Transaction is a contract for which the terms have been adjusted to reflect stock dividend, stock split or similar event. Process as regular trade. | 510 | | 12 | Transaction represents a trade in two options of same class (a buy and a sell in the same class). Process as regular trade. | 511 | | 13 | Transaction represents a trade in two options of same class (a buy and a sell in a put and a call.). Process as regular trade. | 512 | | 14 | Transaction is the execution of a sale at a price agreed upon by the floor personnel involved, where a condition of the trade is that it reported following a non -stopped trade of the same series at the same price. | 513 | | 15 | Cancel stopped transaction. | 514 | | 16 | Transaction represents the option portion of buy/write (buy stock, sell call options). Process as regular trade. | 515 | | 17 | Transaction represents the buying of a call and selling of a put for same underlying stock or index. Process as regular trade. | 516 | | 18 | Transaction was the execution of an order which was “stopped” at a price that did not constitute a Trade-Through on another market at the time of the stop. Process like a normal transaction. | 517 | | 19 | Transaction was the execution of an order identified as an Intermarket Sweep Order. Updates open, high, low, and last. | 518 | | 20 | Transaction reflects the execution of a “benchmark trade”. A “benchmark trade” is a trade resulting from the matching of “benchmark orders”. A “benchmark order” is an order for which the price is not based, directly or indirectly, on the quoted price of th e option at the time of the order’s execution and for which the material terms were not reasonably determinable at the time a commitment to trade the order was made. Updates open, high, and low, but not last unless the trade is the first of the day. | 519 | | 24 | Transaction is trade through exempt, treat like a regular trade. | 520 | | 27 | “a” (Single leg auction non ISO) | 521 | | 28 | “b” (Single leg auction ISO) | 522 | | 29 | “c” (Single leg cross Non ISO) | 523 | | 30 | “d” (Single leg cross ISO) | 524 | | 31 | “e” (Single leg floor trade) | 525 | | 32 | “f” (Multi leg auto electronic trade) | 526 | | 33 | “g” (Multi leg auction trade) | 527 | | 34 | “h” (Multi leg Cross trade) | 528 | | 35 | “i” (Multi leg floor trade) | 529 | | 36 | “j” (Multi leg auto electronic trade against single leg) | 530 | | 37 | “k” (Stock options Auction) | 531 | | 38 | “l” (Multi leg auction trade against single leg) | 532 | | 39 | “m” (Multi leg floor trade against single leg) | 533 | | 40 | “n” (Stock options auto electronic trade) | 534 | | 41 | “o” (Stock options cross trade) | 535 | | 42 | “p” (Stock options floor trade) | 536 | | 43 | “q” (Stock options auto electronic trade against single leg) | 537 | | 44 | “r” (Stock options auction against single leg) | 538 | | 45 | “s” (Stock options floor trade against single leg) | 539 | | 46 | “t” (Multi leg floor trade of proprietary products) | 540 | | 47 | “u” (Multilateral Compression Trade of Proprietary Data Products)Transaction represents an execution in a proprietary product done as part of a multilateral compression. Trades are executed outside of regular trading hours at prices derived from end of day markets. Trades do not update Open, High, Low, and Closing Prices, but will update total volume. | 541 | | 48 | “v” (Extended Hours Trade )Transaction represents a trade that was executed outside of regular market hours. Trades do not update Open, High, Low, and Closing Prices but will update total volume. | 542 | 543 | 544 | ### Quote Message 545 | 546 | ```python 547 | class Quote: 548 | def __init__(self, contract: str, ask_price: float, ask_size: int, bid_price: float, bid_size: int, timestamp: float): 549 | self.contract: str = contract 550 | self.ask_price: float = ask_price 551 | self.bid_price: float = bid_price 552 | self.ask_size: int = ask_size 553 | self.bid_size: int = bid_size 554 | self.timestamp: float = timestamp 555 | ``` 556 | 557 | * **contract** - Identifier for the options contract. This includes the ticker symbol, put/call, expiry, and strike price. 558 | * **ask_price** - the ask price in USD 559 | * **ask_size** - the size of the last ask in hundreds (each contract is for 100 shares). 560 | * **bid_price** - the bid price in USD 561 | * **bid_size** - the size of the last bid in hundreds (each contract is for 100 shares). 562 | * **timestamp** - a Unix timestamp (with microsecond precision) 563 | 564 | 565 | ### Refresh Message 566 | 567 | ```python 568 | class Refresh: 569 | def __init__(self, contract: str, open_interest: int, open_price: float, close_price: float, high_price: float, low_price: float): 570 | self.contract: str = contract 571 | self.open_interest: int = open_interest 572 | self.open_price: float = open_price 573 | self.close_price: float = close_price 574 | self.high_price: float = high_price 575 | self.low_price: float = low_price 576 | ``` 577 | 578 | * **contract** - Identifier for the options contract. This includes the ticker symbol, put/call, expiry, and strike price. 579 | * **openInterest** - the total quantity of opened contracts as reported at the start of the trading day 580 | * **open_price** - the open price in USD 581 | * **close_price** - the close price in USD 582 | * **high_price** - the daily high price in USD 583 | * **low_price** - the daily low price in USD 584 | 585 | ### Unusual Activity Message 586 | ```python 587 | class UnusualActivity: 588 | def __init__(self, 589 | contract: str, 590 | activity_type: UnusualActivityType, 591 | sentiment: UnusualActivitySentiment, 592 | total_value: float, 593 | total_size: int, 594 | average_price: float, 595 | ask_price_at_execution: float, 596 | bid_price_at_execution: float, 597 | underlying_price_at_execution: float, 598 | timestamp: float): 599 | self.contract: str = contract 600 | self.activity_type: UnusualActivityType = activity_type 601 | self.sentiment: UnusualActivitySentiment = sentiment 602 | self.total_value: float = total_value 603 | self.total_size: int = total_size 604 | self.average_price: float = average_price 605 | self.ask_price_at_execution: float = ask_price_at_execution 606 | self.bid_price_at_execution: float = bid_price_at_execution 607 | self.underlying_price_at_execution: float = underlying_price_at_execution 608 | self.timestamp: float = timestamp 609 | ``` 610 | 611 | * **contract** - Identifier for the options contract. This includes the ticker symbol, put/call, expiry, and strike price. 612 | * **activity_type** - The type of unusual activity that was detected 613 | * **`Block`** - represents an 'block' trade 614 | * **`Sweep`** - represents an intermarket sweep 615 | * **`Large`** - represents a trade of at least $100,000 616 | * **`UnusualSweep`** - represents an unusually large sweep near market open 617 | * **sentiment** - The sentiment of the unusual activity event 618 | * **`Neutral`** - Reflects a minimal expected price change 619 | * **`Bullish`** - Reflects an expected positive (upward) change in price 620 | * **`Bearish`** - Reflects an expected negative (downward) change in price 621 | * **total_value** - The total value of the trade in USD. 'Sweeps' and 'blocks' can be comprised of multiple trades. This is the value of the entire event. 622 | * **total_size** - The total size of the trade in number of contracts. 'Sweeps' and 'blocks' can be comprised of multiple trades. This is the total number of contracts exchanged during the event. 623 | * **average_price** - The average price at which the trade was executed. 'Sweeps' and 'blocks' can be comprised of multiple trades. This is the average trade price for the entire event. 624 | * **ask_price_at_execution** - The 'ask' price of the underlying at execution of the trade event. 625 | * **bid_price_at_execution** - The 'bid' price of the underlying at execution of the trade event. 626 | * **underlying_price_at_execution** - The last trade price of the underlying at execution of the trade event. 627 | * **Timestamp** - a Unix timestamp (with microsecond precision). 628 | 629 | ## API Keys 630 | You will receive your Intrinio API Key after [creating an account](https://intrinio.com/signup). You will need a subscription to a [realtime data feed](https://intrinio.com/real-time-multi-exchange) as well. 631 | 632 | ## Documentation 633 | 634 | ### Methods 635 | 636 | `client = IntrinioRealtimeEquitiesClient(configuration)` - Creates an Intrinio Realtime client 637 | * **Parameter** `configuration.api_key`: Your Intrinio API Key 638 | * **Parameter** `configuration.provider`: The real-time data provider to use ("IEX"/"REALTIME", or "DELAYED_SIP", or "NASDAQ_BASIC", or "CBOE_ONE", or "EQUITIES_EDGE") 639 | * **Parameter** `configuration.on_quote(quote, backlog)`: A function that handles received quotes. `backlog` is an integer representing the approximate size of the queue of unhandled quote/trade events. 640 | * **Parameter** `configuration.on_trade(quote, backlog)`: A function that handles received trades. `backlog` is an integer representing the approximate size of the queue of unhandled quote/trade events. 641 | * **Parameter** `configuration.logger`: (optional) A Python Logger instance to use for logging 642 | 643 | `client : IntrinioRealtimeOptionsClient = IntrinioRealtimeOptionsClient(config : Config, on_trade : Callable[[Trade], None], on_quote : Callable[[Quote], None] = None, on_refresh : Callable[[Refresh], None] = None, on_unusual_activity : Callable[[UnusualActivity],None] = None)` - Creates an Intrinio Real-Time client. 644 | * **Parameter** `config`: The configuration to be used by the client. 645 | * **Parameter** `on_trade`: The Callable accepting trades. If no `on_trade` callback is provided, you will not receive trade updates from the server. 646 | * **Parameter** `on_quote`: The Callable accepting quotes. If no `on_quote` callback is provided, you will not receive quote (ask, bid) updates from the server. 647 | * **Parameter** `on_refresh`: The Callable accepting refresh messages. If no `on_refresh` callback is provided, you will not receive open interest, high, low, open, or close data from the server. Note: open interest data is only updated at the beginning of every trading day. If this callback is provided you will recieve an update immediately, as well as every 15 minutes (approx). 648 | * **Parameter** `on_unusual_activity`: The Callable accepting unusual activity events. If no `on_unusual_activity` callback is provided, you will not receive unusual activity updates from the server. 649 | 650 | #### Equities: 651 | ```python 652 | def on_quote(quote, backlog): 653 | print("QUOTE: " , quote, "BACKLOG LENGTH: ", backlog) 654 | def on_trade(trade, backlog): 655 | print("TRADE: " , trade, "BACKLOG LENGTH: ", backlog) 656 | 657 | configuration = { 658 | 'api_key': '', 659 | 'provider': 'IEX', # REALTIME (IEX) or IEX or CBOE_ONE or EQUITIES_EDGE or DELAYED_SIP or NASDAQ_BASIC 660 | #'delayed': True, # Add this if you have realtime (nondelayed) access and want to force delayed mode. If you only have delayed mode access, this is redundant. 661 | 'on_quote': on_quote, 662 | 'on_trade': on_trade 663 | } 664 | 665 | client = IntrinioRealtimeEquitiesClient(configuration) 666 | ``` 667 | 668 | #### Options: 669 | ```python 670 | class Config: 671 | def __init__(self, apiKey : str, provider : Providers, numThreads : int = 4, logLevel : LogLevel = LogLevel.INFO, manualIpAddress : str = None, symbols : set[str] = None): 672 | self.apiKey : str = apiKey 673 | self.provider : Providers = provider # Providers.OPRA or Providers.OPTIONS_EDGE or Providers.MANUAL 674 | self.numThreads : int = numThreads # At least 4 threads are recommended for 'FIREHOSE' connections 675 | self.manualIpAddress : str = manualIpAddress 676 | self.symbols : list[str] = symbols # Static list of symbols to use 677 | self.logLevel : LogLevel = logLevel 678 | ``` 679 | 680 | --------- 681 | 682 | `client.join(channels)` - Joins the given channels. This can be called at any time. The client will automatically register joined channels and establish the proper subscriptions with the WebSocket connection. 683 | * **Parameter** `channels` - A single channel or list of channels. You can also use the special symbol, "lobby" to join the firehose channel and recieved updates for all ticker symbols (you must have a valid "firehose" subscription). 684 | ```python 685 | client.join(["AAPL", "MSFT", "GE"]) 686 | client.join("GOOG") 687 | client.join("lobby") 688 | ``` 689 | --------- 690 | 691 | Equities - `client.connect()` - Retrieves an auth token, opens the WebSocket connection, starts the self-healing and heartbeat intervals, joins requested channels. 692 | Options - `client.start()` 693 | 694 | --------- 695 | 696 | Equities - `client.disconnect()` - Closes the WebSocket, stops the self-healing and heartbeat intervals. You _must_ call this to dispose of the client. 697 | Options - `client.stop()` 698 | 699 | --------- 700 | 701 | `client.on_quote(quote, backlog)` - Changes the quote handler function 702 | ```python 703 | def on_quote(quote, backlog): 704 | print("QUOTE: " , quote, "BACKLOG LENGTH: ", backlog) 705 | 706 | client.on_quote = on_quote 707 | ``` 708 | 709 | --------- 710 | 711 | `client.leave(channels)` - Leaves the given channels. 712 | * **Parameter** `channels` - A single channel or list of channels 713 | ```python 714 | client.leave(["AAPL", "MSFT", "GE"]) 715 | client.leave("GOOG") 716 | ``` 717 | 718 | --------- 719 | 720 | `client.leave_all()` - Leaves all channels. 721 | 722 | --------- 723 | ## Example Equities Replay Client Usage 724 | ```python 725 | def on_quote(quote, backlog): 726 | print("QUOTE: " , quote, "BACKLOG LENGTH: ", backlog) 727 | def on_trade(trade, backlog): 728 | print("TRADE: " , trade, "BACKLOG LENGTH: ", backlog) 729 | 730 | options = { 731 | 'api_key': '', 732 | 'provider': 'IEX', # REALTIME (IEX) or IEX or CBOE_ONE or EQUITIES_EDGE or DELAYED_SIP or NASDAQ_BASIC 733 | 'replay_date': datetime.date.today(), 734 | 'with_simulated_delay': False, # This plays back the events at the same rate they happened in market. 735 | 'delete_file_when_done': True, 736 | 'write_to_csv': False, # needed for ReplayClient 737 | 'csv_file_path': 'data.csv' # needed for ReplayClient 738 | } 739 | 740 | client = IntrinioReplayClient(options, on_trade, on_quote) 741 | ``` 742 | 743 | ### Minimum Hardware Requirements - Trades only 744 | Equities Client: 745 | * Non-lobby mode: 1 hardware core and 1 thread in your configuration for roughly every 100 symbols, up to the lobby mode settings. Absolute minimum 2 cores and threads. 746 | * Lobby mode: 4 hardware cores and 4 threads in your configuration 747 | * 5 Mbps connection 748 | * 0.5 ms latency 749 | 750 | Options Client: 751 | * Non-lobby mode: 1 hardware core and 1 thread in your configuration for roughly every 250 contracts, up to the lobby mode settings. 3 cores and 3 configured threads for each chain, up to the lobby mode settings. Absolute minimum 3 cores and threads. 752 | * Lobby mode: 6 hardware cores and 6 threads in your configuration 753 | * 25 Mbps connection 754 | * 0.5 ms latency 755 | 756 | ### Minimum Hardware Requirements - Trades and Quotes 757 | Equities Client: 758 | * Non-lobby mode: 1 hardware core and 1 thread in your configuration for roughly every 25 symbols, up to the lobby mode settings. Absolute minimum 4 cores and threads. 759 | * Lobby mode: 8 hardware cores and 8 threads in your configuration 760 | * 25 Mbps connection 761 | * 0.5 ms latency 762 | 763 | Options Client: 764 | * Non-lobby mode: 1 hardware core and 1 thread in your configuration for roughly every 100 contracts, up to the lobby mode settings. 4 cores and 4 configured threads for each chain, up to the lobby mode settings. Absolute minimum 4 cores and threads. 765 | * Lobby mode: 12 hardware cores and 12 threads in your configuration 766 | * 100 Mbps connection 767 | * 0.5 ms latency --------------------------------------------------------------------------------