> ## Documentation Index
> Fetch the complete documentation index at: https://molelcule.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Molecule Python SDK Client: Constructor and Methods

> Complete reference for the Molecule and AsyncMolecule Python client classes, including constructor parameters, sub-API namespaces, and convenience methods.

The `Molecule` and `AsyncMolecule` classes are the entry points to the SDK. Both expose the same sub-API namespaces — `Molecule` makes synchronous HTTP calls, while `AsyncMolecule` exposes an async `request()` coroutine suitable for use with `asyncio`. Ed25519 request signing happens inside the process; your private key is never transmitted.

## Molecule (Synchronous)

### Constructor

```python theme={"dark"}
from molecule import Molecule

client = Molecule(
    base_url="https://api.molecule.example",
    key_id="your-key-id",
    private_key="your-base64-encoded-seed",
)
```

<ParamField path="base_url" type="string" required>
  API base URL. Falls back to the `MOLECULE_BASE_URL` environment variable. The SDK raises `ValueError` at construction time if neither is set.
</ParamField>

<ParamField path="key_id" type="string">
  Trading key ID used to identify the signing key. Use together with `private_key` to enable Ed25519 request signing for trading routes. Falls back to `MOLECULE_KEY_ID`.
</ParamField>

<ParamField path="private_key" type="string | bytes">
  Ed25519 private key. Provide the base64-encoded 32-byte seed (the canonical format). Also accepts a hex string or raw bytes. The key never leaves the process. Falls back to `MOLECULE_PRIVATE_KEY`.
</ParamField>

<ParamField path="token" type="string">
  JWT token for management routes. Mutually exclusive with `key_id`/`private_key` for authentication — use one or the other.
</ParamField>

<ParamField path="timeout" type="float" default="30.0">
  HTTP request timeout in seconds applied to all REST calls.
</ParamField>

<ParamField path="transport" type="httpx.BaseTransport">
  Custom `httpx` transport, useful for testing with a mock transport or configuring proxies.
</ParamField>

### Context Manager

Use `Molecule` as a context manager to ensure the client is properly closed after use:

```python theme={"dark"}
from molecule import Molecule

with Molecule(
    base_url="https://api.molecule.example",
    key_id="your-key-id",
    private_key="your-base64-encoded-seed",
) as client:
    venues = client.markets.venues()
    print(venues)
```

## AsyncMolecule (Asynchronous)

`AsyncMolecule` accepts the same constructor parameters as `Molecule`. Its `request()` method is a coroutine — await it inside an async context. The sub-API namespaces (`markets`, `orders`, `portfolio`, etc.) are available as attributes and work the same way as on the synchronous client.

```python theme={"dark"}
import asyncio
from molecule import AsyncMolecule

async def main():
    client = AsyncMolecule(
        base_url="https://api.molecule.example",
        key_id="your-key-id",
        private_key="your-base64-encoded-seed",
    )
    response = await client.request("GET", "/v1/venues")
    print(response)

asyncio.run(main())
```

<ParamField path="transport" type="httpx.AsyncBaseTransport">
  Custom async `httpx` transport for `AsyncMolecule`, useful for testing or proxy configuration.
</ParamField>

## Sub-API Namespaces

Each namespace groups a set of related endpoints. Access them as attributes on the client instance.

| Namespace | Description |
| - | - |
| `client.markets` | Search, retrieve, and stream market data across venues |
| `client.orders` | Create, amend, cancel, and query individual orders |
| `client.complex_orders` | Manage algorithmic order types: ICEBERG, PEG, STOP, TP\_SL, SMART\_ROUTE |
| `client.portfolio` | Query positions, balances, fills, P\&L, fees, and fair values |
| `client.risk` | Read and update risk limits, trigger kill-switch, cancel all orders |
| `client.ws` | Build signed WebSocket URLs for real-time streaming |

## Convenience Methods

The `Molecule` client exposes shortcut methods for the most common operations. Each one delegates to the corresponding sub-API method.

### `client.search_markets(**params)`

Shortcut for `client.markets.search()`. Pass any supported search parameters as keyword arguments.

```python theme={"dark"}
results = client.search_markets(q="election", venue="POLYMARKET", status="open")
```

### `client.create_order(**payload)`

Shortcut for `client.orders.create()`. Pass the full order payload as keyword arguments.

```python theme={"dark"}
order = client.create_order(
    subaccount_id="sub-1",
    instrument_id="instrument-abc",
    side="BUY",
    type="LIMIT",
    tif="GTC",
    price="0.65",
    qty="100",
    routing={"mode": "DIRECT"},
    client_order_id="order-001",
)
```

### `client.create_complex_order(**payload)`

Shortcut for `client.complex_orders.create()`. Pass the full complex order payload as keyword arguments.

```python theme={"dark"}
order = client.create_complex_order(
    subaccount_id="sub-1",
    type="ICEBERG",
    idempotency_key="iceberg-001",
    # ... additional type-specific fields
)
```

### `client.positions(subaccount_id)`

Shortcut for `client.portfolio.positions()`. Returns all open positions for the specified subaccount.

```python theme={"dark"}
positions = client.positions("sub-1")
```

### `client.iter_ws(path, params)`

Yields parsed JSON messages from a signed WebSocket connection. The method handles URL signing, connection management, and JSON decoding. Iterate over it with a `for` loop.

```python theme={"dark"}
for message in client.iter_ws("/v1/ws/orders", {"subaccount_id": "sub-1"}):
    print(message)
```

<Tip>
  `iter_ws` is a blocking generator available on `Molecule` only. Run it in a dedicated thread or use an async framework if you need to consume multiple WebSocket streams concurrently.
</Tip>


This documentation is built and hosted on [Mintlify](https://mintlify.com), a developer documentation platform.