-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathflattern.py
More file actions
216 lines (192 loc) · 6.89 KB
/
flattern.py
File metadata and controls
216 lines (192 loc) · 6.89 KB
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
207
208
209
210
211
212
213
214
215
216
import requests
import yaml
import logging
import urllib3
import time
from datetime import datetime, timedelta, timezone
# Suppress SSL warnings
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
# --- Load config ---
with open("config.yaml") as f:
config = yaml.safe_load(f)
API_URL = "https://api.topstepx.com"
GATEWAY_URL = "https://gateway-api-demo.s2f.projectx.com"
USERNAME = config["username"]
API_KEY = config["api_key"]
# --- Logging setup ---
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
# --- Token cache ---
TOKEN = None
def get_token(force_refresh=False):
global TOKEN
if TOKEN and not force_refresh:
return TOKEN
try:
res = requests.post(
f"{API_URL}/api/Auth/loginKey",
json={"userName": USERNAME, "apiKey": API_KEY},
headers={"Content-Type": "application/json"},
timeout=10,
verify=False
)
res.raise_for_status()
data = res.json()
token = data.get("token") if data.get("success") else None
if token:
TOKEN = token
return TOKEN
else:
logging.error("Token request failed: no token returned.")
return None
except Exception as e:
logging.error(f"Auth error: {e}")
return None
def get_active_accounts(token):
try:
res = requests.post(
f"{API_URL}/api/Account/search",
json={"onlyActiveAccounts": True},
headers={"Authorization": f"Bearer {token}", "Content-Type": "application/json"},
timeout=10,
verify=False
)
res.raise_for_status()
return res.json().get("accounts", [])
except Exception as e:
logging.error(f"Account fetch error: {e}")
return []
def get_positions(token, account_id):
try:
res = requests.post(
f"{API_URL}/api/Position/searchOpen",
json={"accountId": account_id},
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json",
"Accept": "application/json"
},
timeout=10,
verify=False
)
res.raise_for_status()
return res.json().get("positions", [])
except Exception as e:
logging.error(f"Position fetch error for account {account_id}: {e}")
return []
# --- Commented Close Logic ---
def close_contract_position(token, account_id, contract_id):
try:
payload = {
"accountId": account_id,
"contractId": contract_id
}
res = requests.post(
f"{API_URL}/api/Position/closeContract",
json=payload,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
},
timeout=10,
verify=False
)
res.raise_for_status()
data = res.json()
if data.get("success"):
logging.info(f"✅ Closed contract {contract_id} for account {account_id}")
return True
else:
logging.warning(f"❌ Close failed for {contract_id}: {data}")
return False
except Exception as e:
logging.error(f"Error closing contract {contract_id}: {e}")
return False
def search_trades(token, account_id, start_time_iso, end_time_iso=None):
try:
payload = {
"accountId": account_id,
"startTimestamp": start_time_iso
}
if end_time_iso:
payload["endTimestamp"] = end_time_iso
res = requests.post(
f"{API_URL}/api/Trade/search",
json=payload,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
},
timeout=15,
verify=False
)
res.raise_for_status()
return res.json().get("trades", [])
except Exception as e:
logging.error(f"Trade search error for account {account_id}: {e}")
return []
def search_orders(token, account_id, start_time_iso, end_time_iso=None):
try:
payload = {
"accountId": account_id,
"startTimestamp": start_time_iso
}
if end_time_iso:
payload["endTimestamp"] = end_time_iso
res = requests.post(
f"{API_URL}/api/Order/search",
json=payload,
headers={
"Authorization": f"Bearer {token}",
"Content-Type": "application/json"
},
timeout=15,
verify=False
)
res.raise_for_status()
return res.json().get("orders", [])
except Exception as e:
logging.error(f"Order search error for account {account_id}: {e}")
return []
# --- Main execution ---
def main():
token = get_token()
if not token:
logging.error("Authentication failed. Exiting.")
return
accounts = get_active_accounts(token)
time.sleep(0.3)
if not accounts:
logging.info("No active accounts found.")
return
logging.info(f"Found {len(accounts)} active accounts.")
for account in accounts:
account_id = account["id"]
logging.info(f"\nFetching positions for Account ID: {account_id}")
positions = get_positions(token, account_id)
time.sleep(0.3)
if positions:
for pos in positions:
contract_id = pos["contractId"]
logging.info(f" Position ID: {pos['id']}, Contract: {contract_id}, Size: {pos['size']}, Avg Price: {pos['averagePrice']}")
# --- Commented Close Logic ---
success = close_contract_position(token, account_id, contract_id)
time.sleep(0.3)
# # --- Trade Search ---
# now = datetime.now(timezone.utc)
# start_time = (now - timedelta(hours=24)).isoformat()
# trades = search_trades(token, account_id, start_time)
# time.sleep(0.3)
# for trade in trades:
# logging.info(f" Trade ID: {trade.get('id')}, Contract: {trade.get('contractId')}, "
# f"Side: {trade.get('side')}, Size: {trade.get('size')}, Price: {trade.get('price')}")
# --- Order Search ---
# orders = search_orders(token, account_id, start_time)
# time.sleep(0.3)
# for order in orders:
# logging.info(f" Order ID: {order.get('id')}, Contract: {order.get('contractId')}, "
# f"Side: {order.get('side')}, Size: {order.get('size')}, "
# f"Type: {order.get('type')}, Status: {order.get('status')}")
else:
logging.info(" No open positions.")
if __name__ == "__main__":
main()