From 59db14e6f4f0f2bac49e2925c56b7c2d15d17e6a Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 8 Nov 2020 21:46:44 +0100 Subject: [PATCH 01/21] Some fixes of polygon to pydantic ... --- polygon/rest/models/definitions.py | 50 ++++++++++++++++++++++- polygon/rest/models/pm.py | 64 ++++++++++++++++++++++++++++++ requirements.txt | 1 + 3 files changed, 113 insertions(+), 2 deletions(-) create mode 100644 polygon/rest/models/pm.py diff --git a/polygon/rest/models/definitions.py b/polygon/rest/models/definitions.py index cdf443f0..d395e0f9 100644 --- a/polygon/rest/models/definitions.py +++ b/polygon/rest/models/definitions.py @@ -2,7 +2,7 @@ from typing import List, Dict, Any from polygon.rest import models - +from pydantic import BaseModel class Definition: _swagger_name_to_python: Dict[str, str] @@ -147,6 +147,53 @@ def __init__(self): # noinspection SpellCheckingInspection +class HistTrade2(Definition): + _swagger_name_to_python = { + "condition1": "condition1", + "condition2": "condition2", + "condition3": "condition3", + "condition4": "condition4", + "exchange": "exchange", + "price": "price", + "size": "size", + "timestamp": "timestamp", + + } + + _attribute_is_primitive = { + "condition1": True, + "condition2": True, + "condition3": True, + "condition4": True, + "exchange": True, + "price": True, + "size": True, + "timestamp": True, + + } + + _attributes_to_types = { + "condition1": "int", + "condition2": "int", + "condition3": "int", + "condition4": "int", + "exchange": "str", + "price": "int", + "size": "int", + "timestamp": "str", + + } + + def __init__(self): + self.condition1: int + self.condition2: int + self.condition3: int + self.condition4: int + self.exchange: str + self.price: int + self.size: int + self.timestamp: str + class HistTrade(Definition): _swagger_name_to_python = { "condition1": "condition1", @@ -3039,7 +3086,6 @@ def __init__(self): self.symbol: str self.last: LastQuote - # noinspection SpellCheckingInspection class StocksEquitiesDailyOpenCloseApiResponse(Definition): _swagger_name_to_python = { diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py new file mode 100644 index 00000000..8e1914b6 --- /dev/null +++ b/polygon/rest/models/pm.py @@ -0,0 +1,64 @@ +from __future__ import annotations +import keyword +import typing +from typing import List, Dict, Any + +from polygon import RESTClient +from polygon.rest import models +from pydantic import BaseModel +from pydantic import BaseModel, Field +import requests + +_T = typing.TypeVar('_T') + + +class PolygonModel(BaseModel): + class Meta: + client: RESTClient = None + + @classmethod + def _get(cls: PolygonModel, path: str, **kwargs) -> PolygonModel: + c = PolygonModel.Meta.client + assert c is not None + r = requests.Response = c._session.get(f"{c.url}{path}", **kwargs) + if r.status_code == 200: + d : dict = r.json() + # noinspection PyArgumentList + return cls(**d) + else: + r.raise_for_status() + + @classmethod + def get(cls: PolygonModel, *args, **kwargs) -> PolygonModel: + raise NotImplementedError + + +StockSymbol = str + +class TickerDetail(PolygonModel): + logo: str + exchange: str + name: str + symbol: StockSymbol + listdate: str + cik: str + bloomberg: str + figi: str = None + lei: str + sic: float + country: str + industry: str + sector: str + marketcap: float + employees: float + phone: str + ceo: str + url: str + description: str = None + similar: List[StockSymbol] + tags: List[str] + updated: str + + @classmethod + def get(cls, symbol: str, **kwargs) -> TickerDetail: + return TickerDetail._get(f"/v1/meta/symbols/{symbol}/company") diff --git a/requirements.txt b/requirements.txt index a62a3359..9981eaa0 100644 --- a/requirements.txt +++ b/requirements.txt @@ -17,3 +17,4 @@ wcwidth>=0.1.7 websocket-client>=0.56.0 websockets>=8.0.2 zipp>=0.6.0 +pydantic From 80cc692f0e672507a8c1e825931d3a158f129d71 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 8 Nov 2020 23:39:23 +0100 Subject: [PATCH 02/21] Fetching df from polygon, nice! ... --- polygon/rest/models/pm.py | 40 ++++++++++++++++++++++++++++++++++++--- 1 file changed, 37 insertions(+), 3 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 8e1914b6..8f215ddb 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -1,6 +1,7 @@ from __future__ import annotations import keyword import typing +import datetime from typing import List, Dict, Any from polygon import RESTClient @@ -8,6 +9,8 @@ from pydantic import BaseModel from pydantic import BaseModel, Field import requests +import functools +import pandas as pd _T = typing.TypeVar('_T') @@ -17,12 +20,13 @@ class Meta: client: RESTClient = None @classmethod - def _get(cls: PolygonModel, path: str, **kwargs) -> PolygonModel: + def _get(cls: PolygonModel, path: str, params:dict=None) -> PolygonModel: c = PolygonModel.Meta.client assert c is not None - r = requests.Response = c._session.get(f"{c.url}{path}", **kwargs) + r = requests.Response = c._session.get(f"{c.url}{path}", params=params) if r.status_code == 200: - d : dict = r.json() + d: dict = r.json() + print(d) # noinspection PyArgumentList return cls(**d) else: @@ -35,6 +39,7 @@ def get(cls: PolygonModel, *args, **kwargs) -> PolygonModel: StockSymbol = str + class TickerDetail(PolygonModel): logo: str exchange: str @@ -60,5 +65,34 @@ class TickerDetail(PolygonModel): updated: str @classmethod + @functools.lru_cache() def get(cls, symbol: str, **kwargs) -> TickerDetail: return TickerDetail._get(f"/v1/meta/symbols/{symbol}/company") + + +class Bar(BaseModel): + volume: int = Field(alias='v') + open: float = Field(alias='o') + close: float = Field(alias='c') + high: float = Field(alias='h') + low: float = Field(alias='l') + utc_window_start: datetime.datetime = Field(alias='t') + window_size: int = Field(alias='n') + + +class TickerWindow(PolygonModel): + ticker: StockSymbol + status: str + adjusted: bool + query_count: int = Field('queryCount') + results: typing.List[Bar] + + @classmethod + def get(cls: TickerWindow, ticker: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, + unadjusted: bool = False, sort: str = 'asc') -> TickerWindow: + return TickerWindow._get(f"/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}", + params=dict(sort=sort, unadjusted=unadjusted)) + + @property + def df(self) -> pd.DataFrame: + return pd.DataFrame.from_dict(self.dict()['results']) \ No newline at end of file From 99e876688524978ef9bf922fb65232eb919bbffe Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sat, 14 Nov 2020 22:09:19 +0100 Subject: [PATCH 03/21] Finlib commit ... --- polygon/rest/models/pm.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 8f215ddb..02ae473b 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -26,7 +26,6 @@ def _get(cls: PolygonModel, path: str, params:dict=None) -> PolygonModel: r = requests.Response = c._session.get(f"{c.url}{path}", params=params) if r.status_code == 200: d: dict = r.json() - print(d) # noinspection PyArgumentList return cls(**d) else: @@ -77,7 +76,7 @@ class Bar(BaseModel): high: float = Field(alias='h') low: float = Field(alias='l') utc_window_start: datetime.datetime = Field(alias='t') - window_size: int = Field(alias='n') + trades: int = Field(alias='n') class TickerWindow(PolygonModel): @@ -95,4 +94,4 @@ def get(cls: TickerWindow, ticker: StockSymbol, timespan: str, from_: str, to: s @property def df(self) -> pd.DataFrame: - return pd.DataFrame.from_dict(self.dict()['results']) \ No newline at end of file + return pd.DataFrame.from_dict(self.dict()['results']) From e4152d345cd5ea04bf9f85700272b7da6aaeb0e2 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 15 Nov 2020 18:25:30 +0100 Subject: [PATCH 04/21] split up requests due to 5k max bars from polygon ... --- polygon/rest/models/pm.py | 38 ++++++++++++++++++++++++++++++++++---- 1 file changed, 34 insertions(+), 4 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 02ae473b..9db21876 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -11,6 +11,7 @@ import requests import functools import pandas as pd +from dateutil.parser import parser _T = typing.TypeVar('_T') @@ -20,7 +21,7 @@ class Meta: client: RESTClient = None @classmethod - def _get(cls: PolygonModel, path: str, params:dict=None) -> PolygonModel: + def _get(cls: PolygonModel, path: str, params: dict = None) -> PolygonModel: c = PolygonModel.Meta.client assert c is not None r = requests.Response = c._session.get(f"{c.url}{path}", params=params) @@ -86,12 +87,41 @@ class TickerWindow(PolygonModel): query_count: int = Field('queryCount') results: typing.List[Bar] + class __WindowSplitter(BaseModel): + from_: datetime.date + to: datetime.date + timespan: str + + @property + def split_list(self) -> typing.List[typing.Tuple[str, str]]: + res = [] + from_ = self.from_ + while from_ <= self.to: + to = min(self.to, from_ + datetime.timedelta(days=5)) + res.append((from_.isoformat(), to.isoformat())) + from_ = to + datetime.timedelta(days=1) + return res + @classmethod def get(cls: TickerWindow, ticker: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, unadjusted: bool = False, sort: str = 'asc') -> TickerWindow: - return TickerWindow._get(f"/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}", - params=dict(sort=sort, unadjusted=unadjusted)) + # noinspection PyTypeChecker + ws = TickerWindow.__WindowSplitter(**dict(from_=from_, to=to, timespan=timespan)) + res = None + for (from_, to) in ws.split_list: + tmp = cls._get(f"/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}", + params=dict(sort=sort, unadjusted=unadjusted)) + if isinstance(res, TickerWindow): + res.append(tmp) + else: + res = tmp + return res + + def append(self, other: TickerWindow): + self.query_count += other.query_count + self.results.extend(other.results) @property def df(self) -> pd.DataFrame: - return pd.DataFrame.from_dict(self.dict()['results']) + df = pd.DataFrame.from_dict(self.dict()['results']) + return df.set_index('utc_window_start').sort_index() From cf4f15ce90f470666ec7fa16ac1f14d715bc617e Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sat, 21 Nov 2020 01:06:26 +0100 Subject: [PATCH 05/21] Pair trader on the way ... --- polygon/rest/models/pm.py | 135 ++++++++++++++++++++++++++++++-------- polygon/websocket/pm.py | 68 +++++++++++++++++++ 2 files changed, 176 insertions(+), 27 deletions(-) create mode 100644 polygon/websocket/pm.py diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 9db21876..b2d1a6e0 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -1,19 +1,18 @@ from __future__ import annotations -import keyword -import typing -import datetime -from typing import List, Dict, Any -from polygon import RESTClient -from polygon.rest import models -from pydantic import BaseModel -from pydantic import BaseModel, Field -import requests +import datetime import functools +import typing +from typing import List + import pandas as pd -from dateutil.parser import parser +import requests +from pydantic import BaseModel, Field + +from polygon import RESTClient -_T = typing.TypeVar('_T') +# _T = typing.TypeVar('_T') +_T = typing.ClassVar class PolygonModel(BaseModel): @@ -21,25 +20,64 @@ class Meta: client: RESTClient = None @classmethod - def _get(cls: PolygonModel, path: str, params: dict = None) -> PolygonModel: + def _get(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: c = PolygonModel.Meta.client assert c is not None r = requests.Response = c._session.get(f"{c.url}{path}", params=params) if r.status_code == 200: - d: dict = r.json() - # noinspection PyArgumentList - return cls(**d) + d: typing.Union[dict, list] = r.json() + if isinstance(d, list): + # noinspection PyArgumentList + return [cls(**el) for el in d] + else: + # noinspection PyArgumentList + return cls(**d) + else: r.raise_for_status() @classmethod - def get(cls: PolygonModel, *args, **kwargs) -> PolygonModel: + def get(cls: _T, *args, **kwargs) -> typing.Union[_T, typing.List[_T]]: raise NotImplementedError StockSymbol = str +class Ticker(PolygonModel): + symbol: str = Field(alias='ticker') + name: str + market: str + locale: str + currency: str + active: bool + primary_exchange: str = Field(alias='primaryExch') + type_: str = Field(alias='type', default=None) + codes: typing.Dict[str, str] = None + updated: typing.Union[datetime.datetime, datetime.date] + url: str + attrs: typing.Dict[str, str] = None + + @classmethod + def get(cls: _T, *args, **kwargs) -> typing.Union[_T, typing.List[_T]]: + raise NotImplementedError + + +class TickerList(PolygonModel): + page: int + per_page: int = Field(alias='perPage') + count: int + status: str + tickers: typing.List[Ticker] + + @classmethod + @functools.lru_cache() + def get(cls, market: str, search: str = None, active: str = 'true') -> TickerList: + params = locals() + params.pop('cls') + return TickerList._get(f"/v2/reference/tickers", params=params) + + class TickerDetail(PolygonModel): logo: str exchange: str @@ -49,7 +87,7 @@ class TickerDetail(PolygonModel): cik: str bloomberg: str figi: str = None - lei: str + lei: str = None sic: float country: str industry: str @@ -77,15 +115,16 @@ class Bar(BaseModel): high: float = Field(alias='h') low: float = Field(alias='l') utc_window_start: datetime.datetime = Field(alias='t') - trades: int = Field(alias='n') + trades: int = Field(alias='n', default=0) class TickerWindow(PolygonModel): - ticker: StockSymbol + symbol: StockSymbol = Field(alias='ticker') status: str adjusted: bool query_count: int = Field('queryCount') results: typing.List[Bar] + _df : pd.DataFrame = Field(default_factory=pd.DataFrame) class __WindowSplitter(BaseModel): from_: datetime.date @@ -103,25 +142,67 @@ def split_list(self) -> typing.List[typing.Tuple[str, str]]: return res @classmethod - def get(cls: TickerWindow, ticker: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, + def get(cls: TickerWindow, symbol: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, unadjusted: bool = False, sort: str = 'asc') -> TickerWindow: # noinspection PyTypeChecker ws = TickerWindow.__WindowSplitter(**dict(from_=from_, to=to, timespan=timespan)) res = None for (from_, to) in ws.split_list: - tmp = cls._get(f"/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}", + tmp = cls._get(f"/v2/aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from_}/{to}", params=dict(sort=sort, unadjusted=unadjusted)) if isinstance(res, TickerWindow): - res.append(tmp) + res.consume(tmp) else: res = tmp return res - def append(self, other: TickerWindow): - self.query_count += other.query_count - self.results.extend(other.results) + def consume(self, other: TickerWindow): + d_orig = {bar.utc_window_start: bar for bar in self.results} + d_new = {bar.utc_window_start: bar for bar in other.results} + d_orig.update(d_new) + self.results = list(d_orig.values()) + self.results.sort(key=lambda x: x.utc_window_start) + self.query_count = len(self.results) + _df : pd.DataFrame = Field(default_factory=pd.DataFrame) @property def df(self) -> pd.DataFrame: - df = pd.DataFrame.from_dict(self.dict()['results']) - return df.set_index('utc_window_start').sort_index() + if len(self._df) == 0: + df = pd.DataFrame.from_dict(self.dict()['results']) + self._df = df.set_index('utc_window_start').sort_index() + return self._df + + def add_bar(self, bar : Bar): + if len(self.results) == 0 or bar.utc_window_start > self.results[-1].utc_window_start: + self.results.append(bar) + self._df = pd.DataFrame() + elif bar.utc_window_start == self.results[-1].utc_window_start: + self.results[-1] = bar + else: + raise NotImplementedError + +class TickerWindowFetcher(BaseModel): + max_date: datetime.date = Field(default_factory=datetime.date.today) + days_back: int = 5 + timespan: str = 'minute' + symbol: StockSymbol + adjusted: bool = True + + def get_ticker_window(self, new_start_date: bool = True) -> TickerWindow: + if new_start_date: + self.max_date = datetime.date.today() + max_date = self.max_date + min_date = max_date - datetime.timedelta(days=self.days_back) + res = None + tmp = max_date + while min_date < tmp: + tmp = max(min_date, max_date - datetime.timedelta(days=5)) + tw = TickerWindow.get(self.symbol, self.timespan, tmp.isoformat(), max_date.isoformat(), + unadjusted=(not self.adjusted)) + max_date = tmp + if res is None: + res = tw + else: + res.consume(tw) + print(min_date, max_date, tmp) + return res diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py new file mode 100644 index 00000000..6e124bdb --- /dev/null +++ b/polygon/websocket/pm.py @@ -0,0 +1,68 @@ +import time +import typing +import datetime +import pytz +from polygon.rest.models import pm +from pydantic import BaseModel, Field + + +class SocketBase(BaseModel): + symbol: str = Field(alias='sym') + event_type: str = Field(alias='ev') + + + +class Trade(SocketBase): + exchange_id: int = Field(alias='x') + trade_id: int = Field(alias='i') + tape: int = Field(alias='z') + price: float = Field(alias='p') + size: int = Field(alias='s') + trade_conditions: typing.List[int] = Field(alias='c', default=None) + utc: datetime.datetime = Field(alias='t') + + @property + def age(self) -> datetime.timedelta: + return datetime.datetime.now(pytz.utc) - self.utc + + +class Quote(SocketBase): + bid_exchange_id: int = Field(alias='bx') + bid_price: float = Field(alias='bp') + bid_size: int = Field(alias='bs') + ask_exchange_id: int = Field(alias='ax') + ask_price: float = Field(alias='ap') + ask_size: int = Field(alias='as') + quote_conditions: int = Field(alias='c') + utc: datetime.datetime = Field(alias='t') + + @property + def age(self) -> datetime.timedelta: + return datetime.datetime.now(pytz.utc) - self.utc + + @property + def payback(self) -> float: + return (self.bid_price / self.ask_price) ** .5 + + @property + def middle_price(self) -> float: + return (self.ask_price + self.bid_price) / 2.0 + + + +class Bar(SocketBase): + volume : int = Field(alias='v') + volume_today : int = Field(alias='av') + official_open_price : float = Field(alias='op') + vol_weight_price : float = Field(alias='vw') + open_price : float = Field(alias='o') + close_price : float = Field(alias='c') + high_price : float = Field(alias='h') + low_price : float = Field(alias='l') + avg_prive : float = Field(alias='a') + utc_start : datetime.datetime = Field('s') + utc_end : datetime.datetime = Field('e') + + @property + def rest_bar(self) -> pm.Bar: + return pm.Bar(v=self.volume, o=self.open_price, c=self.close_price, h=self.high_price, l=self.low_price, t=self.utc_start, n=1) \ No newline at end of file From 7700c37486fcb88f033894c02ef7b36365495dc2 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Tue, 24 Nov 2020 00:16:35 +0100 Subject: [PATCH 06/21] Trading round dont crash ... --- polygon/rest/models/pm.py | 69 +++++++++++++++++++-------------------- polygon/websocket/pm.py | 7 ++-- 2 files changed, 38 insertions(+), 38 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index b2d1a6e0..6dc7a212 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -22,7 +22,7 @@ class Meta: @classmethod def _get(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: c = PolygonModel.Meta.client - assert c is not None + # assert c is not None r = requests.Response = c._session.get(f"{c.url}{path}", params=params) if r.status_code == 200: d: typing.Union[dict, list] = r.json() @@ -118,43 +118,23 @@ class Bar(BaseModel): trades: int = Field(alias='n', default=0) + + class TickerWindow(PolygonModel): symbol: StockSymbol = Field(alias='ticker') status: str adjusted: bool - query_count: int = Field('queryCount') + query_count: int = Field(alias='queryCount') results: typing.List[Bar] - _df : pd.DataFrame = Field(default_factory=pd.DataFrame) - - class __WindowSplitter(BaseModel): - from_: datetime.date - to: datetime.date - timespan: str - - @property - def split_list(self) -> typing.List[typing.Tuple[str, str]]: - res = [] - from_ = self.from_ - while from_ <= self.to: - to = min(self.to, from_ + datetime.timedelta(days=5)) - res.append((from_.isoformat(), to.isoformat())) - from_ = to + datetime.timedelta(days=1) - return res + + class Meta: + data_frames: typing.Dict[int, pd.DataFrame] = {} @classmethod def get(cls: TickerWindow, symbol: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, unadjusted: bool = False, sort: str = 'asc') -> TickerWindow: - # noinspection PyTypeChecker - ws = TickerWindow.__WindowSplitter(**dict(from_=from_, to=to, timespan=timespan)) - res = None - for (from_, to) in ws.split_list: - tmp = cls._get(f"/v2/aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from_}/{to}", - params=dict(sort=sort, unadjusted=unadjusted)) - if isinstance(res, TickerWindow): - res.consume(tmp) - else: - res = tmp - return res + return cls._get(f"/v2/aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from_}/{to}", + params=dict(sort=sort, unadjusted=unadjusted)) def consume(self, other: TickerWindow): d_orig = {bar.utc_window_start: bar for bar in self.results} @@ -163,24 +143,30 @@ def consume(self, other: TickerWindow): self.results = list(d_orig.values()) self.results.sort(key=lambda x: x.utc_window_start) self.query_count = len(self.results) - _df : pd.DataFrame = Field(default_factory=pd.DataFrame) + self.__set_df() + + def __set_df(self, df: pd.DataFrame = None): + self.Meta.data_frames[id(self)] = df @property def df(self) -> pd.DataFrame: - if len(self._df) == 0: + df = self.Meta.data_frames.get(id(self), None) + if df is None: df = pd.DataFrame.from_dict(self.dict()['results']) - self._df = df.set_index('utc_window_start').sort_index() - return self._df + df = df.set_index('utc_window_start').sort_index() + self.__set_df(df) + return df - def add_bar(self, bar : Bar): + def add_bar(self, bar: Bar): if len(self.results) == 0 or bar.utc_window_start > self.results[-1].utc_window_start: self.results.append(bar) - self._df = pd.DataFrame() + self.__set_df() elif bar.utc_window_start == self.results[-1].utc_window_start: self.results[-1] = bar else: raise NotImplementedError + class TickerWindowFetcher(BaseModel): max_date: datetime.date = Field(default_factory=datetime.date.today) days_back: int = 5 @@ -188,7 +174,7 @@ class TickerWindowFetcher(BaseModel): symbol: StockSymbol adjusted: bool = True - def get_ticker_window(self, new_start_date: bool = True) -> TickerWindow: + def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: if new_start_date: self.max_date = datetime.date.today() max_date = self.max_date @@ -205,4 +191,15 @@ def get_ticker_window(self, new_start_date: bool = True) -> TickerWindow: else: res.consume(tw) print(min_date, max_date, tmp) + assert res is not None return res + + +def __main(): + twf = TickerWindowFetcher(symbol='GOOG') + tw = twf.get_ticker_window() + print(tw.df) + + +if __name__ == '__main__': + __main() diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py index 6e124bdb..ec47102e 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/pm.py @@ -36,6 +36,9 @@ class Quote(SocketBase): quote_conditions: int = Field(alias='c') utc: datetime.datetime = Field(alias='t') + def __str__(self): + return f'{self.bid_price} -- {self.ask_price}' + @property def age(self) -> datetime.timedelta: return datetime.datetime.now(pytz.utc) - self.utc @@ -60,8 +63,8 @@ class Bar(SocketBase): high_price : float = Field(alias='h') low_price : float = Field(alias='l') avg_prive : float = Field(alias='a') - utc_start : datetime.datetime = Field('s') - utc_end : datetime.datetime = Field('e') + utc_start : datetime.datetime = Field(alias='s') + utc_end : datetime.datetime = Field(alias='e') @property def rest_bar(self) -> pm.Bar: From e7eb7478d14da2577eacc0172a028b209e8d92b9 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Thu, 26 Nov 2020 21:08:41 +0100 Subject: [PATCH 07/21] Orders on the move ... --- polygon/rest/models/pm.py | 76 ++++++++++++++++++++++++++++++++---- polygon/websocket/pm.py | 81 +++++++++++++++++++++++++++++++-------- 2 files changed, 134 insertions(+), 23 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 6dc7a212..e84b2a22 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -3,6 +3,9 @@ import datetime import functools import typing +import uuid +from decimal import Decimal +from enum import Enum from typing import List import pandas as pd @@ -118,8 +121,6 @@ class Bar(BaseModel): trades: int = Field(alias='n', default=0) - - class TickerWindow(PolygonModel): symbol: StockSymbol = Field(alias='ticker') status: str @@ -195,11 +196,70 @@ def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: return res -def __main(): - twf = TickerWindowFetcher(symbol='GOOG') - tw = twf.get_ticker_window() - print(tw.df) +class StopLoss(BaseModel): + stop_price: float + limit_price: float + + +class OrderSide(Enum): + BUY = 'buy' + SELL = 'sell' + + +class OrderTimeInFore(Enum): + DAY = 'day' + + +class OrderType(Enum): + LIMIT = 'limit' + +class OrderClass(Enum): + SIMPLE = 'simple' -if __name__ == '__main__': - __main() + +class OrderBase(BaseModel): + client_order_id: str = Field(default_factory=lambda: str(uuid.uuid4())) + qty: int + time_in_force: OrderTimeInFore = OrderTimeInFore.DAY + limit_price: typing.Optional[Decimal] + stop_price: typing.Optional[Decimal] = None + + +class OrderReplace(OrderBase): + trail: typing.Optional[Decimal] = None + + +class OrderPlace(OrderBase): + symbol: str + qty: int + order_type: str = Field(alias='type', default=OrderType.LIMIT) + side: OrderSide + time_in_force: OrderTimeInFore = OrderTimeInFore.DAY + limit_price: Decimal + stop_price: typing.Optional[Decimal] = None + extended_hours: bool = False + legs: typing.Optional[typing.List[Order]] = None + trail_price: typing.Optional[Decimal] = None + trail_percent: typing.Optional[Decimal] = None + order_class: OrderClass = OrderClass.SIMPLE + stop_loss: typing.Optional[StopLoss] = None + + +class Order(OrderPlace): + order_id: str + created_at: datetime.datetime + submitted_at: typing.Optional[datetime.datetime] = None + filled_at: typing.Optional[datetime.datetime] = None + expired_at: typing.Optional[datetime.datetime] = None + cancelled_at: typing.Optional[datetime.datetime] = None + failed_at: typing.Optional[datetime.datetime] = None + replaced_at: typing.Optional[datetime.datetime] = None + replaced_by: typing.Optional[str] = None + replaces: typing.Optional[str] = None + asset_id: str + asset_class: str + filled_qty: int + status: str + legs: typing.Optional[typing.List[Order]] = None + hwm: Decimal diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py index ec47102e..f49bf4ab 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/pm.py @@ -1,6 +1,9 @@ import time import typing import datetime +from decimal import Decimal +from enum import Enum + import pytz from polygon.rest.models import pm from pydantic import BaseModel, Field @@ -11,7 +14,6 @@ class SocketBase(BaseModel): event_type: str = Field(alias='ev') - class Trade(SocketBase): exchange_id: int = Field(alias='x') trade_id: int = Field(alias='i') @@ -37,7 +39,7 @@ class Quote(SocketBase): utc: datetime.datetime = Field(alias='t') def __str__(self): - return f'{self.bid_price} -- {self.ask_price}' + return f'{self.bid_size}:{self.bid_price} -- {self.ask_size}:{self.ask_price}' @property def age(self) -> datetime.timedelta: @@ -52,20 +54,69 @@ def middle_price(self) -> float: return (self.ask_price + self.bid_price) / 2.0 - class Bar(SocketBase): - volume : int = Field(alias='v') - volume_today : int = Field(alias='av') - official_open_price : float = Field(alias='op') - vol_weight_price : float = Field(alias='vw') - open_price : float = Field(alias='o') - close_price : float = Field(alias='c') - high_price : float = Field(alias='h') - low_price : float = Field(alias='l') - avg_prive : float = Field(alias='a') - utc_start : datetime.datetime = Field(alias='s') - utc_end : datetime.datetime = Field(alias='e') + volume: int = Field(alias='v') + volume_today: int = Field(alias='av') + official_open_price: float = Field(alias='op') + vol_weight_price: float = Field(alias='vw') + open_price: float = Field(alias='o') + close_price: float = Field(alias='c') + high_price: float = Field(alias='h') + low_price: float = Field(alias='l') + avg_prive: float = Field(alias='a') + utc_start: datetime.datetime = Field(alias='s') + utc_end: datetime.datetime = Field(alias='e') @property def rest_bar(self) -> pm.Bar: - return pm.Bar(v=self.volume, o=self.open_price, c=self.close_price, h=self.high_price, l=self.low_price, t=self.utc_start, n=1) \ No newline at end of file + return pm.Bar(v=self.volume, o=self.open_price, c=self.close_price, h=self.high_price, l=self.low_price, + t=self.utc_start, n=1) + + +class OrderEventBase(Enum): + + @property + def is_active(self) -> bool: + raise NotImplementedError + + +class OrderEventActive(OrderEventBase): + NEW = 'new' + PARTIAL_FILL = 'partial_fill' + DONE_FOR_DAY = 'done_for_day' + PENDING_NEW = 'pending_new' + REPLACE_REJECTED = 'order_replace_rejected' + CANCEL_REJECTED = 'order_cancel_rejected' + PENDING_CANCEL = 'pending_cancel' + PENDING_REPLACE = 'pending_replace' + + @property + def is_active(self) -> bool: + return True + + +class OrderEventInActive(OrderEventBase): + FILL = 'fill' + CANCELED = 'canceled' + EXPIRED = 'expired' + REPLACED = 'replaced' + REJECTED = 'rejected' + STOPPED = 'stopped' + CALCULATED = 'calculated' + SUSPENDED = 'suspended' + + @property + def is_active(self) -> bool: + return False + + +class TradeBase(BaseModel): + event: typing.Union[OrderEventActive, OrderEventInActive] + price: typing.Optional[Decimal] = None + utc: typing.Optional[datetime.datetime] = Field(alias='timestamp', default=None) + position_qty: typing.Optional[int] = None + order: pm.Order + + @property + def has_qty(self) -> bool: + return self.position_qty is not None From f23e33d05ec429371169b48211d6a2cdec2e0cfa Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Fri, 27 Nov 2020 00:00:16 +0100 Subject: [PATCH 08/21] model refactoring ... --- polygon/rest/models/pm.py | 82 +++------------------------------------ polygon/websocket/pm.py | 47 ---------------------- 2 files changed, 6 insertions(+), 123 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index e84b2a22..7747df14 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -3,9 +3,6 @@ import datetime import functools import typing -import uuid -from decimal import Decimal -from enum import Enum from typing import List import pandas as pd @@ -23,9 +20,9 @@ class Meta: client: RESTClient = None @classmethod - def _get(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: + def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: c = PolygonModel.Meta.client - # assert c is not None + assert c is not None r = requests.Response = c._session.get(f"{c.url}{path}", params=params) if r.status_code == 200: d: typing.Union[dict, list] = r.json() @@ -78,7 +75,7 @@ class TickerList(PolygonModel): def get(cls, market: str, search: str = None, active: str = 'true') -> TickerList: params = locals() params.pop('cls') - return TickerList._get(f"/v2/reference/tickers", params=params) + return TickerList.api_action(f"/v2/reference/tickers", params=params) class TickerDetail(PolygonModel): @@ -108,7 +105,7 @@ class TickerDetail(PolygonModel): @classmethod @functools.lru_cache() def get(cls, symbol: str, **kwargs) -> TickerDetail: - return TickerDetail._get(f"/v1/meta/symbols/{symbol}/company") + return TickerDetail.api_action(f"/v1/meta/symbols/{symbol}/company") class Bar(BaseModel): @@ -134,8 +131,8 @@ class Meta: @classmethod def get(cls: TickerWindow, symbol: StockSymbol, timespan: str, from_: str, to: str, multiplier: int = 1, unadjusted: bool = False, sort: str = 'asc') -> TickerWindow: - return cls._get(f"/v2/aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from_}/{to}", - params=dict(sort=sort, unadjusted=unadjusted)) + return cls.api_action(f"/v2/aggs/ticker/{symbol}/range/{multiplier}/{timespan}/{from_}/{to}", + params=dict(sort=sort, unadjusted=unadjusted)) def consume(self, other: TickerWindow): d_orig = {bar.utc_window_start: bar for bar in self.results} @@ -196,70 +193,3 @@ def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: return res -class StopLoss(BaseModel): - stop_price: float - limit_price: float - - -class OrderSide(Enum): - BUY = 'buy' - SELL = 'sell' - - -class OrderTimeInFore(Enum): - DAY = 'day' - - -class OrderType(Enum): - LIMIT = 'limit' - - -class OrderClass(Enum): - SIMPLE = 'simple' - - -class OrderBase(BaseModel): - client_order_id: str = Field(default_factory=lambda: str(uuid.uuid4())) - qty: int - time_in_force: OrderTimeInFore = OrderTimeInFore.DAY - limit_price: typing.Optional[Decimal] - stop_price: typing.Optional[Decimal] = None - - -class OrderReplace(OrderBase): - trail: typing.Optional[Decimal] = None - - -class OrderPlace(OrderBase): - symbol: str - qty: int - order_type: str = Field(alias='type', default=OrderType.LIMIT) - side: OrderSide - time_in_force: OrderTimeInFore = OrderTimeInFore.DAY - limit_price: Decimal - stop_price: typing.Optional[Decimal] = None - extended_hours: bool = False - legs: typing.Optional[typing.List[Order]] = None - trail_price: typing.Optional[Decimal] = None - trail_percent: typing.Optional[Decimal] = None - order_class: OrderClass = OrderClass.SIMPLE - stop_loss: typing.Optional[StopLoss] = None - - -class Order(OrderPlace): - order_id: str - created_at: datetime.datetime - submitted_at: typing.Optional[datetime.datetime] = None - filled_at: typing.Optional[datetime.datetime] = None - expired_at: typing.Optional[datetime.datetime] = None - cancelled_at: typing.Optional[datetime.datetime] = None - failed_at: typing.Optional[datetime.datetime] = None - replaced_at: typing.Optional[datetime.datetime] = None - replaced_by: typing.Optional[str] = None - replaces: typing.Optional[str] = None - asset_id: str - asset_class: str - filled_qty: int - status: str - legs: typing.Optional[typing.List[Order]] = None - hwm: Decimal diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py index f49bf4ab..3ca2976a 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/pm.py @@ -73,50 +73,3 @@ def rest_bar(self) -> pm.Bar: t=self.utc_start, n=1) -class OrderEventBase(Enum): - - @property - def is_active(self) -> bool: - raise NotImplementedError - - -class OrderEventActive(OrderEventBase): - NEW = 'new' - PARTIAL_FILL = 'partial_fill' - DONE_FOR_DAY = 'done_for_day' - PENDING_NEW = 'pending_new' - REPLACE_REJECTED = 'order_replace_rejected' - CANCEL_REJECTED = 'order_cancel_rejected' - PENDING_CANCEL = 'pending_cancel' - PENDING_REPLACE = 'pending_replace' - - @property - def is_active(self) -> bool: - return True - - -class OrderEventInActive(OrderEventBase): - FILL = 'fill' - CANCELED = 'canceled' - EXPIRED = 'expired' - REPLACED = 'replaced' - REJECTED = 'rejected' - STOPPED = 'stopped' - CALCULATED = 'calculated' - SUSPENDED = 'suspended' - - @property - def is_active(self) -> bool: - return False - - -class TradeBase(BaseModel): - event: typing.Union[OrderEventActive, OrderEventInActive] - price: typing.Optional[Decimal] = None - utc: typing.Optional[datetime.datetime] = Field(alias='timestamp', default=None) - position_qty: typing.Optional[int] = None - order: pm.Order - - @property - def has_qty(self) -> bool: - return self.position_qty is not None From ae948b732d01e6301f52e6d766f962de125be7b0 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 29 Nov 2020 01:08:34 +0100 Subject: [PATCH 09/21] Orders are beeing updated by stream (not tested) --- polygon/websocket/pm.py | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py index 3ca2976a..7a0626e5 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/pm.py @@ -1,13 +1,11 @@ -import time -import typing import datetime -from decimal import Decimal -from enum import Enum +import typing import pytz -from polygon.rest.models import pm from pydantic import BaseModel, Field +from polygon.rest.models import pm + class SocketBase(BaseModel): symbol: str = Field(alias='sym') From 6d29e2bebe0214321648f2fd0749ffe8a4b3740b Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Mon, 30 Nov 2020 22:26:18 +0100 Subject: [PATCH 10/21] Trading is working! --- polygon/rest/models/pm.py | 22 +++++++++++++++------- polygon/websocket/pm.py | 2 +- 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/polygon/rest/models/pm.py b/polygon/rest/models/pm.py index 7747df14..dd522475 100644 --- a/polygon/rest/models/pm.py +++ b/polygon/rest/models/pm.py @@ -7,7 +7,7 @@ import pandas as pd import requests -from pydantic import BaseModel, Field +from pydantic import BaseModel, Field, root_validator from polygon import RESTClient @@ -23,7 +23,9 @@ class Meta: def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: c = PolygonModel.Meta.client assert c is not None - r = requests.Response = c._session.get(f"{c.url}{path}", params=params) + url = f"{c.url}{path}" + print(url) + r = requests.Response = c._session.get(url, params=params) if r.status_code == 200: d: typing.Union[dict, list] = r.json() if isinstance(d, list): @@ -167,16 +169,25 @@ def add_bar(self, bar: Bar): class TickerWindowFetcher(BaseModel): max_date: datetime.date = Field(default_factory=datetime.date.today) - days_back: int = 5 + min_date: typing.Optional[datetime.date] = Field(default=None) + days_back: typing.Optional[int] = None timespan: str = 'minute' symbol: StockSymbol adjusted: bool = True + @root_validator + def check_window_start(cls, values): + k1, k2 = 'min_date', 'days_back' + md, db = values.get(k1), values.get(k2) + if (md is None) is (db is None): + raise ValueError(f'precisely on of {k1} and {k2} must be set!') + return values + def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: if new_start_date: self.max_date = datetime.date.today() max_date = self.max_date - min_date = max_date - datetime.timedelta(days=self.days_back) + min_date = self.min_date if self.min_date else max_date - datetime.timedelta(days=self.days_back) res = None tmp = max_date while min_date < tmp: @@ -188,8 +199,5 @@ def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: res = tw else: res.consume(tw) - print(min_date, max_date, tmp) assert res is not None return res - - diff --git a/polygon/websocket/pm.py b/polygon/websocket/pm.py index 7a0626e5..bfff1411 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/pm.py @@ -33,7 +33,7 @@ class Quote(SocketBase): ask_exchange_id: int = Field(alias='ax') ask_price: float = Field(alias='ap') ask_size: int = Field(alias='as') - quote_conditions: int = Field(alias='c') + quote_conditions: typing.Optional[int] = Field(alias='c', default=None) utc: datetime.datetime = Field(alias='t') def __str__(self): From 5b3a8f019c511c82863c04f204ce622333f8794e Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 6 Dec 2020 18:23:09 +0100 Subject: [PATCH 11/21] Cleanup of unused code ... --- polygon/rest/client.py | 188 - polygon/rest/models/__init__.py | 196 - polygon/rest/models/definitions.py | 3689 ----------------- polygon/rest/models/unmarshal.py | 9 - polygon/rest/{models/pm.py => rest_models.py} | 0 polygon/websocket/{pm.py => stream_models.py} | 8 +- rest-example.py | 15 - websocket-example.py | 30 - 8 files changed, 4 insertions(+), 4131 deletions(-) delete mode 100644 polygon/rest/models/__init__.py delete mode 100644 polygon/rest/models/definitions.py delete mode 100644 polygon/rest/models/unmarshal.py rename polygon/rest/{models/pm.py => rest_models.py} (100%) rename polygon/websocket/{pm.py => stream_models.py} (88%) delete mode 100644 rest-example.py delete mode 100644 websocket-example.py diff --git a/polygon/rest/client.py b/polygon/rest/client.py index 71de2bf7..368dd3ab 100644 --- a/polygon/rest/client.py +++ b/polygon/rest/client.py @@ -1,10 +1,5 @@ -from typing import Dict, Type - import requests -from polygon.rest import models -from polygon.rest.models import unmarshal - class RESTClient: """ This is a custom generated class """ @@ -26,186 +21,3 @@ def __exit__(self, *args): def close(self): self._session.close() - - def _handle_response(self, response_type: str, endpoint: str, params: Dict[str, str]) -> Type[models.AnyDefinition]: - resp: requests.Response = self._session.get(endpoint, params=params, timeout=self.timeout) - if resp.status_code == 200: - return unmarshal.unmarshal_json(response_type, resp.json()) - else: - resp.raise_for_status() - - def reference_tickers(self, **query_params) -> models.ReferenceTickersApiResponse: - endpoint = f"{self.url}/v2/reference/tickers" - return self._handle_response("ReferenceTickersApiResponse", endpoint, query_params) - - def reference_ticker_types(self, **query_params) -> models.ReferenceTickerTypesApiResponse: - endpoint = f"{self.url}/v2/reference/types" - return self._handle_response("ReferenceTickerTypesApiResponse", endpoint, query_params) - - def reference_ticker_details(self, symbol, **query_params) -> models.ReferenceTickerDetailsApiResponse: - endpoint = f"{self.url}/v1/meta/symbols/{symbol}/company" - return self._handle_response("ReferenceTickerDetailsApiResponse", endpoint, query_params) - - def reference_ticker_news(self, symbol, **query_params) -> models.ReferenceTickerNewsApiResponse: - endpoint = f"{self.url}/v1/meta/symbols/{symbol}/news" - return self._handle_response("ReferenceTickerNewsApiResponse", endpoint, query_params) - - def reference_markets(self, **query_params) -> models.ReferenceMarketsApiResponse: - endpoint = f"{self.url}/v2/reference/markets" - return self._handle_response("ReferenceMarketsApiResponse", endpoint, query_params) - - def reference_locales(self, **query_params) -> models.ReferenceLocalesApiResponse: - endpoint = f"{self.url}/v2/reference/locales" - return self._handle_response("ReferenceLocalesApiResponse", endpoint, query_params) - - def reference_stock_splits(self, symbol, **query_params) -> models.ReferenceStockSplitsApiResponse: - endpoint = f"{self.url}/v2/reference/splits/{symbol}" - return self._handle_response("ReferenceStockSplitsApiResponse", endpoint, query_params) - - def reference_stock_dividends(self, symbol, **query_params) -> models.ReferenceStockDividendsApiResponse: - endpoint = f"{self.url}/v2/reference/dividends/{symbol}" - return self._handle_response("ReferenceStockDividendsApiResponse", endpoint, query_params) - - def reference_stock_financials(self, symbol, **query_params) -> models.ReferenceStockFinancialsApiResponse: - endpoint = f"{self.url}/v2/reference/financials/{symbol}" - return self._handle_response("ReferenceStockFinancialsApiResponse", endpoint, query_params) - - def reference_market_status(self, **query_params) -> models.ReferenceMarketStatusApiResponse: - endpoint = f"{self.url}/v1/marketstatus/now" - return self._handle_response("ReferenceMarketStatusApiResponse", endpoint, query_params) - - def reference_market_holidays(self, **query_params) -> models.ReferenceMarketHolidaysApiResponse: - endpoint = f"{self.url}/v1/marketstatus/upcoming" - return self._handle_response("ReferenceMarketHolidaysApiResponse", endpoint, query_params) - - def stocks_equities_exchanges(self, **query_params) -> models.StocksEquitiesExchangesApiResponse: - endpoint = f"{self.url}/v1/meta/exchanges" - return self._handle_response("StocksEquitiesExchangesApiResponse", endpoint, query_params) - - def stocks_equities_historic_trades(self, symbol, date, - **query_params) -> models.StocksEquitiesHistoricTradesApiResponse: - endpoint = f"{self.url}/v1/historic/trades/{symbol}/{date}" - return self._handle_response("StocksEquitiesHistoricTradesApiResponse", endpoint, query_params) - - def historic_trades_v2(self, ticker, date, **query_params) -> models.HistoricTradesV2ApiResponse: - endpoint = f"{self.url}/v2/ticks/stocks/trades/{ticker}/{date}" - return self._handle_response("HistoricTradesV2ApiResponse", endpoint, query_params) - - def stocks_equities_historic_quotes(self, symbol, date, - **query_params) -> models.StocksEquitiesHistoricQuotesApiResponse: - endpoint = f"{self.url}/v1/historic/quotes/{symbol}/{date}" - return self._handle_response("StocksEquitiesHistoricQuotesApiResponse", endpoint, query_params) - - def historic_n___bbo_quotes_v2(self, ticker, date, **query_params) -> models.HistoricNBboQuotesV2ApiResponse: - endpoint = f"{self.url}/v2/ticks/stocks/nbbo/{ticker}/{date}" - return self._handle_response("HistoricNBboQuotesV2ApiResponse", endpoint, query_params) - - def stocks_equities_last_trade_for_a_symbol(self, symbol, - **query_params) -> models.StocksEquitiesLastTradeForASymbolApiResponse: - endpoint = f"{self.url}/v1/last/stocks/{symbol}" - return self._handle_response("StocksEquitiesLastTradeForASymbolApiResponse", endpoint, query_params) - - def stocks_equities_last_quote_for_a_symbol(self, symbol, - **query_params) -> models.StocksEquitiesLastQuoteForASymbolApiResponse: - endpoint = f"{self.url}/v1/last_quote/stocks/{symbol}" - return self._handle_response("StocksEquitiesLastQuoteForASymbolApiResponse", endpoint, query_params) - - def stocks_equities_daily_open_close(self, symbol, date, - **query_params) -> models.StocksEquitiesDailyOpenCloseApiResponse: - endpoint = f"{self.url}/v1/open-close/{symbol}/{date}" - return self._handle_response("StocksEquitiesDailyOpenCloseApiResponse", endpoint, query_params) - - def stocks_equities_condition_mappings(self, ticktype, - **query_params) -> models.StocksEquitiesConditionMappingsApiResponse: - endpoint = f"{self.url}/v1/meta/conditions/{ticktype}" - return self._handle_response("StocksEquitiesConditionMappingsApiResponse", endpoint, query_params) - - def stocks_equities_snapshot_all_tickers(self, - **query_params) -> models.StocksEquitiesSnapshotAllTickersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/us/markets/stocks/tickers" - return self._handle_response("StocksEquitiesSnapshotAllTickersApiResponse", endpoint, query_params) - - def stocks_equities_snapshot_single_ticker(self, ticker, - **query_params) -> models.StocksEquitiesSnapshotSingleTickerApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/us/markets/stocks/tickers/{ticker}" - return self._handle_response("StocksEquitiesSnapshotSingleTickerApiResponse", endpoint, query_params) - - def stocks_equities_snapshot_gainers_losers(self, direction, - **query_params) -> models.StocksEquitiesSnapshotGainersLosersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/us/markets/stocks/{direction}" - return self._handle_response("StocksEquitiesSnapshotGainersLosersApiResponse", endpoint, query_params) - - def stocks_equities_previous_close(self, ticker, **query_params) -> models.StocksEquitiesPreviousCloseApiResponse: - endpoint = f"{self.url}/v2/aggs/ticker/{ticker}/prev" - return self._handle_response("StocksEquitiesPreviousCloseApiResponse", endpoint, query_params) - - def stocks_equities_aggregates(self, ticker, multiplier, timespan, from_, to, - **query_params) -> models.StocksEquitiesAggregatesApiResponse: - endpoint = f"{self.url}/v2/aggs/ticker/{ticker}/range/{multiplier}/{timespan}/{from_}/{to}" - return self._handle_response("StocksEquitiesAggregatesApiResponse", endpoint, query_params) - - def stocks_equities_grouped_daily(self, locale, market, date, - **query_params) -> models.StocksEquitiesGroupedDailyApiResponse: - endpoint = f"{self.url}/v2/aggs/grouped/locale/{locale}/market/{market}/{date}" - return self._handle_response("StocksEquitiesGroupedDailyApiResponse", endpoint, query_params) - - def forex_currencies_historic_forex_ticks(self, from_, to, date, - **query_params) -> models.ForexCurrenciesHistoricForexTicksApiResponse: - endpoint = f"{self.url}/v1/historic/forex/{from_}/{to}/{date}" - return self._handle_response("ForexCurrenciesHistoricForexTicksApiResponse", endpoint, query_params) - - def forex_currencies_real_time_currency_conversion(self, from_, to, - **query_params) -> models.ForexCurrenciesRealTimeCurrencyConversionApiResponse: - endpoint = f"{self.url}/v1/conversion/{from_}/{to}" - return self._handle_response("ForexCurrenciesRealTimeCurrencyConversionApiResponse", endpoint, query_params) - - def forex_currencies_last_quote_for_a_currency_pair(self, from_, to, - **query_params) -> models.ForexCurrenciesLastQuoteForACurrencyPairApiResponse: - endpoint = f"{self.url}/v1/last_quote/currencies/{from_}/{to}" - return self._handle_response("ForexCurrenciesLastQuoteForACurrencyPairApiResponse", endpoint, query_params) - - def forex_currencies_snapshot_all_tickers(self, - **query_params) -> models.ForexCurrenciesSnapshotAllTickersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/forex/tickers" - return self._handle_response("ForexCurrenciesSnapshotAllTickersApiResponse", endpoint, query_params) - - def forex_currencies_snapshot_gainers_losers(self, direction, - **query_params) -> models.ForexCurrenciesSnapshotGainersLosersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/forex/{direction}" - return self._handle_response("ForexCurrenciesSnapshotGainersLosersApiResponse", endpoint, query_params) - - def crypto_crypto_exchanges(self, **query_params) -> models.CryptoCryptoExchangesApiResponse: - endpoint = f"{self.url}/v1/meta/crypto-exchanges" - return self._handle_response("CryptoCryptoExchangesApiResponse", endpoint, query_params) - - def crypto_last_trade_for_a_crypto_pair(self, from_, to, - **query_params) -> models.CryptoLastTradeForACryptoPairApiResponse: - endpoint = f"{self.url}/v1/last/crypto/{from_}/{to}" - return self._handle_response("CryptoLastTradeForACryptoPairApiResponse", endpoint, query_params) - - def crypto_daily_open_close(self, from_, to, date, **query_params) -> models.CryptoDailyOpenCloseApiResponse: - endpoint = f"{self.url}/v1/open-close/crypto/{from_}/{to}/{date}" - return self._handle_response("CryptoDailyOpenCloseApiResponse", endpoint, query_params) - - def crypto_historic_crypto_trades(self, from_, to, date, - **query_params) -> models.CryptoHistoricCryptoTradesApiResponse: - endpoint = f"{self.url}/v1/historic/crypto/{from_}/{to}/{date}" - return self._handle_response("CryptoHistoricCryptoTradesApiResponse", endpoint, query_params) - - def crypto_snapshot_all_tickers(self, **query_params) -> models.CryptoSnapshotAllTickersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/crypto/tickers" - return self._handle_response("CryptoSnapshotAllTickersApiResponse", endpoint, query_params) - - def crypto_snapshot_single_ticker(self, ticker, **query_params) -> models.CryptoSnapshotSingleTickerApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/crypto/tickers/{ticker}" - return self._handle_response("CryptoSnapshotSingleTickerApiResponse", endpoint, query_params) - - def crypto_snapshot_single_ticker_full_book(self, ticker, - **query_params) -> models.CryptoSnapshotSingleTickerFullBookApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/crypto/tickers/{ticker}/book" - return self._handle_response("CryptoSnapshotSingleTickerFullBookApiResponse", endpoint, query_params) - - def crypto_snapshot_gainers_losers(self, direction, - **query_params) -> models.CryptoSnapshotGainersLosersApiResponse: - endpoint = f"{self.url}/v2/snapshot/locale/global/markets/crypto/{direction}" - return self._handle_response("CryptoSnapshotGainersLosersApiResponse", endpoint, query_params) diff --git a/polygon/rest/models/__init__.py b/polygon/rest/models/__init__.py deleted file mode 100644 index a3dec9b9..00000000 --- a/polygon/rest/models/__init__.py +++ /dev/null @@ -1,196 +0,0 @@ -from .definitions import LastTrade -from .definitions import LastQuote -from .definitions import HistTrade -from .definitions import Quote -from .definitions import Aggregate -from .definitions import Company -from .definitions import Symbol -from .definitions import Dividend -from .definitions import News -from .definitions import Earning -from .definitions import Financial -from .definitions import Exchange -from .definitions import Error -from .definitions import NotFound -from .definitions import Conflict -from .definitions import Unauthorized -from .definitions import MarketStatus -from .definitions import MarketHoliday -from .definitions import AnalystRatings -from .definitions import RatingSection -from .definitions import CryptoTick -from .definitions import CryptoTickJson -from .definitions import CryptoExchange -from .definitions import CryptoSnapshotTicker -from .definitions import CryptoSnapshotBookItem -from .definitions import CryptoSnapshotTickerBook -from .definitions import CryptoSnapshotAgg -from .definitions import Forex -from .definitions import LastForexTrade -from .definitions import LastForexQuote -from .definitions import ForexAggregate -from .definitions import ForexSnapshotTicker -from .definitions import ForexSnapshotAgg -from .definitions import Ticker -from .definitions import Split -from .definitions import Financials -from .definitions import Trade -from .definitions import StocksSnapshotTicker -from .definitions import StocksSnapshotBookItem -from .definitions import StocksSnapshotTickerBook -from .definitions import StocksV2Trade -from .definitions import StocksV2NBBO -from .definitions import StocksSnapshotAgg -from .definitions import StocksSnapshotQuote -from .definitions import Aggv2 -from .definitions import AggResponse -from .definitions import ReferenceTickersApiResponse -from .definitions import ReferenceTickerTypesApiResponse -from .definitions import ReferenceTickerDetailsApiResponse -from .definitions import ReferenceTickerNewsApiResponse -from .definitions import ReferenceMarketsApiResponse -from .definitions import ReferenceLocalesApiResponse -from .definitions import ReferenceStockSplitsApiResponse -from .definitions import ReferenceStockDividendsApiResponse -from .definitions import ReferenceStockFinancialsApiResponse -from .definitions import ReferenceMarketStatusApiResponse -from .definitions import ReferenceMarketHolidaysApiResponse -from .definitions import StocksEquitiesExchangesApiResponse -from .definitions import StocksEquitiesHistoricTradesApiResponse -from .definitions import HistoricTradesV2ApiResponse -from .definitions import StocksEquitiesHistoricQuotesApiResponse -from .definitions import HistoricNBboQuotesV2ApiResponse -from .definitions import StocksEquitiesLastTradeForASymbolApiResponse -from .definitions import StocksEquitiesLastQuoteForASymbolApiResponse -from .definitions import StocksEquitiesDailyOpenCloseApiResponse -from .definitions import StocksEquitiesConditionMappingsApiResponse -from .definitions import StocksEquitiesSnapshotAllTickersApiResponse -from .definitions import StocksEquitiesSnapshotSingleTickerApiResponse -from .definitions import StocksEquitiesSnapshotGainersLosersApiResponse -from .definitions import StocksEquitiesPreviousCloseApiResponse -from .definitions import StocksEquitiesAggregatesApiResponse -from .definitions import StocksEquitiesGroupedDailyApiResponse -from .definitions import ForexCurrenciesHistoricForexTicksApiResponse -from .definitions import ForexCurrenciesRealTimeCurrencyConversionApiResponse -from .definitions import ForexCurrenciesLastQuoteForACurrencyPairApiResponse -from .definitions import ForexCurrenciesSnapshotAllTickersApiResponse -from .definitions import ForexCurrenciesSnapshotGainersLosersApiResponse -from .definitions import CryptoCryptoExchangesApiResponse -from .definitions import CryptoLastTradeForACryptoPairApiResponse -from .definitions import CryptoDailyOpenCloseApiResponse -from .definitions import CryptoHistoricCryptoTradesApiResponse -from .definitions import CryptoSnapshotAllTickersApiResponse -from .definitions import CryptoSnapshotSingleTickerApiResponse -from .definitions import CryptoSnapshotSingleTickerFullBookApiResponse -from .definitions import CryptoSnapshotGainersLosersApiResponse -from .definitions import StockSymbol -from .definitions import ConditionTypeMap -from .definitions import SymbolTypeMap -from .definitions import TickerSymbol - - -import typing - -from .definitions import Definition - - -AnyDefinition = typing.TypeVar("AnyDefinition", bound=Definition) - -# noinspection SpellCheckingInspection -name_to_class: typing.Dict[str, typing.Callable[[], typing.Type[AnyDefinition]]] = { - "LastTrade": LastTrade, - "LastQuote": LastQuote, - "HistTrade": HistTrade, - "Quote": Quote, - "Aggregate": Aggregate, - "Company": Company, - "Symbol": Symbol, - "Dividend": Dividend, - "News": News, - "Earning": Earning, - "Financial": Financial, - "Exchange": Exchange, - "Error": Error, - "NotFound": NotFound, - "Conflict": Conflict, - "Unauthorized": Unauthorized, - "MarketStatus": MarketStatus, - "MarketHoliday": MarketHoliday, - "AnalystRatings": AnalystRatings, - "RatingSection": RatingSection, - "CryptoTick": CryptoTick, - "CryptoTickJson": CryptoTickJson, - "CryptoExchange": CryptoExchange, - "CryptoSnapshotTicker": CryptoSnapshotTicker, - "CryptoSnapshotBookItem": CryptoSnapshotBookItem, - "CryptoSnapshotTickerBook": CryptoSnapshotTickerBook, - "CryptoSnapshotAgg": CryptoSnapshotAgg, - "Forex": Forex, - "LastForexTrade": LastForexTrade, - "LastForexQuote": LastForexQuote, - "ForexAggregate": ForexAggregate, - "ForexSnapshotTicker": ForexSnapshotTicker, - "ForexSnapshotAgg": ForexSnapshotAgg, - "Ticker": Ticker, - "Split": Split, - "Financials": Financials, - "Trade": Trade, - "StocksSnapshotTicker": StocksSnapshotTicker, - "StocksSnapshotBookItem": StocksSnapshotBookItem, - "StocksSnapshotTickerBook": StocksSnapshotTickerBook, - "StocksV2Trade": StocksV2Trade, - "StocksV2NBBO": StocksV2NBBO, - "StocksSnapshotAgg": StocksSnapshotAgg, - "StocksSnapshotQuote": StocksSnapshotQuote, - "Aggv2": Aggv2, - "AggResponse": AggResponse, - "ReferenceTickersApiResponse": ReferenceTickersApiResponse, - "ReferenceTickerTypesApiResponse": ReferenceTickerTypesApiResponse, - "ReferenceTickerDetailsApiResponse": ReferenceTickerDetailsApiResponse, - "ReferenceTickerNewsApiResponse": ReferenceTickerNewsApiResponse, - "ReferenceMarketsApiResponse": ReferenceMarketsApiResponse, - "ReferenceLocalesApiResponse": ReferenceLocalesApiResponse, - "ReferenceStockSplitsApiResponse": ReferenceStockSplitsApiResponse, - "ReferenceStockDividendsApiResponse": ReferenceStockDividendsApiResponse, - "ReferenceStockFinancialsApiResponse": ReferenceStockFinancialsApiResponse, - "ReferenceMarketStatusApiResponse": ReferenceMarketStatusApiResponse, - "ReferenceMarketHolidaysApiResponse": ReferenceMarketHolidaysApiResponse, - "StocksEquitiesExchangesApiResponse": StocksEquitiesExchangesApiResponse, - "StocksEquitiesHistoricTradesApiResponse": StocksEquitiesHistoricTradesApiResponse, - "HistoricTradesV2ApiResponse": HistoricTradesV2ApiResponse, - "StocksEquitiesHistoricQuotesApiResponse": StocksEquitiesHistoricQuotesApiResponse, - "HistoricNBboQuotesV2ApiResponse": HistoricNBboQuotesV2ApiResponse, - "StocksEquitiesLastTradeForASymbolApiResponse": StocksEquitiesLastTradeForASymbolApiResponse, - "StocksEquitiesLastQuoteForASymbolApiResponse": StocksEquitiesLastQuoteForASymbolApiResponse, - "StocksEquitiesDailyOpenCloseApiResponse": StocksEquitiesDailyOpenCloseApiResponse, - "StocksEquitiesConditionMappingsApiResponse": StocksEquitiesConditionMappingsApiResponse, - "StocksEquitiesSnapshotAllTickersApiResponse": StocksEquitiesSnapshotAllTickersApiResponse, - "StocksEquitiesSnapshotSingleTickerApiResponse": StocksEquitiesSnapshotSingleTickerApiResponse, - "StocksEquitiesSnapshotGainersLosersApiResponse": StocksEquitiesSnapshotGainersLosersApiResponse, - "StocksEquitiesPreviousCloseApiResponse": StocksEquitiesPreviousCloseApiResponse, - "StocksEquitiesAggregatesApiResponse": StocksEquitiesAggregatesApiResponse, - "StocksEquitiesGroupedDailyApiResponse": StocksEquitiesGroupedDailyApiResponse, - "ForexCurrenciesHistoricForexTicksApiResponse": ForexCurrenciesHistoricForexTicksApiResponse, - "ForexCurrenciesRealTimeCurrencyConversionApiResponse": ForexCurrenciesRealTimeCurrencyConversionApiResponse, - "ForexCurrenciesLastQuoteForACurrencyPairApiResponse": ForexCurrenciesLastQuoteForACurrencyPairApiResponse, - "ForexCurrenciesSnapshotAllTickersApiResponse": ForexCurrenciesSnapshotAllTickersApiResponse, - "ForexCurrenciesSnapshotGainersLosersApiResponse": ForexCurrenciesSnapshotGainersLosersApiResponse, - "CryptoCryptoExchangesApiResponse": CryptoCryptoExchangesApiResponse, - "CryptoLastTradeForACryptoPairApiResponse": CryptoLastTradeForACryptoPairApiResponse, - "CryptoDailyOpenCloseApiResponse": CryptoDailyOpenCloseApiResponse, - "CryptoHistoricCryptoTradesApiResponse": CryptoHistoricCryptoTradesApiResponse, - "CryptoSnapshotAllTickersApiResponse": CryptoSnapshotAllTickersApiResponse, - "CryptoSnapshotSingleTickerApiResponse": CryptoSnapshotSingleTickerApiResponse, - "CryptoSnapshotSingleTickerFullBookApiResponse": CryptoSnapshotSingleTickerFullBookApiResponse, - "CryptoSnapshotGainersLosersApiResponse": CryptoSnapshotGainersLosersApiResponse, - -} - -# noinspection SpellCheckingInspection -name_to_type = { - "StockSymbol": StockSymbol, - "ConditionTypeMap": ConditionTypeMap, - "SymbolTypeMap": SymbolTypeMap, - "TickerSymbol": TickerSymbol, - -} \ No newline at end of file diff --git a/polygon/rest/models/definitions.py b/polygon/rest/models/definitions.py deleted file mode 100644 index d395e0f9..00000000 --- a/polygon/rest/models/definitions.py +++ /dev/null @@ -1,3689 +0,0 @@ -import keyword -from typing import List, Dict, Any - -from polygon.rest import models -from pydantic import BaseModel - -class Definition: - _swagger_name_to_python: Dict[str, str] - _attribute_is_primitive: Dict[str, bool] - _attributes_to_types: Dict[str, Any] - - def unmarshal_json(self, input_json): - if isinstance(input_json, list): - list_attribute_name = list(self._swagger_name_to_python.values())[0] - if list_attribute_name in self._attributes_to_types: - list_type = self._attributes_to_types[list_attribute_name] - known_type = list_type.split("[")[1][:-1] - list_items = self._unmarshal_json_list(input_json, known_type) - else: - list_items = input_json - self.__setattr__(list_attribute_name, list_items) - return self - elif isinstance(input_json, dict): - self._unmarshal_json_object(input_json) - return self - elif isinstance(input_json, float) or isinstance(input_json, int): - return input_json - - @staticmethod - def _unmarshal_json_list(input_json, known_type): - items = [] - for item in input_json: - new_item = models.name_to_class[known_type]() - items.append(new_item._unmarshal_json_object(item)) - - return items - - def _unmarshal_json_object(self, input_json): - for key, value in input_json.items(): - if key in self._swagger_name_to_python: - attribute_name = self._swagger_name_to_python[key] - if not self._attribute_is_primitive[attribute_name]: - if attribute_name in self._attributes_to_types: - attribute_type = self._attributes_to_types[attribute_name] - if attribute_type in models.name_to_class: - model = models.name_to_class[attribute_type]() - value = model.unmarshal_json(input_json[key]) - else: - attribute_name = key + ('_' if keyword.iskeyword(key) else '') - - self.__setattr__(attribute_name, value) - return self - - -# noinspection SpellCheckingInspection -class LastTrade(Definition): - _swagger_name_to_python = { - "price": "price", - "size": "size", - "exchange": "exchange", - "cond1": "cond1", - "cond2": "cond2", - "cond3": "cond3", - "cond4": "cond4", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "price": True, - "size": True, - "exchange": True, - "cond1": True, - "cond2": True, - "cond3": True, - "cond4": True, - "timestamp": True, - - } - - _attributes_to_types = { - "price": "int", - "size": "int", - "exchange": "int", - "cond1": "int", - "cond2": "int", - "cond3": "int", - "cond4": "int", - "timestamp": "int", - - } - - def __init__(self): - self.price: int - self.size: int - self.exchange: int - self.cond1: int - self.cond2: int - self.cond3: int - self.cond4: int - self.timestamp: int - - -# noinspection SpellCheckingInspection -class LastQuote(Definition): - _swagger_name_to_python = { - "askprice": "askprice", - "asksize": "asksize", - "askexchange": "askexchange", - "bidprice": "bidprice", - "bidsize": "bidsize", - "bidexchange": "bidexchange", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "askprice": True, - "asksize": True, - "askexchange": True, - "bidprice": True, - "bidsize": True, - "bidexchange": True, - "timestamp": True, - - } - - _attributes_to_types = { - "askprice": "int", - "asksize": "int", - "askexchange": "int", - "bidprice": "int", - "bidsize": "int", - "bidexchange": "int", - "timestamp": "int", - - } - - def __init__(self): - self.askprice: int - self.asksize: int - self.askexchange: int - self.bidprice: int - self.bidsize: int - self.bidexchange: int - self.timestamp: int - - -# noinspection SpellCheckingInspection -class HistTrade2(Definition): - _swagger_name_to_python = { - "condition1": "condition1", - "condition2": "condition2", - "condition3": "condition3", - "condition4": "condition4", - "exchange": "exchange", - "price": "price", - "size": "size", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "condition1": True, - "condition2": True, - "condition3": True, - "condition4": True, - "exchange": True, - "price": True, - "size": True, - "timestamp": True, - - } - - _attributes_to_types = { - "condition1": "int", - "condition2": "int", - "condition3": "int", - "condition4": "int", - "exchange": "str", - "price": "int", - "size": "int", - "timestamp": "str", - - } - - def __init__(self): - self.condition1: int - self.condition2: int - self.condition3: int - self.condition4: int - self.exchange: str - self.price: int - self.size: int - self.timestamp: str - -class HistTrade(Definition): - _swagger_name_to_python = { - "condition1": "condition1", - "condition2": "condition2", - "condition3": "condition3", - "condition4": "condition4", - "exchange": "exchange", - "price": "price", - "size": "size", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "condition1": True, - "condition2": True, - "condition3": True, - "condition4": True, - "exchange": True, - "price": True, - "size": True, - "timestamp": True, - - } - - _attributes_to_types = { - "condition1": "int", - "condition2": "int", - "condition3": "int", - "condition4": "int", - "exchange": "str", - "price": "int", - "size": "int", - "timestamp": "str", - - } - - def __init__(self): - self.condition1: int - self.condition2: int - self.condition3: int - self.condition4: int - self.exchange: str - self.price: int - self.size: int - self.timestamp: str - - -# noinspection SpellCheckingInspection -class Quote(Definition): - _swagger_name_to_python = { - "c": "condition_of_this_quote", - "bE": "bid_exchange", - "aE": "ask_exchange", - "aP": "ask_price", - "bP": "bid_price", - "bS": "bid_size", - "aS": "ask_size", - "t": "timestamp_of_this_trade", - - } - - _attribute_is_primitive = { - "condition_of_this_quote": True, - "bid_exchange": True, - "ask_exchange": True, - "ask_price": True, - "bid_price": True, - "bid_size": True, - "ask_size": True, - "timestamp_of_this_trade": True, - - } - - _attributes_to_types = { - "condition_of_this_quote": "int", - "bid_exchange": "str", - "ask_exchange": "str", - "ask_price": "int", - "bid_price": "int", - "bid_size": "int", - "ask_size": "int", - "timestamp_of_this_trade": "int", - - } - - def __init__(self): - self.condition_of_this_quote: int - self.bid_exchange: str - self.ask_exchange: str - self.ask_price: int - self.bid_price: int - self.bid_size: int - self.ask_size: int - self.timestamp_of_this_trade: int - - -# noinspection SpellCheckingInspection -class Aggregate(Definition): - _swagger_name_to_python = { - "o": "open_price", - "c": "close_price", - "l": "low_price", - "h": "high_price", - "v": "total_volume_of_all_trades", - "k": "transactions", - "t": "timestamp_of_this_aggregation", - - } - - _attribute_is_primitive = { - "open_price": True, - "close_price": True, - "low_price": True, - "high_price": True, - "total_volume_of_all_trades": True, - "transactions": True, - "timestamp_of_this_aggregation": True, - - } - - _attributes_to_types = { - "open_price": "int", - "close_price": "int", - "low_price": "int", - "high_price": "int", - "total_volume_of_all_trades": "int", - "transactions": "int", - "timestamp_of_this_aggregation": "int", - - } - - def __init__(self): - self.open_price: int - self.close_price: int - self.low_price: int - self.high_price: int - self.total_volume_of_all_trades: int - self.transactions: int - self.timestamp_of_this_aggregation: int - - -# noinspection SpellCheckingInspection -class Company(Definition): - _swagger_name_to_python = { - "logo": "logo", - "exchange": "exchange", - "name": "name", - "symbol": "symbol", - "listdate": "listdate", - "cik": "cik", - "bloomberg": "bloomberg", - "figi": "figi", - "lei": "lei", - "sic": "sic", - "country": "country", - "industry": "industry", - "sector": "sector", - "marketcap": "marketcap", - "employees": "employees", - "phone": "phone", - "ceo": "ceo", - "url": "url", - "description": "description", - "similar": "similar", - "tags": "tags", - "updated": "updated", - - } - - _attribute_is_primitive = { - "logo": True, - "exchange": True, - "name": True, - "symbol": False, - "listdate": True, - "cik": True, - "bloomberg": True, - "figi": True, - "lei": True, - "sic": True, - "country": True, - "industry": True, - "sector": True, - "marketcap": True, - "employees": True, - "phone": True, - "ceo": True, - "url": True, - "description": True, - "similar": False, - "tags": False, - "updated": True, - - } - - _attributes_to_types = { - "logo": "str", - "exchange": "str", - "name": "str", - "symbol": "StockSymbol", - "listdate": "str", - "cik": "str", - "bloomberg": "str", - "figi": "str", - "lei": "str", - "sic": "float", - "country": "str", - "industry": "str", - "sector": "str", - "marketcap": "float", - "employees": "float", - "phone": "str", - "ceo": "str", - "url": "str", - "description": "str", - "similar": "List[StockSymbol]", - "tags": "List[str]", - "updated": "str", - - } - - def __init__(self): - self.logo: str - self.exchange: str - self.name: str - self.symbol: StockSymbol - self.listdate: str - self.cik: str - self.bloomberg: str - self.figi: str - self.lei: str - self.sic: float - self.country: str - self.industry: str - self.sector: str - self.marketcap: float - self.employees: float - self.phone: str - self.ceo: str - self.url: str - self.description: str - self.similar: List[StockSymbol] - self.tags: List[str] - self.updated: str - - -# noinspection SpellCheckingInspection -class Symbol(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "name": "name", - "type": "type", - "url": "url", - "updated": "updated", - "isOTC": "is___otc", - - } - - _attribute_is_primitive = { - "symbol": False, - "name": True, - "type": True, - "url": True, - "updated": True, - "is___otc": True, - - } - - _attributes_to_types = { - "symbol": "StockSymbol", - "name": "str", - "type": "str", - "url": "str", - "updated": "str", - "is___otc": "bool", - - } - - def __init__(self): - self.symbol: StockSymbol - self.name: str - self.type: str - self.url: str - self.updated: str - self.is___otc: bool - - -# noinspection SpellCheckingInspection -class Dividend(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "type": "type", - "exDate": "ex_date", - "paymentDate": "payment_date", - "recordDate": "record_date", - "declaredDate": "declared_date", - "amount": "amount", - "qualified": "qualified", - "flag": "flag", - - } - - _attribute_is_primitive = { - "symbol": False, - "type": True, - "ex_date": True, - "payment_date": True, - "record_date": True, - "declared_date": True, - "amount": True, - "qualified": True, - "flag": True, - - } - - _attributes_to_types = { - "symbol": "StockSymbol", - "type": "str", - "ex_date": "str", - "payment_date": "str", - "record_date": "str", - "declared_date": "str", - "amount": "float", - "qualified": "str", - "flag": "str", - - } - - def __init__(self): - self.symbol: StockSymbol - self.type: str - self.ex_date: str - self.payment_date: str - self.record_date: str - self.declared_date: str - self.amount: float - self.qualified: str - self.flag: str - - -# noinspection SpellCheckingInspection -class News(Definition): - _swagger_name_to_python = { - "symbols": "symbols", - "title": "title", - "url": "url", - "source": "source", - "summary": "summary", - "image": "image", - "timestamp": "timestamp", - "keywords": "keywords", - - } - - _attribute_is_primitive = { - "symbols": False, - "title": True, - "url": True, - "source": True, - "summary": True, - "image": True, - "timestamp": True, - "keywords": False, - - } - - _attributes_to_types = { - "symbols": "List[StockSymbol]", - "title": "str", - "url": "str", - "source": "str", - "summary": "str", - "image": "str", - "timestamp": "str", - "keywords": "List[str]", - - } - - def __init__(self): - self.symbols: List[StockSymbol] - self.title: str - self.url: str - self.source: str - self.summary: str - self.image: str - self.timestamp: str - self.keywords: List[str] - - -# noinspection SpellCheckingInspection -class Earning(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "EPSReportDate": "e___psrep_ortdate", - "EPSReportDateStr": "e___psrep_ort_datestr", - "fiscalPeriod": "fiscal_period", - "fiscalEndDate": "fiscal_en_ddate", - "actualEPS": "actual___eps", - "consensusEPS": "consensus___eps", - "estimatedEPS": "estimated___eps", - "announceTime": "announce_time", - "numberOfEstimates": "number_o_festimates", - "EPSSurpriseDollar": "e___pssurpr_isedollar", - "yearAgo": "year_ago", - "yearAgoChangePercent": "year_ag_ochan_gepercent", - "estimatedChangePercent": "estimated_chang_epercent", - - } - - _attribute_is_primitive = { - "symbol": True, - "e___psrep_ortdate": True, - "e___psrep_ort_datestr": True, - "fiscal_period": True, - "fiscal_en_ddate": True, - "actual___eps": True, - "consensus___eps": True, - "estimated___eps": True, - "announce_time": True, - "number_o_festimates": True, - "e___pssurpr_isedollar": True, - "year_ago": True, - "year_ag_ochan_gepercent": True, - "estimated_chang_epercent": True, - - } - - _attributes_to_types = { - "symbol": "str", - "e___psrep_ortdate": "str", - "e___psrep_ort_datestr": "str", - "fiscal_period": "str", - "fiscal_en_ddate": "str", - "actual___eps": "float", - "consensus___eps": "float", - "estimated___eps": "float", - "announce_time": "str", - "number_o_festimates": "float", - "e___pssurpr_isedollar": "float", - "year_ago": "float", - "year_ag_ochan_gepercent": "float", - "estimated_chang_epercent": "float", - - } - - def __init__(self): - self.symbol: str - self.e___psrep_ortdate: str - self.e___psrep_ort_datestr: str - self.fiscal_period: str - self.fiscal_en_ddate: str - self.actual___eps: float - self.consensus___eps: float - self.estimated___eps: float - self.announce_time: str - self.number_o_festimates: float - self.e___pssurpr_isedollar: float - self.year_ago: float - self.year_ag_ochan_gepercent: float - self.estimated_chang_epercent: float - - -# noinspection SpellCheckingInspection -class Financial(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "reportDate": "report_date", - "reportDateStr": "report_dat_estr", - "grossProfit": "gross_profit", - "costOfRevenue": "cost_o_frevenue", - "operatingRevenue": "operating_revenue", - "totalRevenue": "total_revenue", - "operatingIncome": "operating_income", - "netIncome": "net_income", - "researchAndDevelopment": "research_an_ddevelopment", - "operatingExpense": "operating_expense", - "currentAssets": "current_assets", - "totalAssets": "total_assets", - "totalLiabilities": "total_liabilities", - "currentCash": "current_cash", - "currentDebt": "current_debt", - "totalCash": "total_cash", - "totalDebt": "total_debt", - "shareholderEquity": "shareholder_equity", - "cashChange": "cash_change", - "cashFlow": "cash_flow", - "operatingGainsLosses": "operating_gain_slosses", - - } - - _attribute_is_primitive = { - "symbol": True, - "report_date": True, - "report_dat_estr": True, - "gross_profit": True, - "cost_o_frevenue": True, - "operating_revenue": True, - "total_revenue": True, - "operating_income": True, - "net_income": True, - "research_an_ddevelopment": True, - "operating_expense": True, - "current_assets": True, - "total_assets": True, - "total_liabilities": True, - "current_cash": True, - "current_debt": True, - "total_cash": True, - "total_debt": True, - "shareholder_equity": True, - "cash_change": True, - "cash_flow": True, - "operating_gain_slosses": True, - - } - - _attributes_to_types = { - "symbol": "str", - "report_date": "str", - "report_dat_estr": "str", - "gross_profit": "float", - "cost_o_frevenue": "float", - "operating_revenue": "float", - "total_revenue": "float", - "operating_income": "float", - "net_income": "float", - "research_an_ddevelopment": "float", - "operating_expense": "float", - "current_assets": "float", - "total_assets": "float", - "total_liabilities": "float", - "current_cash": "float", - "current_debt": "float", - "total_cash": "float", - "total_debt": "float", - "shareholder_equity": "float", - "cash_change": "float", - "cash_flow": "float", - "operating_gain_slosses": "float", - - } - - def __init__(self): - self.symbol: str - self.report_date: str - self.report_dat_estr: str - self.gross_profit: float - self.cost_o_frevenue: float - self.operating_revenue: float - self.total_revenue: float - self.operating_income: float - self.net_income: float - self.research_an_ddevelopment: float - self.operating_expense: float - self.current_assets: float - self.total_assets: float - self.total_liabilities: float - self.current_cash: float - self.current_debt: float - self.total_cash: float - self.total_debt: float - self.shareholder_equity: float - self.cash_change: float - self.cash_flow: float - self.operating_gain_slosses: float - - -# noinspection SpellCheckingInspection -class Exchange(Definition): - _swagger_name_to_python = { - "id": "i_d_of_the_exchange", - "type": "type", - "market": "market", - "mic": "mic", - "name": "name", - "tape": "tape", - - } - - _attribute_is_primitive = { - "i_d_of_the_exchange": True, - "type": True, - "market": True, - "mic": True, - "name": True, - "tape": True, - - } - - _attributes_to_types = { - "i_d_of_the_exchange": "float", - "type": "str", - "market": "str", - "mic": "str", - "name": "str", - "tape": "str", - - } - - def __init__(self): - self.i_d_of_the_exchange: float - self.type: str - self.market: str - self.mic: str - self.name: str - self.tape: str - - -# noinspection SpellCheckingInspection -class Error(Definition): - _swagger_name_to_python = { - "code": "code", - "message": "message", - "fields": "fields", - - } - - _attribute_is_primitive = { - "code": True, - "message": True, - "fields": True, - - } - - _attributes_to_types = { - "code": "int", - "message": "str", - "fields": "str", - - } - - def __init__(self): - self.code: int - self.message: str - self.fields: str - - -# noinspection SpellCheckingInspection -class NotFound(Definition): - _swagger_name_to_python = { - "message": "message", - - } - - _attribute_is_primitive = { - "message": True, - - } - - _attributes_to_types = { - "message": "str", - - } - - def __init__(self): - self.message: str - - -# noinspection SpellCheckingInspection -class Conflict(Definition): - _swagger_name_to_python = { - "message": "message", - - } - - _attribute_is_primitive = { - "message": True, - - } - - _attributes_to_types = { - "message": "str", - - } - - def __init__(self): - self.message: str - - -# noinspection SpellCheckingInspection -class Unauthorized(Definition): - _swagger_name_to_python = { - "message": "message", - - } - - _attribute_is_primitive = { - "message": True, - - } - - _attributes_to_types = { - "message": "str", - - } - - def __init__(self): - self.message: str - - -# noinspection SpellCheckingInspection -class MarketStatus(Definition): - _swagger_name_to_python = { - "market": "market", - "serverTime": "server_time", - "exchanges": "exchanges", - "currencies": "currencies", - - } - - _attribute_is_primitive = { - "market": True, - "server_time": True, - "exchanges": True, - "currencies": True, - - } - - _attributes_to_types = { - "market": "str", - "server_time": "str", - "exchanges": "Dict[str, str]", - "currencies": "Dict[str, str]", - - } - - def __init__(self): - self.market: str - self.server_time: str - self.exchanges: Dict[str, str] - self.currencies: Dict[str, str] - - -# noinspection SpellCheckingInspection -class MarketHoliday(Definition): - _swagger_name_to_python = { - "exchange": "exchange", - "name": "name", - "status": "status", - "date": "date", - "open": "open", - "close": "close", - - } - - _attribute_is_primitive = { - "exchange": True, - "name": True, - "status": True, - "date": True, - "open": True, - "close": True, - - } - - _attributes_to_types = { - "exchange": "str", - "name": "str", - "status": "str", - "date": "str", - "open": "str", - "close": "str", - - } - - def __init__(self): - self.exchange: str - self.name: str - self.status: str - self.date: str - self.open: str - self.close: str - - -# noinspection SpellCheckingInspection -class AnalystRatings(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "analysts": "analysts", - "change": "change", - "strongBuy": "strong_buy", - "buy": "buy", - "hold": "hold", - "sell": "sell", - "strongSell": "strong_sell", - "updated": "updated", - - } - - _attribute_is_primitive = { - "symbol": True, - "analysts": True, - "change": True, - "strong_buy": False, - "buy": False, - "hold": False, - "sell": False, - "strong_sell": False, - "updated": True, - - } - - _attributes_to_types = { - "symbol": "str", - "analysts": "float", - "change": "float", - "strong_buy": "RatingSection", - "buy": "RatingSection", - "hold": "RatingSection", - "sell": "RatingSection", - "strong_sell": "RatingSection", - "updated": "str", - - } - - def __init__(self): - self.symbol: str - self.analysts: float - self.change: float - self.strong_buy: RatingSection - self.buy: RatingSection - self.hold: RatingSection - self.sell: RatingSection - self.strong_sell: RatingSection - self.updated: str - - -# noinspection SpellCheckingInspection -class RatingSection(Definition): - _swagger_name_to_python = { - "current": "current", - "month1": "month1", - "month2": "month2", - "month3": "month3", - "month4": "month4", - "month5": "month5", - - } - - _attribute_is_primitive = { - "current": True, - "month1": True, - "month2": True, - "month3": True, - "month4": True, - "month5": True, - - } - - _attributes_to_types = { - "current": "float", - "month1": "float", - "month2": "float", - "month3": "float", - "month4": "float", - "month5": "float", - - } - - def __init__(self): - self.current: float - self.month1: float - self.month2: float - self.month3: float - self.month4: float - self.month5: float - - -# noinspection SpellCheckingInspection -class CryptoTick(Definition): - _swagger_name_to_python = { - "price": "price", - "size": "size", - "exchange": "exchange", - "conditions": "conditions", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "price": True, - "size": True, - "exchange": True, - "conditions": False, - "timestamp": True, - - } - - _attributes_to_types = { - "price": "int", - "size": "int", - "exchange": "int", - "conditions": "List[int]", - "timestamp": "int", - - } - - def __init__(self): - self.price: int - self.size: int - self.exchange: int - self.conditions: List[int] - self.timestamp: int - - -# noinspection SpellCheckingInspection -class CryptoTickJson(Definition): - _swagger_name_to_python = { - "p": "trade_price", - "s": "size_of_the_trade", - "x": "exchange_the_trade_occured_on", - "c": "c", - "t": "timestamp_of_this_trade", - - } - - _attribute_is_primitive = { - "trade_price": True, - "size_of_the_trade": True, - "exchange_the_trade_occured_on": True, - "c": False, - "timestamp_of_this_trade": True, - - } - - _attributes_to_types = { - "trade_price": "int", - "size_of_the_trade": "int", - "exchange_the_trade_occured_on": "int", - "c": "List[int]", - "timestamp_of_this_trade": "int", - - } - - def __init__(self): - self.trade_price: int - self.size_of_the_trade: int - self.exchange_the_trade_occured_on: int - self.c: List[int] - self.timestamp_of_this_trade: int - - -# noinspection SpellCheckingInspection -class CryptoExchange(Definition): - _swagger_name_to_python = { - "id": "i_d_of_the_exchange", - "type": "type", - "market": "market", - "name": "name", - "url": "url", - - } - - _attribute_is_primitive = { - "i_d_of_the_exchange": True, - "type": True, - "market": True, - "name": True, - "url": True, - - } - - _attributes_to_types = { - "i_d_of_the_exchange": "float", - "type": "str", - "market": "str", - "name": "str", - "url": "str", - - } - - def __init__(self): - self.i_d_of_the_exchange: float - self.type: str - self.market: str - self.name: str - self.url: str - - -# noinspection SpellCheckingInspection -class CryptoSnapshotTicker(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "day": "day", - "lastTrade": "last_trade", - "min": "min", - "prevDay": "prev_day", - "todaysChange": "todays_change", - "todaysChangePerc": "todays_chang_eperc", - "updated": "updated", - - } - - _attribute_is_primitive = { - "ticker": True, - "day": False, - "last_trade": False, - "min": False, - "prev_day": False, - "todays_change": True, - "todays_chang_eperc": True, - "updated": True, - - } - - _attributes_to_types = { - "ticker": "str", - "day": "CryptoSnapshotAgg", - "last_trade": "CryptoTickJson", - "min": "CryptoSnapshotAgg", - "prev_day": "CryptoSnapshotAgg", - "todays_change": "int", - "todays_chang_eperc": "int", - "updated": "int", - - } - - def __init__(self): - self.ticker: str - self.day: CryptoSnapshotAgg - self.last_trade: CryptoTickJson - self.min: CryptoSnapshotAgg - self.prev_day: CryptoSnapshotAgg - self.todays_change: int - self.todays_chang_eperc: int - self.updated: int - - -# noinspection SpellCheckingInspection -class CryptoSnapshotBookItem(Definition): - _swagger_name_to_python = { - "p": "price_of_this_book_level", - "x": "exchange_to_size_of_this_price_level", - - } - - _attribute_is_primitive = { - "price_of_this_book_level": True, - "exchange_to_size_of_this_price_level": True, - - } - - _attributes_to_types = { - "price_of_this_book_level": "int", - "exchange_to_size_of_this_price_level": "Dict[str, str]", - - } - - def __init__(self): - self.price_of_this_book_level: int - self.exchange_to_size_of_this_price_level: Dict[str, str] - - -# noinspection SpellCheckingInspection -class CryptoSnapshotTickerBook(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "bids": "bids", - "asks": "asks", - "bidCount": "bid_count", - "askCount": "ask_count", - "spread": "spread", - "updated": "updated", - - } - - _attribute_is_primitive = { - "ticker": True, - "bids": False, - "asks": False, - "bid_count": True, - "ask_count": True, - "spread": True, - "updated": True, - - } - - _attributes_to_types = { - "ticker": "str", - "bids": "List[CryptoSnapshotBookItem]", - "asks": "List[CryptoSnapshotBookItem]", - "bid_count": "int", - "ask_count": "int", - "spread": "int", - "updated": "int", - - } - - def __init__(self): - self.ticker: str - self.bids: List[CryptoSnapshotBookItem] - self.asks: List[CryptoSnapshotBookItem] - self.bid_count: int - self.ask_count: int - self.spread: int - self.updated: int - - -# noinspection SpellCheckingInspection -class CryptoSnapshotAgg(Definition): - _swagger_name_to_python = { - "c": "close_price", - "h": "high_price", - "l": "low_price", - "o": "open_price", - "v": "volume", - - } - - _attribute_is_primitive = { - "close_price": True, - "high_price": True, - "low_price": True, - "open_price": True, - "volume": True, - - } - - _attributes_to_types = { - "close_price": "int", - "high_price": "int", - "low_price": "int", - "open_price": "int", - "volume": "int", - - } - - def __init__(self): - self.close_price: int - self.high_price: int - self.low_price: int - self.open_price: int - self.volume: int - - -# noinspection SpellCheckingInspection -class Forex(Definition): - _swagger_name_to_python = { - "a": "ask_price", - "b": "bid_price", - "t": "timestamp_of_this_trade", - - } - - _attribute_is_primitive = { - "ask_price": True, - "bid_price": True, - "timestamp_of_this_trade": True, - - } - - _attributes_to_types = { - "ask_price": "int", - "bid_price": "int", - "timestamp_of_this_trade": "int", - - } - - def __init__(self): - self.ask_price: int - self.bid_price: int - self.timestamp_of_this_trade: int - - -# noinspection SpellCheckingInspection -class LastForexTrade(Definition): - _swagger_name_to_python = { - "price": "price", - "exchange": "exchange", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "price": True, - "exchange": True, - "timestamp": True, - - } - - _attributes_to_types = { - "price": "int", - "exchange": "int", - "timestamp": "int", - - } - - def __init__(self): - self.price: int - self.exchange: int - self.timestamp: int - - -# noinspection SpellCheckingInspection -class LastForexQuote(Definition): - _swagger_name_to_python = { - "ask": "ask", - "bid": "bid", - "exchange": "exchange", - "timestamp": "timestamp", - - } - - _attribute_is_primitive = { - "ask": True, - "bid": True, - "exchange": True, - "timestamp": True, - - } - - _attributes_to_types = { - "ask": "int", - "bid": "int", - "exchange": "int", - "timestamp": "int", - - } - - def __init__(self): - self.ask: int - self.bid: int - self.exchange: int - self.timestamp: int - - -# noinspection SpellCheckingInspection -class ForexAggregate(Definition): - _swagger_name_to_python = { - "o": "open_price", - "c": "close_price", - "l": "low_price", - "h": "high_price", - "v": "volume_of_all_trades", - "t": "timestamp_of_this_aggregation", - - } - - _attribute_is_primitive = { - "open_price": True, - "close_price": True, - "low_price": True, - "high_price": True, - "volume_of_all_trades": True, - "timestamp_of_this_aggregation": True, - - } - - _attributes_to_types = { - "open_price": "int", - "close_price": "int", - "low_price": "int", - "high_price": "int", - "volume_of_all_trades": "int", - "timestamp_of_this_aggregation": "int", - - } - - def __init__(self): - self.open_price: int - self.close_price: int - self.low_price: int - self.high_price: int - self.volume_of_all_trades: int - self.timestamp_of_this_aggregation: int - - -# noinspection SpellCheckingInspection -class ForexSnapshotTicker(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "day": "day", - "lastTrade": "last_trade", - "min": "min", - "prevDay": "prev_day", - "todaysChange": "todays_change", - "todaysChangePerc": "todays_chang_eperc", - "updated": "updated", - - } - - _attribute_is_primitive = { - "ticker": True, - "day": False, - "last_trade": False, - "min": False, - "prev_day": False, - "todays_change": True, - "todays_chang_eperc": True, - "updated": True, - - } - - _attributes_to_types = { - "ticker": "str", - "day": "ForexSnapshotAgg", - "last_trade": "Forex", - "min": "ForexSnapshotAgg", - "prev_day": "ForexSnapshotAgg", - "todays_change": "int", - "todays_chang_eperc": "int", - "updated": "int", - - } - - def __init__(self): - self.ticker: str - self.day: ForexSnapshotAgg - self.last_trade: Forex - self.min: ForexSnapshotAgg - self.prev_day: ForexSnapshotAgg - self.todays_change: int - self.todays_chang_eperc: int - self.updated: int - - -# noinspection SpellCheckingInspection -class ForexSnapshotAgg(Definition): - _swagger_name_to_python = { - "c": "close_price", - "h": "high_price", - "l": "low_price", - "o": "open_price", - "v": "volume", - - } - - _attribute_is_primitive = { - "close_price": True, - "high_price": True, - "low_price": True, - "open_price": True, - "volume": True, - - } - - _attributes_to_types = { - "close_price": "int", - "high_price": "int", - "low_price": "int", - "open_price": "int", - "volume": "int", - - } - - def __init__(self): - self.close_price: int - self.high_price: int - self.low_price: int - self.open_price: int - self.volume: int - - -# noinspection SpellCheckingInspection -class Ticker(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "name": "name", - "market": "market", - "locale": "locale", - "currency": "currency", - "active": "active", - "primaryExch": "primary_exch", - "url": "url", - "updated": "updated", - "attrs": "attrs", - "codes": "codes", - - } - - _attribute_is_primitive = { - "ticker": False, - "name": True, - "market": True, - "locale": True, - "currency": True, - "active": True, - "primary_exch": True, - "url": True, - "updated": True, - "attrs": True, - "codes": True, - - } - - _attributes_to_types = { - "ticker": "StockSymbol", - "name": "str", - "market": "str", - "locale": "str", - "currency": "str", - "active": "bool", - "primary_exch": "str", - "url": "str", - "updated": "str", - "attrs": "Dict[str, str]", - "codes": "Dict[str, str]", - - } - - def __init__(self): - self.ticker: StockSymbol - self.name: str - self.market: str - self.locale: str - self.currency: str - self.active: bool - self.primary_exch: str - self.url: str - self.updated: str - self.attrs: Dict[str, str] - self.codes: Dict[str, str] - - -# noinspection SpellCheckingInspection -class Split(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "exDate": "ex_date", - "paymentDate": "payment_date", - "recordDate": "record_date", - "declaredDate": "declared_date", - "ratio": "ratio", - "tofactor": "tofactor", - "forfactor": "forfactor", - - } - - _attribute_is_primitive = { - "ticker": False, - "ex_date": True, - "payment_date": True, - "record_date": True, - "declared_date": True, - "ratio": True, - "tofactor": True, - "forfactor": True, - - } - - _attributes_to_types = { - "ticker": "TickerSymbol", - "ex_date": "str", - "payment_date": "str", - "record_date": "str", - "declared_date": "str", - "ratio": "float", - "tofactor": "float", - "forfactor": "float", - - } - - def __init__(self): - self.ticker: TickerSymbol - self.ex_date: str - self.payment_date: str - self.record_date: str - self.declared_date: str - self.ratio: float - self.tofactor: float - self.forfactor: float - - -# noinspection SpellCheckingInspection -class Financials(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "period": "period", - "calendarDate": "calendar_date", - "reportPeriod": "report_period", - "updated": "updated", - "accumulatedOtherComprehensiveIncome": "accumulated_othe_rcomprehensi_veincome", - "assets": "assets", - "assetsAverage": "assets_average", - "assetsCurrent": "assets_current", - "assetTurnover": "asset_turnover", - "assetsNonCurrent": "assets_no_ncurrent", - "bookValuePerShare": "book_valu_ep_ershare", - "capitalExpenditure": "capital_expenditure", - "cashAndEquivalents": "cash_an_dequivalents", - "cashAndEquivalentsUSD": "cash_an_dequivalen___tsusd", - "costOfRevenue": "cost_o_frevenue", - "consolidatedIncome": "consolidated_income", - "currentRatio": "current_ratio", - "debtToEquityRatio": "debt_t_oequi_tyratio", - "debt": "debt", - "debtCurrent": "debt_current", - "debtNonCurrent": "debt_no_ncurrent", - "debtUSD": "debt___usd", - "deferredRevenue": "deferred_revenue", - "depreciationAmortizationAndAccretion": "depreciation_amortizatio_na_ndaccretion", - "deposits": "deposits", - "dividendYield": "dividend_yield", - "dividendsPerBasicCommonShare": "dividends_pe_rbas_iccom_monshare", - "earningBeforeInterestTaxes": "earning_befor_eintere_sttaxes", - "earningsBeforeInterestTaxesDepreciationAmortization": "earnings_befor_eintere_stta_xesdeprecia_tionamortization", - "EBITDAMargin": "e______bitdamargin", - "earningsBeforeInterestTaxesDepreciationAmortizationUSD": "earnings_befor_eintere_stta_xesdeprecia_tionamortiz___ationusd", - "earningBeforeInterestTaxesUSD": "earning_befor_eintere_stta___xesusd", - "earningsBeforeTax": "earnings_befor_etax", - "earningsPerBasicShare": "earnings_pe_rbas_icshare", - "earningsPerDilutedShare": "earnings_pe_rdilut_edshare", - "earningsPerBasicShareUSD": "earnings_pe_rbas_icsh___areusd", - "shareholdersEquity": "shareholders_equity", - "averageEquity": "average_equity", - "shareholdersEquityUSD": "shareholders_equit___yusd", - "enterpriseValue": "enterprise_value", - "enterpriseValueOverEBIT": "enterprise_valu_eov____erebit", - "enterpriseValueOverEBITDA": "enterprise_valu_eov______erebitda", - "freeCashFlow": "free_cas_hflow", - "freeCashFlowPerShare": "free_cas_hfl_ow_pershare", - "foreignCurrencyUSDExchangeRate": "foreign_currenc____yusdexc_hangerate", - "grossProfit": "gross_profit", - "grossMargin": "gross_margin", - "goodwillAndIntangibleAssets": "goodwill_an_dintangib_leassets", - "interestExpense": "interest_expense", - "investedCapital": "invested_capital", - "investedCapitalAverage": "invested_capita_laverage", - "inventory": "inventory", - "investments": "investments", - "investmentsCurrent": "investments_current", - "investmentsNonCurrent": "investments_no_ncurrent", - "totalLiabilities": "total_liabilities", - "currentLiabilities": "current_liabilities", - "liabilitiesNonCurrent": "liabilities_no_ncurrent", - "marketCapitalization": "market_capitalization", - "netCashFlow": "net_cas_hflow", - "netCashFlowBusinessAcquisitionsDisposals": "net_cas_hfl_owbusin_essacquisit_ionsdisposals", - "issuanceEquityShares": "issuance_equit_yshares", - "issuanceDebtSecurities": "issuance_deb_tsecurities", - "paymentDividendsOtherCashDistributions": "payment_dividend_soth_erc_ashdistributions", - "netCashFlowFromFinancing": "net_cas_hfl_owf_romfinancing", - "netCashFlowFromInvesting": "net_cas_hfl_owf_rominvesting", - "netCashFlowInvestmentAcquisitionsDisposals": "net_cas_hfl_owinvestm_entacquisit_ionsdisposals", - "netCashFlowFromOperations": "net_cas_hfl_owf_romoperations", - "effectOfExchangeRateChangesOnCash": "effect_o_fexchan_ger_atecha_n_gesoncash", - "netIncome": "net_income", - "netIncomeCommonStock": "net_incom_ecomm_onstock", - "netIncomeCommonStockUSD": "net_incom_ecomm_onst___ockusd", - "netLossIncomeFromDiscontinuedOperations": "net_los_sinco_mef_romdisconti_nuedoperations", - "netIncomeToNonControllingInterests": "net_incom_e_to_noncontrol_linginterests", - "profitMargin": "profit_margin", - "operatingExpenses": "operating_expenses", - "operatingIncome": "operating_income", - "tradeAndNonTradePayables": "trade_an_dn_ontr_adepayables", - "payoutRatio": "payout_ratio", - "priceToBookValue": "price_t_obo_okvalue", - "priceEarnings": "price_earnings", - "priceToEarningsRatio": "price_t_oearnin_gsratio", - "propertyPlantEquipmentNet": "property_plan_tequipme_ntnet", - "preferredDividendsIncomeStatementImpact": "preferred_dividend_sinco_mestatem_entimpact", - "sharePriceAdjustedClose": "share_pric_eadjust_edclose", - "priceSales": "price_sales", - "priceToSalesRatio": "price_t_osal_esratio", - "tradeAndNonTradeReceivables": "trade_an_dn_ontr_adereceivables", - "accumulatedRetainedEarningsDeficit": "accumulated_retaine_dearnin_gsdeficit", - "revenues": "revenues", - "revenuesUSD": "revenues___usd", - "researchAndDevelopmentExpense": "research_an_ddevelopme_ntexpense", - "returnOnAverageAssets": "return_o_navera_geassets", - "returnOnAverageEquity": "return_o_navera_geequity", - "returnOnInvestedCapital": "return_o_ninvest_edcapital", - "returnOnSales": "return_o_nsales", - "shareBasedCompensation": "share_base_dcompensation", - "sellingGeneralAndAdministrativeExpense": "selling_genera_la_ndadministrat_iveexpense", - "shareFactor": "share_factor", - "shares": "shares", - "weightedAverageShares": "weighted_averag_eshares", - "weightedAverageSharesDiluted": "weighted_averag_eshar_esdiluted", - "salesPerShare": "sales_pe_rshare", - "tangibleAssetValue": "tangible_asse_tvalue", - "taxAssets": "tax_assets", - "incomeTaxExpense": "income_ta_xexpense", - "taxLiabilities": "tax_liabilities", - "tangibleAssetsBookValuePerShare": "tangible_asset_sbo_okva_lu_epershare", - "workingCapital": "working_capital", - - } - - _attribute_is_primitive = { - "ticker": False, - "period": True, - "calendar_date": True, - "report_period": True, - "updated": True, - "accumulated_othe_rcomprehensi_veincome": True, - "assets": True, - "assets_average": True, - "assets_current": True, - "asset_turnover": True, - "assets_no_ncurrent": True, - "book_valu_ep_ershare": True, - "capital_expenditure": True, - "cash_an_dequivalents": True, - "cash_an_dequivalen___tsusd": True, - "cost_o_frevenue": True, - "consolidated_income": True, - "current_ratio": True, - "debt_t_oequi_tyratio": True, - "debt": True, - "debt_current": True, - "debt_no_ncurrent": True, - "debt___usd": True, - "deferred_revenue": True, - "depreciation_amortizatio_na_ndaccretion": True, - "deposits": True, - "dividend_yield": True, - "dividends_pe_rbas_iccom_monshare": True, - "earning_befor_eintere_sttaxes": True, - "earnings_befor_eintere_stta_xesdeprecia_tionamortization": True, - "e______bitdamargin": True, - "earnings_befor_eintere_stta_xesdeprecia_tionamortiz___ationusd": True, - "earning_befor_eintere_stta___xesusd": True, - "earnings_befor_etax": True, - "earnings_pe_rbas_icshare": True, - "earnings_pe_rdilut_edshare": True, - "earnings_pe_rbas_icsh___areusd": True, - "shareholders_equity": True, - "average_equity": True, - "shareholders_equit___yusd": True, - "enterprise_value": True, - "enterprise_valu_eov____erebit": True, - "enterprise_valu_eov______erebitda": True, - "free_cas_hflow": True, - "free_cas_hfl_ow_pershare": True, - "foreign_currenc____yusdexc_hangerate": True, - "gross_profit": True, - "gross_margin": True, - "goodwill_an_dintangib_leassets": True, - "interest_expense": True, - "invested_capital": True, - "invested_capita_laverage": True, - "inventory": True, - "investments": True, - "investments_current": True, - "investments_no_ncurrent": True, - "total_liabilities": True, - "current_liabilities": True, - "liabilities_no_ncurrent": True, - "market_capitalization": True, - "net_cas_hflow": True, - "net_cas_hfl_owbusin_essacquisit_ionsdisposals": True, - "issuance_equit_yshares": True, - "issuance_deb_tsecurities": True, - "payment_dividend_soth_erc_ashdistributions": True, - "net_cas_hfl_owf_romfinancing": True, - "net_cas_hfl_owf_rominvesting": True, - "net_cas_hfl_owinvestm_entacquisit_ionsdisposals": True, - "net_cas_hfl_owf_romoperations": True, - "effect_o_fexchan_ger_atecha_n_gesoncash": True, - "net_income": True, - "net_incom_ecomm_onstock": True, - "net_incom_ecomm_onst___ockusd": True, - "net_los_sinco_mef_romdisconti_nuedoperations": True, - "net_incom_e_to_noncontrol_linginterests": True, - "profit_margin": True, - "operating_expenses": True, - "operating_income": True, - "trade_an_dn_ontr_adepayables": True, - "payout_ratio": True, - "price_t_obo_okvalue": True, - "price_earnings": True, - "price_t_oearnin_gsratio": True, - "property_plan_tequipme_ntnet": True, - "preferred_dividend_sinco_mestatem_entimpact": True, - "share_pric_eadjust_edclose": True, - "price_sales": True, - "price_t_osal_esratio": True, - "trade_an_dn_ontr_adereceivables": True, - "accumulated_retaine_dearnin_gsdeficit": True, - "revenues": True, - "revenues___usd": True, - "research_an_ddevelopme_ntexpense": True, - "return_o_navera_geassets": True, - "return_o_navera_geequity": True, - "return_o_ninvest_edcapital": True, - "return_o_nsales": True, - "share_base_dcompensation": True, - "selling_genera_la_ndadministrat_iveexpense": True, - "share_factor": True, - "shares": True, - "weighted_averag_eshares": True, - "weighted_averag_eshar_esdiluted": True, - "sales_pe_rshare": True, - "tangible_asse_tvalue": True, - "tax_assets": True, - "income_ta_xexpense": True, - "tax_liabilities": True, - "tangible_asset_sbo_okva_lu_epershare": True, - "working_capital": True, - - } - - _attributes_to_types = { - "ticker": "TickerSymbol", - "period": "str", - "calendar_date": "str", - "report_period": "str", - "updated": "str", - "accumulated_othe_rcomprehensi_veincome": "int", - "assets": "int", - "assets_average": "int", - "assets_current": "int", - "asset_turnover": "int", - "assets_no_ncurrent": "int", - "book_valu_ep_ershare": "int", - "capital_expenditure": "int", - "cash_an_dequivalents": "int", - "cash_an_dequivalen___tsusd": "int", - "cost_o_frevenue": "int", - "consolidated_income": "int", - "current_ratio": "int", - "debt_t_oequi_tyratio": "int", - "debt": "int", - "debt_current": "int", - "debt_no_ncurrent": "int", - "debt___usd": "int", - "deferred_revenue": "int", - "depreciation_amortizatio_na_ndaccretion": "int", - "deposits": "int", - "dividend_yield": "int", - "dividends_pe_rbas_iccom_monshare": "int", - "earning_befor_eintere_sttaxes": "int", - "earnings_befor_eintere_stta_xesdeprecia_tionamortization": "int", - "e______bitdamargin": "int", - "earnings_befor_eintere_stta_xesdeprecia_tionamortiz___ationusd": "int", - "earning_befor_eintere_stta___xesusd": "int", - "earnings_befor_etax": "int", - "earnings_pe_rbas_icshare": "int", - "earnings_pe_rdilut_edshare": "int", - "earnings_pe_rbas_icsh___areusd": "int", - "shareholders_equity": "int", - "average_equity": "int", - "shareholders_equit___yusd": "int", - "enterprise_value": "int", - "enterprise_valu_eov____erebit": "int", - "enterprise_valu_eov______erebitda": "int", - "free_cas_hflow": "int", - "free_cas_hfl_ow_pershare": "int", - "foreign_currenc____yusdexc_hangerate": "int", - "gross_profit": "int", - "gross_margin": "int", - "goodwill_an_dintangib_leassets": "int", - "interest_expense": "int", - "invested_capital": "int", - "invested_capita_laverage": "int", - "inventory": "int", - "investments": "int", - "investments_current": "int", - "investments_no_ncurrent": "int", - "total_liabilities": "int", - "current_liabilities": "int", - "liabilities_no_ncurrent": "int", - "market_capitalization": "int", - "net_cas_hflow": "int", - "net_cas_hfl_owbusin_essacquisit_ionsdisposals": "int", - "issuance_equit_yshares": "int", - "issuance_deb_tsecurities": "int", - "payment_dividend_soth_erc_ashdistributions": "int", - "net_cas_hfl_owf_romfinancing": "int", - "net_cas_hfl_owf_rominvesting": "int", - "net_cas_hfl_owinvestm_entacquisit_ionsdisposals": "int", - "net_cas_hfl_owf_romoperations": "int", - "effect_o_fexchan_ger_atecha_n_gesoncash": "int", - "net_income": "int", - "net_incom_ecomm_onstock": "int", - "net_incom_ecomm_onst___ockusd": "int", - "net_los_sinco_mef_romdisconti_nuedoperations": "int", - "net_incom_e_to_noncontrol_linginterests": "int", - "profit_margin": "int", - "operating_expenses": "int", - "operating_income": "int", - "trade_an_dn_ontr_adepayables": "int", - "payout_ratio": "int", - "price_t_obo_okvalue": "int", - "price_earnings": "int", - "price_t_oearnin_gsratio": "int", - "property_plan_tequipme_ntnet": "int", - "preferred_dividend_sinco_mestatem_entimpact": "int", - "share_pric_eadjust_edclose": "int", - "price_sales": "int", - "price_t_osal_esratio": "int", - "trade_an_dn_ontr_adereceivables": "int", - "accumulated_retaine_dearnin_gsdeficit": "int", - "revenues": "int", - "revenues___usd": "int", - "research_an_ddevelopme_ntexpense": "int", - "return_o_navera_geassets": "int", - "return_o_navera_geequity": "int", - "return_o_ninvest_edcapital": "int", - "return_o_nsales": "int", - "share_base_dcompensation": "int", - "selling_genera_la_ndadministrat_iveexpense": "int", - "share_factor": "int", - "shares": "int", - "weighted_averag_eshares": "int", - "weighted_averag_eshar_esdiluted": "int", - "sales_pe_rshare": "int", - "tangible_asse_tvalue": "int", - "tax_assets": "int", - "income_ta_xexpense": "int", - "tax_liabilities": "int", - "tangible_asset_sbo_okva_lu_epershare": "int", - "working_capital": "int", - - } - - def __init__(self): - self.ticker: TickerSymbol - self.period: str - self.calendar_date: str - self.report_period: str - self.updated: str - self.accumulated_othe_rcomprehensi_veincome: int - self.assets: int - self.assets_average: int - self.assets_current: int - self.asset_turnover: int - self.assets_no_ncurrent: int - self.book_valu_ep_ershare: int - self.capital_expenditure: int - self.cash_an_dequivalents: int - self.cash_an_dequivalen___tsusd: int - self.cost_o_frevenue: int - self.consolidated_income: int - self.current_ratio: int - self.debt_t_oequi_tyratio: int - self.debt: int - self.debt_current: int - self.debt_no_ncurrent: int - self.debt___usd: int - self.deferred_revenue: int - self.depreciation_amortizatio_na_ndaccretion: int - self.deposits: int - self.dividend_yield: int - self.dividends_pe_rbas_iccom_monshare: int - self.earning_befor_eintere_sttaxes: int - self.earnings_befor_eintere_stta_xesdeprecia_tionamortization: int - self.e______bitdamargin: int - self.earnings_befor_eintere_stta_xesdeprecia_tionamortiz___ationusd: int - self.earning_befor_eintere_stta___xesusd: int - self.earnings_befor_etax: int - self.earnings_pe_rbas_icshare: int - self.earnings_pe_rdilut_edshare: int - self.earnings_pe_rbas_icsh___areusd: int - self.shareholders_equity: int - self.average_equity: int - self.shareholders_equit___yusd: int - self.enterprise_value: int - self.enterprise_valu_eov____erebit: int - self.enterprise_valu_eov______erebitda: int - self.free_cas_hflow: int - self.free_cas_hfl_ow_pershare: int - self.foreign_currenc____yusdexc_hangerate: int - self.gross_profit: int - self.gross_margin: int - self.goodwill_an_dintangib_leassets: int - self.interest_expense: int - self.invested_capital: int - self.invested_capita_laverage: int - self.inventory: int - self.investments: int - self.investments_current: int - self.investments_no_ncurrent: int - self.total_liabilities: int - self.current_liabilities: int - self.liabilities_no_ncurrent: int - self.market_capitalization: int - self.net_cas_hflow: int - self.net_cas_hfl_owbusin_essacquisit_ionsdisposals: int - self.issuance_equit_yshares: int - self.issuance_deb_tsecurities: int - self.payment_dividend_soth_erc_ashdistributions: int - self.net_cas_hfl_owf_romfinancing: int - self.net_cas_hfl_owf_rominvesting: int - self.net_cas_hfl_owinvestm_entacquisit_ionsdisposals: int - self.net_cas_hfl_owf_romoperations: int - self.effect_o_fexchan_ger_atecha_n_gesoncash: int - self.net_income: int - self.net_incom_ecomm_onstock: int - self.net_incom_ecomm_onst___ockusd: int - self.net_los_sinco_mef_romdisconti_nuedoperations: int - self.net_incom_e_to_noncontrol_linginterests: int - self.profit_margin: int - self.operating_expenses: int - self.operating_income: int - self.trade_an_dn_ontr_adepayables: int - self.payout_ratio: int - self.price_t_obo_okvalue: int - self.price_earnings: int - self.price_t_oearnin_gsratio: int - self.property_plan_tequipme_ntnet: int - self.preferred_dividend_sinco_mestatem_entimpact: int - self.share_pric_eadjust_edclose: int - self.price_sales: int - self.price_t_osal_esratio: int - self.trade_an_dn_ontr_adereceivables: int - self.accumulated_retaine_dearnin_gsdeficit: int - self.revenues: int - self.revenues___usd: int - self.research_an_ddevelopme_ntexpense: int - self.return_o_navera_geassets: int - self.return_o_navera_geequity: int - self.return_o_ninvest_edcapital: int - self.return_o_nsales: int - self.share_base_dcompensation: int - self.selling_genera_la_ndadministrat_iveexpense: int - self.share_factor: int - self.shares: int - self.weighted_averag_eshares: int - self.weighted_averag_eshar_esdiluted: int - self.sales_pe_rshare: int - self.tangible_asse_tvalue: int - self.tax_assets: int - self.income_ta_xexpense: int - self.tax_liabilities: int - self.tangible_asset_sbo_okva_lu_epershare: int - self.working_capital: int - - -# noinspection SpellCheckingInspection -class Trade(Definition): - _swagger_name_to_python = { - "c1": "condition_1_of_this_trade", - "c2": "condition_2_of_this_trade", - "c3": "condition_3_of_this_trade", - "c4": "condition_4_of_this_trade", - "e": "the_exchange_this_trade_happened_on", - "p": "price_of_the_trade", - "s": "size_of_the_trade", - "t": "timestamp_of_this_trade", - - } - - _attribute_is_primitive = { - "condition_1_of_this_trade": True, - "condition_2_of_this_trade": True, - "condition_3_of_this_trade": True, - "condition_4_of_this_trade": True, - "the_exchange_this_trade_happened_on": True, - "price_of_the_trade": True, - "size_of_the_trade": True, - "timestamp_of_this_trade": True, - - } - - _attributes_to_types = { - "condition_1_of_this_trade": "int", - "condition_2_of_this_trade": "int", - "condition_3_of_this_trade": "int", - "condition_4_of_this_trade": "int", - "the_exchange_this_trade_happened_on": "str", - "price_of_the_trade": "int", - "size_of_the_trade": "int", - "timestamp_of_this_trade": "int", - - } - - def __init__(self): - self.condition_1_of_this_trade: int - self.condition_2_of_this_trade: int - self.condition_3_of_this_trade: int - self.condition_4_of_this_trade: int - self.the_exchange_this_trade_happened_on: str - self.price_of_the_trade: int - self.size_of_the_trade: int - self.timestamp_of_this_trade: int - - -# noinspection SpellCheckingInspection -class StocksSnapshotTicker(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "day": "day", - "lastTrade": "last_trade", - "lastQuote": "last_quote", - "min": "min", - "prevDay": "prev_day", - "todaysChange": "todays_change", - "todaysChangePerc": "todays_chang_eperc", - "updated": "updated", - - } - - _attribute_is_primitive = { - "ticker": True, - "day": False, - "last_trade": False, - "last_quote": False, - "min": False, - "prev_day": False, - "todays_change": True, - "todays_chang_eperc": True, - "updated": True, - - } - - _attributes_to_types = { - "ticker": "str", - "day": "StocksSnapshotAgg", - "last_trade": "Trade", - "last_quote": "StocksSnapshotQuote", - "min": "StocksSnapshotAgg", - "prev_day": "StocksSnapshotAgg", - "todays_change": "int", - "todays_chang_eperc": "int", - "updated": "int", - - } - - def __init__(self): - self.ticker: str - self.day: StocksSnapshotAgg - self.last_trade: Trade - self.last_quote: StocksSnapshotQuote - self.min: StocksSnapshotAgg - self.prev_day: StocksSnapshotAgg - self.todays_change: int - self.todays_chang_eperc: int - self.updated: int - - -# noinspection SpellCheckingInspection -class StocksSnapshotBookItem(Definition): - _swagger_name_to_python = { - "p": "price_of_this_book_level", - "x": "exchange_to_size_of_this_price_level", - - } - - _attribute_is_primitive = { - "price_of_this_book_level": True, - "exchange_to_size_of_this_price_level": True, - - } - - _attributes_to_types = { - "price_of_this_book_level": "int", - "exchange_to_size_of_this_price_level": "Dict[str, str]", - - } - - def __init__(self): - self.price_of_this_book_level: int - self.exchange_to_size_of_this_price_level: Dict[str, str] - - -# noinspection SpellCheckingInspection -class StocksSnapshotTickerBook(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "bids": "bids", - "asks": "asks", - "bidCount": "bid_count", - "askCount": "ask_count", - "spread": "spread", - "updated": "updated", - - } - - _attribute_is_primitive = { - "ticker": True, - "bids": False, - "asks": False, - "bid_count": True, - "ask_count": True, - "spread": True, - "updated": True, - - } - - _attributes_to_types = { - "ticker": "str", - "bids": "List[StocksSnapshotBookItem]", - "asks": "List[StocksSnapshotBookItem]", - "bid_count": "int", - "ask_count": "int", - "spread": "int", - "updated": "int", - - } - - def __init__(self): - self.ticker: str - self.bids: List[StocksSnapshotBookItem] - self.asks: List[StocksSnapshotBookItem] - self.bid_count: int - self.ask_count: int - self.spread: int - self.updated: int - - -# noinspection SpellCheckingInspection -class StocksV2Trade(Definition): - _swagger_name_to_python = { - "T": "ticker_of_the_object", - "t": "nanosecond_accuracy_s__ip_unix_timestamp", - "y": "nanosecond_accuracy_participant_exchange_unix_timestamp", - "f": "nanosecond_accuracy_t__rf", - "q": "sequence_number", - "i": "trade_i_d", - "x": "exchange_i_d", - "s": "size_volume_of_the_trade", - "c": "c", - "p": "price_of_the_trade", - "z": "tape_where_trade_occured", - - } - - _attribute_is_primitive = { - "ticker_of_the_object": True, - "nanosecond_accuracy_s__ip_unix_timestamp": True, - "nanosecond_accuracy_participant_exchange_unix_timestamp": True, - "nanosecond_accuracy_t__rf": True, - "sequence_number": True, - "trade_i_d": True, - "exchange_i_d": True, - "size_volume_of_the_trade": True, - "c": False, - "price_of_the_trade": True, - "tape_where_trade_occured": True, - - } - - _attributes_to_types = { - "ticker_of_the_object": "str", - "nanosecond_accuracy_s__ip_unix_timestamp": "int", - "nanosecond_accuracy_participant_exchange_unix_timestamp": "int", - "nanosecond_accuracy_t__rf": "int", - "sequence_number": "int", - "trade_i_d": "str", - "exchange_i_d": "int", - "size_volume_of_the_trade": "int", - "c": "List[int]", - "price_of_the_trade": "int", - "tape_where_trade_occured": "int", - - } - - def __init__(self): - self.ticker_of_the_object: str - self.nanosecond_accuracy_s__ip_unix_timestamp: int - self.nanosecond_accuracy_participant_exchange_unix_timestamp: int - self.nanosecond_accuracy_t__rf: int - self.sequence_number: int - self.trade_i_d: str - self.exchange_i_d: int - self.size_volume_of_the_trade: int - self.c: List[int] - self.price_of_the_trade: int - self.tape_where_trade_occured: int - - -# noinspection SpellCheckingInspection -class StocksV2NBBO(Definition): - _swagger_name_to_python = { - "T": "ticker_of_the_object", - "t": "nanosecond_accuracy_s__ip_unix_timestamp", - "y": "nanosecond_accuracy_participant_exchange_unix_timestamp", - "f": "nanosecond_accuracy_t__rf", - "q": "sequence_number", - "c": "c", - "i": "i", - "p": "b__id_price", - "x": "b__id_exchange__id", - "s": "b__id_size", - "P": "a__sk_price", - "X": "a__sk_exchange__id", - "S": "a__sk_size", - "z": "tape_where_trade_occured", - - } - - _attribute_is_primitive = { - "ticker_of_the_object": True, - "nanosecond_accuracy_s__ip_unix_timestamp": True, - "nanosecond_accuracy_participant_exchange_unix_timestamp": True, - "nanosecond_accuracy_t__rf": True, - "sequence_number": True, - "c": False, - "i": False, - "b__id_price": True, - "b__id_exchange__id": True, - "b__id_size": True, - "a__sk_price": True, - "a__sk_exchange__id": True, - "a__sk_size": True, - "tape_where_trade_occured": True, - - } - - _attributes_to_types = { - "ticker_of_the_object": "str", - "nanosecond_accuracy_s__ip_unix_timestamp": "int", - "nanosecond_accuracy_participant_exchange_unix_timestamp": "int", - "nanosecond_accuracy_t__rf": "int", - "sequence_number": "int", - "c": "List[int]", - "i": "List[int]", - "b__id_price": "int", - "b__id_exchange__id": "int", - "b__id_size": "int", - "a__sk_price": "int", - "a__sk_exchange__id": "int", - "a__sk_size": "int", - "tape_where_trade_occured": "int", - - } - - def __init__(self): - self.ticker_of_the_object: str - self.nanosecond_accuracy_s__ip_unix_timestamp: int - self.nanosecond_accuracy_participant_exchange_unix_timestamp: int - self.nanosecond_accuracy_t__rf: int - self.sequence_number: int - self.c: List[int] - self.i: List[int] - self.b__id_price: int - self.b__id_exchange__id: int - self.b__id_size: int - self.a__sk_price: int - self.a__sk_exchange__id: int - self.a__sk_size: int - self.tape_where_trade_occured: int - - -# noinspection SpellCheckingInspection -class StocksSnapshotAgg(Definition): - _swagger_name_to_python = { - "c": "close_price", - "h": "high_price", - "l": "low_price", - "o": "open_price", - "v": "volume", - - } - - _attribute_is_primitive = { - "close_price": True, - "high_price": True, - "low_price": True, - "open_price": True, - "volume": True, - - } - - _attributes_to_types = { - "close_price": "int", - "high_price": "int", - "low_price": "int", - "open_price": "int", - "volume": "int", - - } - - def __init__(self): - self.close_price: int - self.high_price: int - self.low_price: int - self.open_price: int - self.volume: int - - -# noinspection SpellCheckingInspection -class StocksSnapshotQuote(Definition): - _swagger_name_to_python = { - "p": "bid_price", - "s": "bid_size_in_lots", - "P": "ask_price", - "S": "ask_size_in_lots", - "t": "last_updated_timestamp", - - } - - _attribute_is_primitive = { - "bid_price": True, - "bid_size_in_lots": True, - "ask_price": True, - "ask_size_in_lots": True, - "last_updated_timestamp": True, - - } - - _attributes_to_types = { - "bid_price": "int", - "bid_size_in_lots": "int", - "ask_price": "int", - "ask_size_in_lots": "int", - "last_updated_timestamp": "int", - - } - - def __init__(self): - self.bid_price: int - self.bid_size_in_lots: int - self.ask_price: int - self.ask_size_in_lots: int - self.last_updated_timestamp: int - - -# noinspection SpellCheckingInspection -class Aggv2(Definition): - _swagger_name_to_python = { - "T": "ticker_symbol", - "v": "volume", - "o": "open", - "c": "close", - "h": "high", - "l": "low", - "t": "unix_msec_timestamp", - "n": "number_of_items_in_aggregate_window", - - } - - _attribute_is_primitive = { - "ticker_symbol": True, - "volume": True, - "open": True, - "close": True, - "high": True, - "low": True, - "unix_msec_timestamp": True, - "number_of_items_in_aggregate_window": True, - - } - - _attributes_to_types = { - "ticker_symbol": "str", - "volume": "int", - "open": "int", - "close": "int", - "high": "int", - "low": "int", - "unix_msec_timestamp": "float", - "number_of_items_in_aggregate_window": "float", - - } - - def __init__(self): - self.ticker_symbol: str - self.volume: int - self.open: int - self.close: int - self.high: int - self.low: int - self.unix_msec_timestamp: float - self.number_of_items_in_aggregate_window: float - - -# noinspection SpellCheckingInspection -class AggResponse(Definition): - _swagger_name_to_python = { - "ticker": "ticker", - "status": "status", - "adjusted": "adjusted", - "queryCount": "query_count", - "resultsCount": "results_count", - "results": "results", - - } - - _attribute_is_primitive = { - "ticker": True, - "status": True, - "adjusted": True, - "query_count": True, - "results_count": True, - "results": False, - - } - - _attributes_to_types = { - "ticker": "str", - "status": "str", - "adjusted": "bool", - "query_count": "float", - "results_count": "float", - "results": "List[Aggv2]", - - } - - def __init__(self): - self.ticker: str - self.status: str - self.adjusted: bool - self.query_count: float - self.results_count: float - self.results: List[Aggv2] - - -# noinspection SpellCheckingInspection -class ReferenceTickersApiResponse(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - - } - - _attribute_is_primitive = { - "symbol": False, - - } - - _attributes_to_types = { - "symbol": "List[Symbol]", - - } - - def __init__(self): - self.symbol: List[Symbol] - - -# noinspection SpellCheckingInspection -class ReferenceTickerTypesApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "results": True, - - } - - _attributes_to_types = { - "status": "str", - "results": "Dict[str, str]", - - } - - def __init__(self): - self.status: str - self.results: Dict[str, str] - - -# noinspection SpellCheckingInspection -class ReferenceTickerDetailsApiResponse(Definition): - _swagger_name_to_python = { - "company": "company", - - } - - _attribute_is_primitive = { - "company": False, - - } - - _attributes_to_types = { - "company": "Company", - - } - - def __init__(self): - self.company: Company - - -# noinspection SpellCheckingInspection -class ReferenceTickerNewsApiResponse(Definition): - _swagger_name_to_python = { - "news": "news", - - } - - _attribute_is_primitive = { - "news": False, - - } - - _attributes_to_types = { - "news": "List[News]", - - } - - def __init__(self): - self.news: List[News] - - -# noinspection SpellCheckingInspection -class ReferenceMarketsApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "results": False, - - } - - _attributes_to_types = { - "status": "str", - "results": "List[Dict[str, str]]", - - } - - def __init__(self): - self.status: str - self.results: List[Dict[str, str]] - - -# noinspection SpellCheckingInspection -class ReferenceLocalesApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "results": False, - - } - - _attributes_to_types = { - "status": "str", - "results": "List[Dict[str, str]]", - - } - - def __init__(self): - self.status: str - self.results: List[Dict[str, str]] - - -# noinspection SpellCheckingInspection -class ReferenceStockSplitsApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "count": "count", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "count": True, - "results": False, - - } - - _attributes_to_types = { - "status": "str", - "count": "float", - "results": "List[Split]", - - } - - def __init__(self): - self.status: str - self.count: float - self.results: List[Split] - - -# noinspection SpellCheckingInspection -class ReferenceStockDividendsApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "count": "count", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "count": True, - "results": False, - - } - - _attributes_to_types = { - "status": "str", - "count": "float", - "results": "List[Dividend]", - - } - - def __init__(self): - self.status: str - self.count: float - self.results: List[Dividend] - - -# noinspection SpellCheckingInspection -class ReferenceStockFinancialsApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "count": "count", - "results": "results", - - } - - _attribute_is_primitive = { - "status": True, - "count": True, - "results": False, - - } - - _attributes_to_types = { - "status": "str", - "count": "float", - "results": "List[Financials]", - - } - - def __init__(self): - self.status: str - self.count: float - self.results: List[Financials] - - -# noinspection SpellCheckingInspection -class ReferenceMarketStatusApiResponse(Definition): - _swagger_name_to_python = { - "marketstatus": "marketstatus", - - } - - _attribute_is_primitive = { - "marketstatus": False, - - } - - _attributes_to_types = { - "marketstatus": "MarketStatus", - - } - - def __init__(self): - self.marketstatus: MarketStatus - - -# noinspection SpellCheckingInspection -class ReferenceMarketHolidaysApiResponse(Definition): - _swagger_name_to_python = { - "marketholiday": "marketholiday", - - } - - _attribute_is_primitive = { - "marketholiday": False, - - } - - _attributes_to_types = { - "marketholiday": "List[MarketHoliday]", - - } - - def __init__(self): - self.marketholiday: List[MarketHoliday] - - -# noinspection SpellCheckingInspection -class StocksEquitiesExchangesApiResponse(Definition): - _swagger_name_to_python = { - "exchange": "exchange", - - } - - _attribute_is_primitive = { - "exchange": False, - - } - - _attributes_to_types = { - "exchange": "List[Exchange]", - - } - - def __init__(self): - self.exchange: List[Exchange] - - -# noinspection SpellCheckingInspection -class StocksEquitiesHistoricTradesApiResponse(Definition): - _swagger_name_to_python = { - "day": "day", - "map": "map", - "msLatency": "ms_latency", - "status": "status", - "symbol": "symbol", - "ticks": "ticks", - - } - - _attribute_is_primitive = { - "day": True, - "map": True, - "ms_latency": True, - "status": True, - "symbol": True, - "ticks": False, - - } - - _attributes_to_types = { - "day": "str", - "map": "Dict[str, str]", - "ms_latency": "int", - "status": "str", - "symbol": "str", - "ticks": "List[Trade]", - - } - - def __init__(self): - self.day: str - self.map: Dict[str, str] - self.ms_latency: int - self.status: str - self.symbol: str - self.ticks: List[Trade] - - -# noinspection SpellCheckingInspection -class HistoricTradesV2ApiResponse(Definition): - _swagger_name_to_python = { - "results_count": "results_count", - "db_latency": "db_latency", - "success": "success", - "ticker": "ticker", - "results": "results", - - } - - _attribute_is_primitive = { - "results_count": True, - "db_latency": True, - "success": True, - "ticker": True, - "results": False, - - } - - _attributes_to_types = { - "results_count": "int", - "db_latency": "int", - "success": "bool", - "ticker": "str", - "results": "List[StocksV2Trade]", - - } - - def __init__(self): - self.results_count: int - self.db_latency: int - self.success: bool - self.ticker: str - self.results: List[StocksV2Trade] - - -# noinspection SpellCheckingInspection -class StocksEquitiesHistoricQuotesApiResponse(Definition): - _swagger_name_to_python = { - "day": "day", - "map": "map", - "msLatency": "ms_latency", - "status": "status", - "symbol": "symbol", - "ticks": "ticks", - - } - - _attribute_is_primitive = { - "day": True, - "map": True, - "ms_latency": True, - "status": True, - "symbol": True, - "ticks": False, - - } - - _attributes_to_types = { - "day": "str", - "map": "Dict[str, str]", - "ms_latency": "int", - "status": "str", - "symbol": "str", - "ticks": "List[Quote]", - - } - - def __init__(self): - self.day: str - self.map: Dict[str, str] - self.ms_latency: int - self.status: str - self.symbol: str - self.ticks: List[Quote] - - -# noinspection SpellCheckingInspection -class HistoricNBboQuotesV2ApiResponse(Definition): - _swagger_name_to_python = { - "results_count": "results_count", - "db_latency": "db_latency", - "success": "success", - "ticker": "ticker", - "results": "results", - - } - - _attribute_is_primitive = { - "results_count": True, - "db_latency": True, - "success": True, - "ticker": True, - "results": False, - - } - - _attributes_to_types = { - "results_count": "int", - "db_latency": "int", - "success": "bool", - "ticker": "str", - "results": "List[StocksV2NBBO]", - - } - - def __init__(self): - self.results_count: int - self.db_latency: int - self.success: bool - self.ticker: str - self.results: List[StocksV2NBBO] - - -# noinspection SpellCheckingInspection -class StocksEquitiesLastTradeForASymbolApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "symbol": "symbol", - "last": "last", - - } - - _attribute_is_primitive = { - "status": True, - "symbol": True, - "last": False, - - } - - _attributes_to_types = { - "status": "str", - "symbol": "str", - "last": "LastTrade", - - } - - def __init__(self): - self.status: str - self.symbol: str - self.last: LastTrade - - -# noinspection SpellCheckingInspection -class StocksEquitiesLastQuoteForASymbolApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "symbol": "symbol", - "last": "last", - - } - - _attribute_is_primitive = { - "status": True, - "symbol": True, - "last": False, - - } - - _attributes_to_types = { - "status": "str", - "symbol": "str", - "last": "LastQuote", - - } - - def __init__(self): - self.status: str - self.symbol: str - self.last: LastQuote - -# noinspection SpellCheckingInspection -class StocksEquitiesDailyOpenCloseApiResponse(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "open": "open", - "close": "close", - "afterHours": "after_hours", - - } - - _attribute_is_primitive = { - "symbol": True, - "open": False, - "close": False, - "after_hours": False, - - } - - _attributes_to_types = { - "symbol": "str", - "open": "HistTrade", - "close": "HistTrade", - "after_hours": "HistTrade", - - } - - def __init__(self): - self.symbol: str - self.open: HistTrade - self.close: HistTrade - self.after_hours: HistTrade - - -# noinspection SpellCheckingInspection -class StocksEquitiesConditionMappingsApiResponse(Definition): - _swagger_name_to_python = { - "conditiontypemap": "conditiontypemap", - - } - - _attribute_is_primitive = { - "conditiontypemap": False, - - } - - _attributes_to_types = { - "conditiontypemap": "ConditionTypeMap", - - } - - def __init__(self): - self.conditiontypemap: ConditionTypeMap - - -# noinspection SpellCheckingInspection -class StocksEquitiesSnapshotAllTickersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[StocksSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[StocksSnapshotTicker] - - -# noinspection SpellCheckingInspection -class StocksEquitiesSnapshotSingleTickerApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "ticker": "ticker", - - } - - _attribute_is_primitive = { - "status": True, - "ticker": False, - - } - - _attributes_to_types = { - "status": "str", - "ticker": "StocksSnapshotTicker", - - } - - def __init__(self): - self.status: str - self.ticker: StocksSnapshotTicker - - -# noinspection SpellCheckingInspection -class StocksEquitiesSnapshotGainersLosersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[StocksSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[StocksSnapshotTicker] - - -# noinspection SpellCheckingInspection -class StocksEquitiesPreviousCloseApiResponse(Definition): - _swagger_name_to_python = { - "aggresponse": "aggresponse", - - } - - _attribute_is_primitive = { - "aggresponse": False, - - } - - _attributes_to_types = { - "aggresponse": "AggResponse", - - } - - def __init__(self): - self.aggresponse: AggResponse - - -# noinspection SpellCheckingInspection -class StocksEquitiesAggregatesApiResponse(Definition): - _swagger_name_to_python = { - "aggresponse": "aggresponse", - - } - - _attribute_is_primitive = { - "aggresponse": False, - - } - - _attributes_to_types = { - "aggresponse": "AggResponse", - - } - - def __init__(self): - self.aggresponse: AggResponse - - -# noinspection SpellCheckingInspection -class StocksEquitiesGroupedDailyApiResponse(Definition): - _swagger_name_to_python = { - "aggresponse": "aggresponse", - - } - - _attribute_is_primitive = { - "aggresponse": False, - - } - - _attributes_to_types = { - "aggresponse": "AggResponse", - - } - - def __init__(self): - self.aggresponse: AggResponse - - -# noinspection SpellCheckingInspection -class ForexCurrenciesHistoricForexTicksApiResponse(Definition): - _swagger_name_to_python = { - "day": "day", - "map": "map", - "msLatency": "ms_latency", - "status": "status", - "pair": "pair", - "ticks": "ticks", - - } - - _attribute_is_primitive = { - "day": True, - "map": True, - "ms_latency": True, - "status": True, - "pair": True, - "ticks": False, - - } - - _attributes_to_types = { - "day": "str", - "map": "Dict[str, str]", - "ms_latency": "int", - "status": "str", - "pair": "str", - "ticks": "List[Forex]", - - } - - def __init__(self): - self.day: str - self.map: Dict[str, str] - self.ms_latency: int - self.status: str - self.pair: str - self.ticks: List[Forex] - - -# noinspection SpellCheckingInspection -class ForexCurrenciesRealTimeCurrencyConversionApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "from": "from_", - "to": "to_currency_symbol", - "initialAmount": "initial_amount", - "converted": "converted", - "lastTrade": "last_trade", - "symbol": "symbol", - - } - - _attribute_is_primitive = { - "status": True, - "from_": True, - "to_currency_symbol": True, - "initial_amount": True, - "converted": True, - "last_trade": False, - "symbol": True, - - } - - _attributes_to_types = { - "status": "str", - "from_": "str", - "to_currency_symbol": "str", - "initial_amount": "float", - "converted": "float", - "last_trade": "LastForexTrade", - "symbol": "str", - - } - - def __init__(self): - self.status: str - self.from_: str - self.to_currency_symbol: str - self.initial_amount: float - self.converted: float - self.last_trade: LastForexTrade - self.symbol: str - - -# noinspection SpellCheckingInspection -class ForexCurrenciesLastQuoteForACurrencyPairApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "symbol": "symbol", - "last": "last", - - } - - _attribute_is_primitive = { - "status": True, - "symbol": True, - "last": False, - - } - - _attributes_to_types = { - "status": "str", - "symbol": "str", - "last": "LastForexQuote", - - } - - def __init__(self): - self.status: str - self.symbol: str - self.last: LastForexQuote - - -# noinspection SpellCheckingInspection -class ForexCurrenciesSnapshotAllTickersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[ForexSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[ForexSnapshotTicker] - - -# noinspection SpellCheckingInspection -class ForexCurrenciesSnapshotGainersLosersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[ForexSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[ForexSnapshotTicker] - - -# noinspection SpellCheckingInspection -class CryptoCryptoExchangesApiResponse(Definition): - _swagger_name_to_python = { - "cryptoexchange": "cryptoexchange", - - } - - _attribute_is_primitive = { - "cryptoexchange": False, - - } - - _attributes_to_types = { - "cryptoexchange": "List[CryptoExchange]", - - } - - def __init__(self): - self.cryptoexchange: List[CryptoExchange] - - -# noinspection SpellCheckingInspection -class CryptoLastTradeForACryptoPairApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "symbol": "symbol", - "last": "last", - "lastAverage": "last_average", - - } - - _attribute_is_primitive = { - "status": True, - "symbol": True, - "last": False, - "last_average": True, - - } - - _attributes_to_types = { - "status": "str", - "symbol": "str", - "last": "CryptoTick", - "last_average": "Dict[str, str]", - - } - - def __init__(self): - self.status: str - self.symbol: str - self.last: CryptoTick - self.last_average: Dict[str, str] - - -# noinspection SpellCheckingInspection -class CryptoDailyOpenCloseApiResponse(Definition): - _swagger_name_to_python = { - "symbol": "symbol", - "isUTC": "is___utc", - "day": "day", - "open": "open", - "close": "close", - "openTrades": "open_trades", - "closingTrades": "closing_trades", - - } - - _attribute_is_primitive = { - "symbol": True, - "is___utc": True, - "day": True, - "open": True, - "close": True, - "open_trades": False, - "closing_trades": False, - - } - - _attributes_to_types = { - "symbol": "str", - "is___utc": "bool", - "day": "str", - "open": "int", - "close": "int", - "open_trades": "List[CryptoTickJson]", - "closing_trades": "List[CryptoTickJson]", - - } - - def __init__(self): - self.symbol: str - self.is___utc: bool - self.day: str - self.open: int - self.close: int - self.open_trades: List[CryptoTickJson] - self.closing_trades: List[CryptoTickJson] - - -# noinspection SpellCheckingInspection -class CryptoHistoricCryptoTradesApiResponse(Definition): - _swagger_name_to_python = { - "day": "day", - "map": "map", - "msLatency": "ms_latency", - "status": "status", - "symbol": "symbol", - "ticks": "ticks", - - } - - _attribute_is_primitive = { - "day": True, - "map": True, - "ms_latency": True, - "status": True, - "symbol": True, - "ticks": False, - - } - - _attributes_to_types = { - "day": "str", - "map": "Dict[str, str]", - "ms_latency": "int", - "status": "str", - "symbol": "str", - "ticks": "List[CryptoTickJson]", - - } - - def __init__(self): - self.day: str - self.map: Dict[str, str] - self.ms_latency: int - self.status: str - self.symbol: str - self.ticks: List[CryptoTickJson] - - -# noinspection SpellCheckingInspection -class CryptoSnapshotAllTickersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[CryptoSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[CryptoSnapshotTicker] - - -# noinspection SpellCheckingInspection -class CryptoSnapshotSingleTickerApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "ticker": "ticker", - - } - - _attribute_is_primitive = { - "status": True, - "ticker": False, - - } - - _attributes_to_types = { - "status": "str", - "ticker": "CryptoSnapshotTicker", - - } - - def __init__(self): - self.status: str - self.ticker: CryptoSnapshotTicker - - -# noinspection SpellCheckingInspection -class CryptoSnapshotSingleTickerFullBookApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "data": "data", - - } - - _attribute_is_primitive = { - "status": True, - "data": False, - - } - - _attributes_to_types = { - "status": "str", - "data": "CryptoSnapshotTickerBook", - - } - - def __init__(self): - self.status: str - self.data: CryptoSnapshotTickerBook - - -# noinspection SpellCheckingInspection -class CryptoSnapshotGainersLosersApiResponse(Definition): - _swagger_name_to_python = { - "status": "status", - "tickers": "tickers", - - } - - _attribute_is_primitive = { - "status": True, - "tickers": False, - - } - - _attributes_to_types = { - "status": "str", - "tickers": "List[CryptoSnapshotTicker]", - - } - - def __init__(self): - self.status: str - self.tickers: List[CryptoSnapshotTicker] - - -StockSymbol = str -ConditionTypeMap = Dict[str, str] -SymbolTypeMap = Dict[str, str] -TickerSymbol = str diff --git a/polygon/rest/models/unmarshal.py b/polygon/rest/models/unmarshal.py deleted file mode 100644 index 720fe7c0..00000000 --- a/polygon/rest/models/unmarshal.py +++ /dev/null @@ -1,9 +0,0 @@ -from typing import Type - -from polygon.rest import models - - -def unmarshal_json(response_type, resp_json) -> Type[models.AnyDefinition]: - obj = models.name_to_class[response_type]() - obj.unmarshal_json(resp_json) - return obj diff --git a/polygon/rest/models/pm.py b/polygon/rest/rest_models.py similarity index 100% rename from polygon/rest/models/pm.py rename to polygon/rest/rest_models.py diff --git a/polygon/websocket/pm.py b/polygon/websocket/stream_models.py similarity index 88% rename from polygon/websocket/pm.py rename to polygon/websocket/stream_models.py index bfff1411..75bb3866 100644 --- a/polygon/websocket/pm.py +++ b/polygon/websocket/stream_models.py @@ -4,7 +4,7 @@ import pytz from pydantic import BaseModel, Field -from polygon.rest.models import pm +from polygon.rest import rest_models class SocketBase(BaseModel): @@ -66,8 +66,8 @@ class Bar(SocketBase): utc_end: datetime.datetime = Field(alias='e') @property - def rest_bar(self) -> pm.Bar: - return pm.Bar(v=self.volume, o=self.open_price, c=self.close_price, h=self.high_price, l=self.low_price, - t=self.utc_start, n=1) + def rest_bar(self) -> rest_models.Bar: + return rest_models.Bar(v=self.volume, o=self.open_price, c=self.close_price, h=self.high_price, l=self.low_price, + t=self.utc_start, n=1) diff --git a/rest-example.py b/rest-example.py deleted file mode 100644 index 626f4660..00000000 --- a/rest-example.py +++ /dev/null @@ -1,15 +0,0 @@ -from polygon import RESTClient - - -def main(): - key = "your api key" - - # RESTClient can be used as a context manager to facilitate closing the underlying http session - # https://requests.readthedocs.io/en/master/user/advanced/#session-objects - with RESTClient(key) as client: - resp = client.stocks_equities_daily_open_close("AAPL", "2018-03-02") - print(f"On: {resp.from_} Apple opened at {resp.open} and closed at {resp.close}") - - -if __name__ == '__main__': - main() diff --git a/websocket-example.py b/websocket-example.py deleted file mode 100644 index 10ce55a2..00000000 --- a/websocket-example.py +++ /dev/null @@ -1,30 +0,0 @@ -import time - -from polygon import WebSocketClient, STOCKS_CLUSTER - - -def my_custom_process_message(message): - print("this is my custom message processing", message) - - -def my_custom_error_handler(ws, error): - print("this is my custom error handler", error) - - -def my_custom_close_handler(ws): - print("this is my custom close handler") - - -def main(): - key = 'your api key' - my_client = WebSocketClient(STOCKS_CLUSTER, key, my_custom_process_message) - my_client.run_async() - - my_client.subscribe("T.MSFT", "T.AAPL", "T.AMD", "T.NVDA") - time.sleep(1) - - my_client.close_connection() - - -if __name__ == "__main__": - main() From d59805362c4a89481ceb9d05acbe3829f92af253 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 6 Dec 2020 23:47:30 +0100 Subject: [PATCH 12/21] some warnings ... --- polygon/rest/client.py | 6 +++--- polygon/rest/rest_models.py | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/polygon/rest/client.py b/polygon/rest/client.py index 368dd3ab..a2f4f683 100644 --- a/polygon/rest/client.py +++ b/polygon/rest/client.py @@ -9,8 +9,8 @@ def __init__(self, auth_key: str, timeout: int=None): self.auth_key = auth_key self.url = "https://" + self.DEFAULT_HOST - self._session = requests.Session() - self._session.params["apiKey"] = self.auth_key + self.session = requests.Session() + self.session.params["apiKey"] = self.auth_key self.timeout = timeout def __enter__(self): @@ -20,4 +20,4 @@ def __exit__(self, *args): self.close() def close(self): - self._session.close() + self.session.close() diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index dd522475..408a9c3b 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -25,7 +25,7 @@ def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typi assert c is not None url = f"{c.url}{path}" print(url) - r = requests.Response = c._session.get(url, params=params) + r = requests.Response = c.session.get(url, params=params) if r.status_code == 200: d: typing.Union[dict, list] = r.json() if isinstance(d, list): From 4171453e7078619e3adb528dd075e97a3e8e221c Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Mon, 7 Dec 2020 00:39:13 +0100 Subject: [PATCH 13/21] some warnings ... --- polygon/rest/client.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/polygon/rest/client.py b/polygon/rest/client.py index a2f4f683..462b2322 100644 --- a/polygon/rest/client.py +++ b/polygon/rest/client.py @@ -5,7 +5,7 @@ class RESTClient: """ This is a custom generated class """ DEFAULT_HOST = "api.polygon.io" - def __init__(self, auth_key: str, timeout: int=None): + def __init__(self, auth_key: str, timeout: int = None): self.auth_key = auth_key self.url = "https://" + self.DEFAULT_HOST From bc44f60743cb5865b6628a91559642c59a007b86 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Mon, 7 Dec 2020 22:09:12 +0100 Subject: [PATCH 14/21] Trading without crashing .... --- polygon/rest/rest_models.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index 408a9c3b..d886ac97 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -8,8 +8,9 @@ import pandas as pd import requests from pydantic import BaseModel, Field, root_validator - +import logging from polygon import RESTClient +logger = logging.getLogger(__name__) # _T = typing.TypeVar('_T') _T = typing.ClassVar @@ -24,7 +25,7 @@ def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typi c = PolygonModel.Meta.client assert c is not None url = f"{c.url}{path}" - print(url) + logger.info(f'{url}') r = requests.Response = c.session.get(url, params=params) if r.status_code == 200: d: typing.Union[dict, list] = r.json() From d312b33686d000b45a403393efc891789ceac61b Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Fri, 11 Dec 2020 22:23:16 +0100 Subject: [PATCH 15/21] Added sentry error logging ... --- polygon/rest/rest_models.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index d886ac97..bee8f29f 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -95,8 +95,8 @@ class TickerDetail(PolygonModel): country: str industry: str sector: str - marketcap: float - employees: float + marketcap: typing.Optional[float] = None + employees: typing.Optional[float] = None phone: str ceo: str url: str From ac72dfff311c779ed90ab68a9921f16b07b1eab7 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Mon, 14 Dec 2020 22:04:03 +0100 Subject: [PATCH 16/21] Trade History added ... --- polygon/rest/rest_models.py | 70 +++++++++++++++++++++++++++++- polygon/websocket/stream_models.py | 5 +++ 2 files changed, 74 insertions(+), 1 deletion(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index bee8f29f..441b8a4c 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -7,9 +7,10 @@ import pandas as pd import requests -from pydantic import BaseModel, Field, root_validator +from pydantic import BaseModel, Field, PrivateAttr, root_validator import logging from polygon import RESTClient + logger = logging.getLogger(__name__) # _T = typing.TypeVar('_T') @@ -202,3 +203,70 @@ def get_ticker_window(self, new_start_date: bool = False) -> TickerWindow: res.consume(tw) assert res is not None return res + + +class TradeItem(BaseModel): + original_id: typing.Optional[int] = Field(alias='I', default=None) + exchange_id: typing.Optional[int] = Field(alias='x', default=None) + price: float = Field(alias='p') + correction_indicator: typing.Optional[int] = Field(alias='e', default=None) + reporting_id: typing.Optional[int] = Field(alias='r', default=None) + trade_time: datetime.datetime = Field(alias='t') + quote_time: typing.Optional[datetime.datetime] = Field(alias='y', default=None) + report_time: typing.Optional[datetime.datetime] = Field(alias='f', default=None) + sequence_no: typing.Optional[int] = Field(alias='q') + trade_conditions: typing.Optional[typing.List[int]] = Field(alias='c', default=None) + size: int = Field(alias='s') + + +class Trade(PolygonModel): + symbol: str = Field(alias='ticker') + results_count: int + db_latency: int + success: bool + results: typing.List[TradeItem] + _df: typing.Optional[pd.DataFrame] = PrivateAttr(default=None) + + @property + def df(self) -> pd.DataFrame: + if self._df is None: + df = pd.DataFrame.from_dict(self.dict()['results']) + # df = df.set_index('trade_time').sort_index() + self._df = df + return self._df + + @classmethod + def __get(cls: Trade, symbol: str, date: str, timestamp_min: int = None, timestamp_max: int = None, + limit: int = 50000, reverse: bool = False) -> Trade: + return cls.api_action(f'/v2/ticks/stocks/trades/{symbol}/{date}', + params=dict(timestamp=timestamp_min, timestampLimit=timestamp_max, limit=limit, + reverse=reverse)) + + @property + def size(self) -> int: + return len(self.results) + + def consume(self, other: Trade): + assert self.results[-1].trade_time < other.results[0].trade_time + self.results_count += other.results_count + self.results.extend(other.results) + + @staticmethod + def __n(dt: typing.Union[datetime.datetime, None]) -> typing.Union[int, None]: + if dt is None: + return None + else: + return int(dt.timestamp() * 1000) + + @classmethod + def get(cls: Trade, symbol: str, date: str, timestamp_min: datetime.datetime = None, + timestamp_max: datetime.datetime = None, limit: int = 50000, reverse: bool = False) -> Trade: + use_limit = min(limit, 50000) + t_min = cls.__n(timestamp_min) + t_max = cls.__n(timestamp_max) + trade = tmp_trade = Trade.__get(symbol, date, t_min, t_max, min(limit, 50000), reverse=reverse) + while tmp_trade.size == use_limit and use_limit < limit: + t_min = cls.__n(trade.results[-1].trade_time) + tmp_trade = Trade.__get(symbol, date, t_min, t_max, use_limit, reverse=reverse) + trade.consume(tmp_trade) + return trade diff --git a/polygon/websocket/stream_models.py b/polygon/websocket/stream_models.py index 75bb3866..8d673cd5 100644 --- a/polygon/websocket/stream_models.py +++ b/polygon/websocket/stream_models.py @@ -26,6 +26,11 @@ def age(self) -> datetime.timedelta: return datetime.datetime.now(pytz.utc) - self.utc + @property + def trade_item(self) -> rest_models.TradeItem: + return rest_models.TradeItem(**self.dict()) + + class Quote(SocketBase): bid_exchange_id: int = Field(alias='bx') bid_price: float = Field(alias='bp') From 8ed9331be6b029bd38cee33e999c23d365b1b432 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Wed, 30 Dec 2020 18:41:51 +0100 Subject: [PATCH 17/21] More sticky orders ... --- polygon/rest/rest_models.py | 1 + 1 file changed, 1 insertion(+) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index 441b8a4c..104e19bf 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -161,6 +161,7 @@ def df(self) -> pd.DataFrame: def add_bar(self, bar: Bar): if len(self.results) == 0 or bar.utc_window_start > self.results[-1].utc_window_start: + logger.info(f'Adding BAR {bar} to {self.symbol}') self.results.append(bar) self.__set_df() elif bar.utc_window_start == self.results[-1].utc_window_start: From 13933042d505e27ba699c3b7452f26b3317ced8c Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Thu, 31 Dec 2020 15:52:18 +0100 Subject: [PATCH 18/21] Get trades is working ... --- polygon/rest/rest_models.py | 53 +++++++++++++++++++++++-------------- 1 file changed, 33 insertions(+), 20 deletions(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index 104e19bf..e79a3392 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -21,25 +21,31 @@ class PolygonModel(BaseModel): class Meta: client: RESTClient = None + @classmethod - def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: + def api_action_raw(cls: _T, path: str, params: dict = None) -> typing.Union[dict, list, None]: c = PolygonModel.Meta.client assert c is not None url = f"{c.url}{path}" logger.info(f'{url}') r = requests.Response = c.session.get(url, params=params) + logger.info(f'{r.url} --> {r.status_code}') if r.status_code == 200: - d: typing.Union[dict, list] = r.json() - if isinstance(d, list): - # noinspection PyArgumentList - return [cls(**el) for el in d] - else: - # noinspection PyArgumentList - return cls(**d) - + return r.json() else: r.raise_for_status() + @classmethod + def api_action(cls: _T, path: str, params: dict = None) -> typing.Union[_T, typing.List[_T]]: + d = cls.api_action_raw(path, params) + assert d is not None + if isinstance(d, list): + # noinspection PyArgumentList + return [cls(**el) for el in d] + else: + # noinspection PyArgumentList + return cls(**d) + @classmethod def get(cls: _T, *args, **kwargs) -> typing.Union[_T, typing.List[_T]]: raise NotImplementedError @@ -238,36 +244,43 @@ def df(self) -> pd.DataFrame: @classmethod def __get(cls: Trade, symbol: str, date: str, timestamp_min: int = None, timestamp_max: int = None, - limit: int = 50000, reverse: bool = False) -> Trade: - return cls.api_action(f'/v2/ticks/stocks/trades/{symbol}/{date}', + limit: int = 50000, reverse: bool = False) -> typing.Tuple[Trade, int]: + d= cls.api_action_raw(f'/v2/ticks/stocks/trades/{symbol}/{date}', params=dict(timestamp=timestamp_min, timestampLimit=timestamp_max, limit=limit, reverse=reverse)) + trade = Trade(**d) + last= d['results'][-1]['t'] + return trade, last @property def size(self) -> int: return len(self.results) def consume(self, other: Trade): - assert self.results[-1].trade_time < other.results[0].trade_time - self.results_count += other.results_count - self.results.extend(other.results) + #assert self.results[-1].trade_time > other.results[0].trade_time, (self.results[-1].trade_time, other.results[0].trade_time) + assert self.results[-1].trade_time == other.results[0].trade_time, (self.results[-1].trade_time, other.results[0].trade_time) + self.results_count += (other.results_count-1) + self.results.extend(other.results[1:]) + self._df = None @staticmethod def __n(dt: typing.Union[datetime.datetime, None]) -> typing.Union[int, None]: if dt is None: return None else: - return int(dt.timestamp() * 1000) + return int(dt.timestamp() * 1e6) @classmethod def get(cls: Trade, symbol: str, date: str, timestamp_min: datetime.datetime = None, - timestamp_max: datetime.datetime = None, limit: int = 50000, reverse: bool = False) -> Trade: + timestamp_max: datetime.datetime = None, limit: int = 50000) -> Trade: + reverse = False use_limit = min(limit, 50000) t_min = cls.__n(timestamp_min) t_max = cls.__n(timestamp_max) - trade = tmp_trade = Trade.__get(symbol, date, t_min, t_max, min(limit, 50000), reverse=reverse) + tmp_trade,last = Trade.__get(symbol, date, t_min, t_max, use_limit, reverse=reverse) + trade = tmp_trade while tmp_trade.size == use_limit and use_limit < limit: - t_min = cls.__n(trade.results[-1].trade_time) - tmp_trade = Trade.__get(symbol, date, t_min, t_max, use_limit, reverse=reverse) - trade.consume(tmp_trade) + tmp_trade, last = Trade.__get(symbol, date, last, t_max, use_limit, reverse=reverse) + if len(tmp_trade.results) > 0: + trade.consume(tmp_trade) return trade From e0b76b4a1ad294aaeeac8507dd254310a3c0fc38 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Thu, 31 Dec 2020 16:02:52 +0100 Subject: [PATCH 19/21] Added reverse back to get trades and added protection because code is not working for multi-fetch & reverse=True --- polygon/rest/rest_models.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index e79a3392..5d1b99eb 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -272,9 +272,10 @@ def __n(dt: typing.Union[datetime.datetime, None]) -> typing.Union[int, None]: @classmethod def get(cls: Trade, symbol: str, date: str, timestamp_min: datetime.datetime = None, - timestamp_max: datetime.datetime = None, limit: int = 50000) -> Trade: - reverse = False + timestamp_max: datetime.datetime = None, limit: int = 50000, reverse=False) -> Trade: use_limit = min(limit, 50000) + if reverse: + assert use_limit == limit t_min = cls.__n(timestamp_min) t_max = cls.__n(timestamp_max) tmp_trade,last = Trade.__get(symbol, date, t_min, t_max, use_limit, reverse=reverse) From 5a2ee7ba1de3a64830a5342357035d51b3fed3f6 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Wed, 6 Jan 2021 20:49:02 +0100 Subject: [PATCH 20/21] Added Single Trader ... --- polygon/rest/rest_models.py | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/polygon/rest/rest_models.py b/polygon/rest/rest_models.py index 5d1b99eb..24a738f3 100644 --- a/polygon/rest/rest_models.py +++ b/polygon/rest/rest_models.py @@ -124,6 +124,7 @@ class Bar(BaseModel): close: float = Field(alias='c') high: float = Field(alias='h') low: float = Field(alias='l') + average: typing.Optional[float] = Field(alias='vw', default=None) utc_window_start: datetime.datetime = Field(alias='t') trades: int = Field(alias='n', default=0) @@ -244,12 +245,13 @@ def df(self) -> pd.DataFrame: @classmethod def __get(cls: Trade, symbol: str, date: str, timestamp_min: int = None, timestamp_max: int = None, - limit: int = 50000, reverse: bool = False) -> typing.Tuple[Trade, int]: + limit: int = 50000, reverse: bool = False) -> typing.Tuple[Trade, typing.Union[int, None]]: d= cls.api_action_raw(f'/v2/ticks/stocks/trades/{symbol}/{date}', params=dict(timestamp=timestamp_min, timestampLimit=timestamp_max, limit=limit, reverse=reverse)) trade = Trade(**d) - last= d['results'][-1]['t'] + + last = None if len(trade.results) == 0 else d['results'][-1]['t'] return trade, last @property @@ -280,7 +282,7 @@ def get(cls: Trade, symbol: str, date: str, timestamp_min: datetime.datetime = N t_max = cls.__n(timestamp_max) tmp_trade,last = Trade.__get(symbol, date, t_min, t_max, use_limit, reverse=reverse) trade = tmp_trade - while tmp_trade.size == use_limit and use_limit < limit: + while isinstance(last, int) and tmp_trade.size == use_limit and use_limit < limit: tmp_trade, last = Trade.__get(symbol, date, last, t_max, use_limit, reverse=reverse) if len(tmp_trade.results) > 0: trade.consume(tmp_trade) From d82012236f7c4f8005f57b298a33b92c53902126 Mon Sep 17 00:00:00 2001 From: David Jacquet Date: Sun, 24 Jan 2021 23:22:38 +0100 Subject: [PATCH 21/21] Some less logging + docker file ... --- polygon/websocket/stream_models.py | 16 ++++++++++------ 1 file changed, 10 insertions(+), 6 deletions(-) diff --git a/polygon/websocket/stream_models.py b/polygon/websocket/stream_models.py index 8d673cd5..d19efc55 100644 --- a/polygon/websocket/stream_models.py +++ b/polygon/websocket/stream_models.py @@ -32,18 +32,22 @@ def trade_item(self) -> rest_models.TradeItem: class Quote(SocketBase): - bid_exchange_id: int = Field(alias='bx') - bid_price: float = Field(alias='bp') - bid_size: int = Field(alias='bs') - ask_exchange_id: int = Field(alias='ax') - ask_price: float = Field(alias='ap') - ask_size: int = Field(alias='as') + bid_exchange_id: typing.Optional[int] = Field(alias='bx', default=None) + bid_price: typing.Optional[float] = Field(alias='bp', default=None) + bid_size: typing.Optional[int] = Field(alias='bs', default=None) + ask_exchange_id: typing.Optional[int] = Field(alias='ax', default=None) + ask_price: typing.Optional[float] = Field(alias='ap', default=None) + ask_size: typing.Optional[int] = Field(alias='as', default=None) quote_conditions: typing.Optional[int] = Field(alias='c', default=None) utc: datetime.datetime = Field(alias='t') def __str__(self): return f'{self.bid_size}:{self.bid_price} -- {self.ask_size}:{self.ask_price}' + @property + def is_complete(self) -> bool: + return self.bid_price is not None and self.ask_price is not None + @property def age(self) -> datetime.timedelta: return datetime.datetime.now(pytz.utc) - self.utc