-
Notifications
You must be signed in to change notification settings - Fork 1
Fix PDT gate to detect same-day filled orders (critical PDT protection) #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. Weβll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
IamJasonBian
wants to merge
2
commits into
main
Choose a base branch
from
pdt-guard-same-day-fills
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,118 @@ | ||
| """ | ||
| Test PDT Gate with current live positions and fills | ||
| """ | ||
|
|
||
| import sys | ||
| import os | ||
| from datetime import date | ||
|
|
||
| # Add parent directory to path | ||
| sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) | ||
|
|
||
| from utils.safe_cash_bot import SafeCashBot | ||
| from trading_system.execution.pdt_gate import PDTGate | ||
|
|
||
|
|
||
| def test_pdt_guard(): | ||
| """Test PDT guard against current live positions and fills.""" | ||
| print("\n" + "="*70) | ||
| print("PDT GATE TEST - LIVE DATA") | ||
| print("="*70 + "\n") | ||
|
|
||
| # Initialize bot and PDT gate | ||
| bot = SafeCashBot() | ||
| pdt_gate = PDTGate(trading_bot=bot) | ||
|
|
||
| # Get recent fills (stock and options) | ||
| print("Fetching recent fills (last 1 day)...\n") | ||
| recent_stock_orders = bot.get_recent_orders(days=1) | ||
| recent_option_orders = bot.get_recent_option_orders(days=1) | ||
|
|
||
| stock_fills = [o for o in recent_stock_orders if o['state'] in ('filled', 'confirmed')] | ||
| option_fills = [o for o in recent_option_orders if o['state'] == 'filled'] | ||
|
|
||
| print(f"Stock fills today: {len(stock_fills)}") | ||
| print(f"Option fills today: {len(option_fills)}\n") | ||
|
|
||
| # Display stock fills | ||
| if stock_fills: | ||
| print("STOCK FILLS TODAY:") | ||
| for fill in stock_fills: | ||
| print(f" {fill['side']} {fill['symbol']} x{fill['quantity']:.0f} @ ${fill.get('average_price', 0):.2f}") | ||
| print(f" Filled: {fill.get('last_transaction_at', 'N/A')}") | ||
| print() | ||
|
|
||
| # Display option fills | ||
| if option_fills: | ||
| print("OPTION FILLS TODAY:") | ||
| for fill in option_fills: | ||
| for leg in fill.get('legs', []): | ||
| print(f" {leg['side']} {leg['position_effect']} {leg['chain_symbol']} " | ||
| f"${leg['strike']:.2f} {leg['option_type'].upper()} exp {leg['expiration']}") | ||
| print(f" Premium: ${fill['processed_premium']:.2f}") | ||
| print(f" Updated: {fill['updated_at']}") | ||
| print() | ||
|
|
||
| # Test PDT checks for various scenarios | ||
| print("="*70) | ||
| print("PDT CHECK SCENARIOS") | ||
| print("="*70 + "\n") | ||
|
|
||
| # Collect unique symbols from fills | ||
| test_symbols = set() | ||
| for fill in stock_fills: | ||
| test_symbols.add(fill['symbol']) | ||
| for fill in option_fills: | ||
| for leg in fill.get('legs', []): | ||
| test_symbols.add(leg['chain_symbol']) | ||
|
|
||
| if not test_symbols: | ||
| print("No fills today - testing with common symbols: BTC, SPY, QQQ\n") | ||
| test_symbols = {'BTC', 'SPY', 'QQQ'} | ||
|
|
||
| # Test each symbol for both buy and sell | ||
| for symbol in sorted(test_symbols): | ||
| print(f"Testing {symbol}:") | ||
|
|
||
| # Test BUY | ||
| can_buy, buy_reason = pdt_gate.can_place_order(symbol, 'buy') | ||
| status = "β ALLOWED" if can_buy else "π« BLOCKED" | ||
| print(f" BUY: {status}") | ||
| print(f" {buy_reason}") | ||
|
|
||
| # Test SELL | ||
| can_sell, sell_reason = pdt_gate.can_place_order(symbol, 'sell') | ||
| status = "β ALLOWED" if can_sell else "π« BLOCKED" | ||
| print(f" SELL: {status}") | ||
| print(f" {sell_reason}") | ||
| print() | ||
|
|
||
| # Summary | ||
| print("="*70) | ||
| print("PDT GUARD STATUS") | ||
| print("="*70 + "\n") | ||
|
|
||
| pdt_info = bot.get_pdt_status() | ||
| if pdt_info: | ||
| count = pdt_info.get('day_trade_count', 0) | ||
| flagged = pdt_info.get('flagged', False) | ||
|
|
||
| print(f"Day Trades Used: {count}/3") | ||
| print(f"PDT Flagged: {'YES β οΈ' if flagged else 'NO β '}") | ||
| print(f"Remaining Day Trades: {3 - count}") | ||
|
|
||
| if flagged: | ||
| print("\nβ οΈ ACCOUNT IS PDT FLAGGED") | ||
| print(" Only position-closing sells are allowed") | ||
| elif count >= 2: | ||
| print("\nβ οΈ WARNING: Only 1 day trade remaining") | ||
| else: | ||
| print(f"\nβ Safe to trade ({3 - count} day trades remaining)") | ||
| else: | ||
| print("β Could not fetch PDT status") | ||
|
|
||
| print("\n" + "="*70 + "\n") | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| test_pdt_guard() | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -14,6 +14,9 @@ class PDTGate: | |
|
|
||
| def __init__(self, trading_bot=None): | ||
| self._trading_bot = trading_bot | ||
| # Cache of same-day transactions to prevent round trips | ||
| # Format: {symbol: {'buy': date_str, 'sell': date_str}} | ||
| self._same_day_fills = {} | ||
|
|
||
| def can_place_order(self, symbol: str, side: str) -> tuple: | ||
| """Check if an order is safe to place from a PDT perspective. | ||
|
|
@@ -59,7 +62,13 @@ def can_place_order(self, symbol: str, side: str) -> tuple: | |
| f"PDT warning: {day_trade_count}/3 day trades used, " | ||
| f"this {side} on {symbol} may create another (2/3)") | ||
|
|
||
| # Step 4: Safe to proceed | ||
| # Step 4: Would create day trade but we have capacity | ||
| if would_dt and day_trade_count == 0: | ||
| return (True, | ||
| f"β οΈ WILL CREATE DAY TRADE on {symbol} (opposite side filled today) β " | ||
| f"allowed ({day_trade_count}/3 used)") | ||
|
|
||
| # Step 5: Safe to proceed | ||
| return (True, f"PDT OK: {day_trade_count}/3 day trades") | ||
|
|
||
| except Exception as e: | ||
|
|
@@ -69,29 +78,117 @@ def _would_create_day_trade(self, symbol: str, side: str) -> bool: | |
| """Check if placing this order would create a day trade (round trip). | ||
|
|
||
| Returns True if there's a same-day opposite fill for this symbol. | ||
| Checks both: | ||
| 1. Recent filled orders from Robinhood API | ||
| 2. Local cache of same-day fills (updated on successful order placement) | ||
|
|
||
| Defensive: returns True on API failure (assume worst case). | ||
| """ | ||
| try: | ||
| open_orders = self._trading_bot.get_open_orders() | ||
| if not open_orders: | ||
| return False | ||
| # Clear old cached fills from previous days | ||
| self._clear_old_fills() | ||
|
|
||
| today = date.today().isoformat() | ||
| opposite_side = 'SELL' if side.lower() == 'buy' else 'BUY' | ||
| opposite_side = 'sell' if side.lower() == 'buy' else 'buy' | ||
|
|
||
| for order in open_orders: | ||
| # Check 1: Local cache (updated when orders fill) | ||
| if symbol in self._same_day_fills: | ||
| if opposite_side in self._same_day_fills[symbol]: | ||
| cached_date = self._same_day_fills[symbol][opposite_side] | ||
| if cached_date == today: | ||
| print(f" [pdt_gate] CACHE HIT: {symbol} {opposite_side.upper()} filled today") | ||
| return True | ||
|
|
||
| # Check 2: Recent filled stock orders from API (last 1 day) | ||
| recent_orders = self._trading_bot.get_recent_orders(days=1) | ||
|
|
||
| for order in recent_orders: | ||
| if order.get('symbol') != symbol: | ||
| continue | ||
| order_side = order.get('side', '').upper() | ||
|
|
||
| # Only check filled/confirmed orders | ||
| order_state = order.get('state', '').lower() | ||
| if order_state not in ('filled', 'confirmed'): | ||
| continue | ||
|
|
||
| # Check if it's the opposite side | ||
| order_side = order.get('side', '').lower() | ||
| if order_side != opposite_side: | ||
| continue | ||
| # Check if created today | ||
| created = order.get('created_at', '') | ||
| if isinstance(created, str) and created.startswith(today): | ||
|
|
||
| # Check if it FILLED today (not just created) | ||
| # Use last_transaction_at (when filled) instead of created_at | ||
| filled_at = order.get('last_transaction_at') or order.get('updated_at') | ||
| if isinstance(filled_at, str) and filled_at.startswith(today): | ||
| print(f" [pdt_gate] API HIT: {symbol} {order_side.upper()} filled today at {filled_at}") | ||
| # Update cache for future checks | ||
| self._record_fill(symbol, order_side) | ||
| return True | ||
|
|
||
| # Check 3: Recent filled option orders (options also count for PDT) | ||
| try: | ||
| recent_option_orders = self._trading_bot.get_recent_option_orders(days=1) | ||
|
|
||
| for order in recent_option_orders: | ||
| if order.get('state', '').lower() != 'filled': | ||
| continue | ||
|
|
||
| # Check each leg for same-day open+close on the same underlying | ||
| for leg in order.get('legs', []): | ||
| if leg.get('chain_symbol') != symbol: | ||
| continue | ||
|
|
||
| position_effect = leg.get('position_effect', '').lower() | ||
| leg_side = leg.get('side', '').lower() | ||
|
|
||
| # Map option position_effect to stock buy/sell equivalent | ||
| # BUY to open = debit (like buying stock) | ||
| # SELL to close = credit (like selling stock) | ||
| option_equiv_side = None | ||
| if position_effect == 'open': | ||
| option_equiv_side = 'buy' if leg_side == 'buy' else 'sell' | ||
| elif position_effect == 'close': | ||
| option_equiv_side = 'sell' if leg_side == 'sell' else 'buy' | ||
|
|
||
| if option_equiv_side == opposite_side: | ||
| filled_at = order.get('updated_at', '') | ||
| if isinstance(filled_at, str) and filled_at.startswith(today): | ||
|
Owner
Author
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
def _clear_old_fills(self):
today = date.today().isoformat()
self._same_day_fills = {
sym: {side: d for side, d in sides.items() if d == today}
for sym, sides in self._same_day_fills.items()
}
self._same_day_fills = {s: v for s, v in self._same_day_fills.items() if v}Generated by Claude Code |
||
| print(f" [pdt_gate] OPTION HIT: {symbol} option {position_effect} filled today") | ||
| self._record_fill(symbol, option_equiv_side) | ||
| return True | ||
| except Exception as e: | ||
| print(f" [pdt_gate] Option order check failed (continuing): {e}") | ||
|
|
||
| return False | ||
|
|
||
| except Exception as e: | ||
| print(f" [pdt_gate] _would_create_day_trade error: {e}") | ||
| return True # Assume worst case on failure | ||
|
|
||
| def _record_fill(self, symbol: str, side: str): | ||
| """Record that we filled a buy/sell for this symbol today.""" | ||
| today = date.today().isoformat() | ||
| if symbol not in self._same_day_fills: | ||
| self._same_day_fills[symbol] = {} | ||
| self._same_day_fills[symbol][side.lower()] = today | ||
| print(f" [pdt_gate] Recorded {symbol} {side.upper()} fill for today") | ||
|
|
||
| def _clear_old_fills(self): | ||
| """Remove fills from previous days to keep cache fresh.""" | ||
| today = date.today().isoformat() | ||
| symbols_to_remove = [] | ||
|
|
||
| for symbol in self._same_day_fills: | ||
| sides_to_remove = [] | ||
| for side, fill_date in self._same_day_fills[symbol].items(): | ||
| if fill_date != today: | ||
| sides_to_remove.append(side) | ||
|
|
||
| for side in sides_to_remove: | ||
| del self._same_day_fills[symbol][side] | ||
|
|
||
| if not self._same_day_fills[symbol]: | ||
| symbols_to_remove.append(symbol) | ||
|
|
||
| for symbol in symbols_to_remove: | ||
| del self._same_day_fills[symbol] | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This is a manual script, not a pytest test. It requires live Robinhood credentials, uses
sys.path.inserthacks, and prints results instead of asserting. It will fail in any CI environment and doesn't validate behavior deterministically.Suggestion: replace with proper unit tests that mock
SafeCashBotmethods (e.g.,get_recent_orders,get_recent_option_orders,get_pdt_status) and assert onPDTGate.can_place_orderreturn values. You can delete this file and still have better test coverage.Generated by Claude Code