Determine the fill price of each spread

This commit is contained in:
moshferatu 2023-09-20 11:48:26 -07:00
parent bd4ec63a0f
commit 034769ffc0

View File

@ -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)
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}')