Skip to content

Commit

Permalink
Slightly better error handling
Browse files Browse the repository at this point in the history
  • Loading branch information
ystxn committed Aug 17, 2024
1 parent e663dce commit 0a6189c
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 28 deletions.
48 changes: 26 additions & 22 deletions ibkr.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,32 +27,36 @@ def get_positions(self):
account_id = client.portfolio_accounts().data[0]['id']
full_positions = client.positions(account_id = account_id).data

marketdata_fields = {
'31': 'lastPrice',
'80': 'unrealizedPnlPercent',
'78': 'dailyPnl',
}
client.portfolio_accounts()
marketdata = client.live_marketdata_snapshot(
conids = [ str(item['conid']) for item in full_positions ],
fields = list(marketdata_fields.keys())
).data

marketdata_fields['conid'] = 'conid'
processed_marketdata = [
{ marketdata_fields[key]: value for key, value in item.items() if key in marketdata_fields }
for item in marketdata
]

positions_fields = [ 'avgCost', 'conid', 'ticker', 'name', 'unrealizedPnl', 'mktValue' ]
positions = [
{ k: v for k, v in d.items() if k in positions_fields }
for d in full_positions
]

merged = [
{ **pos, **next(md for md in processed_marketdata if md['conid'] == pos['conid']) }
for pos in positions
]
marketdata_fields = {
'31': 'lastPrice',
'80': 'unrealizedPnlPercent',
'78': 'dailyPnl',
}

return [ self.clean(row) for row in merged ]
try:
client.portfolio_accounts()
marketdata = client.live_marketdata_snapshot(
conids = [ str(item['conid']) for item in full_positions ],
fields = list(marketdata_fields.keys())
).data

marketdata_fields['conid'] = 'conid'
processed_marketdata = [
{ marketdata_fields[key]: value for key, value in item.items() if key in marketdata_fields }
for item in marketdata
]

merged = [
{ **pos, **next(md for md in processed_marketdata if md['conid'] == pos['conid']) }
for pos in positions
]

return [ self.clean(row) for row in merged ]
except Exception:
return positions
10 changes: 8 additions & 2 deletions main.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
from fastapi import FastAPI
from fastapi import FastAPI, HTTPException
from fastapi.staticfiles import StaticFiles
from ibkr import Ibkr
import traceback
import sys

app = FastAPI()

@app.get("/positions")
async def positions():
return Ibkr().get_positions()
try:
return Ibkr().get_positions()
except Exception:
exc_info = sys.exc_info()
raise HTTPException(status_code=500, detail=''.join(traceback.format_exception(*exc_info)))

app.mount("/", StaticFiles(directory="static", html = True), name="static")
9 changes: 5 additions & 4 deletions static/main.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import { render } from 'preact';
import { useState, useEffect } from 'preact/hooks';
import { html } from 'htm/preact';

const formatNumber = (input) => input.toLocaleString('en-US', {
const formatNumber = (input) => !input ? '' : input.toLocaleString('en-US', {
minimumFractionDigits: 2,
maximumFractionDigits: 2,
});
Expand Down Expand Up @@ -93,6 +93,7 @@ const Main = () => {
const [ data, setData ] = useState([]);
const [ summary, setSummary ] = useState({});
const [ sort, setSort ] = useState({ field: 'changePercent', order: 'desc' });
const [ error, setError ] = useState('');

useEffect(() => {
fetch('positions')
Expand All @@ -103,7 +104,7 @@ const Main = () => {
throw Error(await response.text());
})
.then((response) => setData(sortData(response, sort.field, sort.order)))
.catch((e) => console.error(e));
.catch((e) => setError(e.message));
}, []);

useEffect(() => {
Expand All @@ -128,13 +129,13 @@ const Main = () => {
setData(sortData(data, sort.field, sort.order));
}, [ sort ]);

return data.length === 0 ? 'Loading..' : html`
return error || (!data.length ? 'Loading..' : html`
<div class="table">
<${Headers} sort=${sort} setSort=${setSort} />
<${DataRows} data=${data} />
<${SummaryTow} summary=${summary} />
</div>
`;
`);
};

render(html`<${Main} />`, document.getElementById('root'));

0 comments on commit 0a6189c

Please sign in to comment.