1
This commit is contained in:
1 parent
3ae4e18211
commit
730adb3ff2
9 files changed
+206
-33
No files matched your search
+14
-1
@@ -6,7 +6,7 @@
|
||||
|
||||
- Чистый или подготовленный Ubuntu Server 24.04 с доступом `sudo`.
|
||||
- Домен или поддомен, например `trade.example.com`, и DNS `A`-запись на публичный IPv4 сервера. Если добавлена `AAAA`-запись, IPv6 тоже должен вести на этот сервер и принимать 80/443.
|
||||
- В сетевом firewall хостинга разрешить входящие TCP 22 (SSH), 80 и 443. Порт 8765 наружу не открывать.
|
||||
- В режиме Certbot напрямую разрешить входящие TCP 22 (SSH), 80 и 443. В режиме TLS-шлюза разрешить только настроенный вход через шлюз к внутреннему порту 80 контейнера; порт 8765 наружу не открывать.
|
||||
- Исходящий доступ сервера к публичным API Bybit, Gate, MEXC и HTX. Binance в этом варианте не используется.
|
||||
- Подключение к серверу по SSH. Не отключайте текущую SSH-сессию во время настройки firewall.
|
||||
|
||||
@@ -40,12 +40,25 @@ sudo -u cryptosim /opt/crypto-scam/.venv/bin/python /opt/crypto-scam/user_admin.
|
||||
|
||||
Общий Basic Auth пароль можно сменить командой `sudo htpasswd -B /etc/nginx/crypto-scam/htpasswd ИМЯ`, затем выполнить `sudo systemctl reload nginx`.
|
||||
|
||||
### HTTPS на шлюзе хостинга и нестандартный внешний порт
|
||||
|
||||
Если провайдер принимает TLS на внешнем адресе, например `https://zdfn.my.to:25590`, и завершает его до проксирования в контейнер, используйте режим TLS-шлюза. Сначала настройте шлюз на проксирование HTTPS-only трафика в `http://192.168.144.115:80` (или актуальный приватный IP контейнера), с заголовком `Host: zdfn.my.to`. Внешний HTTP должен перенаправляться на HTTPS, а незашифрованный обходной маршрут к контейнеру должен быть закрыт.
|
||||
|
||||
Затем выполните из каталога проекта:
|
||||
|
||||
```bash
|
||||
sudo ./deploy.sh zdfn.my.to --tls-proxy https://zdfn.my.to:25590
|
||||
```
|
||||
|
||||
В этом режиме TLS-сертификат обслуживает шлюз, а Certbot внутри контейнера не запускается. Внутренний Nginx требует Basic Auth и передаёт приложению признак HTTPS. Не используйте этот режим, пока шлюз действительно не настроен на TLS и внешний HTTP-маршрут не закрыт/перенаправлен.
|
||||
|
||||
## Учётные записи, данные и API-ключи
|
||||
|
||||
- Общая БД аккаунтов и хешей паролей, а также пользовательские хранилища расположены в `/var/lib/crypto-scam/`. Для каждого аккаунта создаётся отдельный движок.
|
||||
- Первый аккаунт, созданный по SSH, получает копию старых данных, если они находились в переносимом `web_sim_data`; исходники не удаляются. Остальные аккаунты изолированы.
|
||||
- История рыночных данных сейчас отдельная для каждого пользователя. Сканеры Bybit, Gate, MEXC и HTX запускаются для каждого существующего аккаунта при старте сервиса, в том числе без открытой вкладки.
|
||||
- API-ключи на Linux шифруются AES-256-GCM ключом сервера `/etc/crypto-scam/master.key`; доступ к нему есть у системной службы. Для реальной торговли нужны новые ключи: Windows DPAPI-файлы расшифровать на Linux нельзя.
|
||||
- Журнал реальных ордеров и арбитража отдельный для каждого аккаунта: `real_orders.jsonl` в каталоге данных пользователя. В событиях открытия/закрытия записываются время и цена решения, время подтверждённого исполнения и средняя цена fill; для парных сделок цены/время спота и фьючерса хранятся отдельно. В веб-журнале время отображается по Москве, в JSONL также сохраняется ISO-8601 UTC.
|
||||
- Включайте на бирже только необходимые права, запрещайте вывод средств и сначала проверяйте в симуляции. Публичный HTTPS сам по себе не делает стратегию или реальные ордера безопасными.
|
||||
|
||||
## Управление
|
||||
|
||||
+44
-8
@@ -315,6 +315,12 @@ class Position:
|
||||
tp_price: float = 0.0
|
||||
exact: bool = True # all prices and fees are the exchange's own figures
|
||||
innovation: bool = False # an Innovation Zone perp: its own fee rate
|
||||
decision_open_time: float = 0.0
|
||||
decision_spot_price: float = 0.0
|
||||
decision_futures_price: float = 0.0
|
||||
decision_close_time: float = 0.0
|
||||
decision_close_spot_price: float = 0.0
|
||||
decision_close_futures_price: float = 0.0
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -593,6 +599,10 @@ class BasisEngine:
|
||||
reason = reason or "продажа спота после выкупа шорта"
|
||||
if reason:
|
||||
if pos.real:
|
||||
if not pos.decision_close_time:
|
||||
pos.decision_close_time = now
|
||||
pos.decision_close_spot_price = p.spot_bid
|
||||
pos.decision_close_futures_price = p.fut_ask
|
||||
if pos.uid not in self.busy and now >= pos.retry_at:
|
||||
self.busy.add(pos.uid)
|
||||
self.jobs.put(("close", pos.uid, reason))
|
||||
@@ -874,6 +884,8 @@ class BasisEngine:
|
||||
|
||||
def _real_open(self, p: Pair, amount: float) -> None:
|
||||
import live
|
||||
decision_open_time = time.time()
|
||||
decision_spot_price, decision_futures_price = p.spot_ask, p.fut_bid
|
||||
notes = []
|
||||
# BEFORE buying anything: can the perp be shorted for this amount at all (its minimum lot)?
|
||||
try:
|
||||
@@ -897,7 +909,10 @@ class BasisEngine:
|
||||
or len(held) >= max(1, self.settings.max_real_positions)):
|
||||
self.opening.discard(p.base)
|
||||
return
|
||||
self.pending[p.base] = {"time": time.time(), "amount": amount} # a stop now: found again at start
|
||||
self.pending[p.base] = {"time": time.time(), "amount": amount,
|
||||
"decision_open_time": decision_open_time,
|
||||
"decision_spot_price": decision_spot_price,
|
||||
"decision_futures_price": decision_futures_price} # a stop now: found again at start
|
||||
self.save()
|
||||
# money where it is needed: the amount on spot for the buy, the same on futures for the short's margin
|
||||
# (leverage 1 assumed — the safe side); moved from the other account when one of them is short
|
||||
@@ -915,7 +930,7 @@ class BasisEngine:
|
||||
return
|
||||
self._journal(p.base, "transfer", False, f"перевод не удался: {exc} — пробую без него")
|
||||
if self.settings.entry_limit:
|
||||
self._open_limit_first(c, p, amount)
|
||||
self._open_limit_first(c, p, amount, decision_open_time, decision_spot_price, decision_futures_price)
|
||||
return
|
||||
try:
|
||||
buy = c.spot_buy(p.base, amount)
|
||||
@@ -936,6 +951,7 @@ class BasisEngine:
|
||||
return
|
||||
buy = live.Fill(bought, p.spot_ask, amount * self.settings.spot_fee / 100, exc.order_id)
|
||||
notes.append("покупка не подтверждена биржей — цена оценочная")
|
||||
actual_spot_time = time.time()
|
||||
try:
|
||||
free = c.spot_free(p.base)
|
||||
except live.LiveError:
|
||||
@@ -953,6 +969,7 @@ class BasisEngine:
|
||||
# the short may be open: keep the position (estimated price) — closing it is reduce-only
|
||||
fut = live.Fill(coins, p.fut_bid, coins * p.fut_bid * self._fut_rate(p) / 100, exc.order_id)
|
||||
notes.append("шорт не подтверждён биржей — проверьте позицию, цена оценочная")
|
||||
actual_futures_time = time.time() if fut is not None else 0.0
|
||||
if fut is None:
|
||||
# no hedge → sell the spot back at once
|
||||
try:
|
||||
@@ -971,16 +988,23 @@ class BasisEngine:
|
||||
pos = Position(self.next_uid, p.base, time.time(), fut.coins, buy.price, fut.price,
|
||||
(fut.price / buy.price - 1) * 100, buy.fee_usd + fut.fee_usd, p.next_funding,
|
||||
real=True, spot_qty=held, fut_symbol=p.fut_symbol, error="; ".join(notes),
|
||||
exact=buy.exact and fut.exact and not notes, innovation=self._innovation(p))
|
||||
exact=buy.exact and fut.exact and not notes, innovation=self._innovation(p),
|
||||
decision_open_time=decision_open_time, decision_spot_price=decision_spot_price,
|
||||
decision_futures_price=decision_futures_price)
|
||||
self.next_uid += 1
|
||||
self.positions.append(pos)
|
||||
self.save()
|
||||
self._journal(p.base, "open", True, f"куплено {held:g} по {buy.price:.10g}, шорт {fut.coins:g} по "
|
||||
f"{fut.price:.10g}, разница {pos.entry_gap:+.3f}%" + (f" ({'; '.join(notes)})" if notes else ""),
|
||||
amount=amount)
|
||||
amount=amount, decision_open_time=decision_open_time,
|
||||
decision_spot_price=decision_spot_price, decision_futures_price=decision_futures_price,
|
||||
actual_open_time=max(actual_spot_time, actual_futures_time),
|
||||
actual_spot_time=actual_spot_time, actual_futures_time=actual_futures_time,
|
||||
actual_spot_price=buy.price, actual_futures_price=fut.price)
|
||||
self._place_tp(c, pos)
|
||||
|
||||
def _open_limit_first(self, c, p: Pair, amount: float) -> None:
|
||||
def _open_limit_first(self, c, p: Pair, amount: float, decision_open_time: float,
|
||||
decision_spot_price: float, decision_futures_price: float) -> None:
|
||||
"""Entry with a LIMIT short at the signal's perp bid, kept up to `limit_hold_s` seconds; whatever part of it
|
||||
fills is hedged at once by buying the same coins on spot. Nothing filled → the order is removed, no spot."""
|
||||
import live
|
||||
@@ -1028,6 +1052,7 @@ class BasisEngine:
|
||||
self.last_close[p.base] = time.time()
|
||||
return
|
||||
fut_price = st["price"] or p.fut_bid
|
||||
actual_futures_time = time.time()
|
||||
# hedge: the same coins on spot (the buy fee is taken in coins: a little more USDT)
|
||||
try:
|
||||
buy = c.spot_buy(p.base, shorted * p.spot_ask * (1 + s.spot_fee / 100) * 1.003)
|
||||
@@ -1043,6 +1068,7 @@ class BasisEngine:
|
||||
self.last_close[p.base] = time.time()
|
||||
self._pause_if_balance(str(exc))
|
||||
return
|
||||
actual_spot_time = time.time()
|
||||
try:
|
||||
free = c.spot_free(p.base)
|
||||
except live.LiveError:
|
||||
@@ -1053,12 +1079,18 @@ class BasisEngine:
|
||||
pos = Position(self.next_uid, p.base, time.time(), shorted, buy.price, fut_price,
|
||||
(fut_price / buy.price - 1) * 100, buy.fee_usd + st["fee"], p.next_funding,
|
||||
real=True, spot_qty=held, fut_symbol=p.fut_symbol, exact=buy.exact,
|
||||
innovation=self._innovation(p))
|
||||
innovation=self._innovation(p), decision_open_time=decision_open_time,
|
||||
decision_spot_price=decision_spot_price, decision_futures_price=decision_futures_price)
|
||||
self.next_uid += 1
|
||||
self.positions.append(pos)
|
||||
self.save()
|
||||
self._journal(p.base, "open", True, f"лимитный шорт {shorted:g} по {fut_price:.10g} (заявка {p.fut_bid:.10g}), "
|
||||
f"спот куплен {held:g} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}%", amount=amount)
|
||||
f"спот куплен {held:g} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}%", amount=amount,
|
||||
decision_open_time=decision_open_time, decision_spot_price=decision_spot_price,
|
||||
decision_futures_price=decision_futures_price,
|
||||
actual_open_time=max(actual_futures_time, actual_spot_time),
|
||||
actual_futures_time=actual_futures_time, actual_spot_time=actual_spot_time,
|
||||
actual_futures_price=fut_price, actual_spot_price=buy.price)
|
||||
self._place_tp(c, pos)
|
||||
|
||||
def _place_tp(self, c, pos: Position) -> None:
|
||||
@@ -1252,7 +1284,11 @@ class BasisEngine:
|
||||
self.last_close[pos.base] = now
|
||||
self.save()
|
||||
self._journal(pos.base, "close", True, f"шорт выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет), спот "
|
||||
f"продан по {sell_price:.10g}, итог {net:+.4f} $, комиссии {fees:.4f} $ ({reason})", net=net)
|
||||
f"продан по {sell_price:.10g}, итог {net:+.4f} $, комиссии {fees:.4f} $ ({reason})", net=net,
|
||||
decision_close_time=pos.decision_close_time or None,
|
||||
decision_spot_price=pos.decision_close_spot_price or None,
|
||||
decision_futures_price=pos.decision_close_futures_price or None,
|
||||
actual_close_time=now, actual_spot_price=sell_price, actual_futures_price=pos.fut_exit)
|
||||
|
||||
def reset(self) -> str:
|
||||
with self.lock:
|
||||
|
||||
+25
-8
@@ -1638,8 +1638,9 @@ class CrossEngine:
|
||||
l = self._still_good(l, usual, amount)
|
||||
if l is None:
|
||||
return
|
||||
entry_decision = [time.time(), l.spot_ask, l.fut_bid, l.entry_gap]
|
||||
if l.ss:
|
||||
self._real_open_ss(l, usual, amount)
|
||||
self._real_open_ss(l, usual, amount, entry_decision)
|
||||
return
|
||||
s = self.settings
|
||||
a_fee = spot_fee(l.spot_ex, self.fees)
|
||||
@@ -1667,7 +1668,8 @@ class CrossEngine:
|
||||
or any(p.real and p.closing for p in self.positions)):
|
||||
return
|
||||
self.pending[l.base] = {"time": time.time(), "key": l.key, "coins": coins, "usual": usual,
|
||||
"amount": amount, "link": asdict(l), "phase": "prepared"}
|
||||
"amount": amount, "link": asdict(l), "phase": "prepared",
|
||||
"entry_decision": entry_decision}
|
||||
self.save()
|
||||
notional = coins * l.fut_bid
|
||||
fut_need = max(notional * self.FUT_NEED, equity_for(s.min_liq_pct, notional))
|
||||
@@ -1769,6 +1771,7 @@ class CrossEngine:
|
||||
return
|
||||
shorted, fut_price = held, l.fut_bid
|
||||
fut_fee_usd, fut_exact = held * l.fut_bid * fut_fee(l.fut_ex, self.fees, l.innovation) / 100, False
|
||||
fut_fill_time = time.time()
|
||||
self._pending_update(l.base, phase="hedge_submitted", shorted=shorted)
|
||||
# 2) the hedge: the same coins on spot on A (the buy fee is taken in coins: a little more USDT)
|
||||
try:
|
||||
@@ -1791,6 +1794,7 @@ class CrossEngine:
|
||||
self._pause_if_balance(str(exc), l.spot_ex)
|
||||
return
|
||||
buy = live.Fill(bought, l.spot_ask, bought * l.spot_ask * a_fee / 100, exc.order_id, exact=False)
|
||||
spot_fill_time = time.time()
|
||||
self._pending_update(l.base, phase="hedge_confirmed", buy=asdict(buy), shorted=shorted,
|
||||
fut_price=fut_price, fut_fee=fut_fee_usd)
|
||||
try:
|
||||
@@ -1808,7 +1812,7 @@ class CrossEngine:
|
||||
exact=buy.exact and fut_exact, innovation=l.innovation,
|
||||
liq_price=fut_price * (1 + to_liq / 100), liq_calc=fut_price * (1 + to_liq / 100),
|
||||
liq_src="расчёт", liq_checked=now,
|
||||
entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap],
|
||||
entry_signal=entry_decision,
|
||||
fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact],
|
||||
[l.fut_ex, l.fut_leg, fut_fee_usd, shorted * fut_price, fut_exact]])
|
||||
if mismatch:
|
||||
@@ -1825,7 +1829,11 @@ class CrossEngine:
|
||||
return
|
||||
self._journal(l.base, "open", True, f"шорт {shorted:g} на {l.fut_ex} по {fut_price:.10g}, спот {held:g} на "
|
||||
f"{l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% (обычная {usual:+.3f}%), "
|
||||
f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount)
|
||||
f"ликвидация шорта по расчёту {pos.liq_calc:.10g} (+{to_liq:.0f}%)", amount=amount,
|
||||
decision_open_time=entry_decision[0], decision_spot_price=entry_decision[1],
|
||||
decision_futures_price=entry_decision[2], actual_open_time=max(fut_fill_time, spot_fill_time),
|
||||
actual_spot_price=buy.price, actual_futures_price=fut_price,
|
||||
actual_spot_time=spot_fill_time, actual_futures_time=fut_fill_time)
|
||||
self._refresh_liq(pos.uid, first=True)
|
||||
|
||||
CONFIRM_CHECKS = 2
|
||||
@@ -1875,7 +1883,7 @@ class CrossEngine:
|
||||
self.fast_seen[l.key] = time.time()
|
||||
return fresh
|
||||
|
||||
def _real_open_ss(self, l: Link, usual: float, amount: float) -> None:
|
||||
def _real_open_ss(self, l: Link, usual: float, amount: float, entry_decision: list | None = None) -> None:
|
||||
"""Spot–spot: sell coins from the stock on B's spot first (they are there: nothing can fail half-way on a
|
||||
missing coin), then buy the same coins on A's spot. A failed buy on A buys the stock back on B at once."""
|
||||
import basis
|
||||
@@ -1897,6 +1905,7 @@ class CrossEngine:
|
||||
self._not_tradable(l.base, f"на споте {l.fut_ex} {have:g} {l.base}, а для продажи нужно {coins:.6g} — "
|
||||
f"положите монету на {l.fut_ex}", 300)
|
||||
return
|
||||
entry_decision = entry_decision or [time.time(), l.spot_ask, l.fut_bid, l.entry_gap]
|
||||
with self.lock:
|
||||
held = [x.base for x in self.positions if x.real]
|
||||
if (l.base in held or self.opening - {l.base} or self.elsewhere(l.base) or self.full(l)
|
||||
@@ -1960,7 +1969,7 @@ class CrossEngine:
|
||||
pos = CrossPosition(self.next_uid, l.base, l.spot_ex, l.fut_ex, l.spot_symbol, l.fut_symbol, now,
|
||||
sold.coins, buy.price, sold.price, (sold.price / buy.price - 1) * 100, usual,
|
||||
buy.fee_usd + sold.fee_usd, 0.0, real=True, spot_qty=got, ss=True,
|
||||
exact=buy.exact and sold.exact, entry_signal=[now, l.spot_ask, l.fut_bid, l.entry_gap],
|
||||
exact=buy.exact and sold.exact, entry_signal=entry_decision,
|
||||
fills=[[l.spot_ex, "spot", buy.fee_usd, buy.coins * buy.price, buy.exact],
|
||||
[l.fut_ex, "spot", sold.fee_usd, sold.coins * sold.price, sold.exact]])
|
||||
self.next_uid += 1
|
||||
@@ -1969,7 +1978,10 @@ class CrossEngine:
|
||||
self.save()
|
||||
self._journal(l.base, "open", True, f"спот-спот: продано {sold.coins:g} на {l.fut_ex} по {sold.price:.10g}, "
|
||||
f"куплено {got:g} на {l.spot_ex} по {buy.price:.10g}, разница {pos.entry_gap:+.3f}% "
|
||||
f"(обычная {usual:+.3f}%)", amount=amount)
|
||||
f"(обычная {usual:+.3f}%)", amount=amount,
|
||||
decision_open_time=entry_decision[0], decision_spot_price=entry_decision[1],
|
||||
decision_futures_price=entry_decision[2], actual_open_time=now,
|
||||
actual_spot_price=buy.price, actual_futures_price=sold.price)
|
||||
|
||||
def _refresh_liq(self, uid: int, first: bool = False) -> None:
|
||||
"""The exchange's own liquidation price of the short replaces the estimate (cross margin: it moves with
|
||||
@@ -2174,8 +2186,13 @@ class CrossEngine:
|
||||
self.save()
|
||||
first = (f"монеты на споте {pos.fut_ex} выкуплены по {pos.fut_exit:.10g}" if pos.ss else
|
||||
f"шорт на {pos.fut_ex} выкуплен по {pos.fut_exit:.10g} (биржа: позиции нет)")
|
||||
decision = pos.exit_signal or []
|
||||
self._journal(pos.base, "close", True, f"{first}, спот на {pos.spot_ex} продан по {sell_price:.10g}, итог "
|
||||
f"{net:+.4f} $, комиссии {fees:.4f} $ ({reason}){self._slippage_text(t)}", net=net)
|
||||
f"{net:+.4f} $, комиссии {fees:.4f} $ ({reason}){self._slippage_text(t)}", net=net,
|
||||
decision_close_time=decision[0] if len(decision) > 0 else None,
|
||||
decision_spot_price=decision[1] if len(decision) > 1 else None,
|
||||
decision_futures_price=decision[2] if len(decision) > 2 else None,
|
||||
actual_close_time=now, actual_spot_price=sell_price, actual_futures_price=pos.fut_exit)
|
||||
|
||||
@staticmethod
|
||||
def _slippage_text(t: CrossTrade) -> str:
|
||||
|
||||
+66
-7
@@ -14,16 +14,28 @@ NGINX_SITE="/etc/nginx/sites-available/crypto-scam-app"
|
||||
NGINX_ENABLED="/etc/nginx/sites-enabled/crypto-scam-app"
|
||||
SERVICE_FILE="/etc/systemd/system/crypto-scam.service"
|
||||
DOMAIN="${1:-}"
|
||||
EMAIL="${2:-}"
|
||||
MODE="certbot"
|
||||
EMAIL=""
|
||||
PUBLIC_URL=""
|
||||
if [[ "${2:-}" == "--tls-proxy" ]]; then
|
||||
MODE="tls-proxy"
|
||||
PUBLIC_URL="${3:-}"
|
||||
else
|
||||
EMAIL="${2:-}"
|
||||
fi
|
||||
|
||||
if [[ ! "$DOMAIN" =~ ^[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
|
||||
echo "Укажите домен, уже направленный DNS-записями на этот сервер: $0 example.com admin@example.com" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ ! "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then
|
||||
if [[ "$MODE" == "certbot" && ! "$EMAIL" =~ ^[^[:space:]@]+@[^[:space:]@]+\.[^[:space:]@]+$ ]]; then
|
||||
echo "Укажите email для уведомлений Let's Encrypt: $0 example.com admin@example.com" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ "$MODE" == "tls-proxy" && ! "$PUBLIC_URL" =~ ^https://$DOMAIN:[0-9]{1,5}$ ]]; then
|
||||
echo "Для TLS-шлюза укажите внешний HTTPS URL с портом, например: $0 zdfn.my.to --tls-proxy https://zdfn.my.to:25590" >&2
|
||||
exit 2
|
||||
fi
|
||||
if [[ -e "$NGINX_SITE" ]] && ! grep -q 'Managed by Crypto Scam deploy.sh' "$NGINX_SITE"; then
|
||||
echo "$NGINX_SITE уже занят другой конфигурацией; не перезаписываю его." >&2
|
||||
exit 3
|
||||
@@ -51,7 +63,11 @@ fi
|
||||
|
||||
export DEBIAN_FRONTEND=noninteractive
|
||||
apt-get update
|
||||
apt-get install -y nginx certbot python3-certbot-nginx python3-venv python3-tk python3-cryptography rsync apache2-utils
|
||||
PACKAGES=(nginx python3-venv python3-tk python3-cryptography rsync apache2-utils)
|
||||
if [[ "$MODE" == "certbot" ]]; then
|
||||
PACKAGES+=(certbot python3-certbot-nginx)
|
||||
fi
|
||||
apt-get install -y "${PACKAGES[@]}"
|
||||
|
||||
if ! id "$SERVICE_USER" >/dev/null 2>&1; then
|
||||
useradd --system --home-dir "$DATA_DIR" --create-home --shell /usr/sbin/nologin "$SERVICE_USER"
|
||||
@@ -87,6 +103,7 @@ chmod -R u=rwX,g=,o= "$DATA_DIR"
|
||||
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$SERVICE_FILE" <<EOF
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
[Unit]
|
||||
Description=Crypto Scam multi-user web simulator
|
||||
After=network-online.target
|
||||
@@ -100,6 +117,7 @@ WorkingDirectory=$APP_DIR
|
||||
Environment=PYTHONUNBUFFERED=1
|
||||
Environment=PYTHONDONTWRITEBYTECODE=1
|
||||
Environment=CRYPTO_SCAM_PUBLIC_HOST=$DOMAIN
|
||||
Environment=CRYPTO_SCAM_PUBLIC_PORT=$(if [[ "$MODE" == "tls-proxy" ]]; then printf '%s' "${PUBLIC_URL##*:}"; else printf '443'; fi)
|
||||
Environment=CRYPTO_SCAM_MASTER_KEY_FILE=/etc/crypto-scam/master.key
|
||||
UMask=0077
|
||||
ExecStart=$APP_DIR/.venv/bin/python -B web_proxy.py
|
||||
@@ -130,8 +148,38 @@ chown root:www-data /etc/nginx/crypto-scam/htpasswd
|
||||
chmod 0640 /etc/nginx/crypto-scam/htpasswd
|
||||
unset GATE_PASSWORD
|
||||
|
||||
if [[ "$MODE" == "tls-proxy" ]]; then
|
||||
# TLS terminates at the hosting gateway; it must proxy HTTPS-only traffic to this private HTTP listener.
|
||||
# Do not expose a separate plaintext route from the internet to container port 80 in this mode.
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$NGINX_SITE" <<EOF
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
server_name $DOMAIN;
|
||||
|
||||
auth_basic "Crypto Scam server access";
|
||||
auth_basic_user_file /etc/nginx/crypto-scam/htpasswd;
|
||||
client_max_body_size 128k;
|
||||
|
||||
location / {
|
||||
proxy_pass http://127.0.0.1:8765;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Host \$host;
|
||||
proxy_set_header X-Forwarded-Proto https;
|
||||
proxy_set_header X-Forwarded-For \$proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Real-IP \$remote_addr;
|
||||
proxy_set_header Connection "";
|
||||
proxy_read_timeout 75s;
|
||||
proxy_send_timeout 75s;
|
||||
}
|
||||
}
|
||||
EOF
|
||||
else
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$NGINX_SITE" <<EOF
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$NGINX_SITE" <<EOF
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
@@ -139,13 +187,17 @@ server {
|
||||
location / { return 404; }
|
||||
}
|
||||
EOF
|
||||
fi
|
||||
ln -sfn "$NGINX_SITE" /etc/nginx/sites-enabled/crypto-scam-app
|
||||
nginx -t
|
||||
systemctl reload nginx
|
||||
certbot certonly --nginx --non-interactive --agree-tos --email "$EMAIL" -d "$DOMAIN"
|
||||
|
||||
if [[ "$MODE" == "certbot" ]]; then
|
||||
certbot certonly --nginx --non-interactive --agree-tos --email "$EMAIL" -d "$DOMAIN"
|
||||
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$NGINX_SITE" <<EOF
|
||||
# Managed by Crypto Scam deploy.sh
|
||||
cat > "$NGINX_SITE" <<EOF
|
||||
server {
|
||||
listen 80;
|
||||
listen [::]:80;
|
||||
@@ -179,12 +231,19 @@ server {
|
||||
}
|
||||
}
|
||||
EOF
|
||||
fi
|
||||
|
||||
nginx -t
|
||||
systemctl reload nginx
|
||||
systemctl restart crypto-scam.service
|
||||
|
||||
echo
|
||||
echo "Готово: https://$DOMAIN"
|
||||
if [[ "$MODE" == "tls-proxy" ]]; then
|
||||
echo "Готово после настройки TLS-шлюза: $PUBLIC_URL"
|
||||
echo "Шлюз должен передавать Host=$DOMAIN и проксировать HTTPS на http://192.168.144.115:80."
|
||||
else
|
||||
echo "Готово: https://$DOMAIN"
|
||||
fi
|
||||
echo "Сначала браузер спросит общий Basic Auth пароль, затем откроется форма входа Crypto Scam."
|
||||
echo "Статус сервера: systemctl status crypto-scam nginx"
|
||||
echo "Логи: journalctl -u crypto-scam -f"
|
||||
|
||||
@@ -21,6 +21,7 @@ from persistence import atomic_write_json
|
||||
import queue
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
import live
|
||||
@@ -36,6 +37,10 @@ RECENT: list[dict] = [] # last events of both tabs, newest last
|
||||
def journal(tab: str, exchange: str, coin: str, action: str, ok: bool, text: str, **extra) -> dict:
|
||||
event = {"time": time.time(), "tab": tab, "exchange": exchange, "coin": coin, "action": action, "ok": ok,
|
||||
"text": text, **extra}
|
||||
# Keep epoch seconds for calculations and an ISO-8601 UTC rendering for humans.
|
||||
for key, value in tuple(event.items()):
|
||||
if key.endswith("_time") and isinstance(value, (int, float)) and not isinstance(value, bool):
|
||||
event[f"{key}_utc"] = datetime.fromtimestamp(value, timezone.utc).isoformat(timespec="milliseconds")
|
||||
with _journal_lock:
|
||||
RECENT.append(event)
|
||||
del RECENT[:-300]
|
||||
@@ -312,6 +317,7 @@ class FuturesMirror:
|
||||
units = symbol_units(self.symbol)
|
||||
self.position = {"uid": pos.uid, "side": pos.side, "coins": pos.qty * units,
|
||||
"paper_entry": pos.entry / units, "opened": time.time(),
|
||||
"decision_open_time": pos.opened, "decision_open_price": pos.entry / units,
|
||||
# the paper take-profit as a distance from the entry: the real TP is placed at
|
||||
# the same distance from the REAL fill price, not at the paper price
|
||||
"tp_pct": (pos.target / pos.entry - 1) * 100 if getattr(pos, "target", None) else None,
|
||||
@@ -323,6 +329,9 @@ class FuturesMirror:
|
||||
return
|
||||
self.jobs.put(("open", None))
|
||||
elif event == "close" and self.position and self.position.get("uid") == pos.uid:
|
||||
self.position["decision_close_time"] = getattr(pos, "close_decision_time", time.time())
|
||||
self.position["decision_close_price"] = getattr(pos, "close_decision_price", 0.0)
|
||||
self.position["decision_close_reason"] = getattr(pos, "close_reason", "закрыта в симуляторе")
|
||||
self.jobs.put(("close", "закрыта в симуляторе"))
|
||||
|
||||
def request_close(self, reason: str = "удаление подключения") -> None:
|
||||
@@ -473,9 +482,11 @@ class FuturesMirror:
|
||||
self._failed_open(str(exc))
|
||||
return
|
||||
# Persist the accepted fill before any additional network call (TP, fee sync, etc.).
|
||||
fill_time = time.time()
|
||||
with self.lock:
|
||||
pos.update(phase="filled", coins=fill.coins, entry=fill.price, fee_in=fill.fee_usd,
|
||||
exact=fill.exact, order_in=fill.order_id)
|
||||
exact=fill.exact, order_in=fill.order_id, actual_open_time=fill_time,
|
||||
actual_open_price=fill.price)
|
||||
self._save()
|
||||
# the exchange's real fee rate (it decides how far the TP has to be, and the paper model uses it too)
|
||||
fee_pct = fill.fee_usd / (fill.coins * fill.price) * 100 if fill.exact and fill.coins and fill.price else None
|
||||
@@ -511,7 +522,9 @@ class FuturesMirror:
|
||||
+ (f", пинг {pos['ping']:.0f} мс" if pos.get("ping") is not None else "") + "), "
|
||||
f"комиссия {fill.fee_usd:.4f} $" + (f"; {'; '.join(notes)}" if notes else ""), side=pos["side"],
|
||||
coins=fill.coins, price=fill.price, order=fill.order_id, ping=pos.get("ping"),
|
||||
slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign)
|
||||
slip=(fill.price / pos["paper_entry"] - 1) * 100 * sign,
|
||||
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
|
||||
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"))
|
||||
|
||||
def _top_up_futures(self, c, error: str, notional: float) -> None:
|
||||
"""The exchange refused for lack of money: move USDT from the spot account so the NEXT signal can trade
|
||||
@@ -588,7 +601,7 @@ class FuturesMirror:
|
||||
try:
|
||||
fill = c.fut_order(self.symbol, side, abs(held), reduce_only=True)
|
||||
fills.append({"coins": fill.coins, "price": fill.price, "fee": fill.fee_usd, "exact": fill.exact,
|
||||
"order": fill.order_id})
|
||||
"order": fill.order_id, "time": time.time()})
|
||||
except live.LiveError as exc:
|
||||
if not getattr(exc, "sent", False):
|
||||
raise
|
||||
@@ -618,7 +631,7 @@ class FuturesMirror:
|
||||
for f in theirs:
|
||||
if f.order_id not in ours and done_ours < pos["coins"] * 0.999:
|
||||
fills.append({"coins": f.coins, "price": f.price, "fee": f.fee_usd, "exact": f.exact,
|
||||
"order": f.order_id})
|
||||
"order": f.order_id, "time": time.time()})
|
||||
done_ours += f.coins
|
||||
if theirs and "биржей" not in reason:
|
||||
reason = f"закрыта биржей по TP/SL ({reason})"
|
||||
@@ -635,8 +648,9 @@ class FuturesMirror:
|
||||
coins = min(done, pos["coins"]) if done else pos["coins"]
|
||||
gross = sign * (exit_price - pos.get("entry", exit_price)) * coins
|
||||
fees = pos.get("fee_in", 0.0) + sum(f["fee"] for f in fills)
|
||||
closed_at = time.time()
|
||||
trade = {"side": pos["side"], "coins": coins, "entry": pos.get("entry", 0.0), "exit": exit_price,
|
||||
"opened": pos["opened"], "closed": time.time(), "gross": gross, "fees": fees, "net": gross - fees,
|
||||
"opened": pos["opened"], "closed": closed_at, "gross": gross, "fees": fees, "net": gross - fees,
|
||||
"pct": sign * (exit_price / pos["entry"] - 1) * 100 if pos.get("entry") else 0.0,
|
||||
"reason": reason, "exact": pos.get("exact", True) and all(f["exact"] for f in fills) and bool(fills)}
|
||||
with self.lock:
|
||||
@@ -646,7 +660,12 @@ class FuturesMirror:
|
||||
self.last_sync = 0.0 # pull the exchange's own figures for this trade soon
|
||||
journal("simulator", self.exchange, self.coin, "close", True,
|
||||
f"закрыта по {exit_price:.10g}, биржа подтвердила: позиции нет; итог {trade['net']:+.4f} $ "
|
||||
f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"])
|
||||
f"(комиссии {fees:.4f} $, {reason})", side=pos["side"], coins=coins, price=exit_price, net=trade["net"],
|
||||
decision_open_time=pos.get("decision_open_time"), decision_open_price=pos.get("decision_open_price"),
|
||||
actual_open_time=pos.get("actual_open_time"), actual_open_price=pos.get("actual_open_price"),
|
||||
decision_close_time=pos.get("decision_close_time"), decision_close_price=pos.get("decision_close_price"),
|
||||
actual_close_time=closed_at, actual_close_price=exit_price,
|
||||
actual_close_fill_time=max((f.get("time", closed_at) for f in fills), default=closed_at))
|
||||
|
||||
# --- view ------------------------------------------------------------------------------------------------------
|
||||
def view(self) -> dict:
|
||||
|
||||
@@ -7,6 +7,7 @@ from urllib.parse import urlsplit
|
||||
|
||||
LOCAL_HOSTS = {"127.0.0.1", "localhost", "::1"}
|
||||
PUBLIC_HOST = os.environ.get("CRYPTO_SCAM_PUBLIC_HOST", "").strip().lower().rstrip(".")
|
||||
PUBLIC_PORT = int(os.environ.get("CRYPTO_SCAM_PUBLIC_PORT", "443"))
|
||||
|
||||
|
||||
def _authority(value: str):
|
||||
@@ -33,7 +34,7 @@ def trusted_request(handler, *, command: bool = False) -> bool:
|
||||
return False
|
||||
is_public = bool(PUBLIC_HOST and host[0] == PUBLIC_HOST)
|
||||
if is_public and (handler.headers.get("X-Forwarded-Proto", "").lower() != "https"
|
||||
or host[1] not in (80, 443)):
|
||||
or host[1] not in (80, 443, PUBLIC_PORT)):
|
||||
return False
|
||||
origins = handler.headers.get_all("Origin", [])
|
||||
if len(origins) > 1:
|
||||
@@ -42,8 +43,11 @@ def trusted_request(handler, *, command: bool = False) -> bool:
|
||||
try:
|
||||
origin = urlsplit(origins[0])
|
||||
expected_scheme = "https" if is_public else "http"
|
||||
origin_authority = _authority(origin.netloc)
|
||||
if (origin.scheme != expected_scheme or origin.path or origin.query or origin.fragment
|
||||
or _authority(origin.netloc) != host):
|
||||
or origin_authority is None or origin_authority[0] != host[0]
|
||||
or (is_public and origin_authority[1] not in (80, 443, PUBLIC_PORT))
|
||||
or (not is_public and origin_authority != host)):
|
||||
return False
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
@@ -143,6 +143,9 @@ class Position:
|
||||
features: dict = field(default_factory=dict)
|
||||
uid: int = 0 # unique per ledger, so one of several open positions can be closed by hand
|
||||
margin: float = 0.0 # fixed at entry; changing leverage later must not release collateral
|
||||
close_decision_time: float = 0.0
|
||||
close_decision_price: float = 0.0
|
||||
close_reason: str = ""
|
||||
|
||||
|
||||
@dataclass
|
||||
@@ -406,6 +409,9 @@ class Ledger:
|
||||
self.balance, self._unrealized = old_balance, old_unrealized
|
||||
self._position_marks[pos.uid] = previous_mark
|
||||
return None
|
||||
pos.close_decision_time = now
|
||||
pos.close_decision_price = price
|
||||
pos.close_reason = reason
|
||||
for hook in self.hooks:
|
||||
hook("close", pos)
|
||||
if self.trades_path:
|
||||
|
||||
+16
-1
@@ -748,9 +748,24 @@ async function loadReal() {
|
||||
document.getElementById("realJournal").innerHTML = real.journal.map(j => `<tr>
|
||||
<td>${mskFull(j.time)}</td><td>${j.tab === "basis" ? "Арбитраж" : "Симулятор"}</td><td>${j.exchange}</td><td><b>${j.coin}</b></td>
|
||||
<td>${{open: "открытие", close: "закрытие", orphan: "закрытие осиротевшей", transfer: "перевод USDT"}[j.action] || j.action}</td>
|
||||
<td class="${j.ok ? "pos" : "neg"}" style="white-space:normal">${j.text}</td></tr>`).join("")
|
||||
<td class="${j.ok ? "pos" : "neg"}" style="white-space:normal">${escapeHtml(j.text)}${journalTiming(j)}</td></tr>`).join("")
|
||||
|| '<tr><td colspan="6" class="empty">Реальных ордеров ещё не было</td></tr>';
|
||||
}
|
||||
function journalTiming(j) {
|
||||
const price = value => Number.isFinite(Number(value)) && value != null ? Number(value).toPrecision(9) : "—";
|
||||
const row = (title, time, spot, futures, single) => {
|
||||
if (time == null && spot == null && futures == null && single == null) return "";
|
||||
const prices = single != null ? `цена ${price(single)}` : `спот ${price(spot)} · фьючерс ${price(futures)}`;
|
||||
return `<div class="mut" style="margin-top:3px">${title}: ${time == null ? "время не записано" : mskFull(time)} · ${prices}</div>`;
|
||||
};
|
||||
const isOpen = j.action === "open", isClose = j.action === "close";
|
||||
if (!isOpen && !isClose) return "";
|
||||
return isOpen
|
||||
? row("Решение открыть", j.decision_open_time, j.decision_spot_price, j.decision_futures_price, j.decision_open_price)
|
||||
+ row("Исполнение открытия", j.actual_open_time, j.actual_spot_price, j.actual_futures_price, j.actual_open_price)
|
||||
: row("Решение закрыть", j.decision_close_time, j.decision_spot_price, j.decision_futures_price, j.decision_close_price)
|
||||
+ row("Исполнение закрытия", j.actual_close_time, j.actual_spot_price, j.actual_futures_price, j.actual_close_price);
|
||||
}
|
||||
async function keySave(ex) {
|
||||
const key = document.getElementById(`kk-${ex}`), secret = document.getElementById(`ks-${ex}`);
|
||||
const r = await api(`/api/real/keys/${ex}`, {api_key: key.value, api_secret: secret.value});
|
||||
|
||||
@@ -358,6 +358,10 @@ class Proxy(BaseHTTPRequestHandler):
|
||||
headers = {k: v for k, v in self.headers.items() if k.lower() not in HOP_HEADERS}
|
||||
# Preserve the validated authority so the engine can compare the browser Origin.
|
||||
headers["Host"] = self.headers["Host"]
|
||||
# Forward only the scheme validated at this proxy boundary. The engine repeats
|
||||
# the host/origin checks and must know TLS terminated at the external gateway.
|
||||
if self.headers.get("X-Forwarded-Proto", "").lower() == "https":
|
||||
headers["X-Forwarded-Proto"] = "https"
|
||||
req = urllib.request.Request(ENGINE + self.path, data=body, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
|
||||
Reference in new issue
Block a user