xync-client 0.0.155__py3-none-any.whl → 0.0.156.dev18__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/AdLoader.py +0 -294
- xync_client/Abc/Agent.py +313 -51
- xync_client/Abc/Ex.py +414 -12
- xync_client/Abc/xtype.py +34 -2
- xync_client/Bybit/InAgent.py +225 -436
- xync_client/Bybit/agent.py +529 -397
- xync_client/Bybit/etype/__init__.py +0 -0
- xync_client/Bybit/etype/ad.py +47 -34
- xync_client/Bybit/etype/order.py +33 -48
- xync_client/Bybit/ex.py +20 -46
- xync_client/Htx/agent.py +82 -40
- xync_client/Htx/etype/ad.py +22 -5
- xync_client/Htx/etype/order.py +194 -0
- xync_client/Htx/ex.py +16 -16
- xync_client/Mexc/agent.py +196 -13
- xync_client/Mexc/api.py +955 -336
- xync_client/Mexc/etype/ad.py +52 -1
- xync_client/Mexc/etype/order.py +131 -416
- xync_client/Mexc/ex.py +29 -19
- xync_client/Okx/1.py +14 -0
- xync_client/Okx/agent.py +39 -0
- xync_client/Okx/ex.py +8 -8
- xync_client/Pms/Payeer/agent.py +396 -0
- xync_client/Pms/Payeer/login.py +1 -63
- xync_client/Pms/Payeer/trade.py +58 -0
- xync_client/loader.py +1 -0
- {xync_client-0.0.155.dist-info → xync_client-0.0.156.dev18.dist-info}/METADATA +2 -1
- {xync_client-0.0.155.dist-info → xync_client-0.0.156.dev18.dist-info}/RECORD +30 -26
- xync_client/Pms/Payeer/__init__.py +0 -262
- xync_client/Pms/Payeer/api.py +0 -25
- {xync_client-0.0.155.dist-info → xync_client-0.0.156.dev18.dist-info}/WHEEL +0 -0
- {xync_client-0.0.155.dist-info → xync_client-0.0.156.dev18.dist-info}/top_level.txt +0 -0
xync_client/Abc/AdLoader.py
CHANGED
|
@@ -1,299 +1,5 @@
|
|
|
1
|
-
import logging
|
|
2
|
-
import re
|
|
3
|
-
from asyncio import sleep
|
|
4
|
-
from collections import defaultdict
|
|
5
|
-
from difflib import SequenceMatcher
|
|
6
|
-
|
|
7
|
-
from tortoise.exceptions import OperationalError, IntegrityError
|
|
8
1
|
from xync_schema import models
|
|
9
|
-
from xync_schema.xtype import BaseAd
|
|
10
2
|
|
|
11
3
|
|
|
12
4
|
class AdLoader:
|
|
13
5
|
ex: models.Ex
|
|
14
|
-
all_conds: dict[int, tuple[str, set[int]]] = {}
|
|
15
|
-
cond_sims: dict[int, int] = defaultdict(set)
|
|
16
|
-
rcond_sims: dict[int, set[int]] = defaultdict(set) # backward
|
|
17
|
-
tree: dict = {}
|
|
18
|
-
|
|
19
|
-
async def old_conds_load(self):
|
|
20
|
-
# пока не порешали рейс-кондишн, очищаем сиротские условия при каждом запуске
|
|
21
|
-
# [await c.delete() for c in await Cond.filter(ads__isnull=True)]
|
|
22
|
-
self.all_conds = {
|
|
23
|
-
c.id: (c.raw_txt, {a.maker.exid for a in c.ads})
|
|
24
|
-
for c in await models.Cond.all().prefetch_related("ads__maker")
|
|
25
|
-
}
|
|
26
|
-
for curr, old in await models.CondSim.filter().values_list("cond_id", "cond_rel_id"):
|
|
27
|
-
self.cond_sims[curr] = old
|
|
28
|
-
self.rcond_sims[old] |= {curr}
|
|
29
|
-
|
|
30
|
-
self.build_tree()
|
|
31
|
-
a = set()
|
|
32
|
-
|
|
33
|
-
def check_tree(tre):
|
|
34
|
-
for p, c in tre.items():
|
|
35
|
-
a.add(p)
|
|
36
|
-
check_tree(c)
|
|
37
|
-
|
|
38
|
-
for pr, ch in self.tree.items():
|
|
39
|
-
check_tree(ch)
|
|
40
|
-
if ct := set(self.tree.keys()) & a:
|
|
41
|
-
logging.exception(f"cycle cids: {ct}")
|
|
42
|
-
|
|
43
|
-
async def person_name_update(self, name: str, exid: int) -> models.Person:
|
|
44
|
-
if actor := await models.Actor.get_or_none(exid=exid, ex=self.ex).prefetch_related("person"):
|
|
45
|
-
actor.person.name = name
|
|
46
|
-
await actor.person.save()
|
|
47
|
-
return actor.person
|
|
48
|
-
# tmp dirty fix
|
|
49
|
-
note = f"{self.ex.id}:{exid}"
|
|
50
|
-
if person := await models.Person.get_or_none(note__startswith=note):
|
|
51
|
-
person.name = name
|
|
52
|
-
await person.save()
|
|
53
|
-
return person
|
|
54
|
-
try:
|
|
55
|
-
return await models.Person.create(name=name, note=note)
|
|
56
|
-
except OperationalError as e:
|
|
57
|
-
raise e
|
|
58
|
-
await models.Actor.create(person=person, exid=exid, ex=self.ex)
|
|
59
|
-
return person
|
|
60
|
-
# person = await models.Person.create(note=f'{actor.ex_id}:{actor.exid}:{name}') # no person for just ads with no orders
|
|
61
|
-
# raise ValueError(f"Agent #{exid} not found")
|
|
62
|
-
|
|
63
|
-
async def ad_load(
|
|
64
|
-
self,
|
|
65
|
-
pad: BaseAd,
|
|
66
|
-
cid: int = None,
|
|
67
|
-
ps: models.PairSide = None,
|
|
68
|
-
maker: models.Actor = None,
|
|
69
|
-
coinex: models.CoinEx = None,
|
|
70
|
-
curex: models.CurEx = None,
|
|
71
|
-
rname: str = None,
|
|
72
|
-
) -> models.Ad:
|
|
73
|
-
if not maker:
|
|
74
|
-
if not (maker := await models.Actor.get_or_none(exid=pad.userId, ex=self.ex)):
|
|
75
|
-
person = await models.Person.create(name=rname, note=f"{self.ex.id}:{pad.userId}:{pad.nickName}")
|
|
76
|
-
maker = await models.Actor.create(name=pad.nickName, person=person, exid=pad.userId, ex=self.ex)
|
|
77
|
-
if rname:
|
|
78
|
-
await self.person_name_update(rname, int(pad.userId))
|
|
79
|
-
ps = ps or await models.PairSide.get_or_none(
|
|
80
|
-
is_sell=pad.side,
|
|
81
|
-
pair__coin__ticker=pad.tokenId,
|
|
82
|
-
pair__cur__ticker=pad.currencyId,
|
|
83
|
-
).prefetch_related("pair")
|
|
84
|
-
# if not ps or not ps.pair:
|
|
85
|
-
# ... # THB/USDC: just for initial filling
|
|
86
|
-
ad_upd = models.Ad.validate(pad.model_dump(by_alias=True))
|
|
87
|
-
cur_scale = 10 ** (curex or await models.CurEx.get(cur_id=ps.pair.cur_id, ex=self.ex)).scale
|
|
88
|
-
coin_scale = 10 ** (coinex or await models.CoinEx.get(coin_id=ps.pair.coin_id, ex=self.ex)).scale
|
|
89
|
-
amt = int(float(pad.quantity) * float(pad.price) * cur_scale)
|
|
90
|
-
mxf = pad.maxAmount and int(float(pad.maxAmount) * cur_scale)
|
|
91
|
-
df_unq = ad_upd.df_unq(
|
|
92
|
-
maker_id=maker.id,
|
|
93
|
-
pair_side_id=ps.id,
|
|
94
|
-
amount=amt if amt < 4_294_967_295 else 4_294_967_295,
|
|
95
|
-
quantity=int(float(pad.quantity) * coin_scale),
|
|
96
|
-
min_fiat=int(float(pad.minAmount) * cur_scale),
|
|
97
|
-
max_fiat=mxf if mxf < 4_294_967_295 else 4_294_967_295,
|
|
98
|
-
price=int(float(pad.price) * cur_scale),
|
|
99
|
-
premium=int(float(pad.premium) * 100),
|
|
100
|
-
cond_id=cid,
|
|
101
|
-
status=self.ad_status(ad_upd.status),
|
|
102
|
-
)
|
|
103
|
-
try:
|
|
104
|
-
ad_db, _ = await models.Ad.update_or_create(**df_unq)
|
|
105
|
-
except OperationalError as e:
|
|
106
|
-
raise e
|
|
107
|
-
await ad_db.pms.add(*(await models.Pm.filter(pmexs__ex=self.ex, pmexs__exid__in=pad.payments)))
|
|
108
|
-
return ad_db
|
|
109
|
-
|
|
110
|
-
async def cond_load( # todo: refact from Bybit Ad format to universal
|
|
111
|
-
self,
|
|
112
|
-
ad: BaseAd,
|
|
113
|
-
ps: models.PairSide = None,
|
|
114
|
-
force: bool = False,
|
|
115
|
-
rname: str = None,
|
|
116
|
-
coinex: models.CoinEx = None,
|
|
117
|
-
curex: models.CurEx = None,
|
|
118
|
-
pms_from_cond: bool = False,
|
|
119
|
-
) -> tuple[models.Ad, bool]:
|
|
120
|
-
_sim, cid = None, None
|
|
121
|
-
ad_db = await models.Ad.get_or_none(exid=ad.id, maker__ex=self.ex).prefetch_related("cond")
|
|
122
|
-
# если точно такое условие уже есть в бд
|
|
123
|
-
if not (cleaned := clean(ad.remark)) or (cid := {oc[0]: ci for ci, oc in self.all_conds.items()}.get(cleaned)):
|
|
124
|
-
# и объява с таким ид уже есть, но у нее другое условие
|
|
125
|
-
if ad_db and ad_db.cond_id != cid:
|
|
126
|
-
# то обновляем ид ее условия
|
|
127
|
-
ad_db.cond_id = cid
|
|
128
|
-
await ad_db.save()
|
|
129
|
-
logging.info(f"{ad.nickName} upd cond#{ad_db.cond_id}->{cid}")
|
|
130
|
-
# old_cid = ad_db.cond_id # todo: solve race-condition, а пока что очищаем при каждом запуске
|
|
131
|
-
# if not len((old_cond := await Cond.get(id=old_cid).prefetch_related('ads')).ads):
|
|
132
|
-
# await old_cond.delete()
|
|
133
|
-
# logging.warning(f"Cond#{old_cid} deleted!")
|
|
134
|
-
return (ad_db or force and await self.ad_load(ad, cid, ps, coinex=coinex, curex=curex, rname=rname)), False
|
|
135
|
-
# если эта объява в таким ид уже есть в бд, но с другим условием (или без), а текущего условия еще нет в бд
|
|
136
|
-
if ad_db:
|
|
137
|
-
await ad_db.fetch_related("cond__ads", "maker")
|
|
138
|
-
if not ad_db.cond_id or (
|
|
139
|
-
# у измененного условия этой объявы есть другие объявы?
|
|
140
|
-
(rest_ads := set(ad_db.cond.ads) - {ad_db})
|
|
141
|
-
and
|
|
142
|
-
# другие объявы этого условия принадлежат другим юзерам
|
|
143
|
-
{ra.maker_id for ra in rest_ads} - {ad_db.maker_id}
|
|
144
|
-
):
|
|
145
|
-
# создадим новое условие и присвоим его только текущей объяве
|
|
146
|
-
cond = await self.cond_new(cleaned, {int(ad.userId)})
|
|
147
|
-
ad_db.cond_id = cond.id
|
|
148
|
-
await ad_db.save()
|
|
149
|
-
ad_db.cond = cond
|
|
150
|
-
return ad_db, True
|
|
151
|
-
# а если других объяв со старым условием этой обявы нет, либо они все этого же юзера
|
|
152
|
-
# обновляем условие (в тч во всех ЕГО объявах)
|
|
153
|
-
ad_db.cond.last_ver = ad_db.cond.raw_txt
|
|
154
|
-
ad_db.cond.raw_txt = cleaned
|
|
155
|
-
try:
|
|
156
|
-
await ad_db.cond.save()
|
|
157
|
-
except IntegrityError as e:
|
|
158
|
-
raise e
|
|
159
|
-
await self.cond_upd(ad_db.cond, {ad_db.maker.exid})
|
|
160
|
-
# и подправим коэфициенты похожести нового текста
|
|
161
|
-
await self.fix_rel_sims(ad_db.cond_id, cleaned)
|
|
162
|
-
return ad_db, False
|
|
163
|
-
|
|
164
|
-
cond = await self.cond_new(cleaned, {int(ad.userId)})
|
|
165
|
-
ad_db = await self.ad_load(ad, cond.id, ps, coinex=coinex, curex=curex, rname=rname)
|
|
166
|
-
ad_db.cond = cond
|
|
167
|
-
return ad_db, True
|
|
168
|
-
|
|
169
|
-
async def cond_new(self, txt: str, uids: set[int]) -> models.Cond:
|
|
170
|
-
new_cond, _ = await models.Cond.update_or_create(raw_txt=txt)
|
|
171
|
-
# и максимально похожую связь для нового условия (если есть >= 60%)
|
|
172
|
-
await self.cond_upd(new_cond, uids)
|
|
173
|
-
return new_cond
|
|
174
|
-
|
|
175
|
-
async def cond_upd(self, cond: models.Cond, uids: set[int]):
|
|
176
|
-
self.all_conds[cond.id] = cond.raw_txt, uids
|
|
177
|
-
# и максимально похожую связь для нового условия (если есть >= 60%)
|
|
178
|
-
old_cid, sim = await self.cond_get_max_sim(cond.id, cond.raw_txt, uids)
|
|
179
|
-
await self.actual_sim(cond.id, old_cid, sim)
|
|
180
|
-
|
|
181
|
-
def find_in_tree(self, cid: int, old_cid: int) -> bool:
|
|
182
|
-
if p := self.cond_sims.get(old_cid):
|
|
183
|
-
if p == cid:
|
|
184
|
-
return True
|
|
185
|
-
return self.find_in_tree(cid, p)
|
|
186
|
-
return False
|
|
187
|
-
|
|
188
|
-
async def cond_get_max_sim(self, cid: int, txt: str, uids: set[int]) -> tuple[int | None, int | None]:
|
|
189
|
-
# находим все старые тексты похожие на 90% и более
|
|
190
|
-
if len(txt) < 15:
|
|
191
|
-
return None, None
|
|
192
|
-
sims: dict[int, int] = {}
|
|
193
|
-
for old_cid, (old_txt, old_uids) in self.all_conds.items():
|
|
194
|
-
if len(old_txt) < 15 or uids == old_uids:
|
|
195
|
-
continue
|
|
196
|
-
elif not self.can_add_sim(cid, old_cid):
|
|
197
|
-
continue
|
|
198
|
-
if sim := get_sim(txt, old_txt):
|
|
199
|
-
sims[old_cid] = sim
|
|
200
|
-
# если есть, берем самый похожий из них
|
|
201
|
-
if sims:
|
|
202
|
-
old_cid, sim = max(sims.items(), key=lambda x: x[1])
|
|
203
|
-
await sleep(0.3)
|
|
204
|
-
return old_cid, sim
|
|
205
|
-
return None, None
|
|
206
|
-
|
|
207
|
-
def can_add_sim(self, cid: int, old_cid: int) -> bool:
|
|
208
|
-
if cid == old_cid:
|
|
209
|
-
return False
|
|
210
|
-
elif self.cond_sims.get(cid) == old_cid:
|
|
211
|
-
return False
|
|
212
|
-
elif self.find_in_tree(cid, old_cid):
|
|
213
|
-
return False
|
|
214
|
-
elif self.cond_sims.get(old_cid) == cid:
|
|
215
|
-
return False
|
|
216
|
-
elif cid in self.rcond_sims.get(old_cid, {}):
|
|
217
|
-
return False
|
|
218
|
-
elif old_cid in self.rcond_sims.get(cid, {}):
|
|
219
|
-
return False
|
|
220
|
-
return True
|
|
221
|
-
|
|
222
|
-
async def fix_rel_sims(self, cid: int, new_txt: str):
|
|
223
|
-
for rel_sim in await models.CondSim.filter(cond_rel_id=cid).prefetch_related("cond"):
|
|
224
|
-
if sim := get_sim(new_txt, rel_sim.cond.raw_txt):
|
|
225
|
-
rel_sim.similarity = sim
|
|
226
|
-
await rel_sim.save()
|
|
227
|
-
else:
|
|
228
|
-
await rel_sim.delete()
|
|
229
|
-
|
|
230
|
-
async def actual_cond(self):
|
|
231
|
-
for curr, old in await models.CondSim.all().values_list("cond_id", "cond_rel_id"):
|
|
232
|
-
self.cond_sims[curr] = old
|
|
233
|
-
self.rcond_sims[old] |= {curr}
|
|
234
|
-
for cid, (txt, uids) in self.all_conds.items():
|
|
235
|
-
old_cid, sim = await self.cond_get_max_sim(cid, txt, uids)
|
|
236
|
-
await self.actual_sim(cid, old_cid, sim)
|
|
237
|
-
# хз бля чо это ваще
|
|
238
|
-
# for ad_db in await models.Ad.filter(direction__pairex__ex=self.ex).prefetch_related("cond", "maker"):
|
|
239
|
-
# ad = Ad(id=str(ad_db.exid), userId=str(ad_db.maker.exid), remark=ad_db.cond.raw_txt)
|
|
240
|
-
# await self.cond_upsert(ad, force=True)
|
|
241
|
-
|
|
242
|
-
async def actual_sim(self, cid: int, old_cid: int, sim: int):
|
|
243
|
-
if not sim:
|
|
244
|
-
return
|
|
245
|
-
if old_sim := await models.CondSim.get_or_none(cond_id=cid):
|
|
246
|
-
if old_sim.cond_rel_id != old_cid:
|
|
247
|
-
if sim > old_sim.similarity:
|
|
248
|
-
logging.warning(f"R {cid}: {old_sim.similarity}->{sim} ({old_sim.cond_rel_id}->{old_cid})")
|
|
249
|
-
await old_sim.update_from_dict({"similarity": sim, "old_rel_id": old_cid}).save()
|
|
250
|
-
self._cond_sim_upd(cid, old_cid)
|
|
251
|
-
elif sim != old_sim.similarity:
|
|
252
|
-
logging.info(f"{cid}: {old_sim.similarity}->{sim}")
|
|
253
|
-
await old_sim.update_from_dict({"similarity": sim}).save()
|
|
254
|
-
else:
|
|
255
|
-
await models.CondSim.create(cond_id=cid, cond_rel_id=old_cid, similarity=sim)
|
|
256
|
-
self._cond_sim_upd(cid, old_cid)
|
|
257
|
-
|
|
258
|
-
def _cond_sim_upd(self, cid: int, old_cid: int):
|
|
259
|
-
if old_old_cid := self.cond_sims.get(cid): # если старый cid уже был в дереве:
|
|
260
|
-
self.rcond_sims[old_old_cid].remove(cid) # удаляем из обратного
|
|
261
|
-
self.cond_sims[cid] = old_cid # а в прямом он автоматом переопределится, даже если и был
|
|
262
|
-
self.rcond_sims[old_cid] |= {cid} # ну и в обратное добавим новый
|
|
263
|
-
|
|
264
|
-
def build_tree(self):
|
|
265
|
-
set(self.cond_sims.keys()) | set(self.cond_sims.values())
|
|
266
|
-
tree = defaultdict(dict)
|
|
267
|
-
# Группируем родителей по детям
|
|
268
|
-
for child, par in self.cond_sims.items():
|
|
269
|
-
tree[par] |= {child: {}} # todo: make from self.rcond_sim
|
|
270
|
-
|
|
271
|
-
# Строим дерево снизу вверх
|
|
272
|
-
def subtree(node):
|
|
273
|
-
if not node:
|
|
274
|
-
return node
|
|
275
|
-
for key in node:
|
|
276
|
-
subnode = tree.pop(key, {})
|
|
277
|
-
d = subtree(subnode)
|
|
278
|
-
node[key] |= d # actual tree rebuilding here!
|
|
279
|
-
return node # todo: refact?
|
|
280
|
-
|
|
281
|
-
# Находим корни / без родителей
|
|
282
|
-
roots = set(self.cond_sims.values()) - set(self.cond_sims.keys())
|
|
283
|
-
for root in roots:
|
|
284
|
-
_ = subtree(tree[root])
|
|
285
|
-
|
|
286
|
-
self.tree = tree
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
def get_sim(s1, s2) -> int:
|
|
290
|
-
sim = int((SequenceMatcher(None, s1, s2).ratio() - 0.6) * 10_000)
|
|
291
|
-
return sim if sim > 0 else 0
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
def clean(s) -> str:
|
|
295
|
-
clear = r"[^\w\s.,!?;:()\-]"
|
|
296
|
-
repeat = r"(.)\1{2,}"
|
|
297
|
-
s = re.sub(clear, "", s).lower()
|
|
298
|
-
s = re.sub(repeat, r"\1", s)
|
|
299
|
-
return s.replace("\n\n", "\n").replace(" ", " ").strip(" \n/.,!?-")
|