-
Notifications
You must be signed in to change notification settings - Fork 1
/
send_daily_spx_spread.py
206 lines (171 loc) · 7.98 KB
/
send_daily_spx_spread.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
import time
from datetime import date, timedelta, datetime
import requests
import secretsTDA
import pandas as pd
from tda import auth
from tda.utils import Utils
from interval import Interval
from tda.orders.options import bull_put_vertical_open
buf = []
def output_buf(text, webhook=False):
global buf
buf.append(text)
print(text)
if webhook:
headers = {'Content-type': 'application/json'}
data = {
"username": "bot",
"icon_emoji": ":ghost:",
"text": "\n".join(buf)
}
r = requests.post(secretsTDA.webhook_url, headers=headers, json=data)
r.raise_for_status()
buf = []
def now_in_interval(start_time, end_time):
now_localtime = time.strftime("%H:%M:%S", time.localtime())
now_time = Interval(now_localtime, now_localtime)
if now_time in Interval(start_time, end_time):
return True
else:
return False
def get_sell_put_spread_chains(main_price, put_chains_df, dte):
# Get sell put chain
strike_price = main_price
sp_df = put_chains_df[(put_chains_df.daysToExpiration == dte) & (put_chains_df.strikePrice == strike_price) & (put_chains_df.symbol.str.startswith("SPXW_"))]
if sp_df.shape[0] == 0:
strike_price = main_price - 5
sp_df = put_chains_df[(put_chains_df.daysToExpiration == dte) & (put_chains_df.strikePrice == strike_price) & (put_chains_df.symbol.str.startswith("SPXW_"))]
output_buf(f'Change sell put price to {strike_price}')
if sp_df.shape[0] == 0:
output_buf(f">> Can't find sell put chain by {strike_price=}, {dte=}")
return False, False
# Get buy put chain
strike_price_2 = strike_price - 50
bp_df = put_chains_df[(put_chains_df.daysToExpiration == dte) & (put_chains_df.strikePrice == strike_price_2) & (put_chains_df.symbol.str.startswith("SPXW_"))]
if bp_df.shape[0] == 0:
strike_price_2 = strike_price - 55
bp_df = put_chains_df[(put_chains_df.daysToExpiration == dte) & (put_chains_df.strikePrice == strike_price_2) & (put_chains_df.symbol.str.startswith("SPXW_"))]
output_buf(f'Change buy put price to {strike_price_2}')
if bp_df.shape[0] == 0:
output_buf(f">> Can't find buy put chain by {strike_price_2=}, {dte=}")
return False, False
return sp_df.to_dict('records')[0], bp_df.to_dict('records')[0]
def get_sell_call_spread_chains(main_price, call_chains_df, dte):
# Get sell call chain
strike_price = main_price
sp_df = call_chains_df[(call_chains_df.daysToExpiration == dte) & (call_chains_df.strikePrice == strike_price) & (call_chains_df.symbol.str.startswith("SPXW_"))]
if sp_df.shape[0] == 0:
strike_price = main_price + 5
sp_df = call_chains_df[(call_chains_df.daysToExpiration == dte) & (call_chains_df.strikePrice == strike_price) & (call_chains_df.symbol.str.startswith("SPXW_"))]
output_buf(f'Change sell call price to {strike_price}')
if sp_df.shape[0] == 0:
output_buf(f">> Can't find sell call chain by {strike_price=}, {dte=}")
return False, False
# Get buy call chain
strike_price_2 = strike_price + 50
bp_df = call_chains_df[(call_chains_df.daysToExpiration == dte) & (call_chains_df.strikePrice == strike_price_2) & (call_chains_df.symbol.str.startswith("SPXW_"))]
if bp_df.shape[0] == 0:
strike_price_2 = strike_price + 55
bp_df = call_chains_df[(call_chains_df.daysToExpiration == dte) & (call_chains_df.strikePrice == strike_price_2) & (call_chains_df.symbol.str.startswith("SPXW_"))]
output_buf(f'Change buy call price to {strike_price_2}')
if bp_df.shape[0] == 0:
output_buf(f">> Can't find buy call chain by {strike_price_2=}, {dte=}")
return False, False
return sp_df.to_dict('records')[0], bp_df.to_dict('records')[0]
def place_order(c, long_put_symbol, short_put_symbol, quantity, net_credit):
r = c.place_order(
secretsTDA.account_id,
bull_put_vertical_open(long_put_symbol, short_put_symbol, quantity, net_credit).build()
)
r.raise_for_status()
if r.status_code in [200, 201]:
order_id = Utils(c, secretsTDA.account_id).extract_order_id(r)
else:
output_buf(f'Send order failed: {r.status_code}')
def send_order(main_opt, min_opt, c):
# Get spread type
if main_opt["putCall"] == "PUT":
spread_type = "sell put"
quanity = SP_QUANITY
min_price = SP_MIN_PRICE
else:
spread_type = "sell call"
quanity = SC_QUANITY
min_price = SC_MIN_PRICE
# Get option middle price
mid_price = round(((main_opt["bid"] + main_opt["ask"]) - (min_opt["bid"] + min_opt["ask"])) / 2 // 0.05 * 0.05, 2)
order_price = max(mid_price, min_price)
description = " ".join(main_opt["description"].split(" ")[0:4])
output_buf(f'{description} {main_opt["strikePrice"]:.0f}/{min_opt["strikePrice"]:.0f} {spread_type} spread, {order_price=}')
# Send mid_price order
output_buf(f'\t Send {quanity - 1} order, get ${order_price*(quanity - 1)*100:,.0f} premium')
if PLACE_ORDER:
place_order(c, min_opt["symbol"], main_opt["symbol"], quanity - 1, order_price)
# Send mid_price+0.5 order
output_buf(f'\t Send 1 order, get ${(order_price + 0.05)*1*100:,.0f} premium')
if PLACE_ORDER:
place_order(c, min_opt["symbol"], main_opt["symbol"], 1, order_price + 0.05)
def main():
# Get days to expiration
today = datetime.today()
weekly = today.weekday() + 1
if weekly in [1, 2, 3, 4]:
dte = 1
elif weekly == 5:
dte = 3
else:
raise ValueError(f'{today} is Week {weekly}')
output_buf(f'Today is {today:%Y/%m/%d %H:%M}')
# Login TD
try:
c = auth.client_from_token_file(secretsTDA.token_path, secretsTDA.api_key)
except FileNotFoundError:
c = auth.client_from_manual_flow(secretsTDA.api_key, secretsTDA.redirect_uri, secretsTDA.token_path)
# Get latest SPX option chain
chains = c.get_option_chain(symbol="$SPX.X", to_date=date.today() + timedelta(days=dte)).json()
underlying_price = chains["underlyingPrice"]
output_buf(f'SPX index price: {underlying_price}')
# Get put option map
put_chains_df = pd.json_normalize(chains["putExpDateMap"])
put_chains_df = [pd.json_normalize(put_chains_df[c].explode()) for c in put_chains_df.columns]
put_chains_df = pd.concat(put_chains_df).reset_index()
put_chains_df.delta = put_chains_df.delta.astype(float)
# Get call option map
call_chains_df = pd.json_normalize(chains["callExpDateMap"])
call_chains_df = [pd.json_normalize(call_chains_df[c].explode()) for c in call_chains_df.columns]
call_chains_df = pd.concat(call_chains_df).reset_index()
call_chains_df.delta = call_chains_df.delta.astype(float)
# Send sell put spread order
if SP_QUANITY:
try:
strike_price = int(underlying_price * 0.96 // 5 * 5)
sp, bp = get_sell_put_spread_chains(strike_price, put_chains_df, dte)
if sp and bp:
send_order(sp, bp, c)
except ValueError as e:
output_buf(f"{e}")
# Send sell call spread order
if SC_QUANITY:
try:
strike_price = int(underlying_price * 1.04 // 5 * 5)
sc, bc = get_sell_call_spread_chains(strike_price, call_chains_df, dte)
if sc and bc:
send_order(sc, bc, c)
except ValueError as e:
output_buf(f"{e}")
output_buf(f'End time: {datetime.today():%Y/%m/%d %H:%M}', webhook=ENABLE_WEBHOOK)
if __name__ == "__main__":
ENABLE_WEBHOOK = True # Must webhook_url exist in secretsTDA module
if now_in_interval("15:00", "16:00"):
PLACE_ORDER = True
else:
PLACE_ORDER = False
# Sell put spreads
SP_QUANITY = 2 # Quanity must >= 2, or == 0
SP_MIN_PRICE = 0.15 # If middle price < min_price, use min_price
# Sell call spreads
SC_QUANITY = 0 # Quanity must >= 2, or == 0
SC_MIN_PRICE = 0.15 # If middle price < min_price, use min_price
main()
print('-' * 50)