Skip to content

Client

Note

To use the client, which is needed for all communication with the API, you need a user account and a partner id. You can request a partner id by contacting KM in the Alpha-Trader user interface.

Client

Bases: BaseModel

Client for interacting with the Alpha Trader API.

Example

Authenticate and get a personal token:

    >>> from alpha_trader.client import Client
    >>> client = Client(
    ...     base_url="https://stable.alpha-trader.com",
    ...     username="YOUR_USERNAME",
    ...     password="YOUR_PASSWORD",
    ...     partner_id="YOUR_PARTNER_ID")
    >>> client.login()
    2023-04-29 09:34:54,872 - alpha_trader.logging - INFO - Client successfully authenticated.
    >>> client.authenticated
    True
from alpha_trader.client import Client
Source code in alpha_trader/client/__init__.py
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
class Client(BaseModel):
    """
    Client for interacting with the Alpha Trader API.

    Example:
        Authenticate and get a personal token:

        ```python

            >>> from alpha_trader.client import Client
            >>> client = Client(
            ...     base_url="https://stable.alpha-trader.com",
            ...     username="YOUR_USERNAME",
            ...     password="YOUR_PASSWORD",
            ...     partner_id="YOUR_PARTNER_ID")
            >>> client.login()
            2023-04-29 09:34:54,872 - alpha_trader.logging - INFO - Client successfully authenticated.
            >>> client.authenticated
            True
        ```

        ```python
        from alpha_trader.client import Client

        ```

    """

    base_url: str
    username: str
    password: str
    partner_id: str
    token: Union[str, None] = None
    authenticated: bool = False

    def login(self) -> str:
        """
        Login to the API and get a token.

        Returns:
            Token string
        """
        url = os.path.join(self.base_url, "user/token/")

        payload = {
            "username": self.username,
            "password": self.password,
            "partnerId": self.partner_id,
        }

        response = requests.request("POST", url, data=payload)

        self.token = response.json()["message"]
        self.authenticated = True

        logger.info("Client successfully authenticated.")

        return self.token

    def __get_headers(self):
        """"""
        headers = {"Authorization": f"Bearer {self.token}"}

        return headers

    def request(
            self, method: str, endpoint: str, data: Dict = None, json: Dict = None, additional_headers: Dict = None, params: Dict = None
    ) -> requests.Response:
        """Make a request using the authenticated client. This method is mainly used internally by other classes
        to retrieve more information from the API.

        Example:
            ```python
            >>> response = client.request("GET", "api/user")
            >>> user_information = response.json()
            >>> user_information["username"]
            Malte

        Args:
            body: body parameters
            additional_headers: Additional headers to be added to the request
            method: HTTP method
            endpoint: Endpoint
            data: Data

        Returns:
            HTTP Response
        """

        url = os.path.join(self.base_url, endpoint)

        if not self.authenticated:
            raise Exception("Client is not authenticated.")

        if additional_headers is None:
            headers = self.__get_headers()
        else:
            headers = self.__get_headers() | additional_headers

        response = requests.request(
            method, url, data=data, headers=headers, params=params, json=json
        )

        return response

    def get_user(self) -> User:
        """Get the user information for the authenticated user.
        Example:
            ```python
            >>> user = client.get_user()
            >>> user.username
            'Malte'
            >>> user.companies
            [Company(name=Argo, security_identifier=STAD9A0F12), Company(name=Argo2, security_identifier=STA8D0230B)]
            >>> user.securities_accounts
            SecuritiesAccount(id=7b3f6182-be88-4b98-aa75-4c2fd10487ae)
            ```

        Returns:
            User
        """
        from alpha_trader.user import User

        response = self.request("GET", "api/user")

        return User.initialize_from_api_response(response.json(), self)

    def get_miner(self) -> Miner:
        """Get the miner information for the authenticated user.
        :return: Miner
        """
        from alpha_trader.miner import Miner

        url = os.path.join(self.base_url, "api/v2/my/miner")

        response = requests.get(url, headers=self.__get_headers())

        return Miner.from_api_response(response.json(), client=self)

    def get_listing(self, security_identifier: str) -> Listing:
        """Get the listing information for a security.
        :param security_identifier: Security identifier
        :return: Listing
        """
        from alpha_trader.listing import Listing

        response = self.request("GET", f"api/listings/{security_identifier}")

        return Listing.initialize_from_api_response(response.json(), client=self)

    def get_price_spread(self, security_identifier: str) -> PriceSpread:
        """Get the price spread for a security.
        :param security_identifier: Security identifier
        :return: Price spread
        """
        from alpha_trader.price.price_spread import PriceSpread

        response = self.request("GET", f"api/pricespreads/{security_identifier}")

        return PriceSpread.initialize_from_api_response(response.json(), client=self)

    def get_securities_account(self, securities_account_id: str) -> SecuritiesAccount:
        """Get the securities account for a given ID.
        :param securities_account_id: Securities account ID
        :return: Securities account
        """
        from alpha_trader.securities_account import SecuritiesAccount

        response = self.request(
            "GET", f"api/v2/securitiesaccountdetails/{securities_account_id}"
        )

        return SecuritiesAccount.initialize_from_api_response(
            response.json(), client=self
        )

    def filter_listings(self, filter_id: str = None, filter_definition: Dict = None) -> List[PriceSpread]:
        """

        Returns:
            Price Spreads

        """
        from alpha_trader.price.price_spread import PriceSpread

        if filter_definition is None:
            filter_definition = {}

        if filter_id is None:
            params = None
        else:
            params = {"filterId": filter_id}

        response = self.request(
            "POST",
            "api/v2/filter/pricespreads",
            json=filter_definition,
            additional_headers={"Content-Type": "application/json"},
            params=params
        )

        return [
            PriceSpread.initialize_from_filter_api_response(item, client=self) for item in response.json()["results"]
        ]

    def get_bond(self, security_identifier: str, price_spread: Union[PriceSpread, None] = None) -> Bond:
        """
            Get the bond information for a security.

        Args:
            price_spread: manually set the price spread
            security_identifier: Security identifier

        Returns:
            Bond
        """
        from alpha_trader.bonds import Bond

        response = self.request("GET", f"api/bonds/securityidentifier/{security_identifier}")

        Bond.update_forward_refs()

        return Bond.initialize_from_api_response(response.json(), client=self, price_spread=price_spread)

    def get_company(self, security_identifier: str) -> Company:
        """
            Get the company information for a security.

        Args:
            security_identifier: Security identifier

        Returns:
            Company
        """
        from alpha_trader.company import Company

        response = self.request("GET", f"api/companies/securityIdentifier/{security_identifier}")

        return Company.initialize_from_api_response(response.json(), client=self)

    def get_order(self, order_id: str) -> Order:
        """
            Get the order information for a given order ID.

        Args:
            order_id: Order ID

        Returns:
            Order
        """
        from alpha_trader.order import Order

        response = self.request("GET", f"api/securityorders//{order_id}")

        return Order.initialize_from_api_response(response.json(), client=self)

    def get_bonds(self, page: int, search: str, page_size: int):
        pass

    def register_user(self, username: str, password: str, email: str, locale: str = None) -> User:
        """
            Register a new user
        Args:
            username: Username
            password: Password
            email: Email
            locale: Locale

        Returns:
            User
        """
        from alpha_trader.user import User

        data = {
            "username": username,
            "password": password,
            "emailAddress": email,
            "locale": locale,
        }

        response = requests.post(f"{self.base_url}/user/register", data=data)
        if response.status_code != 201:
            raise Exception(response.text)

        self.login()

        return User.initialize_from_api_response(response.json(), self)

__get_headers()

Source code in alpha_trader/client/__init__.py
82
83
84
85
86
def __get_headers(self):
    """"""
    headers = {"Authorization": f"Bearer {self.token}"}

    return headers

filter_listings(filter_id=None, filter_definition=None)

Returns:

Type Description
List[PriceSpread]

Price Spreads

Source code in alpha_trader/client/__init__.py
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
def filter_listings(self, filter_id: str = None, filter_definition: Dict = None) -> List[PriceSpread]:
    """

    Returns:
        Price Spreads

    """
    from alpha_trader.price.price_spread import PriceSpread

    if filter_definition is None:
        filter_definition = {}

    if filter_id is None:
        params = None
    else:
        params = {"filterId": filter_id}

    response = self.request(
        "POST",
        "api/v2/filter/pricespreads",
        json=filter_definition,
        additional_headers={"Content-Type": "application/json"},
        params=params
    )

    return [
        PriceSpread.initialize_from_filter_api_response(item, client=self) for item in response.json()["results"]
    ]

get_bond(security_identifier, price_spread=None)

Get the bond information for a security.

Parameters:

Name Type Description Default
price_spread Union[PriceSpread, None]

manually set the price spread

None
security_identifier str

Security identifier

required

Returns:

Type Description
Bond

Bond

Source code in alpha_trader/client/__init__.py
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
def get_bond(self, security_identifier: str, price_spread: Union[PriceSpread, None] = None) -> Bond:
    """
        Get the bond information for a security.

    Args:
        price_spread: manually set the price spread
        security_identifier: Security identifier

    Returns:
        Bond
    """
    from alpha_trader.bonds import Bond

    response = self.request("GET", f"api/bonds/securityidentifier/{security_identifier}")

    Bond.update_forward_refs()

    return Bond.initialize_from_api_response(response.json(), client=self, price_spread=price_spread)

get_company(security_identifier)

Get the company information for a security.

Parameters:

Name Type Description Default
security_identifier str

Security identifier

required

Returns:

Type Description
Company

Company

Source code in alpha_trader/client/__init__.py
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
def get_company(self, security_identifier: str) -> Company:
    """
        Get the company information for a security.

    Args:
        security_identifier: Security identifier

    Returns:
        Company
    """
    from alpha_trader.company import Company

    response = self.request("GET", f"api/companies/securityIdentifier/{security_identifier}")

    return Company.initialize_from_api_response(response.json(), client=self)

get_listing(security_identifier)

Get the listing information for a security. :param security_identifier: Security identifier :return: Listing

Source code in alpha_trader/client/__init__.py
162
163
164
165
166
167
168
169
170
171
def get_listing(self, security_identifier: str) -> Listing:
    """Get the listing information for a security.
    :param security_identifier: Security identifier
    :return: Listing
    """
    from alpha_trader.listing import Listing

    response = self.request("GET", f"api/listings/{security_identifier}")

    return Listing.initialize_from_api_response(response.json(), client=self)

get_miner()

Get the miner information for the authenticated user. :return: Miner

Source code in alpha_trader/client/__init__.py
150
151
152
153
154
155
156
157
158
159
160
def get_miner(self) -> Miner:
    """Get the miner information for the authenticated user.
    :return: Miner
    """
    from alpha_trader.miner import Miner

    url = os.path.join(self.base_url, "api/v2/my/miner")

    response = requests.get(url, headers=self.__get_headers())

    return Miner.from_api_response(response.json(), client=self)

get_order(order_id)

Get the order information for a given order ID.

Parameters:

Name Type Description Default
order_id str

Order ID

required

Returns:

Type Description
Order

Order

Source code in alpha_trader/client/__init__.py
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
def get_order(self, order_id: str) -> Order:
    """
        Get the order information for a given order ID.

    Args:
        order_id: Order ID

    Returns:
        Order
    """
    from alpha_trader.order import Order

    response = self.request("GET", f"api/securityorders//{order_id}")

    return Order.initialize_from_api_response(response.json(), client=self)

get_price_spread(security_identifier)

Get the price spread for a security. :param security_identifier: Security identifier :return: Price spread

Source code in alpha_trader/client/__init__.py
173
174
175
176
177
178
179
180
181
182
def get_price_spread(self, security_identifier: str) -> PriceSpread:
    """Get the price spread for a security.
    :param security_identifier: Security identifier
    :return: Price spread
    """
    from alpha_trader.price.price_spread import PriceSpread

    response = self.request("GET", f"api/pricespreads/{security_identifier}")

    return PriceSpread.initialize_from_api_response(response.json(), client=self)

get_securities_account(securities_account_id)

Get the securities account for a given ID. :param securities_account_id: Securities account ID :return: Securities account

Source code in alpha_trader/client/__init__.py
184
185
186
187
188
189
190
191
192
193
194
195
196
197
def get_securities_account(self, securities_account_id: str) -> SecuritiesAccount:
    """Get the securities account for a given ID.
    :param securities_account_id: Securities account ID
    :return: Securities account
    """
    from alpha_trader.securities_account import SecuritiesAccount

    response = self.request(
        "GET", f"api/v2/securitiesaccountdetails/{securities_account_id}"
    )

    return SecuritiesAccount.initialize_from_api_response(
        response.json(), client=self
    )

get_user()

Get the user information for the authenticated user. Example:

>>> user = client.get_user()
>>> user.username
'Malte'
>>> user.companies
[Company(name=Argo, security_identifier=STAD9A0F12), Company(name=Argo2, security_identifier=STA8D0230B)]
>>> user.securities_accounts
SecuritiesAccount(id=7b3f6182-be88-4b98-aa75-4c2fd10487ae)

Returns:

Type Description
User

User

Source code in alpha_trader/client/__init__.py
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def get_user(self) -> User:
    """Get the user information for the authenticated user.
    Example:
        ```python
        >>> user = client.get_user()
        >>> user.username
        'Malte'
        >>> user.companies
        [Company(name=Argo, security_identifier=STAD9A0F12), Company(name=Argo2, security_identifier=STA8D0230B)]
        >>> user.securities_accounts
        SecuritiesAccount(id=7b3f6182-be88-4b98-aa75-4c2fd10487ae)
        ```

    Returns:
        User
    """
    from alpha_trader.user import User

    response = self.request("GET", "api/user")

    return User.initialize_from_api_response(response.json(), self)

login()

Login to the API and get a token.

Returns:

Type Description
str

Token string

Source code in alpha_trader/client/__init__.py
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
def login(self) -> str:
    """
    Login to the API and get a token.

    Returns:
        Token string
    """
    url = os.path.join(self.base_url, "user/token/")

    payload = {
        "username": self.username,
        "password": self.password,
        "partnerId": self.partner_id,
    }

    response = requests.request("POST", url, data=payload)

    self.token = response.json()["message"]
    self.authenticated = True

    logger.info("Client successfully authenticated.")

    return self.token

register_user(username, password, email, locale=None)

Register a new user

Args: username: Username password: Password email: Email locale: Locale

Returns:

Type Description
User

User

Source code in alpha_trader/client/__init__.py
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
def register_user(self, username: str, password: str, email: str, locale: str = None) -> User:
    """
        Register a new user
    Args:
        username: Username
        password: Password
        email: Email
        locale: Locale

    Returns:
        User
    """
    from alpha_trader.user import User

    data = {
        "username": username,
        "password": password,
        "emailAddress": email,
        "locale": locale,
    }

    response = requests.post(f"{self.base_url}/user/register", data=data)
    if response.status_code != 201:
        raise Exception(response.text)

    self.login()

    return User.initialize_from_api_response(response.json(), self)

request(method, endpoint, data=None, json=None, additional_headers=None, params=None)

Make a request using the authenticated client. This method is mainly used internally by other classes to retrieve more information from the API.

Example

```python

response = client.request("GET", "api/user") user_information = response.json() user_information["username"] Malte

Parameters:

Name Type Description Default
body

body parameters

required
additional_headers Dict

Additional headers to be added to the request

None
method str

HTTP method

required
endpoint str

Endpoint

required
data Dict

Data

None

Returns:

Type Description
Response

HTTP Response

Source code in alpha_trader/client/__init__.py
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
def request(
        self, method: str, endpoint: str, data: Dict = None, json: Dict = None, additional_headers: Dict = None, params: Dict = None
) -> requests.Response:
    """Make a request using the authenticated client. This method is mainly used internally by other classes
    to retrieve more information from the API.

    Example:
        ```python
        >>> response = client.request("GET", "api/user")
        >>> user_information = response.json()
        >>> user_information["username"]
        Malte

    Args:
        body: body parameters
        additional_headers: Additional headers to be added to the request
        method: HTTP method
        endpoint: Endpoint
        data: Data

    Returns:
        HTTP Response
    """

    url = os.path.join(self.base_url, endpoint)

    if not self.authenticated:
        raise Exception("Client is not authenticated.")

    if additional_headers is None:
        headers = self.__get_headers()
    else:
        headers = self.__get_headers() | additional_headers

    response = requests.request(
        method, url, data=data, headers=headers, params=params, json=json
    )

    return response