├── TradovatePy ├── util │ ├── __init__.py │ ├── text.py │ └── date_and_time.py ├── models │ ├── __init__.py │ └── session.py ├── config.py ├── positions.py ├── configuration.py ├── accounting.py ├── alerts.py ├── contractLibrary.py ├── risks.py ├── orders.py └── users.py ├── requirements.txt ├── .github └── workflows │ ├── commitlint.yml │ ├── pre-commit.yml │ └── commitlint.config.js ├── setup.py ├── README.md ├── LICENSE ├── .pre-commit-config.yaml └── .gitignore /TradovatePy/util/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /TradovatePy/models/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | aiohttp==3.12.14 2 | -------------------------------------------------------------------------------- /TradovatePy/util/text.py: -------------------------------------------------------------------------------- 1 | def multi_ids(array: list[int]) -> str: 2 | """Convert multiple ids to string""" 3 | return ','.join(str(i) for i in array) 4 | -------------------------------------------------------------------------------- /TradovatePy/util/date_and_time.py: -------------------------------------------------------------------------------- 1 | def parse_hour(times: list[str]) -> dict: 2 | """Parse a datetime string for the hour.""" 3 | output = {} 4 | for time in times: 5 | output[time] = time[time.find(" ")+1:-3] 6 | 7 | return output 8 | -------------------------------------------------------------------------------- /TradovatePy/config.py: -------------------------------------------------------------------------------- 1 | URLs = { 2 | "DEMO": "https://demo.tradovateapi.com/v1", 3 | "LIVE": "https://live.tradovateapi.com/v1", 4 | "MD": "wss://md.tradovateapi.com/v1/websocket", 5 | "WS_DEMO": "wss://demo.tradovateapi.com/v1/websocket", 6 | "WS_LIVE": "wss://live.tradovateapi.com/v1/websocket", 7 | } 8 | -------------------------------------------------------------------------------- /.github/workflows/commitlint.yml: -------------------------------------------------------------------------------- 1 | name: "Commit Linter" 2 | on: pull_request 3 | jobs: 4 | lint-commits: 5 | runs-on: ubuntu-latest 6 | steps: 7 | - uses: actions/checkout@v2.3.1 8 | with: 9 | fetch-depth: 0 10 | - uses: wagoid/commitlint-github-action@v4 11 | with: 12 | configFile: .github/workflows/commitlint.config.js 13 | -------------------------------------------------------------------------------- /.github/workflows/pre-commit.yml: -------------------------------------------------------------------------------- 1 | name: pre-commit 2 | 3 | on: 4 | pull_request: 5 | push: 6 | branches: [main] 7 | 8 | jobs: 9 | pre-commit: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - uses: actions/checkout@v2 13 | - name: Install dependencies 14 | run: | 15 | sudo apt-get install python3.9 16 | sudo update-alternatives --install /usr/bin/python3 python3 /usr/bin/python3.9 1 17 | python3 -m pip install --upgrade pip 18 | pip3 install -r requirements.txt 19 | - uses: pre-commit/action@v2.0.3 20 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | 3 | setup( 4 | name="TradovatePy", 5 | version="0.2", 6 | packages=find_packages(), 7 | install_requires=[ 8 | "aiohttp", 9 | ], 10 | author="Antonio Hickey", 11 | author_email="contact@antoniohickey.com", 12 | description="A description of my package", 13 | long_description=open("README.md").read(), 14 | long_description_content_type="text/markdown", 15 | url="https://github.com/antonio-hickey/TradovatePy", 16 | classifiers=[ 17 | "Programming Language :: Python :: 3", 18 | "License :: OSI Approved :: MIT License", 19 | "Operating System :: OS Independent", 20 | ], 21 | python_requires='>=3.6', 22 | ) 23 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # TradovatePy 2 | Python wrapper for the Tradovate API 3 | 4 | ### Installation 5 | ``` 6 | pip install TradovatePy==0.1 7 | ``` 8 | 9 | ### Example 10 | 11 | Get the current positions you have open. 12 | 13 | *NOTE: You need to replace values below with your info* 14 | 15 | ```python 16 | import asyncio 17 | from TradovatePy.models.session import Session 18 | from TradovatePy.positions import Positions 19 | 20 | if __name__ == "__main__": 21 | session = Session( 22 | "LIVE", 23 | "YOUR_USERNAME", 24 | "YOUR_PASSWORD", 25 | "YOUR_SECRET_KEY", 26 | "YOUR_DEVICE_ID", 27 | "YOUR_APP_VERSION", 28 | "YOUR_APP_ID", 29 | 123, # YOUR CID 30 | ) 31 | print( 32 | asyncio.run(Positions(session).position_list()) 33 | ) 34 | ``` 35 | -------------------------------------------------------------------------------- /.github/workflows/commitlint.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | rules: { 3 | "body-leading-blank": [1, "always"], 4 | "body-max-line-length": [2, "always", 100], 5 | "footer-leading-blank": [1, "always"], 6 | "footer-max-line-length": [2, "always", 100], 7 | "header-max-length": [2, "always", 72], 8 | "scope-case": [2, "always", "lower-case"], 9 | "subject-case": [ 10 | 2, 11 | "never", 12 | ["upper-case", "pascal-case", "sentence-case", "start-case"], 13 | ], 14 | "subject-empty": [2, "never"], 15 | "subject-full-stop": [2, "never", "."], 16 | "type-case": [2, "always", "lower-case"], 17 | "type-empty": [2, "never"], 18 | "type-enum": [ 19 | 2, 20 | "always", 21 | [ 22 | "build", 23 | "chore", 24 | "ci", 25 | "docs", 26 | "feat", 27 | "fix", 28 | "perf", 29 | "refactor", 30 | "revert", 31 | "test", 32 | ], 33 | ], 34 | }, 35 | }; 36 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2022 Antonio Hickey 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | repos: 2 | - repo: https://github.com/pre-commit/pre-commit-hooks 3 | rev: v2.5.0 4 | hooks: 5 | - id: check-yaml 6 | - id: end-of-file-fixer 7 | - id: trailing-whitespace 8 | - id: check-case-conflict 9 | - id: check-docstring-first 10 | - id: check-executables-have-shebangs 11 | - id: check-json 12 | - id: check-merge-conflict 13 | - id: debug-statements 14 | - id: check-ast 15 | - repo: https://gitlab.com/PyCQA/flake8 16 | rev: 3.8.3 17 | hooks: 18 | - id: flake8 19 | additional_dependencies: 20 | - flake8-commas==2.0.0 21 | - flake8-tidy-imports>=1.1.0<2 22 | - flake8-mutable>=1.2.0 23 | args: [--max-line-length=131] 24 | - repo: https://github.com/pre-commit/mirrors-mypy 25 | rev: v0.910 26 | hooks: 27 | - id: mypy 28 | verbose: true 29 | args: [--ignore-missing-imports] 30 | 31 | - repo: https://github.com/pycqa/isort 32 | rev: 5.8.0 33 | hooks: 34 | - id: isort 35 | name: isort (python) 36 | - id: isort 37 | name: isort (cython) 38 | types: [cython] 39 | - id: isort 40 | name: isort (pyi) 41 | types: [pyi] 42 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /TradovatePy/positions.py: -------------------------------------------------------------------------------- 1 | class Positions: 2 | def __init__(self, session) -> None: 3 | self.session = session 4 | 5 | async def fill_pair_dependents(self, master_id: int) -> dict: 6 | """Retrieves all entities of FillPair type related to Position entity.""" 7 | return await self.session.get(f"fillPair/deps?id={master_id}") 8 | 9 | async def fill_pair_item(self, id: int) -> dict: 10 | """Retrieves an entity of FillPair type by its id.""" 11 | return await self.session.get(f"/fillPair/item?id={id}") 12 | 13 | async def fill_pair_items(self, ids: list[int]) -> dict: 14 | """Retrieves multiple entities of FillPair type by its ids.""" 15 | return await self.session.get(f"/fillPair/items?ids{','.join([str(id) for id in ids])}") 16 | 17 | async def fill_pair_l_dependents(self, master_ids: list[int]) -> dict: 18 | """Retrieves all entities of FillPair type related to multiple entities of Position type.""" 19 | return await self.session.get(f"/fillPair/ldeps?masterids={','.join([str(id) for id in master_ids])}") 20 | 21 | async def fill_pair_list(self) -> dict: 22 | """Retrieves all entities of FillPair type.""" 23 | return await self.session.get("/fillPair/list") 24 | 25 | async def position_dependents(self, master_id: int) -> dict: 26 | """Retrieves all entities of Position type related to Account entity.""" 27 | return await self.session.get(f"/postion/deps?masterid={master_id}") 28 | 29 | async def position_find(self, name: str) -> dict: 30 | """Retrieves an entity of Position type by its name.""" 31 | return await self.session.get(f"/position/find?name={name}") 32 | 33 | async def position_item(self, id: int) -> dict: 34 | """Retrieves an entity of Position type by its id.""" 35 | return await self.session.get(f"/position/item?id={id}") 36 | 37 | async def position_items(self, ids: list[int]) -> dict: 38 | """Retrieves multiple entities of Position type by its ids.""" 39 | return await self.session.get(f"/position/items?ids={','.join([str(id) for id in ids])}") 40 | 41 | async def position_l_dependents(self, master_ids: list[int]) -> dict: 42 | """Retrieves all entities of Position type related to multiple entities of Account type.""" 43 | return await self.session.get(f"/postion/ldeps?masterids={','.join([str(id) for id in master_ids])}") 44 | 45 | async def position_list(self) -> dict: 46 | """Retrieves all entities of Position type.""" 47 | return await self.session.get("/position/list") 48 | -------------------------------------------------------------------------------- /TradovatePy/models/session.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from datetime import datetime 3 | 4 | from aiohttp import ClientSession 5 | 6 | from TradovatePy.config import URLs 7 | from TradovatePy.util.date_and_time import parse_hour 8 | 9 | 10 | class Session: 11 | def __init__(self, 12 | environment: str, 13 | username: str, 14 | password: str, 15 | secret_key: str = "", 16 | device_id: str = "", 17 | app_version: str = "", 18 | app_id: str = "", 19 | cid: int = 0) -> None: 20 | """Session constructor.""" 21 | self.env: str = environment 22 | self.username: str = username 23 | self.password: str = password 24 | self.secret_key: str = secret_key 25 | self.device_id: str = device_id 26 | self.app_version: str = app_version 27 | self.app_id: str = app_id 28 | self.cid: int = cid 29 | self.URL: str = URLs[self.env] 30 | self.CREDs: dict = self.render_credentials_payload() 31 | self.access_tokens: dict = asyncio.run(self.get_access_tokens()) 32 | self.access_token: str = self.access_tokens['accessToken'] 33 | self.market_data_access_token: str = self.access_tokens['mdAccessToken'] 34 | self.token_expiration_time: str = self.access_tokens['expirationTime'].replace("T", " ")[:-8] 35 | self.headers: dict = { 36 | 'Authorization': f'Bearer {self.access_token}', 37 | 'Content-Type': 'application/json', 38 | 'Accept': 'application/json', 39 | } 40 | 41 | async def __aenter__(self): 42 | """Enter client session.""" 43 | self._session = ClientSession() 44 | return self 45 | 46 | async def __aexit__(self): 47 | """Exit client session.""" 48 | await self._session.close() 49 | 50 | async def get_access_tokens(self): 51 | """Trade credentials for tokens.""" 52 | await self.__aenter__() 53 | url = f"{self.URL}/auth/accesstokenrequest" 54 | async with self._session.post(url, json=self.CREDs, ssl=False) as resp: 55 | await self.__aexit__() 56 | return await resp.json() 57 | 58 | async def get(self, url: str): 59 | """Send GET request to a spicified url.""" 60 | await self.__aenter__() 61 | url = f"{self.URL + url}" 62 | async with self._session.get(url, headers=self.headers, ssl=False) as resp: 63 | await self.__aexit__() 64 | return await resp.json() 65 | 66 | async def post(self, url: str, payload: dict): 67 | """Send POST request to a specified url with a specified payload.""" 68 | await self.__aenter__() 69 | url = f"{self.URL + url}" 70 | async with self._session.post(url, headers=self.headers, json=payload, ssl=False) as resp: 71 | await self.__aexit__() 72 | return await resp.json() 73 | 74 | def render_credentials_payload(self) -> dict: 75 | """Create credentials payload.""" 76 | payload = { 77 | "name": self.username, 78 | "password": self.password, 79 | } 80 | 81 | if self.secret_key != "": 82 | payload['sec'] = self.secret_key 83 | if self.device_id != "": 84 | payload['deviceId'] = self.device_id 85 | if self.app_id != "": 86 | payload['appId'] = self.app_id 87 | if self.app_version != "": 88 | payload['appVersion'] = self.app_version 89 | if self.cid != 0: 90 | payload['cid'] = str(self.cid) 91 | 92 | return payload 93 | 94 | async def expiration_check(self) -> bool: 95 | """Check if tokens are close to expiration.""" 96 | right_now = str(datetime.now())[:-10] 97 | hours = parse_hour([right_now, self.token_expiration_time]) 98 | 99 | if hours[right_now] == hours[self.token_expiration_time]: 100 | return True 101 | return False 102 | -------------------------------------------------------------------------------- /TradovatePy/configuration.py: -------------------------------------------------------------------------------- 1 | class Configuration: 2 | 3 | def __init__(self, session) -> None: 4 | """Configuration Constructor""" 5 | self.session = session 6 | print(type(session)) 7 | 8 | async def admin_alert_find(self, name: str) -> dict: 9 | """Retrieves an entity of AdminAlert type by its name.""" 10 | return await self.session.get(f"/adminAlert/find?name={name}") 11 | 12 | async def admin_alert_item(self, id: int) -> dict: 13 | """Retrieves an entity of AdminAlert type by its id.""" 14 | return await self.session.get(f"/adminAlert/item?id={id}") 15 | 16 | async def admin_alert_items(self, ids: list[int]) -> dict: 17 | """Retrieves multiple entities of AdminAlert type by its ids.""" 18 | return await self.session.get( 19 | f"/adminAlert/items?ids={','.join([str(id) for id in ids])}", 20 | ) 21 | 22 | async def admin_alert_list(self) -> dict: 23 | """Retrieves all entities of AdminAlert type.""" 24 | return await self.session.get("/adminAlert/list") 25 | 26 | async def admin_alert_suggest(self, text: str, n_entities: int) -> dict: 27 | """Retrieves entities of AdminAlert type filtered by an occurrence of a text in one of its fields.""" 28 | return await self.session.get(f"/adminAlert/suggest?t={text}&l={n_entities}") 29 | 30 | async def clearing_house_find(self, name: str) -> dict: 31 | """Retrieves an entity of ClearingHouse type by its name.""" 32 | return await self.session.get(f"/clearingHouse/find?name={name}") 33 | 34 | async def clearing_house_item(self, id: int) -> dict: 35 | """Retrieves an entity of ClearingHouse type by its id.""" 36 | return await self.session.get(f"/clearingHouse/item?id={id}") 37 | 38 | async def clearing_house_items(self, ids: list[int]) -> dict: 39 | """Retrieves multiple entities of ClearingHouse type by its ids.""" 40 | return await self.session.get( 41 | f"/clearingHouse/items?ids={','.join([str(id) for id in ids])}", 42 | ) 43 | 44 | async def clearing_house_list(self) -> dict: 45 | """Retrieves all entities of ClearingHouse type.""" 46 | return await self.session.get("/clearingHouse/list") 47 | 48 | async def clearing_house_suggest(self, text: str, n_entities: int) -> dict: 49 | """Retrieves entities of ClearingHouse type filtered by an occurrence of a text in one of its fields.""" 50 | return await self.session.get(f"/clearingHouse/suggest?t={text}&l={n_entities}") 51 | 52 | async def entitlement_item(self, id: int) -> dict: 53 | """Retrieves an entity of Entitlement type by its id.""" 54 | return await self.session.get(f"/entitlement/item?id={id}") 55 | 56 | async def entitlement_items(self, ids: list[int]) -> dict: 57 | """Retrieves multiple entities of Entitlement type by its ids.""" 58 | return await self.session.get(f"/entitlement/items?ids={','.join([str(id) for id in ids])}") 59 | 60 | async def entitlement_list(self) -> dict: 61 | """Retrieves all entities of Entitlement type.""" 62 | return await self.session.get("/entitlement/list") 63 | 64 | async def order_strategy_type_find(self, name: str) -> dict: 65 | """Retrieves an entity of OrderStrategyType type by its name.""" 66 | return await self.session.get(f"/OrderStrategyType/find?name={name}") 67 | 68 | async def order_strategy_type_item(self, id: int) -> dict: 69 | """Retrieves an entity of OrderStrategyType type by its id.""" 70 | return await self.session.get(f"/orderStrategyType/item?id={id}") 71 | 72 | async def order_strategy_type_items(self, ids: list[int]) -> dict: 73 | """Retrieves multiple entities of OrderStrategyType type by its ids.""" 74 | return await self.session.get(f"/orderStrategyType/items?ids={','.join([str(id) for id in ids])}") 75 | 76 | async def order_strategy_type_list(self) -> dict: 77 | """Retrieves all entities of OrderStrategyType type.""" 78 | return await self.session.get("/orderStrategyType/list") 79 | 80 | async def order_strategy_type_suggest(self, text: str, n_entities: int) -> dict: 81 | """Retrieves entities of OrderStrategyType type filtered by an occurrence of a text in one of its fields.""" 82 | return await self.session.get(f"/orderStrategyType/suggest?t={text}&l={n_entities}") 83 | 84 | async def property_find(self, name: str) -> dict: 85 | """Retrieves an entity of Property type by its name.""" 86 | return await self.session.get(f"/property/find?name={name}") 87 | 88 | async def property_item(self, id: int) -> dict: 89 | """Retrieves an entity of Property type by its id.""" 90 | return await self.session.get(f"/property/item?id={id}") 91 | 92 | async def property_items(self, ids: list[int]) -> dict: 93 | """Retrieves multiple entities of Property type by its ids.""" 94 | return await self.session.get( 95 | f"/property/items?ids={','.join([str(id) for id in ids])}", 96 | ) 97 | 98 | async def property_list(self) -> dict: 99 | """Retrieves all entities of Property type.""" 100 | return await self.session.get("/property/list") 101 | 102 | async def property_suggest(self, text: str, n_entities: int) -> dict: 103 | """Retrieves entities of Property type filtered by an occurrence of a text in one of its fields.""" 104 | return await self.session.get(f"/property/suggest?t={text}&l={n_entities}") 105 | -------------------------------------------------------------------------------- /TradovatePy/accounting.py: -------------------------------------------------------------------------------- 1 | class Accounting: 2 | 3 | def __init__(self, session) -> None: 4 | """Accounting constructor""" 5 | self.session = session 6 | 7 | async def account_dependents(self, master_id: int) -> dict: 8 | """Retrieves all entities of Account type related to User entity.""" 9 | return await self.session.get(f"/account/deps?masterid={master_id}") 10 | 11 | async def account_find(self, name: str) -> dict: 12 | """Retrieves an entity of Account type by its name.""" 13 | return await self.session.get(f"/account/find?name={name}") 14 | 15 | async def account_item(self, id: int) -> dict: 16 | """Retrieves an entity of Account type by its id.""" 17 | return await self.session.get(f"/account/item?id={id}") 18 | 19 | async def account_items(self, ids: list[int]) -> dict: 20 | """Retrieves an entity of Account type by its ids.""" 21 | return await self.session.get(f"/account/items?ids={','.join([str(id) for id in ids])}") 22 | 23 | async def account_L_dependents(self, master_ids: list[int]) -> dict: 24 | """Retrieves all entities of Account type related to multiple entities of User type""" 25 | return await self.session.get(f"/account/deps?masterid={','.join([str(id) for id in master_ids])}") 26 | 27 | async def account_list(self) -> dict: 28 | """Retrieves all entities of Account type.""" 29 | return await self.session.get("/account/list") 30 | 31 | async def account_suggest(self, text: str, n_entities: int) -> dict: 32 | """Retrieves entities of Account type filtered by an occurrence of a text in one of its fields.""" 33 | return await self.session.get(f"/account/suggest?t={text}&l={n_entities}") 34 | 35 | async def cash_balance_dependents(self, master_id: int) -> dict: 36 | """Retrieves all entities of CashBalance type related to Account entity.""" 37 | return await self.session.get(f"/cashBalance/deps?masterid={master_id}") 38 | 39 | async def cash_balance_snapshot(self, account_id: int) -> dict: 40 | """Get a snapshot of an account's current cash balance.""" 41 | return await self.session.post( 42 | url="/cashBalance/getcashbalancesnapshot", 43 | payload={"accountId": account_id}, 44 | ) 45 | 46 | async def cash_balance_item(self, id: int) -> dict: 47 | """Retrieves an entity of CashBalance type by its id.""" 48 | return await self.session.get(f"/cashBalance/item?id={id}") 49 | 50 | async def cash_balance_items(self, ids: list[int]) -> dict: 51 | """Retrieves multiple entities of CashBalance type by its ids.""" 52 | return await self.session.get(f"/cashBalance/items?ids={','.join([str(id) for id in ids])}") 53 | 54 | async def cash_balance_L_dependents(self, master_ids: list[int]) -> dict: 55 | """Retrieves all entities of CashBalance type related to multiple entities of Account type.""" 56 | return await self.session.get(f"/cashBalance/ldeps?masterids={','.join([str(id) for id in master_ids])}") 57 | 58 | async def cash_balance_list(self) -> dict: 59 | """Retrieves all entities of CashBalance type.""" 60 | return await self.session.get("/cashBalance/list") 61 | 62 | async def cash_balance_log_dependents(self, master_id: int) -> dict: 63 | """Retrieves all entities of CashBalanceLog type related to Account entity.""" 64 | return await self.session.get(f"/cashBalanceLog/deps?masterid={master_id}") 65 | 66 | async def cash_balance_log_item(self, id: int) -> dict: 67 | """Retrieves an entity of CashBalanceLog type by its id.""" 68 | return await self.session.get(f"/cashBalanceLog/item?id={id}") 69 | 70 | async def cash_balance_log_items(self, ids: list[int]) -> dict: 71 | """Retrieves an entity of CashBalanceLog type by its id.""" 72 | return await self.session.get(f"/cashBalanceLog/item?ids={','.join(str(id) for id in ids)}") 73 | 74 | async def cash_balance_log_L_dependents(self, master_ids: list[int]) -> dict: 75 | """Retrieves all entities of CashBalanceLog type related to multiple entities of Account type.""" 76 | return await self.session.get(f"/cashBalanceLog/ldeps?masterids={','.join([str(id) for id in master_ids])}") 77 | 78 | async def margin_snapshot_dependents(self, master_id: int) -> dict: 79 | """Retrieves all entities of MarginSnapshot type related to Account entity.""" 80 | return await self.session.get(f"/marginSnapshot/deps?masterid={master_id}") 81 | 82 | async def margin_snapshot_item(self, id: int) -> dict: 83 | """Retrieves an entity of MarginSnapshot type by its id.""" 84 | return await self.session.get(f"/marginSnapshot/item?id={id}") 85 | 86 | async def margin_snapshot_items(self, ids: list[int]) -> dict: 87 | """Retrieves multiple entities of MarginSnapshot type by its ids.""" 88 | return await self.session.get(f"/marginSnapshot/items?ids={','.join(str(id) for id in ids)}") 89 | 90 | async def margin_snapshot_L_dependents(self, master_ids: list[int]) -> dict: 91 | """Retrieves all entities of MarginSnapshot type related to multiple entities of Account type.""" 92 | return await self.session.get(f"/marginSnapshot/ldeps?masterids={','.join([str(id) for id in master_ids])}") 93 | 94 | async def margin_snapshot_list(self) -> dict: 95 | """Retrieves all entities of MarginSnapshot type.""" 96 | return await self.session.get("/marginSnapshot/list") 97 | 98 | async def permission_dependents(self, master_id: int) -> dict: 99 | """Retrieves all entities of TradingPermission type related to User entity.""" 100 | return await self.session.get(f"/tradingPermission/deps?masterid={master_id}") 101 | 102 | async def permission_item(self, id: int) -> dict: 103 | """Retrieves an entity of TradingPermission type by its id.""" 104 | return await self.session.get(f"/tradingPermission/item?id={id}") 105 | 106 | async def permission_items(self, ids: list[int]) -> dict: 107 | """Retrieves multiple entities of TradingPermission type by its ids.""" 108 | return await self.session.get(f"/tradingPermission/items?ids={','.join([str(id) for id in ids])}") 109 | 110 | async def permission_L_Dependents(self, master_ids: list[int]) -> dict: 111 | """Retrieves all entities of TradingPermission type related to multiple entities of User type.""" 112 | return await self.session.get(f"/tradingPermission/ldeps?masterids={','.join([str(id) for id in master_ids])}") 113 | 114 | async def permission_list(self) -> dict: 115 | """Retrieves all entities of TradingPermission type.""" 116 | return await self.session.get("/tradingPermission/list") 117 | -------------------------------------------------------------------------------- /TradovatePy/alerts.py: -------------------------------------------------------------------------------- 1 | class Alerts: 2 | """Class of methods related to alerts.""" 3 | 4 | def __init__(self, session) -> None: 5 | """Alerts constructor.""" 6 | self.session = session 7 | 8 | async def complete_alert_signal(self, admin_alert_signal_id: int) -> dict: 9 | """An "Incomplete" notification is one that has not yet been viewed by a user. 10 | Once a user has interacted with a notification it should be "completed".""" 11 | return await self.session.post( 12 | url="/adminAlertSignal/completealertsignal", 13 | payload={"adminAlertSignalId": admin_alert_signal_id}, 14 | ) 15 | 16 | async def admin_alert_signal_dependents(self, master_id: int) -> dict: 17 | """Retrieves all entities of AdminAlertSignal type related to AdminAlert entity.""" 18 | return await self.session.get(f"/adminAlertSignal/deps?master_id={master_id}") 19 | 20 | async def admin_alert_signal_item(self, id: int) -> dict: 21 | """Retrieves an entity of AdminAlertSignal type by its id.""" 22 | return await self.session.get(f"/adminAlertSignal/item?id={id}") 23 | 24 | async def admin_alert_signal_items(self, ids: list[int]) -> dict: 25 | """Retrieves multiple entities of AdminAlertSignal type by its ids.""" 26 | return await self.session.get(f"/adminAlertSignal/items?ids={','.join([str(id) for id in ids])}") 27 | 28 | async def admin_alert_signal_L_dependents(self, master_ids: list[int]) -> dict: 29 | """Retrieves all entities of AdminAlertSignal type related to multiple entities of AdminAlert type.""" 30 | return await self.session.get(f"/adminAlertSignal/ldeps?masterids={','.join([str(id) for id in master_ids])}") 31 | 32 | async def admin_alert_signal_list(self) -> dict: 33 | """Retrieves all entities of AdminAlertSignal type.""" 34 | return await self.session.get("/adminAlertSignal/list") 35 | 36 | async def take_alert_signal_ownership(self, admin_alert_signal_id: int) -> dict: 37 | """Internal. Can be used by B2B partners to mark an adminAlertSignal entity for further handling.""" 38 | return await self.session.post( 39 | url="/adminAlertSignal/takealertsignalownership", 40 | payload={"adminAlertSignalId": admin_alert_signal_id}, 41 | ) 42 | 43 | async def create_alert(self, 44 | expression: str, 45 | valid_until: str, 46 | trigger_limits: int, 47 | message: str) -> dict: 48 | """Create an alert entity associated with the user.""" 49 | return await self.session.post( 50 | url="/alert/createalert", 51 | payload={ 52 | "expression": expression, 53 | "validUntil": valid_until, 54 | "triggerLimits": trigger_limits, 55 | "message": message, 56 | }, 57 | ) 58 | 59 | async def delete_alert(self, alert_id: int) -> dict: 60 | """Remove an alert entity associated with the user.""" 61 | return await self.session.post( 62 | url="/alert/deletealert", 63 | payload={"alertId": alert_id}, 64 | ) 65 | 66 | async def alert_dependents(self, master_id: int) -> dict: 67 | """Retrieves all entities of Alert type related to User entity.""" 68 | return await self.session.get(f"/alert/deps?master_id={master_id}") 69 | 70 | async def dismiss_alert(self, alert_id: int) -> dict: 71 | """Dismiss an alert for a user.""" 72 | return await self.session.post( 73 | url="/alert/dismissalert", 74 | payload={"alertId": alert_id}, 75 | ) 76 | 77 | async def alert_item(self, id: int) -> dict: 78 | """Retrieves an entity of Alert type by its id.""" 79 | return await self.session.get(f"/alert/item?id={id}") 80 | 81 | async def alert_items(self, ids: list[int]) -> dict: 82 | """Retrieves multiple entities of Alert type by its ids.""" 83 | return await self.session.get(f"/alert/items?ids={','.join([str(id) for id in ids])}") 84 | 85 | async def alert_L_dependents(self, master_ids: list[int]) -> dict: 86 | """Retrieves all entities of Alert type related to multiple entities of User type.""" 87 | return await self.session.get(f"/alert/ldeps?masterids={','.join([str(id) for id in master_ids])}") 88 | 89 | async def alert_list(self) -> dict: 90 | """Retrieves all entities of Alert type.""" 91 | return await self.session.get("/alert/list") 92 | 93 | async def mark_read_alert_signal(self, alert_id: int, alert_signal_id: int) -> dict: 94 | """Mark an alert entity as 'read' for a user.""" 95 | return await self.session.post( 96 | url="/alert/markreadalertsignal", 97 | payload={ 98 | "alertId": alert_id, 99 | "alertSignalId": alert_signal_id, 100 | }, 101 | ) 102 | 103 | async def modify_alert(self, 104 | alert_id: int, 105 | expression: str, 106 | valid_until: str = None, 107 | trigger_limits: int = None, 108 | message: str = "") -> dict: 109 | """Change the parameters of an existing alert.""" 110 | payload = { 111 | "alertId": alert_id, 112 | "expression": expression, 113 | } 114 | if valid_until is not None: 115 | payload["validUntil"] = valid_until 116 | if trigger_limits is not None: 117 | payload["triggerLimits"] = trigger_limits 118 | if message is not None: 119 | payload["message"] = message 120 | 121 | return await self.session.post( 122 | url="/alert/modifyalert", 123 | payload=payload, 124 | ) 125 | 126 | async def reset_alert(self, alert_id: int) -> dict: 127 | """ 128 | Resets an alert. 129 | You can use this method after an alert has been triggered 130 | to keep the alert and wait for the alert to be triggered again. 131 | """ 132 | return await self.session.post( 133 | url="/alert/resetalert", 134 | payload={"alertId": alert_id}, 135 | ) 136 | 137 | async def alert_signal_dependents(self, master_id: int) -> dict: 138 | """Retrieves all entities of AlertSignal type related to Alert entity.""" 139 | return await self.session.get(f"/alertSignal/deps?masterid={master_id}") 140 | 141 | async def alert_signal_item(self, id: int) -> dict: 142 | """Retrieves an entity of AlertSignal type by its id.""" 143 | return await self.session.get(f"/alertSignal/item?id={id}") 144 | 145 | async def alert_signal_items(self, ids: list[int]) -> dict: 146 | """Retrieves multiple entities of AlertSignal type by its ids.""" 147 | return await self.session.get(f"/alertSignal/items?ids={','.join([str(id) for id in ids])}") 148 | 149 | async def alert_signal_L_dependents(self, master_ids: list[int]) -> dict: 150 | """Retrieves all entities of AlertSignal type related to multiple entities of Alert type.""" 151 | return await self.session.get(f"/alertSignal/ldeps?masterids={','.join([str(id) for id in master_ids])}") 152 | 153 | async def alert_signal_list(self) -> dict: 154 | """Retrieves all entities of AlertSignal type.""" 155 | return await self.session.get("/alertSignal/list") 156 | -------------------------------------------------------------------------------- /TradovatePy/contractLibrary.py: -------------------------------------------------------------------------------- 1 | class Contract_Library: 2 | def __init__(self, session) -> None: 3 | self.session = session 4 | 5 | async def conteract_dependents(self, master_id: int) -> dict: 6 | """Retrieves all entities of Contract type related to ContractMaturity entity.""" 7 | return await self.session.get(f"/contract/deps?masterid={master_id}") 8 | 9 | async def conteract_find(self, name: str) -> dict: 10 | """Retrieves an entity of Contract type by its name.""" 11 | return await self.session.get(f"/contract/find?name={name}") 12 | 13 | async def contract_item(self, id: int) -> dict: 14 | """Retrieves an entity of Contract type by its id.""" 15 | return await self.session.get(f"/contract/item?id={id}") 16 | 17 | async def contract_items(self, ids: list[int]) -> dict: 18 | """Retrieves multiple entities of Contract type by its ids.""" 19 | return await self.session.get(f"/contract/items?ids={','.join([str(id) for id in ids])}") 20 | 21 | async def product_fee_params(self, product_ids: list[int]) -> dict: 22 | """Query the a product's fee parameters.""" 23 | return await self.session.post( 24 | url="/contract/getproductfeeparams", 25 | payload={"productIds": [id for id in product_ids]}, 26 | ) 27 | 28 | async def contract_L_dependents(self, master_ids: list[int]) -> dict: 29 | """Retrieves all entities of Contract type related to multiple entities of ContractMaturity type.""" 30 | return await self.session.get(f"/contract/ldeps?masterids={','.join([str(id) for id in master_ids])}") 31 | 32 | async def roll_contract(self, name: str, forward: bool, ifExpired: bool) -> dict: 33 | """Request the best upcoming maturity date for a given contract.""" 34 | return await self.session.post( 35 | url="/contract/rollcontract", 36 | payload={ 37 | "name": name, 38 | "forward": forward, 39 | "ifExpired": ifExpired, 40 | }, 41 | ) 42 | 43 | async def contract_suggest(self, text: str, n_entities: int) -> dict: 44 | """Retrieves entities of Contract type filtered by an occurrence of a text in one of its fields.""" 45 | return await self.session.get(f"/contract/suggest?t={text}&l={n_entities}") 46 | 47 | async def contract_group_find(self, name: str) -> dict: 48 | """Retrieves an entity of ContractGroup type by its name.""" 49 | return await self.session.get(f"/contractGroup/find?name={name}") 50 | 51 | async def contract_group_item(self, id: int) -> dict: 52 | """Retrieves an entity of ContractGroup type by its id.""" 53 | return await self.session.get(f"/contractGroup/item?id={id}") 54 | 55 | async def contract_group_items(self, ids: list[int]) -> dict: 56 | """Retrieves multiple entities of ContractGroup type by its ids.""" 57 | return await self.session.get(f"/contractGroup/items?ids={','.join([str(id) for id in ids])}") 58 | 59 | async def contract_group_list(self) -> dict: 60 | """Retrieves all entities of ContractGroup type.""" 61 | return await self.session.get("/contractGroup/list") 62 | 63 | async def contract_group_suggest(self, text: str, n_entities: int) -> dict: 64 | """Retrieves entities of ContractGroup type filtered by an occurrence of a text in one of its fields.""" 65 | return await self.session.get(f"/contractGroup/suggest?t={text}&l={n_entities}") 66 | 67 | async def contract_maturity_dependents(self, master_id: int) -> dict: 68 | """Retrieves all entities of ContractMaturity type related to Product entity.""" 69 | return await self.session.get(f"/ContractMaturity/deps?master_id={master_id}") 70 | 71 | async def contract_maturity_item(self, id: int) -> dict: 72 | """Retrieves an entity of ContractMaturity type by its id.""" 73 | return await self.session.get(f"/ContractMaturity/item?id={id}") 74 | 75 | async def contract_maturity_items(self, ids: list[int]) -> dict: 76 | """Retrieves multiple entities of ContractMaturity type by its ids.""" 77 | return await self.session.get(f"/ContractMaturity/items?ids={','.join([str(id) for id in ids])}") 78 | 79 | async def contract_maturity_L_dependents(self, master_ids: list[int]) -> dict: 80 | """Retrieves all entities of ContractMaturity type related to multiple entities of Product type.""" 81 | return await self.session.get(f"/contractMaturity/ldeps?masterids={','.join([str(id) for id in master_ids])}") 82 | 83 | async def currency_find(self, name: str) -> dict: 84 | """Retrieves an entity of Currency type by its name.""" 85 | return await self.session.get(f"/currency/find?name={name}") 86 | 87 | async def currency_item(self, id: int) -> dict: 88 | """Retrieves an entity of Currency type by its id.""" 89 | return await self.session.get(f"/currency/item?id={id}") 90 | 91 | async def currency_items(self, ids: list[int]) -> dict: 92 | """Retrieves multiple entities of Currency type by its ids.""" 93 | return await self.session.get(f"/currency/items?ids={','.join([str(id) for id in ids])}") 94 | 95 | async def currency_list(self) -> dict: 96 | """Retrieves all entities of Currency type.""" 97 | return await self.session.get("/currency/list") 98 | 99 | async def currency_suggest(self, text: str, n_entities: int) -> dict: 100 | """Retrieves entities of Currency type filtered by an occurrence of a text in one of its fields.""" 101 | return await self.session.get(f"/currency/suggest?t={text}&l={n_entities}") 102 | 103 | async def currency_rate_dependents(self, master_id: int) -> dict: 104 | """Retrieves all entities of CurrencyRate type related to Currency entity.""" 105 | return await self.session.get(f"/currencyRate/deps?masterid={master_id}") 106 | 107 | async def currency_rate_item(self, id: int) -> dict: 108 | """Retrieves an entity of CurrencyRate type by its id.""" 109 | return await self.session.get(f"/currencyRate/item?id={id}") 110 | 111 | async def currency_rate_items(self, ids: list[int]) -> dict: 112 | """Retrieves multiple entities of CurrencyRate type by its ids.""" 113 | return await self.session.get(f"/currencyRate/items?ids={','.join([str(id) for id in ids])}") 114 | 115 | async def currency_rate_L_dependents(self, master_ids: list[int]) -> dict: 116 | """Retrieves all entities of CurrencyRate type related to multiple entities of Currency type.""" 117 | return await self.session.get(f"/currencyRate/ldeps?masterids={','.join([str(id) for id in master_ids])}") 118 | 119 | async def currency_rate_list(self) -> dict: 120 | """Retrieves all entities of CurrencyRate type.""" 121 | return await self.session.get("/currencyRate/list") 122 | 123 | async def exchange_find(self, name: str) -> dict: 124 | """Retrieves an entity of Exchange type by its name.""" 125 | return await self.session.get(f"/exchange/find?name={name}") 126 | 127 | async def exchange_item(self, id: int) -> dict: 128 | """Retrieves an entity of Exchange type by its id.""" 129 | return await self.session.get(f"/exchange/item?id={id}") 130 | 131 | async def exchange_items(self, ids: list[int]) -> dict: 132 | """Retrieves multiple entities of Exchange type by its ids.""" 133 | return await self.session.get(f"/exchange/items?ids={','.join([str(id) for id in ids])}") 134 | 135 | async def exchange_list(self) -> dict: 136 | """Retrieves all entities of Exchange type.""" 137 | return await self.session.get("/exchange/list") 138 | 139 | async def exchange_suggest(self, text: str, n_entities: int) -> dict: 140 | """Retrieves entities of Exchange type filtered by an occurrence of a text in one of its fields.""" 141 | return await self.session.get(f"/exchange/suggest?t={text}&l={n_entities}") 142 | 143 | async def product_dependents(self, master_id: int) -> dict: 144 | """Retrieves all entities of Product type related to Exchange entity.""" 145 | return await self.session.get(f"/product/deps?masterid={master_id}") 146 | 147 | async def product_find(self, name: str) -> dict: 148 | """Retrieves an entity of Product type by its name.""" 149 | return await self.session.get(f"/product/find?name={name}") 150 | 151 | async def product_item(self, id: int) -> dict: 152 | """Retrieves an entity of Product type by its id.""" 153 | return await self.session.get(f"/product/id={id}") 154 | 155 | async def product_items(self, ids: list[int]) -> dict: 156 | """Retrieves multiple entities of Product type by its ids.""" 157 | return await self.session.get(f"/product/items?ids={','.join(str(id) for id in ids)}") 158 | 159 | async def product_L_dependents(self, master_ids: list[int]) -> dict: 160 | """Retrieves all entities of Product type related to multiple entities of Exchange type.""" 161 | return await self.session.get(f"/product/ldeps?masterid={','.join([str(id) for id in master_ids])}") 162 | 163 | async def product_list(self) -> dict: 164 | """Retrieves all entities of Product type.""" 165 | return await self.session.get("/product/list") 166 | 167 | async def product_suggest(self, text: str, n_entities: int) -> dict: 168 | """Retrieves entities of Product type filtered by an occurrence of a text in one of its fields.""" 169 | return await self.session.get(f"/product/suggest?t={text}&l={n_entities}") 170 | 171 | async def product_sess_dependents(self, master_id: int) -> dict: 172 | """Retrieves all entities of ProductSession type related to Product entity.""" 173 | return await self.session.get(f"/productSession/deps?masterid={master_id}") 174 | 175 | async def product_sess_item(self, id: int) -> dict: 176 | """Retrieves an entity of ProductSession type by its id.""" 177 | return await self.session.get(f"/productSession/item?id={id}") 178 | 179 | async def product_session_items(self, ids: list[int]) -> dict: 180 | """Retrieves multiple entities of ProductSession type by its ids.""" 181 | return await self.session.get(f"/productSession/items?ids={','.join([str(id) for id in ids])}") 182 | 183 | async def product_session_L_dependents(self, master_ids: list[int]) -> dict: 184 | """Retrieves all entities of ProductSession type related to multiple entities of Product type.""" 185 | return await self.session.get(f"/productSession/ldeps?masterids={','.join([str(id) for id in master_ids])}") 186 | 187 | async def spread_definition_item(self, id: int) -> dict: 188 | """Retrieves an entity of SpreadDefinition type by its id.""" 189 | return await self.session.get(f"/SpreadDefinition/item?id={id}") 190 | 191 | async def spread_definition_items(self, ids: list[int]) -> dict: 192 | """Retrieves multiple entities of SpreadDefinition type by its ids.""" 193 | return await self.session.get(f"/SpreadDefinition/items?ids={','.join([str(id) for id in ids])}") 194 | -------------------------------------------------------------------------------- /TradovatePy/risks.py: -------------------------------------------------------------------------------- 1 | class Risk: 2 | """Class of methods related to risk.""" 3 | 4 | def __init__(self, session) -> None: 5 | """Risk constructor.""" 6 | self.session = session 7 | 8 | async def account_risk_status_dependents(self, master_id: int) -> dict: 9 | """Retrieves all entities of AccountRiskStatus type related to Account entity.""" 10 | return await self.session.get(f"/accountRiskStatus/deps?masterid={master_id}") 11 | 12 | async def account_risk_status_item(self, id: int) -> dict: 13 | """Retrieves an entity of AccountRiskStatus type by its id.""" 14 | return await self.session.get(f"/accountRiskStatus/id={id}") 15 | 16 | async def account_risk_status_items(self, ids: list[int]) -> dict: 17 | """Retrieves multiple entities of AccountRiskStatus type by its ids.""" 18 | return await self.session.get(f"/accountRiskStatus/items?ids={','.join([str(id) for id in ids])}") 19 | 20 | async def account_risk_status_L_dependents(self, master_ids: list[int]) -> dict: 21 | """Retrieves all entities of AccountRiskStatus type related to multiple entities of Account type.""" 22 | return await self.session.get(f"/accountRiskStatus/ldeps?masterids={''.join([str(id) for id in master_ids])}") 23 | 24 | async def account_risk_status_list(self) -> dict: 25 | """Retrieves all entities of AccountRiskStatus type.""" 26 | return await self.session.get("/accountRiskStatus/list") 27 | 28 | async def contract_margin_dependents(self, master_id: int) -> dict: 29 | """Retrieves all entities of ContractMargin type related to Contract entity.""" 30 | return await self.session.get(f"/contractMargin/deps?masterid={master_id}") 31 | 32 | async def contract_margin_item(self, id: int) -> dict: 33 | """Retrieves an entity of ContractMargin type by its id.""" 34 | return await self.session.get(f"/contractMargin/item?id={id}") 35 | 36 | async def contract_margin_items(self, ids: list[int]) -> dict: 37 | """Retrieves multiple entities of ContractMargin type by its ids.""" 38 | return await self.session.get(f"/contractMargin/items?ids={','.join([str(id) for id in ids])}") 39 | 40 | async def contract_margin_L_dependents(self, master_ids: list[int]) -> dict: 41 | """Retrieves all entities of ContractMargin type related to multiple entities of Contract type.""" 42 | return await self.session.get(f"/contractMargin/ldeps?masterids={','.join([str(id) for id in master_ids])}") 43 | 44 | async def product_margin_dependents(self, master_id: int) -> dict: 45 | """Retrieves all entities of ProductMargin type related to Product entity.""" 46 | return await self.session.get(f"/productMargin/deps?masterid={master_id}") 47 | 48 | async def product_margin_item(self, id: int) -> dict: 49 | """Retrieves an entity of ProductMargin type by its id.""" 50 | return await self.session.get(f"/productMargin/item?id={id}") 51 | 52 | async def product_margin_items(self, ids: list[int]) -> dict: 53 | """Retrieves multiple entities of ProductMargin type by its ids.""" 54 | return await self.session.get(f"/productMargin/items?ids={','.join([str(id) for id in ids])}") 55 | 56 | async def product_margin_L_dependents(self, master_ids: list[int]) -> dict: 57 | """Retrieves all entities of ProductMargin type related to multiple entities of Product type.""" 58 | return await self.session.get(f"/productMargin/ldeps?masterids={master_ids}") 59 | 60 | async def product_margin_list(self) -> dict: 61 | """Retrieves all entities of ProductMargin type.""" 62 | return await self.session.get("/productMargin/list") 63 | 64 | async def user_account_auto_liq_create(self, 65 | id: int, 66 | changes_locked: bool, 67 | margin_percent_alert: int, 68 | daily_loss_percent_alert: int, 69 | daily_loss_alert: int, 70 | margin_percent_liq_only: int, 71 | daily_loss_percent_liq_only: int, 72 | daily_loss_liq_only: int, 73 | margin_percent_auto_liq: int, 74 | daily_loss_percent_auto_liq: int, 75 | daily_loss_auto_liq: int, 76 | weekly_loss_auto_liq: int, 77 | flatten_timestamp: str, 78 | trailing_max_drawdown: int, 79 | trailing_max_drawdown_limit: int, 80 | daily_profit_auto_liq: int, 81 | weekly_profit_auto_liq: int) -> dict: 82 | """Creates a new entity of UserAccountAutoLiq.""" 83 | return await self.session.post( 84 | url="/userAccountAutoLiq/create", 85 | payload={ 86 | "id": id, 87 | "changesLocked": changes_locked, 88 | "marginPercentageAlert": margin_percent_alert, 89 | "dailyLossPercentageAlert": daily_loss_percent_alert, 90 | "dailyLossAlert": daily_loss_alert, 91 | "marginPercentageLiqOnly": margin_percent_liq_only, 92 | "dailyLossPercentageLiqOnly": daily_loss_percent_liq_only, 93 | "dailyLossLiqOnly": daily_loss_liq_only, 94 | "marginPercentageAutoLiq": margin_percent_auto_liq, 95 | "dailyLossPercentageAutoLiq": daily_loss_percent_auto_liq, 96 | "dailyLossAutoLiq": daily_loss_auto_liq, 97 | "weeklyLossAutoLiq": weekly_loss_auto_liq, 98 | "flattenTimestamp": flatten_timestamp, 99 | "trailingMaxDrawdown": trailing_max_drawdown, 100 | "trailingMaxDrawdownLimit": trailing_max_drawdown_limit, 101 | "dailyProfitAutoLiq": daily_profit_auto_liq, 102 | "weeklyProfitAutoLiq": weekly_profit_auto_liq, 103 | }, 104 | ) 105 | 106 | async def user_account_auto_liq_dependents(self, master_id: int) -> dict: 107 | """Retrieves all entities of UserAccountAutoLiq type related to Account entity.""" 108 | return await self.session.get(f"/userAccountAutoLiq/deps?masterid={master_id}") 109 | 110 | async def user_account_auto_liq_item(self, id: int) -> dict: 111 | """Retrieves an entity of UserAccountAutoLiq type by its id.""" 112 | return await self.session.get(f"/userAccountAutoLiq/item?id={id}") 113 | 114 | async def user_account_auto_liq_items(self, ids: list[int]) -> dict: 115 | """Retrieves multiple entities of UserAccountAutoLiq type by its ids.""" 116 | return await self.session.get(f"/userAccountAutoLiq/item?ids={','.join([str(id) for id in ids])}") 117 | 118 | async def user_account_auto_liq_L_dependents(self, master_ids: list[int]) -> dict: 119 | """Retrieves all entities of UserAccountAutoLiq type related to multiple entities of Account type.""" 120 | return await self.session.get(f"/userAccountAutoLiq/deps?masterid={','.join([str(id) for id in master_ids])}") 121 | 122 | async def user_account_auto_liq_list(self) -> dict: 123 | """Retrieves all entities of UserAccountAutoLiq type.""" 124 | return await self.session.get("/userAccountAutoLiq/list") 125 | 126 | async def user_account_auto_liq_update(self, 127 | id: int, 128 | changes_locked: bool, 129 | margin_percent_alert: int, 130 | daily_loss_percent_alert: int, 131 | daily_loss_alert: int, 132 | margin_percent_liq_only: int, 133 | daily_loss_percent_liq_only: int, 134 | daily_loss_liq_only: int, 135 | margin_percent_auto_liq: int, 136 | daily_loss_percent_auto_liq: int, 137 | daily_loss_auto_liq: int, 138 | weekly_loss_auto_liq: int, 139 | flatten_timestamp: str, 140 | trailing_max_drawdown: int, 141 | trailing_max_drawdown_limit: int, 142 | daily_profit_auto_liq: int, 143 | weekly_profit_auto_liq: int) -> dict: 144 | """Updates an existing entity of UserAccountAutoLiq.""" 145 | return await self.session.post( 146 | url="/userAccountAutoLiq/update", 147 | payload={ 148 | "id": id, 149 | "changesLocked": changes_locked, 150 | "marginPercentageAlert": margin_percent_alert, 151 | "dailyLossPercentageAlert": daily_loss_percent_alert, 152 | "dailyLossAlert": daily_loss_alert, 153 | "marginPercentageLiqOnly": margin_percent_liq_only, 154 | "dailyLossPercentageLiqOnly": daily_loss_percent_liq_only, 155 | "dailyLossLiqOnly": daily_loss_liq_only, 156 | "marginPercentageAutoLiq": margin_percent_auto_liq, 157 | "dailyLossPercentageAutoLiq": daily_loss_percent_auto_liq, 158 | "dailyLossAutoLiq": daily_loss_auto_liq, 159 | "weeklyLossAutoLiq": weekly_loss_auto_liq, 160 | "flattenTimestamp": flatten_timestamp, 161 | "trailingMaxDrawdown": trailing_max_drawdown, 162 | "trailingMaxDrawdownLimit": trailing_max_drawdown_limit, 163 | "dailyProfitAutoLiq": daily_profit_auto_liq, 164 | "weeklyProfitAutoLiq": weekly_profit_auto_liq, 165 | }, 166 | ) 167 | 168 | async def user_account_positions_limit(self, 169 | account_id: int, 170 | active: bool, 171 | total_by: str, 172 | id: int = None, 173 | contract_id: int = None, 174 | product_id: int = None, 175 | exchange_id: int = None, 176 | product_type: str = None, 177 | risk_discount_contract_group_id: int = None, 178 | product_verification_status: str = None, 179 | contract_group_id: int = None, 180 | risk_time_period_id: int = None, 181 | short_limit: int = None, 182 | long_limit: int = None, 183 | exposed_limit: int = None, 184 | description: str = None) -> dict: 185 | """Creates a new entity of UserAccountPositionLimit.""" 186 | return await self.session.post( 187 | url="/userAccountPositionLimit/create", 188 | payload={ 189 | "id": id, 190 | "contractId": contract_id, 191 | "productId": product_id, 192 | "exchangeId": exchange_id, 193 | "productType": product_type, 194 | "riskDiscountContractGroupId": risk_discount_contract_group_id, 195 | "productVerificationStatus": product_verification_status, 196 | "contractGroupId": contract_group_id, 197 | "active": active, 198 | "riskTimePeriodId": risk_time_period_id, 199 | "totalBy": total_by, 200 | "shortLimit": short_limit, 201 | "longLimit": long_limit, 202 | "exposedLimit": exposed_limit, 203 | "description": description, 204 | "accountId": account_id, 205 | }, 206 | ) 207 | 208 | async def delete_user_account_position_limit(self, user_position_limit_id: int) -> dict: 209 | """Remove an account position limit for a user.""" 210 | return await self.session.post( 211 | url="/userAccountPositionLimit/deleteuseraccountpositionlimit", 212 | payload={"userAccountPositionLimitId": user_position_limit_id}, 213 | ) 214 | 215 | async def delete_user_account_risk_parameter(self, user_account_risk_parameter_id: int) -> dict: 216 | """Remove a Risk Setting parameter.""" 217 | return await self.session.post( 218 | url="/userAccountPositionLimit/deleteuseraccountriskparameter", 219 | payload={"userAccountRiskParameterId": user_account_risk_parameter_id}, 220 | ) 221 | 222 | async def user_account_position_limit_dependents(self, master_id: int) -> dict: 223 | """Retrieves all entities of UserAccountPositionLimit type related to Account entity.""" 224 | return await self.session.get(f"/userAccountPositionLimit/deps?masterid={master_id}") 225 | 226 | async def user_account_position_limit_item(self, id: int) -> dict: 227 | """Retrieves an entity of UserAccountPositionLimit type by its id.""" 228 | return await self.session.get(f"/userAccountPositionLimit/item?id={id}") 229 | 230 | async def user_account_position_limit_items(self, ids: list[int]) -> dict: 231 | """Retrieves multiple entities of UserAccountPositionLimit type by its ids.""" 232 | return await self.session.get(f"/userAccountPositionLimit/item?id={','.join([str(id) for id in ids])}") 233 | 234 | async def user_account_position_limit_L_dependents(self, master_ids: list[int]) -> dict: 235 | """Retrieves all entities of UserAccountPositionLimit type related to multiple entities of Account type.""" 236 | return await self.session.get(f"/userAccountPositionLimit/ldeps?masterids={','.join([str(id) for id in master_ids])}") 237 | 238 | async def user_account_position_limit_update(self, 239 | account_id: int, 240 | active: bool, 241 | total_by: str, 242 | id: int = None, 243 | contract_id: int = None, 244 | product_id: int = None, 245 | exchange_id: int = None, 246 | product_type: str = None, 247 | risk_discount_contract_group_id: int = None, 248 | product_verification_status: str = None, 249 | contract_group_id: int = None, 250 | risk_time_period_id: int = None, 251 | short_limit: int = None, 252 | long_limit: int = None, 253 | exposed_limit: int = None, 254 | description: str = None) -> dict: 255 | """Updates an existing entity of UserAccountPositionLimit.""" 256 | return await self.session.post( 257 | url="/userAccountPositionLimit/update", 258 | payload={ 259 | "id": id, 260 | "contractId": contract_id, 261 | "productId": product_id, 262 | "exchangeId": exchange_id, 263 | "productType": product_type, 264 | "riskDiscountContractGroupId": risk_discount_contract_group_id, 265 | "productVerificationStatus": product_verification_status, 266 | "contractGroupId": contract_group_id, 267 | "active": active, 268 | "riskTimePeriodId": risk_time_period_id, 269 | "totalBy": total_by, 270 | "shortLimit": short_limit, 271 | "longLimit": long_limit, 272 | "exposedLimit": exposed_limit, 273 | "description": description, 274 | "accountId": account_id, 275 | }, 276 | ) 277 | 278 | async def user_account_risk_parameter_create(self, 279 | user_account_position_limit_id: int, 280 | id: int = None, 281 | contract_id: int = None, 282 | product_id: int = None, 283 | exchange_id: int = None, 284 | product_type: str = None, 285 | risk_discount_contract_group_id: int = None, 286 | product_verification_status: str = None, 287 | contract_group_id: int = None, 288 | max_opening_order_qty: int = None, 289 | max_closing_order_qty: int = None, 290 | max_back_month: int = None, 291 | pre_expiration_days: int = None, 292 | margin_percentage: int = None, 293 | margin_dollar_value: int = None, 294 | hard_limit: bool = None) -> dict: 295 | """Creates a new entity of UserAccountRiskParameter.""" 296 | return await self.session.post( 297 | url="/userAccountRiskParameter/create", 298 | payload={ 299 | "id": id, 300 | "contractId": contract_id, 301 | "productId": product_id, 302 | "exchangeId": exchange_id, 303 | "productType": product_type, 304 | "riskDiscountContractGroupId": risk_discount_contract_group_id, 305 | "productVerificationStatus": product_verification_status, 306 | "contractGroupId": contract_group_id, 307 | "maxOpeningOrderQty": max_opening_order_qty, 308 | "maxClosingOrderQty": max_closing_order_qty, 309 | "maxBackMonth": max_back_month, 310 | "preExpirationDays": pre_expiration_days, 311 | "marginPercentage": margin_percentage, 312 | "marginDollarValue": margin_dollar_value, 313 | "hardLimit": hard_limit, 314 | "userAccountPositionLimitId": user_account_position_limit_id, 315 | }, 316 | ) 317 | 318 | async def user_account_risk_parameter_dependents(self, master_id: int) -> dict: 319 | """Retrieves all entities of UserAccountRiskParameter type related to UserAccountPositionLimit entity.""" 320 | return await self.session.get(f"/userAccountRiskParameter/deps?masterid={master_id}") 321 | 322 | async def user_account_risk_parameter_item(self, id: int) -> dict: 323 | """Retrieves an entity of UserAccountRiskParameter type by its id.""" 324 | return await self.session.get(f"/userAccountRiskParameter/item?id={id}") 325 | 326 | async def user_account_risk_parameter_items(self, ids: list[int]) -> dict: 327 | """Retrieves multiple entities of UserAccountRiskParameter type by its ids.""" 328 | return await self.session.get( 329 | f"/userAccountRiskParameter/item?id={','.join([str(id) for id in ids])}", 330 | ) 331 | 332 | async def user_account_risk_parameter_L_dependents(self, master_ids: list[int]) -> dict: 333 | """ 334 | Retrieves all entities of UserAccountRiskParameter type related to multiple entities of 335 | UserAccountPositionLimit type. 336 | """ 337 | return await self.session.get( 338 | f"/userAccountRiskParameter/ldeps?masterids={','.join([str(id) for id in master_ids])}", 339 | ) 340 | 341 | async def user_account_risk_parameter_update(self, 342 | user_account_position_limit_id: int, 343 | id: int = None, 344 | contract_id: int = None, 345 | product_id: int = None, 346 | exchange_id: int = None, 347 | product_type: str = None, 348 | risk_discount_contract_group_id: int = None, 349 | product_verification_status: str = None, 350 | contract_group_id: int = None, 351 | max_opening_order_qty: int = None, 352 | max_closing_order_qty: int = None, 353 | max_back_month: int = None, 354 | pre_expiration_days: int = None, 355 | margin_percentage: int = None, 356 | margin_dollar_value: int = None, 357 | hard_limit: bool = None) -> dict: 358 | """Updates an existing entity of UserAccountRiskParameter.""" 359 | return await self.session.post( 360 | url="/userAccountRiskParameter/update", 361 | payload={ 362 | "id": id, 363 | "contractId": contract_id, 364 | "productId": product_id, 365 | "exchangeId": exchange_id, 366 | "productType": product_type, 367 | "riskDiscountContractGroupId": risk_discount_contract_group_id, 368 | "productVerificationStatus": product_verification_status, 369 | "contractGroupId": contract_group_id, 370 | "maxOpeningOrderQty": max_opening_order_qty, 371 | "maxClosingOrderQty": max_closing_order_qty, 372 | "maxBackMonth": max_back_month, 373 | "preExpirationDays": pre_expiration_days, 374 | "marginPercentage": margin_percentage, 375 | "marginDollarValue": margin_dollar_value, 376 | "hardLimit": hard_limit, 377 | "userAccountPositionLimitId": user_account_position_limit_id, 378 | }, 379 | ) 380 | -------------------------------------------------------------------------------- /TradovatePy/orders.py: -------------------------------------------------------------------------------- 1 | class Orders: 2 | """Class of methods related to orders.""" 3 | 4 | def __init__(self, session) -> None: 5 | self.session = session 6 | 7 | async def command_dependents(self, master_id: int) -> dict: 8 | """Retrieves all entities of Command type related to Order entity.""" 9 | return await self.session.get(f"/command/deps?masterid={master_id}") 10 | 11 | async def command_item(self, id: int) -> dict: 12 | """Retrieves an entity of Command type by its id.""" 13 | return await self.session.get(f"/command/item?id={id}") 14 | 15 | async def command_items(self, ids: list[int]) -> dict: 16 | """Retrieves multiple entities of Command type by its ids.""" 17 | return await self.session.get( 18 | f"/command/items?ids={','.join([str(id) for id in ids])}", 19 | ) 20 | 21 | async def command_L_dependents(self, master_ids: list[int]) -> dict: 22 | """Retrieves all entities of Command type related to multiple entities of Order type.""" 23 | return await self.session.get( 24 | f"/command/ldeps?masterids={','.join([str(id) for id in master_ids])}", 25 | ) 26 | 27 | async def command_list(self) -> dict: 28 | """Retrieves all entities of Command type.""" 29 | return await self.session.get("/command/list") 30 | 31 | async def command_report_dependents(self, master_id: int) -> dict: 32 | """Retrieves all entities of CommandReport type related to Command entity.""" 33 | return await self.session.get(f"/commandReport/deps?masterid={master_id}") 34 | 35 | async def command_report_item(self, id: int) -> dict: 36 | """Retrieves an entity of CommandReport type by its id.""" 37 | return await self.session.get(f"/commandReport/item?id={id}") 38 | 39 | async def command_report_items(self, ids: list[int]) -> dict: 40 | """Retrieves multiple entities of CommandReport type by its ids.""" 41 | return await self.session.get( 42 | f"/commandReport/items?ids={','.join([str(id) for id in ids])}", 43 | ) 44 | 45 | async def command_report_L_dependents(self, master_ids: list[int]) -> dict: 46 | """Retrieves all entities of CommandReport type related to multiple entities of Command type.""" 47 | return await self.session.get( 48 | f"/commandReport/ldeps?masterids={','.join([str(id) for id in master_ids])}", 49 | ) 50 | 51 | async def command_report_list(self) -> dict: 52 | """Retrieves all entities of CommandReport type.""" 53 | return await self.session.get("/commandReport/list") 54 | 55 | async def execution_report_dependents(self, master_id: int) -> dict: 56 | """Retrieves all entities of ExecutionReport type related to Command entity.""" 57 | return await self.session.get(f"/executionReport/deps?masterid={master_id}") 58 | 59 | async def execution_report_find(self, name: str) -> dict: 60 | """Retrieves an entity of ExecutionReport type by its name.""" 61 | return await self.session.get(f"/executionReport/find?name={name}") 62 | 63 | async def execution_report_item(self, id: int) -> dict: 64 | """Retrieves an entity of ExecutionReport type by its id.""" 65 | return await self.session.get(f"/executionReport/item?id={id}") 66 | 67 | async def execution_report_items(self, ids: list[int]) -> dict: 68 | """Retrieves multiple entities of ExecutionReport type by its ids.""" 69 | return await self.session.get( 70 | f"/executionReport/items?ids={','.join([str(id) for id in ids])}", 71 | ) 72 | 73 | async def execution_report_L_dependents(self, master_ids: list[int]) -> dict: 74 | """Retrieves all entities of ExecutionReport type related to multiple entities of Command type.""" 75 | return await self.session.get( 76 | f"/executionReport/ldeps?masterids={','.join([str(id) for id in master_ids])}", 77 | ) 78 | 79 | async def execution_report_list(self) -> dict: 80 | """Retrieves all entities of ExecutionReport type.""" 81 | return await self.session.get("/executionReport/list") 82 | 83 | async def execution_report_suggest(self, text: str, n_entities: int) -> dict: 84 | """Retrieves entities of ExecutionReport type filtered by an occurrence of a text in one of its fields.""" 85 | return await self.session.get(f"/executionReport/suggest?t={text}&l={n_entities}") 86 | 87 | async def fill_dependents(self, master_id: int) -> dict: 88 | """Retrieves all entities of Fill type related to Order entity.""" 89 | return await self.session.get(f"/fill/deps?masterid={master_id}") 90 | 91 | async def fill_item(self, id: int) -> dict: 92 | """Retrieves an entity of Fill type by its id.""" 93 | return await self.session.get(f"/fill/item?id={id}") 94 | 95 | async def fill_items(self, ids: list[int]) -> dict: 96 | """Retrieves multiple entities of Fill type by its ids.""" 97 | return await self.session.get( 98 | f"/fill/items?ids={','.join([str(id) for id in ids])}", 99 | ) 100 | 101 | async def fill_L_dependents(self, master_ids: list[int]) -> dict: 102 | """Retrieves all entities of Fill type related to multiple entities of Order type.""" 103 | return await self.session.get( 104 | f"/fill/ldeps?masterids={','.join([str(id) for id in master_ids])}", 105 | ) 106 | 107 | async def fill_list(self) -> dict: 108 | """Retrieves all entities of Fill type.""" 109 | return await self.session.get("/fill/list") 110 | 111 | async def fill_fee_dependent(self, master_id: int) -> dict: 112 | """Retrieves all entities of FillFee type related to Fill entity.""" 113 | return await self.session.get(f"/fillFee/deps?masterid={master_id}") 114 | 115 | async def fill_fee_item(self, id: int) -> dict: 116 | """Retrieves an entity of FillFee type by its id.""" 117 | return await self.session.get(f"/fillFee/item?id={id}") 118 | 119 | async def fill_fee_items(self, ids: list[int]) -> dict: 120 | """Retrieves multiple entities of FillFee type by its ids.""" 121 | return await self.session.get( 122 | f"/fillFee/items?ids={','.join([str(id) for id in ids])}", 123 | ) 124 | 125 | async def fill_fee_L_dependents(self, master_ids: list[int]) -> dict: 126 | """Retrieves all entities of FillFee type related to multiple entities of Fill type.""" 127 | return await self.session.get( 128 | f"/fillFee/ldeps?masterids={','.join([str(id) for id in master_ids])}", 129 | ) 130 | 131 | async def fill_fee_list(self) -> dict: 132 | """Retrieves all entities of FillFee type.""" 133 | return self.session.get("/fillFee/list") 134 | 135 | async def cancel_order(self, 136 | order_id: int, 137 | cl_ord_id: str = None, 138 | activation_time: str = None, 139 | custom_tag_50: str = None, 140 | is_automated: bool = None) -> dict: 141 | """Make a request to cancel an order.""" 142 | return await self.session.post( 143 | url="/order/cancelorder", 144 | payload={ 145 | "orderId": order_id, 146 | "clOrdId": cl_ord_id, 147 | "activationTime": activation_time, 148 | "customTag50": custom_tag_50, 149 | "isAutomated": is_automated, 150 | }, 151 | ) 152 | 153 | async def order_dependents(self, master_id: int) -> dict: 154 | """Retrieves all entities of Order type related to Account entity.""" 155 | return await self.session.get(f"/order/deps?masterid={master_id}") 156 | 157 | async def order_item(self, id: int) -> dict: 158 | """Retrieves an entity of Order type by its id.""" 159 | return await self.session.get(f"/order/item?id={id}") 160 | 161 | async def order_items(self, ids: list[int]) -> dict: 162 | """Retrieves multiple entities of Order type by its ids.""" 163 | return await self.session.get( 164 | f"/order/items?ids={','.join([str(id) for id in ids])}", 165 | ) 166 | 167 | async def order_L_dependents(self, master_ids: list[int]) -> dict: 168 | """Retrieves all entities of Order type related to multiple entities of Account type.""" 169 | return await self.session.get( 170 | f"/order/ldeps?masterids={','.join([str(id) for id in master_ids])}", 171 | ) 172 | 173 | async def liquidate_position(self, 174 | account_id: int, 175 | contract_id: int, 176 | admin: bool, 177 | custom_tag_50: str = None) -> dict: 178 | """ 179 | Send a request to cancel orders for a specific contract and close that position for the given account. 180 | This request initiates the cancellation process of open orders for an existing position held by this account. 181 | 182 | Note: This is a request to cancel orders and close a position, not a guarantee. 183 | Any operation could fail for a number of reasons, ranging from Exchange 184 | rejection to incorrect parameterization. 185 | """ 186 | return await self.session.post( 187 | url="/order/liquidateposition", 188 | payload={ 189 | "accountId": account_id, "contractId": contract_id, 190 | "admin": admin, "customTag50": custom_tag_50, 191 | }, 192 | ) 193 | 194 | async def order_list(self) -> dict: 195 | """Retrieves all entities of Order type.""" 196 | return await self.session.get("/order/limit") 197 | 198 | async def modify_order(self, 199 | order_id: int, 200 | order_qty: int, 201 | order_type: str, 202 | cl_ord_id: str = None, 203 | price: float = None, 204 | stop_price: float = None, 205 | max_show: int = None, 206 | peg_difference: float = None, 207 | time_in_force: str = None, 208 | expire_time: str = None, 209 | text: str = None, 210 | activation_time: str = None, 211 | custom_tag_50: str = None, 212 | is_automated: bool = None) -> dict: 213 | """ 214 | Make a request to modify the parameters of an order. 215 | You can request changes to an order, such as the trigger price for a Stop or Limit order. 216 | 217 | Note: This is no guarantee that the order can be modified in a given way. 218 | Market and exchange rules apply. 219 | """ 220 | return await self.session.post( 221 | url="/order/modifyorder", 222 | payload={ 223 | "orderId": order_id, "clOrdId": cl_ord_id, 224 | "orderQty": order_qty, "orderType": order_type, 225 | "price": price, "stopPrice": stop_price, 226 | "maxShow": max_show, "pegDifference": peg_difference, 227 | "timeInForce": time_in_force, "expireTime": expire_time, 228 | "text": text, "activationTime": activation_time, 229 | "customTag50": custom_tag_50, "isAutomated": is_automated, 230 | }, 231 | ) 232 | 233 | async def place_OCO(self, 234 | action: str, 235 | symbol: str, 236 | order_qty: int, 237 | order_type: str, 238 | other_action: str, 239 | other_order_type: str, 240 | account_spec: str = None, 241 | account_id: int = None, 242 | cl_ord_id: str = None, 243 | price: float = None, 244 | stop_price: float = None, 245 | max_show: int = None, 246 | peg_difference: float = None, 247 | time_in_force: str = None, 248 | expire_time: str = None, 249 | text: str = None, 250 | activation_time: str = None, 251 | custom_tag_50: str = None, 252 | is_automated: bool = None, 253 | other_cl_ord_id: str = None, 254 | other_price: float = None, 255 | other_stop_price: float = None, 256 | other_max_show: int = None, 257 | other_peg_difference: float = None, 258 | other_time_in_force: str = None, 259 | other_expire_time: str = None, 260 | other_text: str = None) -> dict: 261 | """ 262 | Place a Order Cancels Order order strategy. 263 | 264 | OCO order strategies link 2 orders together such that if one order is filled, 265 | the other order is cancelled. You must provide an other parameter pertaining 266 | to the order linked to this one. The other must specify an action and an orderType 267 | which determines the other parameters that must be set. For example a Limit or Stop 268 | order must use the price parameter, but a Stop-Limit will require a price and a stopPrice. 269 | """ 270 | return await self.session.post( 271 | url="/order/placeoco", 272 | payload={ 273 | "accountSpec": account_spec, "accountId": account_id, "clOrdId": cl_ord_id, 274 | "action": action, "symbol": symbol, "orderQty": order_qty, "orderType": order_type, 275 | "price": price, "stopPrice": stop_price, "maxShow": max_show, "pegDifference": peg_difference, 276 | "timeInForce": time_in_force, "expireTime": expire_time, "text": text, "activationTime": activation_time, 277 | "customTag50": custom_tag_50, "isAutomated": is_automated, 278 | "other": { 279 | "action": other_action, "clOrdId": other_cl_ord_id, "orderType": other_order_type, 280 | "price": other_price, "stopPrice": other_stop_price, "maxShow": other_max_show, 281 | "pegDifference": other_peg_difference, "timeInForce": other_time_in_force, 282 | "expireTime": other_expire_time, "text": other_text, 283 | }, 284 | }, 285 | ) 286 | 287 | async def place_order(self, 288 | action: str, 289 | symbol: str, 290 | order_qty: int, 291 | order_type: str, 292 | account_spec: str = None, 293 | account_id: int = None, 294 | cl_ord_id: str = None, 295 | price: float = None, 296 | stop_price: float = None, 297 | max_show: int = None, 298 | peg_difference: float = None, 299 | time_in_force: str = None, 300 | expire_time: str = None, 301 | text: str = None, 302 | activation_time: str = None, 303 | custom_tag_50: str = None, 304 | is_automated: bool = None) -> dict: 305 | """ 306 | Make a request to place an order. 307 | Depending on the order type, the parameters vary. 308 | """ 309 | return await self.session.post( 310 | url="/order/placeorder", 311 | payload={ 312 | "accountSpec": account_spec, "accountId": account_id, "clOrdId": cl_ord_id, 313 | "action": action, "symbol": symbol, "orderQty": order_qty, "orderType": order_type, 314 | "price": price, "stopPrice": stop_price, "maxShow": max_show, "pegDifference": peg_difference, 315 | "timeInForce": time_in_force, "expireTime": expire_time, "text": text, "activationTime": activation_time, 316 | "customTag50": custom_tag_50, "isAutomated": is_automated, 317 | }, 318 | ) 319 | 320 | async def place_OSO(self, 321 | action: str, 322 | symbol: str, 323 | order_qty: int, 324 | order_type: str, 325 | bracket_1_action: str, 326 | bracket_1_order_type: str, 327 | account_spec: str = None, 328 | account_id: int = None, 329 | cl_ord_id: str = None, 330 | price: float = None, 331 | stop_price: float = None, 332 | max_show: int = None, 333 | peg_difference: float = None, 334 | time_in_force: str = None, 335 | expire_time: str = None, 336 | text: str = None, 337 | activation_time: str = None, 338 | custom_tag_50: str = None, 339 | is_automated: bool = None, 340 | bracket_1_cl_order_id: str = None, 341 | bracket_1_price: float = None, 342 | bracket_1_stop_price: float = None, 343 | bracket_1_max_show: int = None, 344 | bracket_1_peg_difference: float = None, 345 | bracket_1_time_in_force: str = None, 346 | bracket_1_expire_time: str = None, 347 | bracket_1_text: str = None, 348 | bracket_2_action: str = None, 349 | bracket_2_order_type: str = None, 350 | bracket_2_cl_order_id: str = None, 351 | bracket_2_price: float = None, 352 | bracket_2_stop_price: float = None, 353 | bracket_2_max_show: int = None, 354 | bracket_2_peg_difference: float = None, 355 | bracket_2_time_in_force: str = None, 356 | bracket_2_expire_time: str = None, 357 | bracket_2_text: str = None) -> dict: 358 | """ 359 | Place an Order Sends Order order strategy. 360 | OSO orders allow for the most complex multi-bracket trading strategies. 361 | """ 362 | return await self.session.post( 363 | url="/order/placeoso", 364 | payload={ 365 | "accountSpec": account_spec, "accountId": account_id, "clOrdId": cl_ord_id, 366 | "action": action, "symbol": symbol, "orderQty": order_qty, "orderType": order_type, 367 | "price": price, "stopPrice": stop_price, "maxShow": max_show, "pegDifference": peg_difference, 368 | "timeInForce": time_in_force, "expireTime": expire_time, "text": text, "activationTime": activation_time, 369 | "customTag50": custom_tag_50, "isAutomated": is_automated, 370 | "bracket1": { 371 | "action": bracket_1_action, "clOrdId": bracket_1_cl_order_id, "orderType": bracket_1_order_type, 372 | "price": bracket_1_price, "stopPrice": bracket_1_stop_price, "maxShow": bracket_1_max_show, 373 | "pegDifference": bracket_1_peg_difference, "timeInForce": bracket_1_time_in_force, 374 | "expireTime": bracket_1_expire_time, "text": bracket_1_text, 375 | }, 376 | "bracket2": { 377 | "action": bracket_2_action, "clOrdId": bracket_2_cl_order_id, "orderType": bracket_2_order_type, 378 | "price": bracket_2_price, "stopPrice": bracket_2_stop_price, "maxShow": bracket_2_max_show, 379 | "pegDifference": bracket_2_peg_difference, "timeInForce": bracket_2_time_in_force, 380 | "expireTime": bracket_2_expire_time, "text": bracket_2_text, 381 | }, 382 | }, 383 | ) 384 | 385 | async def order_strategy_dependents(self, master_id: int) -> dict: 386 | """Retrieves all entities of OrderStrategy type related to Account entity.""" 387 | return await self.session.get(f"/orderStrategy/deps?masterid={master_id}") 388 | 389 | async def interrupt_order_strategy(self, order_strategy_id: int) -> dict: 390 | """Stop a running multi-bracket strategy.""" 391 | return await self.session.post( 392 | url="/orderStrategy/interruptorderstrategy", 393 | payload={"orderStrategyId": order_strategy_id}, 394 | ) 395 | 396 | async def order_strategy_item(self, id: int) -> dict: 397 | """Retrieves an entity of OrderStrategy type by its id.""" 398 | return await self.session.get(f"/orderStrategy/item?id={id}") 399 | 400 | async def order_strategy_items(self, ids: list[int]) -> dict: 401 | """Retrieves multiple entities of OrderStrategy type by its ids.""" 402 | return await self.session.get( 403 | f"/orderStrategy/items?ids={','.join([str(id) for id in ids])}", 404 | ) 405 | 406 | async def order_strategy_L_dependents(self, master_ids: list[int]) -> dict: 407 | """Retrieves all entities of OrderStrategy type related to multiple entities of Account type.""" 408 | return await self.session.get( 409 | f"/orderStrategy/ldeps?masterids={','.join([str(id) for id in master_ids])}", 410 | ) 411 | 412 | async def order_strategy_list(self) -> dict: 413 | """Retrieves all entities of OrderStrategy type.""" 414 | return await self.session.get("/orderStrategy/list") 415 | 416 | async def modify_order_strategy(self, 417 | order_strategy_id: int, 418 | command: str, 419 | custom_tag_50: str = None) -> dict: 420 | """Modify the order strategy used for an existing order.""" 421 | return await self.session.post( 422 | url="/orderStrategy/modifyorderstrategy", 423 | payload={ 424 | "orderStrategyId": order_strategy_id, 425 | "command": command, 426 | "customTag50": custom_tag_50, 427 | }, 428 | ) 429 | 430 | async def start_order_strategy(self, 431 | symbol: str, 432 | order_strategy_type_id: int, 433 | action: str, 434 | account_id: int = None, 435 | account_spec: str = None, 436 | params: str = None, 437 | uuid: str = None, 438 | custom_tag_50: str = None) -> dict: 439 | """ 440 | Start a multi-bracket trading strategy. 441 | 442 | This endpoint is used with a WebSocket. 443 | 444 | You can create any number of brackets and 445 | add them to brackets field on the params 446 | object as a JSON string. 447 | """ 448 | return await self.session.post( 449 | url="/orderStrategy/startorderstrategy", 450 | payload={ 451 | "accountId": account_id, 452 | "accountSpec": account_spec, 453 | "symbol": symbol, 454 | "orderStrategyTypeId": order_strategy_type_id, 455 | "action": action, 456 | "params": params, 457 | "uuid": uuid, 458 | "customTag50": custom_tag_50, 459 | }, 460 | ) 461 | 462 | async def order_strategy_link_item(self, id: int) -> dict: 463 | """Retrieves an entity of OrderStrategyLink type by its id.""" 464 | return await self.session.get(f"/orderStrategyLink/item?id={id}") 465 | 466 | async def order_strategy_link_items(self, ids: list[int]) -> dict: 467 | """Retrieves multiple entities of OrderStrategyLink type by its ids.""" 468 | return await self.session.get( 469 | f"/orderStrategyLink/items?ids={','.join([str(id) for id in ids])}", 470 | ) 471 | 472 | async def order_strategy_link_L_dependents(self, master_ids: list[int]) -> dict: 473 | """"Retrieves all entities of OrderStrategyLink type related to multiple entities of OrderStrategy type""" 474 | return await self.session.get( 475 | f"/orderStrategyLink/ldeps?masterids={','.join([str(id) for id in master_ids])}", 476 | ) 477 | 478 | async def order_strategy_link_list(self) -> dict: 479 | """Retrieves all entities of OrderStrategyLink type.""" 480 | return await self.session.get("/orderStrategyLink/list") 481 | 482 | async def order_version_dependents(self, master_id: int) -> dict: 483 | """Retrieves all entities of OrderVersion type related to Order entity.""" 484 | return await self.session.get(f"/orderVersion/deps?masterid={master_id}") 485 | 486 | async def order_version_item(self, id: int) -> dict: 487 | """Retrieves an entity of OrderVersion type by its id.""" 488 | return await self.session.get(f"/orderVersion/items?id={id}") 489 | 490 | async def order_version_items(self, ids: list[int]) -> dict: 491 | """Retrieves multiple entities of OrderVersion type by its ids.""" 492 | return await self.session.get( 493 | f"/orderVersion/items?ids={','.join([str(id) for id in ids])}", 494 | ) 495 | 496 | async def order_version_L_dependents(self, master_ids: list[int]) -> dict: 497 | """Retrieves all entities of OrderVersion type related to multiple entities of Order type.""" 498 | return await self.session.get( 499 | f"/orderVersion/masterids={','.join([str(id) for id in master_ids])}", 500 | ) 501 | 502 | async def order_version_list(self) -> dict: 503 | """Retrieves all entities of OrderVersion type.""" 504 | return await self.session.get("/orderVersion/list") 505 | -------------------------------------------------------------------------------- /TradovatePy/users.py: -------------------------------------------------------------------------------- 1 | class Users: 2 | 3 | def __init__(self, session) -> None: 4 | """User's constructor.""" 5 | self.session = session 6 | 7 | async def contract_info_dependents(self, master_id: int) -> dict: 8 | """Retrieves all entities of ContactInfo type related to User entity.""" 9 | return self.session.get(f"/contractInfo/deps?masterid={master_id}") 10 | 11 | async def contract_info_item(self, id: int) -> dict: 12 | """Retrieves an entity of ContactInfo type by its id.""" 13 | return self.session.get(f"/contractInfo/item?id={id}") 14 | 15 | async def contract_info_items(self, ids: list[int]) -> dict: 16 | """Retrieves multiple entities of ContactInfo type by its ids.""" 17 | return self.session.get( 18 | f"/contractInfo/items?ids={','.join([str(id) for id in ids])}", 19 | ) 20 | 21 | async def contract_info_L_dependents(self, master_ids: list[int]) -> dict: 22 | """Retrieves all entities of ContactInfo type related to multiple entities of User type.""" 23 | return self.session.get( 24 | f"/contractInfo/ldeps?masterids={','.join([str(id) for id in master_ids])}", 25 | ) 26 | 27 | async def market_data_subscription_create(self, 28 | user_id: int, 29 | plan_price: float, 30 | market_data_sub_plan_id: int, 31 | timestamp: str, 32 | year: int, 33 | month: int, 34 | id: int = None, 35 | credit_card_transaction_id: int = None, 36 | cash_balance_log_id: int = None, 37 | credit_card_id: int = None, 38 | account_id: int = None, 39 | renewal_credit_card_id: int = None, 40 | renewal_account_id: int = None) -> dict: 41 | """Creates a new entity of MarketDataSubscription.""" 42 | return self.session.post( 43 | url="/marketDataSubscription/create", 44 | payload={ 45 | "id": id, "userId": user_id, "timestamp": timestamp, 46 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 47 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, 48 | "accountId": account_id, "MarketDataSubscriptionPlanId": market_data_sub_plan_id, 49 | "year": year, "month": month, "renewalCreditCardId": renewal_credit_card_id, 50 | "renewalAccountId": renewal_account_id, 51 | }, 52 | ) 53 | 54 | async def market_data_subscription_dependents(self, master_id: int) -> dict: 55 | """Retrieves all entities of MarketDataSubscription type related to User entity.""" 56 | return self.session.get(f"/marketDataSubscription/deps?masterid={master_id}") 57 | 58 | async def market_data_subscription_item(self, id: int) -> dict: 59 | """Retrieves an entity of MarketDataSubscription type by its id.""" 60 | return self.session.get(f"/marketDataSubscription/item?id={id}") 61 | 62 | async def market_data_subscription_items(self, ids: list[int]) -> dict: 63 | """Retrieves multiple entities of MarketDataSubscription type by its ids.""" 64 | return self.session.get( 65 | f"/marketDataSubscription/items?ids={','.join([str(id) for id in ids])}", 66 | ) 67 | 68 | async def market_data_subscription_L_dependents(self, master_ids: list[int]) -> dict: 69 | """Retrieves all entities of MarketDataSubscription type related to multiple entities of User type.""" 70 | return self.session.get( 71 | f"/marketDataSubscription/ldeps?masterids={','.join([str(id) for id in master_ids])}", 72 | ) 73 | 74 | async def market_data_subscription_list(self) -> dict: 75 | """Retrieves all entities of MarketDataSubscription type.""" 76 | return self.session.get("/marketDataSubscription/list") 77 | 78 | async def market_data_subscription_update(self, 79 | user_id: int, 80 | timestamp: str, 81 | plan_price: float, 82 | market_data_sub_plan_id: int, 83 | year: int, 84 | month: int, 85 | id: int = None, 86 | credit_card_transaction_id: int = None, 87 | cash_balance_log_id: int = None, 88 | credit_card_id: int = None, 89 | account_id: int = None, 90 | renewal_credit_card_id: int = None, 91 | renewal_account_id: int = None) -> dict: 92 | """Updates an existing entity of MarketDataSubscription.""" 93 | return await self.session.post( 94 | url="/marketDataSubscription/update", 95 | payload={ 96 | "id": id, "userId": user_id, "timestamp": timestamp, 97 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 98 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, 99 | "accountId": account_id, "marketDataSubscriptionPlanId": market_data_sub_plan_id, 100 | "year": year, "month": month, "renewalCreditCardId": renewal_credit_card_id, 101 | "renewalAccountId": renewal_account_id, 102 | }, 103 | ) 104 | 105 | async def organization_find(self, name: str) -> dict: 106 | """Retrieves an entity of Organization type by its name.""" 107 | return await self.session.get(f"/organization/find?name={name}") 108 | 109 | async def organization_item(self, id: int) -> dict: 110 | """Retrieves an entity of Organization type by its id.""" 111 | return await self.session.get(f"/organization/item?id={id}") 112 | 113 | async def organization_items(self, ids: list[int]) -> dict: 114 | """Retrieves multiple entities of Organization type by its ids.""" 115 | return await self.session.get( 116 | f"/organization/ids={','.join([str(id) for id in ids])}", 117 | ) 118 | 119 | async def organization_list(self) -> dict: 120 | """Retrieves all entities of Organization type.""" 121 | return await self.session.get("/organization/list") 122 | 123 | async def organization_suggest(self, text: str, n_entities: int) -> dict: 124 | """Retrieves entities of Organization type filtered by an occurrence of a text in one of its fields.""" 125 | return await self.session.get(f"/organization/suggest?t={text}&l={n_entities}") 126 | 127 | async def second_market_data_subscription_dependents(self, master_id: int) -> dict: 128 | """Retrieves all entities of SecondMarketDataSubscription type related to User entity.""" 129 | return await self.session.get(f"/secondMarketDataSubscription/deps?masterid={master_id}") 130 | 131 | async def second_market_data_subscription_item(self, id: int) -> dict: 132 | """Retrieves an entity of SecondMarketDataSubscription type by its id.""" 133 | return await self.session.get(f"/secondMarketDataSubscription/item?id={id}") 134 | 135 | async def second_market_data_subscription_items(self, ids: list[int]) -> dict: 136 | """Retrieves multiple entities of SecondMarketDataSubscription type by its ids.""" 137 | return await self.session.get( 138 | f"/secondMarketDataSubscription/items?ids={','.join([str(id) for id in ids])}", 139 | ) 140 | 141 | async def second_market_data_subscription_L_dependents(self, master_ids: list[int]) -> dict: 142 | """Retrieves all entities of SecondMarketDataSubscription type related to multiple entities of User type.""" 143 | return await self.session.get( 144 | f"/secondMarketDataSubscription/ldeps?masterids={','.join([str(id) for id in master_ids])}", 145 | ) 146 | 147 | async def second_market_data_subscription_list(self) -> dict: 148 | """Retrieves all entities of SecondMarketDataSubscription type.""" 149 | return await self.session.get("/secondMarketDataSubscription/list") 150 | 151 | async def tradovate_subscription_create(self, 152 | user_id: int, 153 | timestamp: str, 154 | plan_price: float, 155 | tradovate_subscription_plan_id: int, 156 | start_date: str, 157 | expiration_date: str, 158 | paid_amount: float, 159 | id: int = None, 160 | credit_card_transaction_id: int = None, 161 | cash_balance_log_id: int = None, 162 | credit_card_id: int = None, 163 | account_id: int = None, 164 | cancelled_renewal: bool = None, 165 | cancel_reason: str = None) -> dict: 166 | """Creates a new entity of TradovateSubscription.""" 167 | return await self.session.post( 168 | url="/tradovateSubscription/create", 169 | payload={ 170 | "id": id, "userId": user_id, "timestamp": timestamp, 171 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 172 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, 173 | "accountId": account_id, "tradovateSubscriptionPlanId": tradovate_subscription_plan_id, 174 | "startDate": start_date, "expirationDate": expiration_date, "paidAmount": paid_amount, 175 | "cancelledRenewal": cancelled_renewal, "cancelReason": cancel_reason, 176 | }, 177 | ) 178 | 179 | async def tradovate_subscription_dependents(self, master_id: int) -> dict: 180 | """Retrieves all entities of SecondMarketDataSubscription type related to multiple entities of User type.""" 181 | return await self.session.get(f"/tradovateSubscription/deps?masterid={master_id}") 182 | 183 | async def tradovate_subscription_item(self, id: int) -> dict: 184 | """Retrieves an entity of TradovateSubscription type by its id.""" 185 | return await self.session.get(f"/tradovateSubscription/item?id={id}") 186 | 187 | async def tradovate_subscription_items(self, ids: list[int]) -> dict: 188 | """Retrieves multiple entities of TradovateSubscription type by its ids.""" 189 | return await self.session.get( 190 | f"/tradovateSubscription/items?ids={','.join([str(id) for id in ids])}", 191 | ) 192 | 193 | async def tradovate_subscription_L_dependents(self, master_ids: list[int]) -> dict: 194 | """Retrieves all entities of TradovateSubscription type related to multiple entities of User type.""" 195 | return await self.session.get( 196 | f"/tradovateSubscription/ldeps?masterids={master_ids}", 197 | ) 198 | 199 | async def tradovate_subscription_list(self) -> dict: 200 | """Retrieves all entities of TradovateSubscription type.""" 201 | return await self.session.get("/tradovateSubscription/list") 202 | 203 | async def tradovate_subscription_update(self, 204 | user_id: int, 205 | timestamp: str, 206 | plan_price: float, 207 | tradovate_subscription_plan_id: int, 208 | start_date: dict, 209 | expiration_date: dict, 210 | paid_amount: float, 211 | id: int = None, 212 | credit_card_transaction_id: int = None, 213 | cash_balance_log_id: int = None, 214 | credit_card_id: int = None, 215 | account_id: int = None, 216 | cancelled_renewal: bool = None, 217 | cancel_reason: str = None) -> dict: 218 | """Updates an existing entity of TradovateSubscription.""" 219 | return await self.session.post( 220 | url="/tradovateSubscription/update", 221 | payload={ 222 | "id": id, "userId": user_id, "timestamp": timestamp, 223 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 224 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, 225 | "accountId": account_id, "tradovateSubscriptionPlanId": tradovate_subscription_plan_id, 226 | "startDate": start_date, "expirationDate": expiration_date, "paidAmount": paid_amount, 227 | "cancelledRenewal": cancelled_renewal, "cancelReason": cancel_reason, 228 | }, 229 | ) 230 | 231 | async def accept_trading_permission(self, trading_permission_id: int) -> dict: 232 | """Called to accept a given trading permission granted by another party.""" 233 | return await self.session.post( 234 | url="/user/accepttradingpermission", 235 | payload={"tradingPermissionId": trading_permission_id}, 236 | ) 237 | 238 | async def activate_second_market_data_subscription_renewal(self, second_market_data_sub_id: int) -> dict: 239 | """Used to setup a second market data subscription with active auto-renewal.""" 240 | return await self.session.post( 241 | url="/user/activatesecondmarketdatasubscriptionrenewal", 242 | payload={"secondMarketDataSubscriptionId": second_market_data_sub_id}, 243 | ) 244 | 245 | async def add_market_data_subscription(self, 246 | market_data_subscription_plan_ids: list[int], 247 | year: int, 248 | month: int, 249 | credit_card_id: int = None, 250 | account_id: int = None, 251 | user_id: int = None) -> dict: 252 | """Add a subscription to Market Data for a user.""" 253 | return await self.session.post( 254 | url="/user/addmarketdatasubscription", 255 | payload={ 256 | "marketDataSubscriptionPlanIds": market_data_subscription_plan_ids, 257 | "year": year, "month": month, "creditCardId": credit_card_id, 258 | "accountId": account_id, "userId": user_id, 259 | }, 260 | ) 261 | 262 | async def add_second_market_data_subscription(self, 263 | year: int, 264 | month: int, 265 | credit_card_id: int = None, 266 | account_id: int = None, 267 | user_id: int = None) -> dict: 268 | """Add a subscription to Market Data for a user.""" 269 | return await self.session.post( 270 | url="/user/addmarketdatasubscription", 271 | payload={ 272 | "year": year, "month": month, "creditCardId": credit_card_id, 273 | "accountId": account_id, "userId": user_id, 274 | }, 275 | ) 276 | 277 | async def add_tradovate_subscription(self, 278 | tradovate_subscription_plan_id: int, 279 | credit_card_id: int = None, 280 | account_id: int = None, 281 | user_id: int = None) -> dict: 282 | """Used to add a Tradovate Trader membership plan for a user.""" 283 | return await self.session.post( 284 | url="/user/addtradovatesubscription", 285 | payload={ 286 | "tradovateSubscriptionPlanId": tradovate_subscription_plan_id, 287 | "creditCardId": credit_card_id, "accountId": account_id, "userId": user_id, 288 | }, 289 | ) 290 | 291 | async def cancel_second_market_data_subscription(self, second_market_data_sub_id: int) -> dict: 292 | """Cancel a second market data subscription for a user.""" 293 | return await self.session.post( 294 | url="", 295 | payload={ 296 | "secondMarketDataSubscriptionId": second_market_data_sub_id, 297 | }, 298 | ) 299 | 300 | async def cancel_second_market_data_subscription_renewal(self, second_market_data_sub_id: int) -> dict: 301 | """Cancel the auto-renewal for a second market data subscription for a user.""" 302 | return self.session.post( 303 | url="/user/cancelsecondmarketdatasubscriptionrenewal", 304 | payload={ 305 | "secondMarketDataSubscriptionId": second_market_data_sub_id, 306 | }, 307 | ) 308 | 309 | async def cancel_tradovate_subscription(self, 310 | tradovate_sub_id: int, 311 | cancel_reason: str = None, 312 | expire: bool = None) -> dict: 313 | """Cancel a Tradovate Trader membership plan.""" 314 | return await self.session.post( 315 | url="/user/canceltradovatesubscription", 316 | payload={ 317 | "tradovateSubscriptionId": tradovate_sub_id, "cancelReason": cancel_reason, 318 | "expire": expire, 319 | }, 320 | ) 321 | 322 | async def user_find(self, name: str) -> dict: 323 | """Retrieves an entity of User type by its name.""" 324 | return await self.session.get(f"/user/find?name={name}") 325 | 326 | async def get_account_trading_permissions(self, account_id: int) -> dict: 327 | """Query the granted trading permissions associated with this account.""" 328 | return await self.session.post( 329 | url="/user/getaccounttradingpermissions", 330 | payload={"accountId": account_id}, 331 | ) 332 | 333 | async def get_second_market_data_subscription_cost(self, 334 | year: int, 335 | month: int, 336 | user_id: int = None) -> dict: 337 | """Query the current price of a second market data subscription for a user.""" 338 | return await self.session.post( 339 | url="/user/getsecondmarketdatasubscriptioncost", 340 | payload={ 341 | "year": year, "month": month, "userId": user_id, 342 | }, 343 | ) 344 | 345 | async def user_item(self, id: int) -> dict: 346 | """Retrieves an entity of User type by its id.""" 347 | return await self.session.get(f"/user/item?id={id}") 348 | 349 | async def user_items(self, ids: list[int]) -> dict: 350 | """Retrieves multiple entities of User type by its ids.""" 351 | return await self.session.get( 352 | f"/user/items?ids={','.join([str(id) for id in ids])}", 353 | ) 354 | 355 | async def user_list(self) -> dict: 356 | """Retrieves all entities of User type.""" 357 | return await self.session.get("/user/list") 358 | 359 | async def modify_credentials(self, 360 | name: str, 361 | new_password: str, 362 | current_password: str, 363 | user_id: int = None) -> dict: 364 | """Used to modify account username and password.""" 365 | return await self.session.post( 366 | url="/user/modifycredentials", 367 | payload={ 368 | "userId": user_id, "name": name, "password": new_password, 369 | "currentPassword": current_password, "userId": user_id, 370 | }, 371 | ) 372 | 373 | async def modify_email_address(self, 374 | email: str, 375 | user_id: int) -> dict: 376 | """Change account email address information.""" 377 | return await self.session.post( 378 | url="/user/modifyemailaddress", 379 | payload={ 380 | "userId": user_id, "email": email, 381 | }, 382 | ) 383 | 384 | async def modify_password(self, 385 | password: str, 386 | current_password: str, 387 | user_id: int) -> dict: 388 | """Change account password information.""" 389 | return await self.session.post( 390 | url="/user/modifypassword", 391 | payload={ 392 | "userId": user_id, "password": password, "currentPassword": current_password, 393 | }, 394 | ) 395 | 396 | async def open_demo_account(self, 397 | template_account_id: int = None, 398 | name: str = None, 399 | initial_balance: float = None) -> dict: 400 | """Request to open a Demo account for a user.""" 401 | return await self.session.post( 402 | url="/user/opendemoaccount", 403 | payload={ 404 | "templateAccountId": template_account_id, "name": name, "initialBalance": initial_balance, 405 | }, 406 | ) 407 | 408 | async def request_trading_permission(self, 409 | account_id: int, 410 | cta_contact: str, 411 | cta_email: str) -> dict: 412 | """ 413 | Send a request to grant trading permission for your account to another party. 414 | 415 | Once this request is reviewed by our accounting and compliance, the other party 416 | will be allowed to access your account as if it was one of that party's own accounts. 417 | """ 418 | return await self.session.post( 419 | url="/user/requesttradingpermission", 420 | payload={ 421 | "accountId": account_id, "ctaContact": cta_contact, "ctaEmail": cta_email, 422 | }, 423 | ) 424 | 425 | async def revoke_trading_permissions(self, trading_permission_id: int) -> dict: 426 | """ 427 | Revoke an existing trading permission granted to another party. 428 | 429 | If a user wants to end the terms of a granted permission to trade using your account, 430 | a user can revoke those permissions using this endpoint. 431 | """ 432 | return await self.session.post( 433 | url="/user/revoketradingpermissions", 434 | payload={"tradingPermissionId": trading_permission_id}, 435 | ) 436 | 437 | async def sign_up_organization_member(self, name: str, 438 | email: str, password: str, 439 | first_name: str, last_name: str) -> dict: 440 | """Used by B2B partners to create users for their own organizations.""" 441 | return await self.session.post( 442 | url="/user/signuporganizationmember", 443 | payload={ 444 | "name": name, "email": email, "password": password, 445 | "firstName": first_name, "lastName": last_name, 446 | }, 447 | ) 448 | 449 | async def user_suggest(self, text: str, n_entities: int) -> dict: 450 | """Retrieves entities of User type filtered by an occurrence of a text in one of its fields.""" 451 | return await self.session.get(f"/user/suggest?t={text}&n_entities={n_entities}") 452 | 453 | async def sync_request(self, 454 | users: list[int] = None, 455 | accounts: list[int] = None, 456 | split_responses: bool = None) -> dict: 457 | """ 458 | Used with WebSocket protocol. Returns all data associated with the user. 459 | This endpoint is essential for efficient use of the WebSocket API. 460 | """ 461 | return await self.session.post( 462 | url="/user/syncrequest", 463 | payload={ 464 | "users": users, "accounts": accounts, "splitResponses": split_responses, 465 | }, 466 | ) 467 | 468 | async def add_entitlement_subscription(self, 469 | entitlement_id: int, 470 | credit_card_id: int = None, 471 | account_id: int = None, 472 | user_id: int = None) -> dict: 473 | """For use with Add-ons, allows for purchase of entitlements such as Market Replay.""" 474 | return await self.session.post( 475 | url="/userPlugin/addentitlementsubscription", 476 | payload={ 477 | "entitlementId": entitlement_id, "creditCardId": credit_card_id, 478 | "accountId": account_id, "userId": user_id, 479 | }, 480 | ) 481 | 482 | async def change_plugin_permission(self, 483 | pluginName: str, 484 | approval: bool, 485 | user_id: int = None) -> dict: 486 | """Change the permissions for a Trader plugin.""" 487 | return await self.session.post( 488 | url="/userPlugin/changepermission", 489 | payload={ 490 | "userId": user_id, "pluginName": pluginName, 491 | "approval": approval, 492 | }, 493 | ) 494 | 495 | async def user_plugin_create(self, 496 | user_id: int, 497 | timestamp: str, 498 | plan_price: float, 499 | plugin_name: str, 500 | apporval: bool, 501 | start_date: dict, 502 | paid_amount: float, 503 | credit_card_transaction_id: int = None, 504 | cash_balance_log_id: int = None, 505 | credit_card_id: int = None, 506 | account_id: int = None, 507 | id: int = None, 508 | entitlement_id: int = None, 509 | expiration_date: dict = None, 510 | auto_renewal: bool = None, 511 | plan_categories: str = None) -> dict: 512 | """Creates a new entity of UserPlugin.""" 513 | return self.session.post( 514 | url="/userPlugin/create", 515 | payload={ 516 | "id": id, "userId": user_id, "timestamp": timestamp, 517 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 518 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, "accountId": account_id, 519 | "pluginName": plugin_name, "apporval": apporval, "entitlementId": entitlement_id, 520 | "startDate": start_date, "expirationDate": expiration_date, "paidAmount": paid_amount, 521 | "autorenewal": auto_renewal, "planCategories": plan_categories, 522 | }, 523 | ) 524 | 525 | async def user_plugin_dependents(self, master_id: int) -> dict: 526 | """Retrieves all entities of UserPlugin type related to User entity.""" 527 | return await self.session.get(f"/userPlugin/deps?masterid={master_id}") 528 | 529 | async def user_plugin_item(self, id: int) -> dict: 530 | """Retrieves an entity of UserPlugin type by its id.""" 531 | return await self.session.get(f"/userPlugin/item?id={id}") 532 | 533 | async def user_plugin_items(self, ids: list[int]) -> dict: 534 | """Retrieves multiple entities of UserPlugin type by its ids.""" 535 | return await self.session.get( 536 | f"/userPlugin/items?ids={','.join([str(id) for id in ids])}", 537 | ) 538 | 539 | async def user_plugin_L_dependents(self, master_ids: list[int]) -> dict: 540 | """Retrieves all entities of UserPlugin type related to multiple entities of User type.""" 541 | return await self.session.get( 542 | f"/userPlugin/ldeps?masterids={','.join([str(id) for id in master_ids])}", 543 | ) 544 | 545 | async def user_plugin_list(self) -> dict: 546 | """Retrieves all entities of UserPlugin type.""" 547 | return await self.session.get("/userPlugin/list") 548 | 549 | async def user_plugin_update(self, 550 | user_id: int, 551 | timestamp: str, 552 | plan_price: float, 553 | plugin_name: str, 554 | approval: bool, 555 | start_date: dict, 556 | paid_amount: float, 557 | id: int = None, 558 | credit_card_transaction_id: int = None, 559 | cash_balance_log_id: int = None, 560 | credit_card_id: int = None, 561 | account_id: int = None, 562 | entitlement_id: int = None, 563 | expiration_date: dict = None, 564 | auto_renewal: bool = None, 565 | plan_categories: str = None) -> dict: 566 | """Updates an existing entity of UserPlugin.""" 567 | return await self.session.post( 568 | url="/userPlugin/update", 569 | payload={ 570 | "id": id, "userId": user_id, "timestamp": timestamp, 571 | "planPrice": plan_price, "creditCardTransactionId": credit_card_transaction_id, 572 | "cashBalanceLogId": cash_balance_log_id, "creditCardId": credit_card_id, 573 | "accountId": account_id, "pluginName": plugin_name, "approval": approval, 574 | "entitlementId": entitlement_id, "startDate": start_date, "expirationDate": expiration_date, 575 | "paidAmount": paid_amount, "autoRenewal": auto_renewal, "planCategories": plan_categories, 576 | }, 577 | ) 578 | 579 | async def user_property_dependents(self, master_id: int) -> dict: 580 | """Retrieves all entities of UserProperty type related to User entity.""" 581 | return await self.session.get(f"/userProperty/deps?masterid={master_id}") 582 | 583 | async def user_property_item(self, id: int) -> dict: 584 | """Retrieves multiple entities of UserProperty type by its ids.""" 585 | return await self.session.get(f"/userProperty/item?id={id}") 586 | 587 | async def user_property_items(self, ids: list[int]) -> dict: 588 | """Retrieves multiple entities of UserProperty type by its ids.""" 589 | return await self.session.get( 590 | f"/userProperty/items?ids={','.join([str(id) for id in ids])}", 591 | ) 592 | 593 | async def user_property_L_dependents(self, master_ids: list[int]) -> dict: 594 | """Retrieves all entities of UserProperty type related to multiple entities of User type.""" 595 | return await self.session.get( 596 | f"/userProperty/ldeps?masterids={','.join([str(id) for id in master_ids])}", 597 | ) 598 | 599 | async def user_session_item(self, id: int) -> dict: 600 | """Retrieves an entity of UserSession type by its id.""" 601 | return await self.session.get(f"/userSession/item?id={id}") 602 | 603 | async def user_session_items(self, ids: list[int]) -> dict: 604 | """Retrieves multiple entities of UserSession type by its ids.""" 605 | return await self.session.get( 606 | f"/userSession/items?ids={','.join(str(id) for id in ids)}", 607 | ) 608 | 609 | async def user_session_stats_dependents(self, master_id: int) -> dict: 610 | """Retrieves all entities of UserSessionStats type related to User entity.""" 611 | return await self.session.get(f"/userSessionStats/deps?masterid={master_id}") 612 | 613 | async def user_session_stats_item(self, id: int) -> dict: 614 | """Retrieves an entity of UserSessionStats type by its id.""" 615 | return await self.session.get(f"/userSessionStats/item?id={id}") 616 | 617 | async def user_session_stats_items(self, ids: list[int]) -> dict: 618 | """Retrieves multiple entities of UserSessionStats type by its ids.""" 619 | return await self.session.get( 620 | f"/userSessionStats/items?ids={','.join(str(id) for id in ids)}", 621 | ) 622 | 623 | async def user_session_stats_L_dependents(self, master_ids: list[int]) -> dict: 624 | """Retrieves all entities of UserSessionStats type related to multiple entities of User type.""" 625 | return await self.session.get( 626 | f"/userSessionStats/ldeps?masterids={','.join([str(id) for id in master_ids])}", 627 | ) 628 | 629 | async def user_session_stats_list(self) -> dict: 630 | """Retrieves all entities of UserSessionStats type.""" 631 | return await self.session.get("/userSessionStats/list") 632 | --------------------------------------------------------------------------------