Skip to content

Commit

Permalink
mark old orders stale
Browse files Browse the repository at this point in the history
  • Loading branch information
r0fls committed Nov 26, 2024
1 parent d8fb223 commit d0d1a59
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 2 deletions.
13 changes: 13 additions & 0 deletions database/db_manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,19 @@ async def add_account_info(self, account_info):
await session.rollback()
logger.error('Failed to add account info', extra={'error': str(e)})

async def update_trade_status(self, trade_id, status):
async with self.Session() as session:
try:
logger.debug('Updating trade status', extra={'trade_id': trade_id, 'status': status})
result = await session.execute(select(Trade).filter_by(id=trade_id))
trade = result.scalar()
trade.status = status
await session.commit()
logger.debug('Trade status updated', extra={'trade': trade})
except Exception as e:
await session.rollback()
logger.error('Failed to update trade status', extra={'error': str(e)})

async def get_trade(self, trade_id):
async with self.Session() as session:
try:
Expand Down
28 changes: 26 additions & 2 deletions order_manager/manager.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from database.db_manager import DBManager
from utils.logger import logger

MARK_ORDER_STALE_AFTER = 60 * 60 * 24 * 2 # 2 days

class OrderManager:
def __init__(self, engine, brokers):
logger.info('Initializing OrderManager')
Expand All @@ -15,9 +17,31 @@ async def reconcile_orders(self, orders):
# Commit the transaction

async def reconcile_order(self, order):
logger.info(f'Reconciling order {order.id}', extra={'order_id': order.id, 'broker': order.broker, 'symbol': order.symbol, 'quantity': order.quantity, 'price': order.price, 'side': order.side, 'status': order.status})
logger.info(f'Reconciling order {order.id}', extra={
'order_id': order.id,
'broker': order.broker,
'symbol': order.symbol,
'quantity': order.quantity,
'price': order.price,
'side': order.side,
'status': order.status
})

# Calculate the stale threshold
stale_threshold = datetime.utcnow() - timedelta(seconds=MARK_ORDER_STALE_AFTER)

# Check if the order is stale
if order.timestamp < stale_threshold and order.status not in ['filled', 'canceled']:
try:
logger.info(f'Marking order {order.id} as stale', extra={'order_id': order.id})
await self.db_manager.update_trade_status(order.id, 'stale')
return # Exit early if the order is stale
except Exception as e:
logger.error(f'Error marking order {order.id} as stale', extra={'error': str(e)})
return

# If the order is not stale, reconcile it
broker = self.brokers[order.broker]
# TODO: handle partial fill
filled = await broker.is_order_filled(order.id)
if filled:
try:
Expand Down

0 comments on commit d0d1a59

Please sign in to comment.