From 034769ffc0ffb5330a261f35203484140490b900 Mon Sep 17 00:00:00 2001 From: moshferatu Date: Wed, 20 Sep 2023 11:48:26 -0700 Subject: [PATCH] Determine the fill price of each spread --- iron_condor.py | 44 +++++++++++++++++++++++++++++++++++++++++--- 1 file changed, 41 insertions(+), 3 deletions(-) diff --git a/iron_condor.py b/iron_condor.py index 98835d2..8acafae 100644 --- a/iron_condor.py +++ b/iron_condor.py @@ -1,11 +1,12 @@ -from datetime import datetime +from datetime import datetime, timezone from dotenv import load_dotenv from ibkr import Client from option_type import CALL, PUT from os import getenv from tastytrade import Tastytrade -from tastytrade.order import create_credit_spread +from tastytrade.order import create_credit_spread, create_stop_limit_order from tastytrade.symbology import zero_dte_spx_contract as contract +from time import sleep load_dotenv() @@ -84,8 +85,45 @@ call_credit_spread = create_credit_spread( call_spread_limit_price, 1 ) +entry_time = datetime.now(timezone.utc).isoformat() + put_spread_result = tastytrade_client.submit_order(tastytrade_account, put_credit_spread) call_spread_result = tastytrade_client.submit_order(tastytrade_account, call_credit_spread) print(put_spread_result) -print(call_spread_result) \ No newline at end of file +print(call_spread_result) + +def spread_fill_price(short_position, long_position): + short_leg_price = float(short_position['average-open-price']) + long_leg_price = float(long_position['average-open-price']) + return short_leg_price - long_leg_price + +def fill_time(position): + return datetime.strptime(position["created-at"], '%Y-%m-%dT%H:%M:%S.%f%z') + +def wait_for_fill(): + while True: + positions = tastytrade_client.get_positions(tastytrade_account) + positions = positions.get('data', {}).get('items', []) + print(positions) + # Consider only positions created after the order was submitted. + new_positions = [position for position in positions if fill_time(position) > entry_time] + + if len(new_positions) == 4: # Assuming no other positions, 4 legs in an iron condor. + short_put = next(p for p in new_positions if str(int(short_put_strike)) in p['symbol']) + long_put = next(p for p in new_positions if str(int(long_put_strike)) in p['symbol']) + short_call = next(p for p in new_positions if str(int(short_call_strike)) in p['symbol']) + long_call = next(p for p in new_positions if str(int(long_call_strike)) in p['symbol']) + + put_spread_fill_price = spread_fill_price(short_put, long_put) + call_spread_fill_price = spread_fill_price(short_call, long_call) + + return put_spread_fill_price, call_spread_fill_price + + # If not all positions are filled, sleep for a few seconds, then retry. + sleep(3) + +put_spread_fill_price, call_spread_fill_price = wait_for_fill() + +print(f'Put Spread Fill Price: {put_spread_fill_price}') +print(f'Call Spread Fill Price: {call_spread_fill_price}') \ No newline at end of file