Skip to main content

Introducing the Apex Python SDK

In today's fast-paced digital ecosystem, developers need tools that not only streamline the development process but also unlock new possibilities for innovation and efficiency.

Enter the Apex Python SDK, a cutting-edge software development kit designed to empower fintech app developers like never before. With our SDK, you can more easily integrate new account creation, optimize trading, and elevate your applications with realtime buying power, all through a seamless, SDK interface.

Whether you're building complex, data-driven platforms or simplified, user-centric applications, Apex Python SDK was created to offer the flexibility, power, and ease of use to bring your visions to life faster and more effectively. Join us in redefining the boundaries of what your applications can achieve. Start your journey with Apex today.

SDK Installation

PIP

pip install ascend-sdk

Poetry

poetry add ascend-sdk

Supported Python Versions

  • Python 3.9 or later

Initializing the SDK

The following sample shows how to initialise the SDK, using the API Key and Service Account Credentials you received during sign-up:

from ascend_sdk import SDK
from ascend_sdk.models import components

s = SDK(
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
)

# With an instance of the SDK, invoke any operation e.g.
resp = s.account_creation.get_account(account_id="VALID_ACCOUNT_ID")

Error Handling

SDKBaseError is the base class for all HTTP error responses. It has the following properties:

Property Type Description
err.message str Error message
err.status_code int HTTP response status code eg 404
err.headers httpx.Headers HTTP response headers
err.body str HTTP body. Can be empty string if no body is returned.
err.raw_response httpx.Response Raw HTTP response
err.data Optional. Some errors may contain structured data. See Error Classes.

Example

from ascend_sdk import SDK
from ascend_sdk.models import components, errors, operations


with SDK(
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:
    res = None
    try:

        res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

        assert res.account is not None

        # Handle response
        print(res.account)


    except errors.SDKBaseError as e:
        # The base class for HTTP error responses
        print(e.message)
        print(e.status_code)
        print(e.body)
        print(e.headers)
        print(e.raw_response)

        # Depending on the method different errors may be thrown
        if isinstance(e, errors.Status):
            print(e.data.code)  # Optional[int]
            print(e.data.details)  # Optional[List[components.AnyT]]
            print(e.data.message)  # Optional[str]

Error Classes

Primary errors:

  • SDKBaseError: The base class for HTTP error responses.
    • Status: The status message serves as the general-purpose service error message. Each status message includes a gRPC error code, error message, and error details. *
Less common errors (5)

Network errors:

Inherit from SDKBaseError:

  • ResponseValidationError: Type mismatch between the response data and the expected Pydantic model. Provides access to the Pydantic validation error via the cause attribute.

* Check the method documentation to see if the error is applicable.

Server Selection

Select Server by Name

You can override the default server globally by passing a server name to the server: str optional parameter when initializing the SDK client instance. The selected server will then be used as the default on the operations that use it. This table lists the names associated with the available servers:

Name Server Description
uat https://uat.apexapis.com our uat environment
prod https://api.apexapis.com our production environment
sbx https://sbx.apexapis.com our sandbox environment

Example

from ascend_sdk import SDK
from ascend_sdk.models import components, operations


with SDK(
    server="sbx",
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:

    res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

    assert res.account is not None

    # Handle response
    print(res.account)

Override Server URL Per-Client

The default server can also be overridden globally by passing a URL to the server_url: str optional parameter when initializing the SDK client instance. For example:

from ascend_sdk import SDK
from ascend_sdk.models import components, operations


with SDK(
    server_url="https://uat.apexapis.com",
    security=components.Security(
        api_key="ABCDEFGHIJ0123456789abcdefghij0123456789",
        service_account_creds=components.ServiceAccountCreds(
            private_key="-----BEGIN PRIVATE KEY--{OMITTED FOR BREVITY}",
            name="FinFirm",
            organization="correspondents/00000000-0000-0000-0000-000000000000",
            type="serviceAccount",
        ),
    ),
) as sdk:

    res = sdk.account_creation.get_account(account_id="01HC3MAQ4DR9QN1V8MJ4CN1HMK", view=operations.QueryParamView.FULL)

    assert res.account is not None

    # Handle response
    print(res.account)

Custom HTTP Client

The Python SDK makes API calls using the httpx HTTP library. In order to provide a convenient way to configure timeouts, cookies, proxies, custom headers, and other low-level configuration, you can initialize the SDK client with your own HTTP client instance. Depending on whether you are using the sync or async version of the SDK, you can pass an instance of HttpClient or AsyncHttpClient respectively, which are Protocol's ensuring that the client has the necessary methods to make API calls. This allows you to wrap the client with your own custom logic, such as adding custom headers, logging, or error handling, or you can just pass an instance of httpx.Client or httpx.AsyncClient directly.

For example, you could specify a header for every request that this sdk makes as follows:

from ascend_sdk import SDK
import httpx

http_client = httpx.Client(headers={"x-custom-header": "someValue"})
s = SDK(client=http_client)

or you could wrap the client with your own custom logic:

from ascend_sdk import SDK
from ascend_sdk.httpclient import AsyncHttpClient
import httpx

class CustomClient(AsyncHttpClient):
    client: AsyncHttpClient

    def __init__(self, client: AsyncHttpClient):
        self.client = client

    async def send(
        self,
        request: httpx.Request,
        *,
        stream: bool = False,
        auth: Union[
            httpx._types.AuthTypes, httpx._client.UseClientDefault, None
        ] = httpx.USE_CLIENT_DEFAULT,
        follow_redirects: Union[
            bool, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
    ) -> httpx.Response:
        request.headers["Client-Level-Header"] = "added by client"

        return await self.client.send(
            request, stream=stream, auth=auth, follow_redirects=follow_redirects
        )

    def build_request(
        self,
        method: str,
        url: httpx._types.URLTypes,
        *,
        content: Optional[httpx._types.RequestContent] = None,
        data: Optional[httpx._types.RequestData] = None,
        files: Optional[httpx._types.RequestFiles] = None,
        json: Optional[Any] = None,
        params: Optional[httpx._types.QueryParamTypes] = None,
        headers: Optional[httpx._types.HeaderTypes] = None,
        cookies: Optional[httpx._types.CookieTypes] = None,
        timeout: Union[
            httpx._types.TimeoutTypes, httpx._client.UseClientDefault
        ] = httpx.USE_CLIENT_DEFAULT,
        extensions: Optional[httpx._types.RequestExtensions] = None,
    ) -> httpx.Request:
        return self.client.build_request(
            method,
            url,
            content=content,
            data=data,
            files=files,
            json=json,
            params=params,
            headers=headers,
            cookies=cookies,
            timeout=timeout,
            extensions=extensions,
        )

s = SDK(async_client=CustomClient(httpx.AsyncClient()))

IDE Support

PyCharm

Generally, the SDK will work well with most IDEs out of the box. However, when using PyCharm, you can enjoy much better integration with Pydantic by installing an additional plugin.

Available Resources and Operations

Available methods

account_creation

account_management

account_transfers

ach_transfers

alternative_account_accreditation

alternative_investment_documents

alternative_investments

alternative_orders

asset_trading_config

assets

authentication

bank_relationships

basket_orders

buying_power

cash_balances

checks

cost_basis_service

data_retrieval

enrollments_and_agreements

fees_and_credits

fixed_income_pricing

instant_cash_transfer_ict

investigations

investor_docs

journals

ledger

option_instructions

option_orders

orders

person_management

position_journals

pre_ipo_companies

pre_ipo_funding_rounds

pre_ipo_news_events

pre_ipo_research_documents

reader

retirements

schedule_transfers

subscriber

test_simulation

trade_allocation

trade_booking

wires

Pagination

Some of the endpoints in this SDK support pagination. To use pagination, you make your SDK calls as usual, but the returned response object will have a Next method that can be called to pull down the next group of results. If the return value of Next is None, then there are no more pages to be fetched.

Here's an example of one such pagination call:

from ascend_sdk import SDK
from ascend_sdk.models import operations


with SDK() as sdk:

    res = sdk.authentication.list_signing_keys(security=operations.AuthenticationListSigningKeysSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), page_size=50, page_token="ZXhhbXBsZQo")

    while res is not None:
        # Handle items

        res = res.next()

Retries

Some of the endpoints in this SDK support retries. If you use the SDK without any configuration, it will fall back to the default retry strategy provided by the API. However, the default retry strategy can be overridden on a per-operation basis, or across the entire SDK.

To change the default retry strategy for a single API call, simply provide a RetryConfig object to the call:

from ascend_sdk import SDK
from ascend_sdk.models import operations
from ascend_sdk.utils import BackoffStrategy, RetryConfig


with SDK() as sdk:

    res = sdk.authentication.generate_service_account_token(security=operations.AuthenticationGenerateServiceAccountTokenSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), request={
        "jws": "eyJhbGciOiAiUlMyNTYifQ.eyJuYW1lIjogImpkb3VnaCIsIm9yZ2FuaXphdGlvbiI6ICJjb3JyZXNwb25kZW50cy8xMjM0NTY3OC0xMjM0LTEyMzQtMTIzNC0xMjM0NTY3ODkxMDEiLCJkYXRldGltZSI6ICIyMDI0LTAyLTA1VDIxOjAyOjI3LjkwMTE4MFoifQ.IMy3KmYoG8Ppf+7hXN7tm7J4MrNpQLGL7WCWvhh4nZWAVKkluL3/u3KC6hZ6Mb/5p7Y54CgZ68aWT2BcP5y4VtzIZR1Chm5pxbLfgE4aJuk+FnF6K3Gc3bBjOWCL58pxY2aTb0iU/exDEA1cbMDvbCzmY5kRefDvorLOqgUS/tS2MJ2jv4RlZFPlmHv5PtOruJ8xUW19gEgGhsPXYYeSHFTE1ZlaDvyXrKtpOvlf+FVc2RTuEw529LZnzwH4/eJJR3BpSpHyJTjQqiaMT3wzpXXYKfCRqnDkSSKJDzCzTb0/uWK/Lf0uafxPXk5YLdis+dbo1zNQhVVKjwnMpk1vLw",
    },
        RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False))

    assert res.token is not None

    # Handle response
    print(res.token)

If you'd like to override the default retry strategy for all operations that support retries, you can use the retry_config optional parameter when initializing the SDK:

from ascend_sdk import SDK
from ascend_sdk.models import operations
from ascend_sdk.utils import BackoffStrategy, RetryConfig


with SDK(
    retry_config=RetryConfig("backoff", BackoffStrategy(1, 50, 1.1, 100), False),
) as sdk:

    res = sdk.authentication.generate_service_account_token(security=operations.AuthenticationGenerateServiceAccountTokenSecurity(
        api_key_auth="<YOUR_API_KEY_HERE>",
    ), request={
        "jws": "eyJhbGciOiAiUlMyNTYifQ.eyJuYW1lIjogImpkb3VnaCIsIm9yZ2FuaXphdGlvbiI6ICJjb3JyZXNwb25kZW50cy8xMjM0NTY3OC0xMjM0LTEyMzQtMTIzNC0xMjM0NTY3ODkxMDEiLCJkYXRldGltZSI6ICIyMDI0LTAyLTA1VDIxOjAyOjI3LjkwMTE4MFoifQ.IMy3KmYoG8Ppf+7hXN7tm7J4MrNpQLGL7WCWvhh4nZWAVKkluL3/u3KC6hZ6Mb/5p7Y54CgZ68aWT2BcP5y4VtzIZR1Chm5pxbLfgE4aJuk+FnF6K3Gc3bBjOWCL58pxY2aTb0iU/exDEA1cbMDvbCzmY5kRefDvorLOqgUS/tS2MJ2jv4RlZFPlmHv5PtOruJ8xUW19gEgGhsPXYYeSHFTE1ZlaDvyXrKtpOvlf+FVc2RTuEw529LZnzwH4/eJJR3BpSpHyJTjQqiaMT3wzpXXYKfCRqnDkSSKJDzCzTb0/uWK/Lf0uafxPXk5YLdis+dbo1zNQhVVKjwnMpk1vLw",
    })

    assert res.token is not None

    # Handle response
    print(res.token)

Resource Management

The SDK class implements the context manager protocol and registers a finalizer function to close the underlying sync and async HTTPX clients it uses under the hood. This will close HTTP connections, release memory and free up other resources held by the SDK. In short-lived Python programs and notebooks that make a few SDK method calls, resource management may not be a concern. However, in longer-lived programs, it is beneficial to create a single SDK instance via a context manager and reuse it across the application.

from ascend_sdk import SDK
def main():

    with SDK() as sdk:
        # Rest of application here...


# Or when using async:
async def amain():

    async with SDK() as sdk:
        # Rest of application here...

Debugging

You can setup your SDK to emit debug logs for SDK requests and responses.

You can pass your own logger class directly into your SDK.

from ascend_sdk import SDK
import logging

logging.basicConfig(level=logging.DEBUG)
s = SDK(debug_logger=logging.getLogger("ascend_sdk"))

Qase TestOps Integration

Test results can be reported to Qase TestOps for centralized visibility using pytest's built-in --junitxml report and a small internal script to upload it. Neither is a module dependency of this SDK.

Running Tests with Qase Reporting

# Without Qase (default)
.venv/bin/pytest tests/ -v

# With Qase reporting: produce a JUnit report, then upload it
.venv/bin/pytest tests/ -v --junitxml=results.xml
QASE_API_TOKEN=<token> python3 ascend-sdk/scripts/testing/qase_report_junit.py --path results.xml --title "Ascend SDK Python Tests"

The upload script talks to the Qase REST API directly rather than relying on a native pytest plugin -- qase-pytest's own case-matching turned out to be unreliable for results with no pre-existing case, silently dropping most failed/errored results.

In CI, the test-published-sdk workflow reads the token from the GitHub organisation secret CDX_QASE_API_TOKEN, a Qase app token named cdx-sdk-tests-github-actions. Rotation steps are in the docstring of ascend-sdk/scripts/testing/qase_report_junit.py.

Metadata

Release files for ascend-sdk 1.8.14

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Built distribution (wheel)

Table of built distributions (wheels) for ascend-sdk 1.8.14
File Interpreter ABI Platform Actions
ascend_sdk-1.8.14-py3-none-any.whl Python 3 none any Details for ascend_sdk-1.8.14-py3-none-any.whl

Release files / ascend_sdk-1.8.14-py3-none-any.whl

Download URL ascend_sdk-1.8.14-py3-none-any.whl
Size 1.3 MB
Tags Python 3
SHA-256 checksum
How to use checksums
25f2560a2dc97f8dceb908d5692e3cdadbfe55eca610138eb47b8a4bee9a4081
BLAKE2b-256 checksum
How to use checksums
f4730b37933354f475f0b2b62c46e07984f9f6b9013e1853048a1df7bfafa81e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for ascend-sdk 1.8.14

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page