Skip to content

Commit db1e3e8

Browse files
authored
Merge pull request #4 from Patch-Code-Prosperity/dev
post overhaul cleanup
2 parents 7e0a864 + 12db739 commit db1e3e8

File tree

7 files changed

+25
-18
lines changed

7 files changed

+25
-18
lines changed

accounts.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,18 @@
1-
from config import TRADER_BASE_URL
1+
import datetime
22
import logging
33

4+
45
class Accounts:
56
def __init__(self, client):
67
self.client = client
78
self.logger = logging.getLogger(__name__)
8-
self.base_url = TRADER_BASE_URL
9+
self.base_url = client.config.TRADER_BASE_URL
910

1011
def get_account_numbers(self):
1112
"""Retrieve account numbers associated with the user's profile."""
1213
try:
13-
return self.client.get(f'{self.base_url}/accountNumbers')
14+
response = self.client.get(f'{self.base_url}/accountNumbers')
15+
return response.json()
1416
except Exception as e:
1517
self.logger.error(f"Failed to get account numbers: {e}")
1618
return None

api_client.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
from datetime import datetime, timedelta
55
from config import APIConfig
66

7+
78
class APIClient:
89
def __init__(self):
910
self.session = requests.Session()
@@ -12,7 +13,7 @@ def __init__(self):
1213
if not self.validate_credentials():
1314
logging.error("Invalid or missing credentials. Please check your configuration.")
1415
exit(1)
15-
16+
1617
self.token_info = self.load_token() or self.authenticate()
1718

1819
def setup_logging(self):

config.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,15 +3,16 @@
33

44
load_dotenv()
55

6+
67
class APIConfig:
78
API_BASE_URL = "https://api.schwabapi.com"
89
TRADER_BASE_URL = f"{API_BASE_URL}/trader/v1"
910
MARKET_DATA_BASE_URL = f"{API_BASE_URL}/marketdata/v1"
1011
ORDER_BASE_URL = f"{API_BASE_URL}/accounts"
1112
REQUEST_TIMEOUT = 30 # Timeout for API requests in seconds
1213
RETRY_STRATEGY = {
13-
'total': 3, # Total number of retries to allow
14-
'backoff_factor': 1 # Factor by which the delay between retries will increase
14+
'total': 3, # Total number of retries to allow
15+
'backoff_factor': 1 # Factor by which the delay between retries will increase
1516
}
1617
TOKEN_REFRESH_THRESHOLD_SECONDS = 300 # Time in seconds before token expiration to attempt refresh
1718
DEBUG_MODE = False

main.py

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,16 +2,15 @@
22
from api_client import APIClient
33
from accounts import Accounts
44
from orders import Orders
5-
from market_data import MarketData
5+
66

77
def main():
88
client = APIClient() # Initialize the API client
99
accounts_api = Accounts(client)
1010
orders_api = Orders(client)
11-
market_data_api = MarketData(client)
1211

1312
# Get account numbers for linked accounts
14-
print(accounts_api.get_account_numbers().json())
13+
print(accounts_api.get_account_numbers())
1514

1615
# Get positions for linked accounts
1716
print(accounts_api.get_all_accounts().json())
@@ -46,7 +45,8 @@ def main():
4645
print(orders_api.get_orders(3000, datetime.now() - timedelta(days=7), datetime.now()).json())
4746

4847
# Get all transactions for an account
49-
print(accounts_api.get_account_transactions('account_hash', datetime.now() - timedelta(days=7), datetime.now(), "TRADE").json())
48+
print(accounts_api.get_account_transactions('account_hash', datetime.now() - timedelta(days=7), datetime.now(),
49+
"TRADE").json())
5050

5151
# Get user preferences for an account
5252
print(accounts_api.get_user_preferences('account_hash').json())
@@ -83,6 +83,8 @@ def main():
8383
# Get instruments for a CUSIP
8484
print(instruments.by_cusip("037833100").json()) # 037833100 = AAPL
8585

86+
8687
if __name__ == '__main__':
87-
print("Welcome to the unofficial Schwab API interface!\nGitHub: https://github.com/Patch-Code-Prosperity/Pythonic-Schwab-API")
88+
print(
89+
"Welcome to the unofficial Schwab API interface!\nGitHub: https://github.com/Patch-Code-Prosperity/Pythonic-Schwab-API")
8890
main()

market_data.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ def get_single(self, symbol_id, fields=None):
1515
params = {'fields': fields}
1616
return self.client.get(f"{self.base_url}/{symbol_id}", params=params)
1717

18+
1819
class Options:
1920
def __init__(self, client, base_url):
2021
self.client = client
@@ -24,6 +25,7 @@ def get_chains(self, symbol, **kwargs):
2425
params = {'symbol': symbol, **kwargs}
2526
return self.client.get(self.base_url, params=params)
2627

28+
2729
class PriceHistory:
2830
def __init__(self, client, base_url):
2931
self.client = client
@@ -33,6 +35,7 @@ def by_symbol(self, symbol, **kwargs):
3335
params = {'symbol': symbol, **kwargs}
3436
return self.client.get(self.base_url, params=params)
3537

38+
3639
class Movers:
3740
def __init__(self, client, base_url):
3841
self.client = client
@@ -42,6 +45,7 @@ def get_movers(self, index, **kwargs):
4245
params = {'index': index, **kwargs}
4346
return self.client.get(self.base_url, params=params)
4447

48+
4549
class MarketHours:
4650
def __init__(self, client, base_url):
4751
self.client = client
@@ -55,6 +59,7 @@ def by_market(self, market_id, date):
5559
params = {'date': date}
5660
return self.client.get(f"{self.base_url}/{market_id}", params=params)
5761

62+
5863
class Instruments:
5964
def __init__(self, client, base_url):
6065
self.client = client

orders.py

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,7 @@
1-
from config import ORDER_BASE_URL
2-
31
class Orders:
42
def __init__(self, client):
53
self.client = client
6-
self.base_url = ORDER_BASE_URL
4+
self.base_url = client.config.ORDER_BASE_URL
75

86
def get_orders(self, account_hash, max_results=100, from_entered_time=None, to_entered_time=None, status=None):
97
"""Retrieve a list of orders for a specified account."""

utilities.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,8 @@
1-
# utilities.py
2-
3-
import datetime
4-
51
def clean_params(params):
62
"""Remove None values from a dictionary of parameters."""
73
return {k: v for k, v in params.items() if v is not None}
84

5+
96
def convert_time(dt=None, format_type="8601"):
107
"""Convert datetime objects into a string format according to a specified type."""
118
if dt is None:
@@ -19,6 +16,7 @@ def convert_time(dt=None, format_type="8601"):
1916
formatter = formats.get(format_type, str)
2017
return formatter(dt)
2118

19+
2220
def format_list(items):
2321
"""Convert a list of items into a comma-separated string or return single item as string."""
2422
if items is None:

0 commit comments

Comments
 (0)