brokerage-connect 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (28) hide show
  1. brokerage_connect-0.1.0/.gitignore +10 -0
  2. brokerage_connect-0.1.0/LICENSE +21 -0
  3. brokerage_connect-0.1.0/PKG-INFO +77 -0
  4. brokerage_connect-0.1.0/README.md +54 -0
  5. brokerage_connect-0.1.0/brokerage/__init__.py +35 -0
  6. brokerage_connect-0.1.0/brokerage/_logging.py +59 -0
  7. brokerage_connect-0.1.0/brokerage/_vendor.py +76 -0
  8. brokerage_connect-0.1.0/brokerage/broker_adapter.py +95 -0
  9. brokerage_connect-0.1.0/brokerage/config.py +51 -0
  10. brokerage_connect-0.1.0/brokerage/ibkr/__init__.py +3 -0
  11. brokerage_connect-0.1.0/brokerage/ibkr/adapter.py +603 -0
  12. brokerage_connect-0.1.0/brokerage/plaid/__init__.py +34 -0
  13. brokerage_connect-0.1.0/brokerage/plaid/client.py +289 -0
  14. brokerage_connect-0.1.0/brokerage/plaid/connections.py +109 -0
  15. brokerage_connect-0.1.0/brokerage/plaid/secrets.py +140 -0
  16. brokerage_connect-0.1.0/brokerage/schwab/__init__.py +19 -0
  17. brokerage_connect-0.1.0/brokerage/schwab/adapter.py +610 -0
  18. brokerage_connect-0.1.0/brokerage/schwab/client.py +330 -0
  19. brokerage_connect-0.1.0/brokerage/snaptrade/__init__.py +42 -0
  20. brokerage_connect-0.1.0/brokerage/snaptrade/_shared.py +175 -0
  21. brokerage_connect-0.1.0/brokerage/snaptrade/adapter.py +389 -0
  22. brokerage_connect-0.1.0/brokerage/snaptrade/client.py +257 -0
  23. brokerage_connect-0.1.0/brokerage/snaptrade/connections.py +318 -0
  24. brokerage_connect-0.1.0/brokerage/snaptrade/secrets.py +174 -0
  25. brokerage_connect-0.1.0/brokerage/snaptrade/trading.py +283 -0
  26. brokerage_connect-0.1.0/brokerage/snaptrade/users.py +97 -0
  27. brokerage_connect-0.1.0/brokerage/trade_objects.py +463 -0
  28. brokerage_connect-0.1.0/pyproject.toml +26 -0
@@ -0,0 +1,10 @@
1
+ venv/
2
+ __pycache__/
3
+ *.pyc
4
+ .DS_Store
5
+ .env
6
+ cache/
7
+ dist/
8
+ *.egg-info/
9
+ .mypy_cache/
10
+ .pytest_cache/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Henry Chien
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.
@@ -0,0 +1,77 @@
1
+ Metadata-Version: 2.4
2
+ Name: brokerage-connect
3
+ Version: 0.1.0
4
+ Summary: Unified Python interface for brokerage APIs — Schwab, SnapTrade, IBKR, Plaid
5
+ License-Expression: MIT
6
+ License-File: LICENSE
7
+ Requires-Python: >=3.11
8
+ Requires-Dist: python-dotenv
9
+ Provides-Extra: ibkr
10
+ Requires-Dist: ib-async; extra == 'ibkr'
11
+ Provides-Extra: plaid
12
+ Requires-Dist: boto3; extra == 'plaid'
13
+ Requires-Dist: botocore; extra == 'plaid'
14
+ Requires-Dist: certifi; extra == 'plaid'
15
+ Requires-Dist: plaid-python; extra == 'plaid'
16
+ Provides-Extra: schwab
17
+ Requires-Dist: schwab-py; extra == 'schwab'
18
+ Provides-Extra: snaptrade
19
+ Requires-Dist: boto3; extra == 'snaptrade'
20
+ Requires-Dist: botocore; extra == 'snaptrade'
21
+ Requires-Dist: snaptrade-python-sdk; extra == 'snaptrade'
22
+ Description-Content-Type: text/markdown
23
+
24
+ # brokerage-connect
25
+
26
+ Unified Python interface for brokerage APIs. One abstract adapter, multiple brokers.
27
+
28
+ ## Supported Brokers
29
+
30
+ | Broker | Extra | Status |
31
+ |--------|-------|--------|
32
+ | **Schwab** | `pip install brokerage-connect[schwab]` | Token-based auth via `schwab-py` |
33
+ | **SnapTrade** | `pip install brokerage-connect[snaptrade]` | OAuth connection flow |
34
+ | **IBKR** | `pip install brokerage-connect[ibkr]` | Gateway/TWS via `ib-async` |
35
+ | **Plaid** | `pip install brokerage-connect[plaid]` | Investments + account APIs via `plaid-python` |
36
+
37
+ ## Install
38
+
39
+ ```bash
40
+ pip install brokerage-connect
41
+
42
+ # With broker-specific dependencies:
43
+ pip install brokerage-connect[schwab]
44
+ pip install brokerage-connect[schwab,ibkr]
45
+ pip install brokerage-connect[plaid]
46
+ ```
47
+
48
+ ## Quick Start
49
+
50
+ ```python
51
+ from brokerage import BrokerAdapter
52
+
53
+ # Every broker adapter implements the same interface:
54
+ class MyBroker(BrokerAdapter):
55
+ provider_name = "my_broker"
56
+
57
+ def owns_account(self, account_id: str) -> bool: ...
58
+ def list_accounts(self): ...
59
+ def search_symbol(self, account_id, ticker): ...
60
+ def preview_order(self, account_id, ticker, side, quantity, order_type, time_in_force, **kw): ...
61
+ def place_order(self, account_id, order_params): ...
62
+ def get_orders(self, account_id, state="all", days=30): ...
63
+ def cancel_order(self, account_id, order_id): ...
64
+ def get_account_balance(self, account_id): ...
65
+ def refresh_after_trade(self, account_id): ...
66
+ ```
67
+
68
+ ## Architecture
69
+
70
+ - **`BrokerAdapter`** — abstract base class defining the trade interface
71
+ - **`trade_objects`** — shared dataclasses (`OrderResult`, `OrderPreview`, `OrderStatus`, etc.)
72
+ - **`schwab/`**, **`snaptrade/`**, **`ibkr/`**, **`plaid/`** — broker/provider integrations
73
+ - **`config.py`** — broker configuration and credential loading via environment variables
74
+
75
+ ## License
76
+
77
+ MIT
@@ -0,0 +1,54 @@
1
+ # brokerage-connect
2
+
3
+ Unified Python interface for brokerage APIs. One abstract adapter, multiple brokers.
4
+
5
+ ## Supported Brokers
6
+
7
+ | Broker | Extra | Status |
8
+ |--------|-------|--------|
9
+ | **Schwab** | `pip install brokerage-connect[schwab]` | Token-based auth via `schwab-py` |
10
+ | **SnapTrade** | `pip install brokerage-connect[snaptrade]` | OAuth connection flow |
11
+ | **IBKR** | `pip install brokerage-connect[ibkr]` | Gateway/TWS via `ib-async` |
12
+ | **Plaid** | `pip install brokerage-connect[plaid]` | Investments + account APIs via `plaid-python` |
13
+
14
+ ## Install
15
+
16
+ ```bash
17
+ pip install brokerage-connect
18
+
19
+ # With broker-specific dependencies:
20
+ pip install brokerage-connect[schwab]
21
+ pip install brokerage-connect[schwab,ibkr]
22
+ pip install brokerage-connect[plaid]
23
+ ```
24
+
25
+ ## Quick Start
26
+
27
+ ```python
28
+ from brokerage import BrokerAdapter
29
+
30
+ # Every broker adapter implements the same interface:
31
+ class MyBroker(BrokerAdapter):
32
+ provider_name = "my_broker"
33
+
34
+ def owns_account(self, account_id: str) -> bool: ...
35
+ def list_accounts(self): ...
36
+ def search_symbol(self, account_id, ticker): ...
37
+ def preview_order(self, account_id, ticker, side, quantity, order_type, time_in_force, **kw): ...
38
+ def place_order(self, account_id, order_params): ...
39
+ def get_orders(self, account_id, state="all", days=30): ...
40
+ def cancel_order(self, account_id, order_id): ...
41
+ def get_account_balance(self, account_id): ...
42
+ def refresh_after_trade(self, account_id): ...
43
+ ```
44
+
45
+ ## Architecture
46
+
47
+ - **`BrokerAdapter`** — abstract base class defining the trade interface
48
+ - **`trade_objects`** — shared dataclasses (`OrderResult`, `OrderPreview`, `OrderStatus`, etc.)
49
+ - **`schwab/`**, **`snaptrade/`**, **`ibkr/`**, **`plaid/`** — broker/provider integrations
50
+ - **`config.py`** — broker configuration and credential loading via environment variables
51
+
52
+ ## License
53
+
54
+ MIT
@@ -0,0 +1,35 @@
1
+ """Public exports for extracted brokerage contracts and adapters."""
2
+
3
+ from brokerage.broker_adapter import BrokerAdapter
4
+ from brokerage.trade_objects import (
5
+ ALLOWED_ORDER_TYPES,
6
+ ALLOWED_SIDES,
7
+ ALLOWED_TIME_IN_FORCE,
8
+ BrokerAccount,
9
+ CancelResult,
10
+ OrderListResult,
11
+ OrderPreview,
12
+ OrderResult,
13
+ OrderStatus,
14
+ PreTradeValidation,
15
+ TradeExecutionResult,
16
+ TradePreviewResult,
17
+ _iso,
18
+ )
19
+
20
+ __all__ = [
21
+ "ALLOWED_ORDER_TYPES",
22
+ "ALLOWED_SIDES",
23
+ "ALLOWED_TIME_IN_FORCE",
24
+ "BrokerAccount",
25
+ "BrokerAdapter",
26
+ "CancelResult",
27
+ "OrderListResult",
28
+ "OrderPreview",
29
+ "OrderResult",
30
+ "OrderStatus",
31
+ "PreTradeValidation",
32
+ "TradeExecutionResult",
33
+ "TradePreviewResult",
34
+ "_iso",
35
+ ]
@@ -0,0 +1,59 @@
1
+ """Brokerage package-local logging shims with monorepo fallback behavior."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import logging
6
+ import sys
7
+ from typing import Any
8
+
9
+
10
+ def _make_fallback_logger(name: str) -> logging.Logger:
11
+ logger = logging.getLogger(f"brokerage.{name}")
12
+ if not logger.handlers:
13
+ handler = logging.StreamHandler(sys.stderr)
14
+ handler.setFormatter(logging.Formatter("%(asctime)s [%(name)s] %(levelname)s: %(message)s"))
15
+ logger.addHandler(handler)
16
+ logger.setLevel(logging.INFO)
17
+ return logger
18
+
19
+
20
+ try:
21
+ from utils.logging import (
22
+ log_alert,
23
+ log_critical_alert,
24
+ log_error,
25
+ log_event,
26
+ log_portfolio_operation,
27
+ log_service_health,
28
+ plaid_logger,
29
+ portfolio_logger,
30
+ trading_logger,
31
+ )
32
+ except Exception:
33
+ portfolio_logger = _make_fallback_logger("portfolio")
34
+ trading_logger = _make_fallback_logger("trading")
35
+ plaid_logger = _make_fallback_logger("plaid")
36
+
37
+ def log_error(module: str, operation: str, error: Any, **kwargs: Any) -> None:
38
+ portfolio_logger.warning(
39
+ "[%s:%s] %s (extra=%s)",
40
+ module,
41
+ operation,
42
+ error,
43
+ kwargs,
44
+ )
45
+
46
+ def log_portfolio_operation(operation: str, details: Any) -> None:
47
+ portfolio_logger.info("[%s] %s", operation, details)
48
+
49
+ def log_critical_alert(*args: Any, **kwargs: Any) -> None:
50
+ return None
51
+
52
+ def log_service_health(*args: Any, **kwargs: Any) -> None:
53
+ return None
54
+
55
+ def log_alert(*args: Any, **kwargs: Any) -> None:
56
+ return None
57
+
58
+ def log_event(*args: Any, **kwargs: Any) -> None:
59
+ return None
@@ -0,0 +1,76 @@
1
+ """Vendor helpers used by the standalone brokerage package."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from datetime import datetime
6
+ from typing import Any
7
+
8
+ try:
9
+ import numpy as np
10
+ except Exception: # pragma: no cover - optional dependency
11
+ np = None
12
+
13
+ try:
14
+ import pandas as pd
15
+ except Exception: # pragma: no cover - optional dependency
16
+ pd = None
17
+
18
+
19
+ def make_json_safe(obj: Any) -> Any:
20
+ """Recursively convert values into JSON-serializable forms."""
21
+ if isinstance(obj, dict):
22
+ safe_dict = {}
23
+ for key, value in obj.items():
24
+ if pd is not None and isinstance(key, (pd.Timestamp, datetime)):
25
+ safe_key = key.strftime("%Y-%m-%d %H:%M:%S")
26
+ elif isinstance(key, (int, float, str, bool, type(None))):
27
+ safe_key = key
28
+ else:
29
+ safe_key = str(key)
30
+ safe_dict[safe_key] = make_json_safe(value)
31
+ return safe_dict
32
+
33
+ if isinstance(obj, list):
34
+ return [make_json_safe(item) for item in obj]
35
+
36
+ if pd is not None and isinstance(obj, pd.DataFrame):
37
+ return obj.to_dict("records")
38
+
39
+ if pd is not None and isinstance(obj, pd.Series):
40
+ return {str(k): make_json_safe(v) for k, v in obj.to_dict().items()}
41
+
42
+ if np is not None and isinstance(obj, np.ndarray):
43
+ return obj.tolist()
44
+
45
+ if np is not None and isinstance(obj, (np.int64, np.int32)):
46
+ return int(obj)
47
+
48
+ if np is not None and isinstance(obj, (np.float64, np.float32)):
49
+ return float(obj)
50
+
51
+ if np is not None and isinstance(obj, np.bool_):
52
+ return bool(obj)
53
+
54
+ if pd is not None and isinstance(obj, (pd.Timestamp, datetime)):
55
+ return obj.strftime("%Y-%m-%d %H:%M:%S")
56
+
57
+ if pd is not None:
58
+ try:
59
+ if pd.isna(obj):
60
+ return None
61
+ except Exception:
62
+ pass
63
+
64
+ if isinstance(obj, (int, float, str, bool, type(None))):
65
+ return obj
66
+
67
+ return str(obj)
68
+
69
+
70
+ def _to_float(value: Any) -> float | None:
71
+ try:
72
+ if value is None:
73
+ return None
74
+ return float(value)
75
+ except (TypeError, ValueError):
76
+ return None
@@ -0,0 +1,95 @@
1
+ """Abstract broker adapter interface for trade operations."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from abc import ABC, abstractmethod
6
+ from typing import Any, Dict, List, Optional
7
+
8
+ from brokerage.trade_objects import (
9
+ BrokerAccount,
10
+ CancelResult,
11
+ OrderPreview,
12
+ OrderResult,
13
+ OrderStatus,
14
+ )
15
+
16
+
17
+ class BrokerAdapter(ABC):
18
+ """Abstract trade adapter contract used by ``TradeExecutionService``.
19
+
20
+ Called by:
21
+ - ``services.trade_execution_service.TradeExecutionService``.
22
+
23
+ Implemented by:
24
+ - SnapTrade/IBKR/Schwab adapter classes.
25
+
26
+ Contract semantics:
27
+ - Methods should raise clear exceptions on broker-side errors.
28
+ - Returned dataclasses in ``core.trade_objects`` must be populated with
29
+ broker-native details in ``broker_data`` where available.
30
+ """
31
+
32
+ @property
33
+ @abstractmethod
34
+ def provider_name(self) -> str:
35
+ """Return the provider identifier (e.g., 'snaptrade', 'ibkr')."""
36
+
37
+ @abstractmethod
38
+ def owns_account(self, account_id: str) -> bool:
39
+ """Return True if this adapter manages the given account_id."""
40
+
41
+ @abstractmethod
42
+ def list_accounts(self) -> List[BrokerAccount]:
43
+ """List tradeable accounts managed by this broker."""
44
+
45
+ @abstractmethod
46
+ def search_symbol(self, account_id: str, ticker: str) -> Dict[str, Any]:
47
+ """Resolve a ticker symbol for the given account."""
48
+
49
+ @abstractmethod
50
+ def preview_order(
51
+ self,
52
+ account_id: str,
53
+ ticker: str,
54
+ side: str,
55
+ quantity: float,
56
+ order_type: str,
57
+ time_in_force: str,
58
+ limit_price: Optional[float] = None,
59
+ stop_price: Optional[float] = None,
60
+ symbol_id: Optional[str] = None,
61
+ ) -> OrderPreview:
62
+ """Preview an order and return estimated cost/commission."""
63
+
64
+ @abstractmethod
65
+ def place_order(
66
+ self,
67
+ account_id: str,
68
+ order_params: Dict[str, Any],
69
+ ) -> OrderResult:
70
+ """Place an order and return execution details."""
71
+
72
+ @abstractmethod
73
+ def get_orders(
74
+ self,
75
+ account_id: str,
76
+ state: str = "all",
77
+ days: int = 30,
78
+ ) -> List[OrderStatus]:
79
+ """Fetch order history from the broker."""
80
+
81
+ @abstractmethod
82
+ def cancel_order(
83
+ self,
84
+ account_id: str,
85
+ order_id: str,
86
+ ) -> CancelResult:
87
+ """Cancel an order and return status."""
88
+
89
+ @abstractmethod
90
+ def get_account_balance(self, account_id: str) -> Optional[float]:
91
+ """Return available cash balance for the account."""
92
+
93
+ @abstractmethod
94
+ def refresh_after_trade(self, account_id: str) -> None:
95
+ """Trigger post-trade position refresh/cache invalidation."""
@@ -0,0 +1,51 @@
1
+ """Brokerage package-local configuration loaded from environment variables."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import os
6
+ from pathlib import Path
7
+
8
+ try:
9
+ from dotenv import load_dotenv
10
+
11
+ _pkg_dir = Path(__file__).resolve().parent
12
+ load_dotenv(_pkg_dir / ".env", override=False)
13
+ load_dotenv(_pkg_dir.parent / ".env", override=False)
14
+ except Exception:
15
+ pass
16
+
17
+
18
+ def _int_env(name: str, default: int) -> int:
19
+ raw = os.getenv(name)
20
+ if raw is None:
21
+ return default
22
+ try:
23
+ return int(raw)
24
+ except (TypeError, ValueError):
25
+ return default
26
+
27
+
28
+ IBKR_READONLY: bool = os.getenv("IBKR_READONLY", "false").lower() == "true"
29
+ IBKR_AUTHORIZED_ACCOUNTS: list[str] = [
30
+ account.strip()
31
+ for account in os.getenv("IBKR_AUTHORIZED_ACCOUNTS", "").split(",")
32
+ if account.strip()
33
+ ]
34
+ IBKR_GATEWAY_HOST: str = os.getenv("IBKR_GATEWAY_HOST", "127.0.0.1")
35
+ IBKR_GATEWAY_PORT: int = _int_env("IBKR_GATEWAY_PORT", 7496)
36
+
37
+ SCHWAB_APP_KEY: str = os.getenv("SCHWAB_APP_KEY", "")
38
+ SCHWAB_APP_SECRET: str = os.getenv("SCHWAB_APP_SECRET", "")
39
+ SCHWAB_TOKEN_PATH: str = os.path.expanduser(os.getenv("SCHWAB_TOKEN_PATH", "~/.schwab_token.json"))
40
+ SCHWAB_CALLBACK_URL: str = os.getenv("SCHWAB_CALLBACK_URL", "https://127.0.0.1:8182")
41
+
42
+ SNAPTRADE_CLIENT_ID: str = os.getenv("SNAPTRADE_CLIENT_ID", "")
43
+ SNAPTRADE_CONSUMER_KEY: str = os.getenv("SNAPTRADE_CONSUMER_KEY", "")
44
+ SNAPTRADE_ENVIRONMENT: str = os.getenv("SNAPTRADE_ENVIRONMENT", "production")
45
+
46
+ PLAID_CLIENT_ID: str = os.getenv("PLAID_CLIENT_ID", "")
47
+ PLAID_SECRET: str = os.getenv("PLAID_SECRET", "")
48
+ PLAID_ENV: str = os.getenv("PLAID_ENV", "production")
49
+ AWS_DEFAULT_REGION: str = os.getenv("AWS_DEFAULT_REGION", "us-east-1")
50
+
51
+ FRONTEND_BASE_URL: str = os.getenv("FRONTEND_BASE_URL", "http://localhost:3000")
@@ -0,0 +1,3 @@
1
+ from brokerage.ibkr.adapter import IBKRBrokerAdapter, ibkr_to_common_status
2
+
3
+ __all__ = ["IBKRBrokerAdapter", "ibkr_to_common_status"]