-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathstrategyClient.py
More file actions
308 lines (262 loc) · 11.7 KB
/
strategyClient.py
File metadata and controls
308 lines (262 loc) · 11.7 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
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import requests
from requests.adapters import HTTPAdapter
from urllib3.util.retry import Retry
import warnings
from urllib3.util.retry import Retry
from requests.adapters import HTTPAdapter
import random
import time
import threading
timeout=60*30
class StrategyClient:
def __init__(self,p):
self.verify_ssl = True
api_urls=["https://127.0.0.1:443","https://pyroboadvisor.org","https://pyroboadvisor.org:441","https://pyroboadvisor.org:442","https://pyroboadvisor.org:444","https://pyroboadvisor.org:445"]
# if self.verify_ssl is False:
# print("WARNING: SSL verification is disabled. This is not recommended for production use.")
# # un numero random entre 2 y 4
# import random
# puerto=random.randint(2, 4)
# api_url="https://127.0.0.1:443"#+str(puerto)
# warnings.filterwarnings(
# "ignore",
# message="Unverified HTTPS request"
# )
# self.api_url = api_url.rstrip("/")
# Create requests session to handle ConnectionError
i=0
intento=0
while True:
intento+=1
if i==0:
self.verify_ssl = False
warnings.filterwarnings(
"ignore",
message="Unverified HTTPS request"
)
else:
self.verify_ssl = True
warnings.filterwarnings(
"default",
message="Unverified HTTPS request"
)
api_url=api_urls[i]
self.api_url = api_url.rstrip("/")
self.requests_session = self._configure_requests_session(retries=3, backof_factor=0.5)
self.session_id = None
try:
self.create_session(p)
print(f"Connected to {self.api_url}")
break
except requests.exceptions.RequestException as e:
if intento>10:
raise e
time.sleep(2)
# random i
i=random.randint(0, len(api_urls)-1)
def old_init(self,p):
self.verify_ssl = False
api_url="https://pyroboadvisor.org"
if self.verify_ssl is False:
print("WARNING: SSL verification is disabled. This is not recommended for production use.")
# un numero random entre 2 y 4
import random
puerto=random.randint(2, 4)
api_url="https://127.0.0.1:443"#+str(puerto)
warnings.filterwarnings(
"ignore",
message="Unverified HTTPS request"
)
self.api_url = api_url.rstrip("/")
# Create requests session to handle ConnectionError
self.requests_session = self._configure_requests_session(retries=3, backof_factor=0.5)
self.session_id = None
self.create_session(p)
def _configure_requests_session(self, retries: int, backof_factor: float) -> requests.Session:
session = requests.Session()
retry = Retry(connect=retries, backoff_factor=backof_factor)
adapter = HTTPAdapter(max_retries=retry)
session.mount('http://', adapter)
session.mount('https://', adapter)
return session
def create_session(self, config: dict):
resp = self.requests_session.post(f"{self.api_url}/sessions", json={"config": config,"email": config["email"],
"license_key": config["key"]},verify=self.verify_ssl, timeout=timeout)
resp.raise_for_status()
resp_json=resp.json()
self.session_id = resp_json["session_id"]
self.name = resp_json.get("strategy_name", "")
if config.get("index",None) is not None:
self.tickers = resp_json.get("tickers", [])
return self.session_id
"""
def open(self, open20,signoMultiplexado=None):
if not self.session_id:
raise Exception("Session not created")
payload = {"open20": list(open20)}
if signoMultiplexado is not None:
payload["signoMultiplexado"]=signoMultiplexado
resp = self.requests_session.post(f"{self.api_url}/sessions/{self.session_id}/open", json=payload, verify=self.verify_ssl,timeout=timeout )
resp.raise_for_status()
return resp.json() # {'programSell': [...], 'programBuy': [...]}
"""
def open(self, open20, signoMultiplexado=None):
import requests, time
if not self.session_id:
raise Exception("Session not created")
payload = {"open20": list(open20)}
if signoMultiplexado is not None:
payload["signoMultiplexado"] = signoMultiplexado
max_attempts = 8
base_wait = 2 # segundos
for attempt in range(1, max_attempts + 1):
try:
# Solo mostramos mensajes desde el intento 2
if attempt >= 2:
if attempt == 2:
print(f"[open] intento 1/{max_attempts} ha fallado (timeout). Reintentando...")
print(f"[open] intento {attempt}/{max_attempts} → {self.api_url}")
resp = self.requests_session.post(
f"{self.api_url}/sessions/{self.session_id}/open",
json=payload,
verify=self.verify_ssl,
timeout=(10, timeout)
)
resp.raise_for_status()
if attempt >= 2:
print("[open] OK")
return resp.json()
except requests.exceptions.ReadTimeout:
wait_s = base_wait * (2 ** (attempt - 1)) # 2,4,8,16,32
# Solo avisamos del timeout desde el intento 2 (porque el 1 se omite)
if attempt >= 2:
print(f"[open] timeout. Reintentando en {wait_s}s...")
time.sleep(wait_s)
except requests.exceptions.RequestException as e:
# Para errores no-timeout: si ocurren en el intento 1, saldrá sin log; si quieres log siempre, dímelo.
if attempt >= 2:
print(f"[open] error: {e}")
raise
raise requests.exceptions.ReadTimeout(
f"Timeout en open() tras {max_attempts} intentos (api={self.api_url})"
)
"""
def execute(self, low, high, close, date,volume=None):
if not self.session_id:
raise Exception("Session not created")
payload = {
"low": list(low),
"high": list(high),
"close": list(close),
"date": str(date) # Puede ser datetime.isoformat()
}
if volume!=None:
payload["volume"]=list(volume)
resp = self.requests_session.post(f"{self.api_url}/sessions/{self.session_id}/execute", json=payload, verify=self.verify_ssl, timeout=timeout)
resp.raise_for_status()
return resp.json() # {'success': True}
"""
def execute(self, low, high, close, date, volume=None):
if not self.session_id:
raise Exception("Session not created")
payload = {
"low": list(low),
"high": list(high),
"close": list(close),
"date": str(date)
}
if volume is not None:
payload["volume"] = list(volume)
budgets = [15, 60, 180, 600]
connect_s = 5
last_err = None
for idx, budget in enumerate(budgets, start=1):
# intento 1: silencioso
if idx == 1:
try:
resp = self.requests_session.post(
f"{self.api_url}/sessions/{self.session_id}/execute",
json=payload,
verify=self.verify_ssl,
timeout=(connect_s, budget),
)
resp.raise_for_status()
return resp.json()
except requests.exceptions.Timeout as e:
last_err = e
except requests.exceptions.RequestException as e:
raise
continue
# intento 2+ : mensaje + contador
if idx == 2:
print(f"[execute] intento 1/{len(budgets)} ha fallado (timeout ~{budgets[0]}s).", flush=True)
print(f"[execute] intento {idx}/{len(budgets)}: ejecutando ({budget}s)...", flush=True)
result = {"resp": None, "err": None}
def worker():
try:
r = self.requests_session.post(
f"{self.api_url}/sessions/{self.session_id}/execute",
json=payload,
verify=self.verify_ssl,
timeout=(connect_s, budget),
)
r.raise_for_status()
result["resp"] = r
except Exception as e:
result["err"] = e
th = threading.Thread(target=worker, daemon=True)
th.start()
t0 = time.time()
while th.is_alive():
elapsed = int(time.time() - t0)
if elapsed > budget:
break
print(f"[execute] {idx}/{len(budgets)} esperando... {elapsed}/{budget}s", end="\r", flush=True)
time.sleep(1)
print(" " * 90, end="\r")
th.join(timeout=1)
if result["resp"] is not None:
print(f"[execute] OK (intento {idx}/{len(budgets)})", flush=True)
return result["resp"].json()
err = result["err"] or last_err or requests.exceptions.ReadTimeout()
last_err = err
if isinstance(err, requests.exceptions.Timeout):
print(f"[execute] timeout en intento {idx}/{len(budgets)}.", flush=True)
continue
if isinstance(err, requests.exceptions.HTTPError):
code = getattr(err.response, "status_code", None)
if code is not None and 500 <= code < 600:
print(f"[execute] HTTP {code} en intento {idx}/{len(budgets)}. Reintentando...", flush=True)
continue
raise err
raise requests.exceptions.ReadTimeout(
f"[execute] abortado: no respondió tras {len(budgets)} intentos (15/60/180/600s). Último error: {last_err}"
)
def set_portfolio(self, cash, portfolio):
if not self.session_id:
raise Exception("Session not created")
payload = {
"cash": cash,
"portfolio": portfolio
}
resp = self.requests_session.post(f"{self.api_url}/sessions/{self.session_id}/set_portfolio", json=payload, verify=self.verify_ssl, timeout=timeout)
resp.raise_for_status()
return resp.json()
def get_index(self,id):
if not self.session_id:
raise Exception("Session not created")
resp = self.requests_session.get(f"{self.api_url}/sessions/{self.session_id}/get_index/{id}", verify=self.verify_ssl, timeout=timeout)
resp.raise_for_status()
return resp.json()
# def get_m2(self):
# if not self.session_id:
# raise Exception("Session not created")
# resp = self.requests_session.get(f"{self.api_url}/sessions/{self.session_id}/m2/", verify=self.verify_ssl, timeout=timeout)
# resp.raise_for_status()
# return resp.json()
# def program_orders(self, orders, simulator):
# # Utiliza el mismo simulador que el bucle original
# for order in orders.get("programBuy", []):
# simulator.programBuy(order["id"], order["price"], order["amount"])
# for order in orders.get("programSell", []):
# simulator.programSell(order["id"], order["price"], order["amount"])