xync-client 0.0.155__py3-none-any.whl → 0.0.162__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
xync_client/Abc/Agent.py CHANGED
@@ -1,15 +1,15 @@
1
+ import logging
1
2
  from abc import abstractmethod
2
- from asyncio.tasks import gather
3
+ from asyncio import create_task, sleep
3
4
  from collections import defaultdict
5
+ from typing import Literal
4
6
 
5
- from playwright.async_api import async_playwright
6
7
  from pydantic import BaseModel
7
8
  from pyro_client.client.file import FileClient
8
9
  from x_client import df_hdrs
9
10
  from x_client.aiohttp import Client as HttpClient
10
11
  from xync_bot import XyncBot
11
12
  from xync_client.Abc.PmAgent import PmAgentClient
12
- from xync_schema.enums import UserStatus
13
13
 
14
14
  from xync_client.Abc.InAgent import BaseInAgentClient
15
15
 
@@ -19,7 +19,7 @@ from xync_schema.models import OrderStatus, Coin, Cur, Ad, AdStatus, Actor, Agen
19
19
  from xync_schema.xtype import BaseAd
20
20
 
21
21
  from xync_client.Abc.Ex import BaseExClient
22
- from xync_client.Abc.xtype import CredExOut, BaseOrderReq, BaseAdUpdate, AdUpd
22
+ from xync_client.Abc.xtype import CredExOut, BaseOrderReq, BaseAdUpdate, AdUpd, GetAds
23
23
  from xync_client.Gmail import GmClient
24
24
 
25
25
 
@@ -29,16 +29,22 @@ class BaseAgentClient(HttpClient, BaseInAgentClient):
29
29
  bbot: XyncBot
30
30
  fbot: FileClient
31
31
  ex_client: BaseExClient
32
+ orders: dict[int, tuple[models.Order, BaseModel]] = {} # pending
32
33
  pm_clients: dict[int, PmAgentClient] # {pm_id: PmAgentClient}
34
+ api: HttpClient
35
+ cred_x2e: dict[int, int] = {}
36
+ cred_e2x: dict[int, int] = {}
33
37
 
34
38
  def __init__(
35
39
  self,
36
- agent: Agent,
40
+ agent: Agent, # agent.actor.person.user
37
41
  ex_client: BaseExClient,
38
42
  fbot: FileClient,
39
43
  bbot: XyncBot,
44
+ pm_clients: dict[int, PmAgentClient] = None,
40
45
  headers: dict[str, str] = df_hdrs,
41
46
  cookies: dict[str, str] = None,
47
+ proxy: models.Proxy = None,
42
48
  ):
43
49
  self.bbot = bbot
44
50
  self.fbot = fbot
@@ -47,34 +53,284 @@ class BaseAgentClient(HttpClient, BaseInAgentClient):
47
53
  self.gmail = agent.actor.person.user.gmail and GmClient(agent.actor.person.user)
48
54
  self.ex_client: BaseExClient = ex_client
49
55
  self.pm_clients: dict[int, PmAgentClient] = defaultdict()
50
- super().__init__(self.actor.ex.host_p2p, headers, cookies)
51
-
52
- async def start(self, debug: bool = False):
53
- tasks = []
54
- if not self.is_started:
55
- if self.agent.status & 1: # race
56
- tasks.append(self.start_race())
57
-
58
- if self.agent.status & 2: # in agent
59
- if not self.pm_clients:
60
- pm_agents = await models.PmAgent.filter(
61
- active=True,
62
- auth__isnull=False,
63
- user__status=UserStatus.ACTIVE,
64
- ).prefetch_related("pm", "user__gmail")
65
- # payeer_cl = Client(actor.person.user.username_id)
66
- pw = await async_playwright().start()
67
- browser = await pw.chromium.launch(
68
- channel="chrome-beta" if debug else "chromium-headless-shell", headless=not debug
69
- )
70
- self.pm_clients = {pma.pm_id: pma.client(browser, self.bbot) for pma in pm_agents}
71
- [tasks.append(pmcl.start()) for pmcl in self.pm_clients.values()]
72
- # tasks.append(self.start_listen())
73
-
74
- if self.agent.status & 4: # for further
75
- ...
76
- self.is_started = True
77
- return await gather(*tasks)
56
+ super().__init__(self.actor.ex.host_p2p, headers, cookies, proxy) # and proxy.str()
57
+ # start
58
+ create_task(self.start())
59
+
60
+ async def x2e_cred(self, cred_id: int) -> int: # cred.exid
61
+ if not self.cred_x2e.get(cred_id):
62
+ self.cred_x2e[cred_id] = (await models.CredEx.get(cred_id=cred_id)).exid
63
+ self.cred_e2x[self.cred_x2e[cred_id]] = cred_id
64
+ return self.cred_x2e[cred_id]
65
+
66
+ async def e2x_cred(self, exid: int) -> int: # cred.id
67
+ if not self.cred_e2x.get(exid):
68
+ self.cred_e2x[exid] = (await models.CredEx.get(exid=exid, ex=self.ex_client.ex)).cred_id
69
+ self.cred_x2e[self.cred_e2x[exid]] = exid
70
+ return self.cred_e2x[exid]
71
+
72
+ async def start(self):
73
+ if self.agent.status & 1: # race
74
+ for race in await models.Race.filter(started=True, road__ad__maker_id=self.agent.actor_id).prefetch_related(
75
+ "road__ad__pair_side__pair__cur", "road__credexs__cred"
76
+ ):
77
+ create_task(self.racing(race))
78
+ if self.agent.status & 2: # listen
79
+ await self.start_listen()
80
+
81
+ async def racing(self, race: models.Race):
82
+ pair = race.road.ad.pair_side.pair
83
+ taker_side: int = not race.road.ad.pair_side.is_sell
84
+ # конвертим наши параметры гонки в ex-овые для конкретной биржи текущего агента
85
+ coinex: models.CoinEx = await models.CoinEx.get(coin_id=pair.coin_id, ex=self.actor.ex).prefetch_related("coin")
86
+ curex: models.CurEx = await models.CurEx.get(cur_id=pair.cur_id, ex=self.actor.ex).prefetch_related("cur")
87
+ creds = [c.cred for c in race.road.credexs]
88
+ pm_ids = [pm.id for pm in race.road.ad.pms]
89
+ pmexs: list[models.PmEx] = [pmex for pm in race.road.ad.pms for pmex in pm.pmexs if pmex.ex_id == 4]
90
+ post_pm_ids = {c.cred.ovr_pm_id for c in race.road.credexs if c.cred.ovr_pm_id}
91
+ post_pmexs = set(await models.PmEx.filter(pm_id__in=post_pm_ids, ex=self.actor.ex).prefetch_related("pm"))
92
+
93
+ k = (-1) ** taker_side # on_buy=1, on_sell=-1
94
+ sleep_sec = 3 # 1 if set(pms) & {"volet"} and coinex.coin_id == 1 else 5
95
+ _lstat, volume = None, 0
96
+
97
+ # погнали цикл гонки
98
+ while self.actor.person.user.status > 0: # todo: separate agents, not whole user.activity
99
+ # подгружаем из бд обновления по текущей гонке
100
+ await race.refresh_from_db()
101
+ if not race.started: # пока выключена
102
+ await sleep(5)
103
+ continue
104
+
105
+ # конверт бд int фильтровочной суммы в float конкретной биржи
106
+ amt = race.filter_amount * 10**-curex.cur.scale if race.filter_amount else None
107
+ ceils = await self.get_ceils(coinex, curex, pmexs, 0.003, 0, amt, post_pmexs)
108
+ race.ceil = int(ceils[taker_side] * 10**curex.scale)
109
+ await race.save()
110
+
111
+ last_vol = volume
112
+ if taker_side: # гонка в стакане продажи - мы покупаем монету за ФИАТ
113
+ fiat = max(await models.Fiat.filter(cred_id__in=[c.id for c in creds]), key=lambda x: x.amount)
114
+ volume = (fiat.amount * 10**-curex.cur.scale) / (race.road.ad.price * 10**-curex.scale)
115
+ else: # гонка в стакане покупки - мы продаем МОНЕТУ за фиат
116
+ asset = await models.Asset.get(addr__actor=self.actor, addr__coin_id=coinex.coin_id)
117
+ volume = asset.free * 10**-coinex.scale
118
+ volume = str(round(volume, coinex.scale))
119
+ get_ads_req = GetAds(
120
+ coin_id=pair.coin_id, cur_id=pair.cur_id, is_sell=bool(taker_side), pm_ids=pm_ids, amount=amt, limit=50
121
+ )
122
+ try:
123
+ ads: list[Ad] = await self.ex_client.ads(get_ads_req)
124
+ except Exception:
125
+ await sleep(1)
126
+ ads: list[Ad] = await self.ads(coinex, curex, taker_side, pmexs, amt, 50, race.vm_filter, post_pmexs)
127
+
128
+ self.overprice_filter(ads, race.ceil * 10**-curex.scale, k) # обрезаем сверху все ads дороже нашего потолка
129
+
130
+ if not ads:
131
+ print(coinex.exid, curex.exid, taker_side, "no ads!")
132
+ await sleep(15)
133
+ continue
134
+ # определяем наше текущее место в уже обрезанном списке ads
135
+ if not (cur_plc := [i for i, ad in enumerate(ads) if int(ad.userId) == self.actor.exid]):
136
+ logging.warning(f"No racing in {pmexs[0].name} {'-' if taker_side else '+'}{coinex.exid}/{curex.exid}")
137
+ await sleep(15)
138
+ continue
139
+ (cur_plc,) = cur_plc # может упасть если в списке > 1 наш ad
140
+ [(await self.ex_client.cond_load(ad, race.road.ad.pair_side, True))[0] for ad in ads[:cur_plc]]
141
+ # rivals = [
142
+ # (await models.RaceStat.update_or_create({"place": plc, "price": ad.price, "premium": ad.premium}, ad=ad))[
143
+ # 0
144
+ # ]
145
+ # for plc, ad in enumerate(rads)
146
+ # ]
147
+ mad: Ad = ads.pop(cur_plc)
148
+ # if (
149
+ # not (lstat := lstat or await race.stats.order_by("-created_at").first())
150
+ # or lstat.place != cur_plc
151
+ # or lstat.price != float(mad.price)
152
+ # or set(rivals) != set(await lstat.rivals)
153
+ # ):
154
+ # lstat = await models.RaceStat.create(race=race, place=cur_plc, price=mad.price, premium=mad.premium)
155
+ # await lstat.rivals.add(*rivals)
156
+ if not ads:
157
+ await sleep(60)
158
+ continue
159
+ if not (cad := self.get_cad(ads, race.ceil * 10**-curex.scale, k, race.target_place, cur_plc)):
160
+ continue
161
+ new_price = round(float(cad.price) - k * step(mad, cad, curex.scale), curex.scale)
162
+ if (
163
+ float(mad.price) == new_price and volume == last_vol
164
+ ): # Если место уже нужное или нужная цена и так уже стоит
165
+ print(
166
+ f"{'v' if taker_side else '^'}{mad.price}",
167
+ end=f"[{race.ceil * 10**-curex.scale}+{cur_plc}] ",
168
+ flush=True,
169
+ )
170
+ await sleep(sleep_sec)
171
+ continue
172
+ if cad.priceType: # Если цена конкурента плавающая, то повышаем себе не цену, а %
173
+ new_premium = (float(mad.premium) or float(cad.premium)) - k * step(mad, cad, 2)
174
+ # if float(mad.premium) == new_premium: # Если нужный % и так уже стоит
175
+ # if mad.priceType and cur_plc != race.target_place:
176
+ # new_premium -= k * step(mad, cad, 2)
177
+ # elif volume == last_vol:
178
+ # print(end="v" if taker_side else "^", flush=True)
179
+ # await sleep(sleep_sec)
180
+ # continue
181
+ mad.premium = str(round(new_premium, 2))
182
+ mad.priceType = cad.priceType
183
+ mad.quantity = volume
184
+ mad.maxAmount = str(2_000_000 if curex.cur_id == 1 else 40_000)
185
+ # req = AdUpdateRequest.model_validate(
186
+ # {
187
+ # **mad.model_dump(),
188
+ # "price": str(round(new_price, curex.scale)),
189
+ # "paymentIds": [str(cx.exid) for cx in race.road.credexs],
190
+ # }
191
+ # )
192
+ # try:
193
+ # print(
194
+ # f"c{race.ceil * 10**-curex.scale}+{cur_plc} {coinex.coin.ticker}{'-' if taker_side else '+'}{req.price}{curex.cur.ticker}"
195
+ # f"{[pm.norm for pm in race.road.ad.pms]}{f'({req.premium}%)' if req.premium != '0' else ''} "
196
+ # f"t{race.target_place} ;",
197
+ # flush=True,
198
+ # )
199
+ # _res = self.ad_upd(req)
200
+ # except FailedRequestError as e:
201
+ # if ExcCode(e.status_code) == ExcCode.FixPriceLimit:
202
+ # if limits := re.search(
203
+ # r"The fixed price set is lower than ([0-9]+\.?[0-9]{0,2}) or higher than ([0-9]+\.?[0-9]{0,2})",
204
+ # e.message,
205
+ # ):
206
+ # req.price = limits.group(1 if taker_side else 2)
207
+ # if req.price != mad.price:
208
+ # _res = self.ad_upd(req)
209
+ # else:
210
+ # raise e
211
+ # elif ExcCode(e.status_code) == ExcCode.InsufficientBalance:
212
+ # asset = await models.Asset.get(addr__actor=self.actor, addr__coin_id=coinex.coin_id)
213
+ # req.quantity = str(round(asset.free * 10**-coinex.scale, coinex.scale))
214
+ # _res = self.ad_upd(req)
215
+ # elif ExcCode(e.status_code) == ExcCode.RareLimit:
216
+ # if not (
217
+ # sads := [
218
+ # ma
219
+ # for ma in self.my_ads(False)
220
+ # if (
221
+ # ma.currencyId == curex.exid
222
+ # and ma.tokenId == coinex.exid
223
+ # and taker_side != ma.side
224
+ # and set(ma.payments) == set([pe.exid for pe in pmexs])
225
+ # )
226
+ # ]
227
+ # ):
228
+ # logging.error(f"Need reserve Ad {'sell' if taker_side else 'buy'} {coinex.exid}/{curex.exid}")
229
+ # await sleep(90)
230
+ # continue
231
+ # self.ad_del(ad_id=int(mad.id))
232
+ # req.id = sads[0].id
233
+ # req.actionType = "ACTIVE"
234
+ # self.api.update_ad(**req.model_dump())
235
+ # logging.warning(f"Ad#{mad.id} recreated")
236
+ # # elif ExcCode(e.status_code) == ExcCode.Timestamp:
237
+ # # await sleep(3)
238
+ # else:
239
+ # raise e
240
+ # except (ReadTimeoutError, ConnectionDoesNotExistError):
241
+ # logging.warning("Connection failed. Restarting..")
242
+ await sleep(6)
243
+
244
+ async def get_books(
245
+ self,
246
+ coinex: models.CoinEx,
247
+ curex: models.CurEx,
248
+ pmexs: list[models.PmEx],
249
+ amount: int,
250
+ post_pmexs: list[models.PmEx] = None,
251
+ ) -> tuple[list[Ad], list[Ad]]:
252
+ buy: list[Ad] = await self.ads(coinex, curex, False, pmexs, amount, 40, False, post_pmexs)
253
+ sell: list[Ad] = await self.ads(coinex, curex, True, pmexs, amount, 30, False, post_pmexs)
254
+ return buy, sell
255
+
256
+ async def get_spread(
257
+ self, bb: list[Ad], sb: list[Ad], perc: float, place: int = 0
258
+ ) -> tuple[tuple[float, float], float, int] | None:
259
+ if len(bb) and len(sb):
260
+ buy_price, sell_price = float(bb[place].price), float(sb[place].price)
261
+ half_spread = (buy_price - sell_price) / (buy_price + sell_price)
262
+ if half_spread * 2 < perc:
263
+ return await self.get_spread(bb, sb, perc, place)
264
+ return (buy_price, sell_price), half_spread, place
265
+ return None
266
+
267
+ async def get_ceils(
268
+ self,
269
+ coinex: models.CoinEx,
270
+ curex: models.CurEx,
271
+ pmexs: list[models.PmEx],
272
+ min_prof=0.02,
273
+ place: int = 0,
274
+ amount: int = None,
275
+ post_pmexs: set[models.PmEx] = None,
276
+ ) -> tuple[float, float]: # todo: refact to Pairex
277
+ for pmc_id in {pmx.pm_id for pmx in pmexs} | set(self.pm_clients.keys()):
278
+ if ceils := self.pm_clients[pmc_id].get_ceils():
279
+ return ceils
280
+ bb, sb = await self.get_books(coinex, curex, pmexs, amount, post_pmexs)
281
+ perc = list(post_pmexs or pmexs)[0].pm.fee * 0.0001 + min_prof
282
+ (bf, sf), _hp, _zplace = await self.get_spread(bb, sb, perc, place)
283
+ mdl = (bf + sf) / 2 # middle price
284
+ bc, sc = mdl + mdl * (perc / 2), mdl - mdl * (perc / 2)
285
+ return bc, sc
286
+
287
+ async def mad_upd(self, mad: Ad, attrs: dict, cxids: list[str]):
288
+ if not [setattr(mad, k, v) for k, v in attrs.items() if getattr(mad, k) != v]:
289
+ print(end="v" if mad.side else "^", flush=True)
290
+ return await sleep(5)
291
+ # req = AdUpdateRequest.model_validate({**mad.model_dump(), "paymentIds": cxids})
292
+ # try:
293
+ # return self.ad_upd(req)
294
+ # except FailedRequestError as e:
295
+ # if ExcCode(e.status_code) == ExcCode.FixPriceLimit:
296
+ # if limits := re.search(
297
+ # r"The fixed price set is lower than ([0-9]+\.?[0-9]{0,2}) or higher than ([0-9]+\.?[0-9]{0,2})",
298
+ # e.message,
299
+ # ):
300
+ # return await self.mad_upd(mad, {"price": limits.group(1 if mad.side else 2)}, cxids)
301
+ # elif ExcCode(e.status_code) == ExcCode.RareLimit:
302
+ # await sleep(180)
303
+ # else:
304
+ # raise e
305
+ # except (ReadTimeoutError, ConnectionDoesNotExistError):
306
+ # logging.warning("Connection failed. Restarting..")
307
+ # print("-" if mad.side else "+", end=req.price, flush=True)
308
+ await sleep(60)
309
+
310
+ def overprice_filter(self, ads: list[Ad], ceil: float, k: Literal[-1, 1]):
311
+ # вырезаем ads с ценами выше потолка
312
+ if ads and (ceil - float(ads[0].price)) * k > 0:
313
+ if int(ads[0].userId) != self.actor.exid:
314
+ ads.pop(0)
315
+ self.overprice_filter(ads, ceil, k)
316
+
317
+ def get_cad(self, ads: list[Ad], ceil: float, k: Literal[-1, 1], target_place: int, cur_plc: int) -> Ad:
318
+ if not ads:
319
+ return None
320
+ # чью цену будем обгонять, предыдущей или слещующей объявы?
321
+ # cad: Ad = ads[place] if cur_plc > place else ads[cur_plc]
322
+ # переделал пока на жесткую установку целевого места, даже если текущее выше:
323
+ if len(ads) <= target_place:
324
+ logging.error(f"target place {target_place} not found in ads {len(ads)}-lenght list")
325
+ target_place = len(ads) - 1
326
+ cad: Ad = ads[target_place]
327
+ # а цена обгоняемой объявы не выше нашего потолка?
328
+ if (float(cad.price) - ceil) * k <= 0:
329
+ # тогда берем следующую
330
+ ads.pop(target_place)
331
+ cad = self.get_cad(ads, ceil, k, target_place, cur_plc)
332
+ # todo: добавить фильтр по лимитам min-max
333
+ return cad
78
334
 
79
335
  # 0: Получшение ордеров в статусе status, по монете coin, в валюте coin, в направлении is_sell: bool
80
336
  @abstractmethod
@@ -133,31 +389,23 @@ class BaseAgentClient(HttpClient, BaseInAgentClient):
133
389
  @abstractmethod
134
390
  async def my_ads(self, status: AdStatus = None) -> list[BaseAd]: ...
135
391
 
392
+ @abstractmethod
393
+ async def x2e_req_ad_upd(self, xreq: AdUpd) -> BaseAdUpdate: ...
394
+
136
395
  # 30: Создание объявления
137
396
  @abstractmethod
138
397
  async def ad_new(self, ad: BaseAd) -> Ad: ...
139
398
 
140
- async def ad_upd(self, ad_upd_req: AdUpd) -> Ad:
141
- pmex_exids = await models.PmEx.filter(ex_id=self.actor.ex_id, pm_id__in=ad_upd_req.pm_ids).values_list(
142
- "exid", flat=True
143
- )
144
- credexs = await models.CredEx.filter(
399
+ async def ad_upd(self, xreq: AdUpd) -> Ad:
400
+ xreq.credexs = await models.CredEx.filter(
145
401
  ex_id=self.actor.ex_id,
146
- cred__pmcur__pm_id__in=ad_upd_req.pm_ids,
147
- cred__pmcur__cur_id=ad_upd_req.cur_id,
402
+ cred__pmcur__pm_id__in=xreq.pm_ids,
403
+ cred__pmcur__cur_id=xreq.cur_id,
148
404
  cred__person_id=self.actor.person_id,
149
405
  ).prefetch_related("cred__pmcur")
150
- coinex = await models.CoinEx.get(coin_id=ad_upd_req.coin_id, ex=self.ex_client.ex)
151
- curex = await models.CurEx.get(cur_id=ad_upd_req.cur_id, ex=self.ex_client.ex)
152
- # override
153
- ad_upd_req.coin_id = coinex.exid
154
- ad_upd_req.cur_id = curex.exid
155
- ad_upd_req.pm_ids = pmex_exids
156
- ad_upd_req.credexs = credexs
157
- ad_upd_req.price = round(ad_upd_req.price, curex.scale)
158
- ad_upd_req.amount = round(ad_upd_req.amount, curex.scale)
159
- ad_upd_req.quantity = round(ad_upd_req.amount / ad_upd_req.price, coinex.scale)
160
- return await self._ad_upd(ad_upd_req)
406
+ # xreq.credexs = credexs
407
+ ereq = await self.x2e_req_ad_upd(xreq)
408
+ return await self._ad_upd(ereq)
161
409
 
162
410
  # 31: Редактирование объявления
163
411
  @abstractmethod
@@ -214,3 +462,30 @@ class BaseAgentClient(HttpClient, BaseInAgentClient):
214
462
  # if banks: # only for SBP
215
463
  # await cred_db.banks.add(*[await PmExBank.get(exid=b) for b in banks])
216
464
  # return True
465
+
466
+ @abstractmethod
467
+ async def _start_listen(self): ...
468
+
469
+ @abstractmethod
470
+ async def load_pending_orders(self): ...
471
+
472
+ async def start_listen(self):
473
+ create_task(self._start_listen())
474
+ await self.load_pending_orders()
475
+
476
+
477
+ def step_is_need(mad, cad) -> bool:
478
+ # todo: пока не решен непонятный кейс, почему то конкурент по всем параметрам слабже, но в списке ранжируется выше.
479
+ # текущая версия: recentExecuteRate округляется до целого, но на бэке байбита его дробная часть больше
480
+ return (
481
+ bool(set(cad.authTag) & {"VA2", "BA"})
482
+ or cad.recentExecuteRate > mad.recentExecuteRate
483
+ or (
484
+ cad.recentExecuteRate
485
+ == mad.recentExecuteRate # and cad.finishNum > mad.finishNum # пока прибавляем для равных
486
+ )
487
+ )
488
+
489
+
490
+ def step(mad, cad, scale: int = 2) -> float:
491
+ return float(int(step_is_need(mad, cad)) * 10**-scale).__round__(scale)