grid closures channel: remove 'Archived' + 'no free USDT' noise messages; sweep only messages on actual transfer (margin returns to FUND directly)
be35258 Download trader/app.py from deanpowers/blind-monkeys: direct link, hf CLI and curl.
- Browser
- Download file 144 kB
-
https://huggingface.co/deanpowers/blind-monkeys/resolve/main/trader/app.py
- Command line
-
hf download hf://deanpowers/blind-monkeys/trader/app.py
-
curl -L -o app.py https://huggingface.co/deanpowers/blind-monkeys/resolve/main/trader/app.py
144 kB
import os
import json
import math
import time
import hmac
import hashlib
import urllib.request
import urllib.parse
from flask import Flask, request
from google.cloud import storage
import re as _re_full
from datetime import datetime, timezone, timedelta
app = Flask(__name__)
# ---------------------------------------------------------------------------
# Config (env-driven; secrets injected by Cloud Run)
# ---------------------------------------------------------------------------
BYBIT_API_KEY = os.environ.get("BYBIT_API_KEY", "")
BYBIT_API_SECRET = os.environ.get("BYBIT_API_SECRET", "")
BYBIT_HOST = os.environ.get("BYBIT_HOST", "https://api.bybit.com") # mainnet
CATEGORY = os.environ.get("BYBIT_CATEGORY", "spot") # spot (no leverage)
DRY_RUN = os.environ.get("DRY_RUN", "true").lower() in ("1", "true", "yes")
SCANNER_URL = os.environ.get("SCANNER_URL", "https://blind-monkeys-scanner-353804379600.europe-west1.run.app")
ORDER_NOTIONAL = float(os.environ.get("ORDER_NOTIONAL", "100")) # $100 seed per trade
TAKE_PROFIT_PCT = float(os.environ.get("TAKE_PROFIT_PCT", "3")) # +3%
STOP_LOSS_PCT = float(os.environ.get("STOP_LOSS_PCT", "5")) # -5%
MAX_POSITIONS = int(os.environ.get("MAX_POSITIONS", "3"))
MAX_DAILY_BUY = float(os.environ.get("MAX_DAILY_BUY", "500"))
AMOUNT_FLOOR = float(os.environ.get("AMOUNT_FLOOR", "10")) # compounding floor
# Compounding feedback-loop defaults (seed amount is always $100)
INCREASE_PCT = float(os.environ.get("INCREASE_PCT", "25")) # +25% on TP
DECREASE_PCT = float(os.environ.get("DECREASE_PCT", "25")) # -25% on SL
STATE_BUCKET = os.environ.get("STATE_BUCKET", "blind-monkeys-trader-state")
STATE_OBJECT = "config.json"
BALANCE_HISTORY_OBJECT = "balance_history.json"
SCORE_WEIGHTS_HISTORY_OBJECT = "score_weights_history.json"
UPWARD_WEIGHTS_HISTORY_OBJECT = "upward_weights_history.json"
TELEGRAM_BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
# Strong-tier constants (matches the "star" in the Rising Coins app)
STRONG_TOP_N = 100
STRONG_MIN_RISE = 2.0
STRONG_MIN_VOLUME = 5_000_000
STRONG_MIN_RATIO = 2.0
# Grid-opportunity scan constants (range-bound detection)
GRID_TOP_N = 100
GRID_MIN_WIDTH = 3.0 # % min 7d range width
GRID_MAX_WIDTH = 25.0 # % max 7d range width
GRID_MIN_OSC = 4 # min midpoint oscillations
GRID_DRIFT_RATIO = 0.6 # net drift must be < ratio * width
GRID_LOOKBACK_H = 168 # 7d hourly candles
GRID_SNAP_H = 24 # 24h snapshot
BINANCE_FUTURES = "https://fapi.binance.com"
COINGECKO = "https://api.coingecko.com/api/v3"
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def http_json(url, retries=3, timeout=20):
last = None
for i in range(retries):
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode())
except Exception as e:
last = e
time.sleep(1.5 * (i + 1))
raise last
def top_symbols(n):
url = (f"{COINGECKO}/coins/markets?vs_currency=usd&order=market_cap_desc"
f"&per_page={n}&page=1&sparkline=false")
out = {}
for c in http_json(url):
s = (c.get("symbol") or "").upper()
out.setdefault(s, []).append(c.get("market_cap_rank"))
return {s: v[0] for s, v in out.items() if len(v) == 1 and v[0]}
def futures_symbols():
data = http_json(f"{BINANCE_FUTURES}/fapi/v1/exchangeInfo")
return {s["baseAsset"] for s in data["symbols"]
if s.get("contractType") == "PERPETUAL" and s.get("quoteAsset") == "USDT"
and s.get("status") == "TRADING"}
def one_hour(sym):
k = http_json(f"{BINANCE_FUTURES}/fapi/v1/klines?symbol={sym}USDT&interval=1h&limit=169")
if len(k) < 169:
return None, None, None
pct = (float(k[-1][4]) - float(k[-2][4])) / float(k[-2][4]) * 100.0
vol = float(k[-1][7])
avg = sum(float(c[7]) for c in k[:-1]) / 168.0
ratio = vol / avg if avg > 0 else 0.0
return pct, vol, ratio
def funding(sym):
p = http_json(f"{BINANCE_FUTURES}/fapi/v1/premiumIndex?symbol={sym}USDT")
return float(p["lastFundingRate"]) * 100.0
def oi_change(sym):
h = http_json(f"{BINANCE_FUTURES}/futures/data/openInterestHist?"
f"symbol={sym}USDT&period=1h&limit=2")
return 0.0 if float(h[0]["sumOpenInterest"]) == 0 else \
(float(h[1]["sumOpenInterest"]) - float(h[0]["sumOpenInterest"])) / float(h[0]["sumOpenInterest"]) * 100.0
def scan_strong():
"""Return list of strong-tier coins (matches the app's ⭐): (rank, sym, pct, vol, ratio, fund, oi)."""
top = top_symbols(STRONG_TOP_N)
fut = futures_symbols()
strong = []
for sym in [s for s in top if s in fut]:
try:
pct, vol, ratio = one_hour(sym)
if pct is None:
continue
if pct >= STRONG_MIN_RISE and vol >= STRONG_MIN_VOLUME and ratio >= STRONG_MIN_RATIO:
f = funding(sym)
oi = oi_change(sym)
strong.append((top[sym], sym, pct, vol, ratio, f, oi))
except Exception:
continue
strong.sort(key=lambda x: -x[2])
return strong
def grid_klines(sym, hours):
return http_json(f"{BINANCE_FUTURES}/fapi/v1/klines?symbol={sym}USDT&interval=1h&limit={hours}")
def count_crossings(closes, mid):
n = 0
prev = None
for c in closes:
cur = c > mid
if prev is not None and cur != prev:
n += 1
prev = cur
return n
def scan_grid(top_n=GRID_TOP_N):
"""Range-bound futures coins (grid-bot candidates).
Returns list of (rank, sym, width7d, oscillations, drift7d, width24h) sorted
by oscillation count (most bounces = best grid candidate).
"""
top = top_symbols(top_n)
fut = futures_symbols()
out = []
for sym in [s for s in top if s in fut]:
try:
k = grid_klines(sym, GRID_LOOKBACK_H + 1)
if len(k) < GRID_LOOKBACK_H:
continue
closes = [float(c[4]) for c in k[-GRID_LOOKBACK_H:]]
highs = [float(c[2]) for c in k[-GRID_LOOKBACK_H:]]
lows = [float(c[3]) for c in k[-GRID_LOOKBACK_H:]]
hi = max(highs)
lo = min(lows)
if lo <= 0 or closes[0] <= 0:
continue
width = (hi - lo) / lo * 100.0
if width < GRID_MIN_WIDTH or width > GRID_MAX_WIDTH:
continue
drift = abs(closes[-1] - closes[0]) / closes[0] * 100.0
if drift > width * GRID_DRIFT_RATIO:
continue
osc = count_crossings(closes, (hi + lo) / 2.0)
if osc < GRID_MIN_OSC:
continue
snap = closes[-GRID_SNAP_H:] if len(closes) >= GRID_SNAP_H else closes
w24 = (max(snap) - min(snap)) / min(snap) * 100.0
out.append((top[sym], sym, width, osc, drift, w24))
except Exception:
continue
out.sort(key=lambda x: -x[3])
return out
# ---------------------------------------------------------------------------
# Bybit authenticated client
# ---------------------------------------------------------------------------
def bybit_request(method, path, params=None, body=None):
timestamp = str(int(time.time() * 1000))
recv_window = "5000"
if body is not None:
body_str = json.dumps(body)
param_str = timestamp + BYBIT_API_KEY + recv_window + body_str
else:
qs = urllib.parse.urlencode(params) if params else ""
param_str = timestamp + BYBIT_API_KEY + recv_window + qs
sig = hmac.new(BYBIT_API_SECRET.encode(), param_str.encode(), hashlib.sha256).hexdigest()
headers = {
"X-BAPI-API-KEY": BYBIT_API_KEY,
"X-BAPI-TIMESTAMP": timestamp,
"X-BAPI-RECV-WINDOW": recv_window,
"X-BAPI-SIGN": sig,
"Content-Type": "application/json",
}
url = BYBIT_HOST + path
data = json.dumps(body).encode() if body is not None else None
if data is None and params:
url += "?" + urllib.parse.urlencode(params)
req = urllib.request.Request(url, data=data, headers=headers, method=method)
with urllib.request.urlopen(req, timeout=20) as r:
return json.loads(r.read().decode())
def bybit_get(path, params=None):
return bybit_request("GET", path, params=params)
def bybit_post(path, body):
return bybit_request("POST", path, body=body)
def day_start_ms():
from datetime import datetime, timezone
now = datetime.now(timezone.utc)
start = datetime(now.year, now.month, now.day, tzinfo=timezone.utc)
return int(start.timestamp() * 1000)
def today_buy_notional():
"""Sum today's executed BUY notional (USD) via Bybit spot execution history."""
total = 0.0
cursor = None
start = day_start_ms()
for _ in range(5): # up to 5 pages
params = {"category": "spot", "startTime": str(start), "limit": "100"}
if cursor:
params["cursor"] = cursor
try:
r = bybit_get("/v5/execution/list", params)
except Exception:
break
res = r.get("result", {})
trades = res.get("list", [])
for t in trades:
if t.get("side") == "Buy":
ev = float(t.get("execValue") or 0)
if not ev:
qty = float(t.get("execQty") or t.get("orderQty") or 0)
px = float(t.get("execPrice") or 0)
ev = qty * px
total += ev
cursor = res.get("nextPageCursor")
if not cursor or not trades:
break
return total
def round_to(value, step):
"""Floor a quantity to the nearest lot/price step."""
if not step or step <= 0:
return value
return math.floor(value / step) * step
def spot_price(symbol):
try:
r = bybit_get("/v5/market/tickers", {"category": "spot", "symbol": symbol})
for t in r.get("result", {}).get("list", []):
p = t.get("lastPrice")
if p:
return float(p)
except Exception:
pass
return 0.0
def linear_price(symbol):
try:
r = bybit_get("/v5/market/tickers", {"category": "linear", "symbol": symbol})
for t in r.get("result", {}).get("list", []):
p = t.get("lastPrice")
if p:
return float(p)
except Exception:
pass
return 0.0
def linear_tick(symbol):
try:
r = bybit_get("/v5/market/instruments-info", {"category": "linear", "symbol": symbol})
for inst in r.get("result", {}).get("list", []):
ts = (inst.get("priceFilter", {}) or {}).get("tickSize") or "0.01"
return float(ts)
except Exception:
pass
return 0.01
def spot_instrument(symbol):
defaults = {"basePrecision": 0.0001, "quotePrecision": 0.01,
"minOrderQty": 0.0, "minOrderAmt": 0.0, "tickSize": 0.01}
try:
r = bybit_get("/v5/market/instruments-info", {"category": "spot", "symbol": symbol})
for inst in r.get("result", {}).get("list", []):
if inst.get("symbol") == symbol:
lot = inst.get("lotSizeFilter", {})
pf = inst.get("priceFilter", {})
return {
"basePrecision": float(lot.get("basePrecision") or defaults["basePrecision"]),
"quotePrecision": float(lot.get("quotePrecision") or defaults["quotePrecision"]),
"minOrderQty": float(lot.get("minOrderQty") or 0),
"minOrderAmt": float(lot.get("minOrderAmt") or 0),
"tickSize": float(pf.get("tickSize") or defaults["tickSize"]),
}
except Exception:
pass
return defaults
def spot_fill(symbol, since_ms):
"""Compute the base-filled qty + avg price of BUY executions since `since_ms`."""
try:
r = bybit_get("/v5/execution/list", {"category": "spot", "symbol": symbol,
"startTime": str(since_ms), "limit": "50"})
except Exception:
return None
qty = 0.0
value = 0.0
for t in r.get("result", {}).get("list", []):
if t.get("side") == "Buy":
eq = float(t.get("execQty") or t.get("orderQty") or 0)
ev = float(t.get("execValue") or 0)
if not ev:
ev = eq * float(t.get("execPrice") or 0)
qty += eq
value += ev
if qty <= 0:
return None
return {"qty": qty, "avg_price": value / qty, "cost": value}
def bybit_balance():
"""Return balances across Bybit account types (dict of floats).
Grid bots draw from the Funding Account; spot/derivative funds may sit in
SPOT / CONTRACT / UNIFIED accounts. Report each so it's clear where funds
actually live (and why any one account may show 0).
"""
out = {
"fund_usdt": 0.0,
"unified_total": 0.0, "unified_usdt": 0.0,
"spot_total": 0.0, "spot_usdt": 0.0,
"contract_total": 0.0, "contract_usdt": 0.0,
"investment_total": 0.0, "investment_usdt": 0.0,
"fiat_available": 0.0, "fiat_total": 0.0,
}
try:
r = bybit_get("/v5/asset/transfer/query-account-coins-balance",
{"accountType": "FUND"})
for b in r.get("result", {}).get("balance", []):
if b.get("coin") == "USDT":
out["fund_usdt"] = float(b.get("walletBalance") or 0.0)
break
except Exception:
pass
# Trading Bot account (grid bots, DCA bots, combo bots) is reported as
# accountType "TradingBot" in the asset-overview endpoint.
try:
r = bybit_get("/v5/asset/asset-overview")
for a in r.get("result", {}).get("list", []) or []:
if a.get("accountType") == "TradingBot":
out["investment_total"] = float(a.get("totalEquity") or 0.0)
out["investment_usdt"] = out["investment_total"]
break
except Exception:
pass
out["total_equity_direct"] = 0.0
for acct, kt, ku in (("UNIFIED", "unified_total", "unified_usdt"),
("SPOT", "spot_total", "spot_usdt"),
("CONTRACT", "contract_total", "contract_usdt")):
try:
r = bybit_get("/v5/account/wallet-balance", {"accountType": acct})
for a in r.get("result", {}).get("list", []):
if acct == "UNIFIED" and a.get("totalEquity") not in (None, ""):
out["total_equity_direct"] = float(a.get("totalEquity") or 0.0)
out[kt] = float(a.get("totalWalletBalance") or 0.0)
for c in a.get("coin", []):
if c.get("coin") == "USDT":
out[ku] = float(c.get("walletBalance") or 0.0)
break
except Exception:
pass
# Fiat balance (separate from crypto; must be converted to USDT before trading)
try:
r = bybit_get("/v5/fiat/balance-query")
for item in r.get("result", []) or []:
out["fiat_available"] += float(item.get("balance") or 0.0)
out["fiat_total"] += float(item.get("totalBalance") or 0.0)
except Exception:
pass
return out
def open_position(symbol, notional=ORDER_NOTIONAL):
"""Spot market BUY (by value) with native TP/SL attached.
`takeProfit`/`stopLoss` are accepted on spot market orders (verified against
the live API), so we buy at market and attach the take-profit/stop-loss sell
triggers in the same request — they fire near-instantly on Bybit's side.
"""
if DRY_RUN:
return True, (f"DRY-RUN: would buy {symbol} ${notional:.2f} spot "
f"(native TP +{TAKE_PROFIT_PCT}%, SL -{STOP_LOSS_PCT}%)"), None
price = spot_price(symbol)
if price <= 0:
return False, f"no price for {symbol}", None
info = spot_instrument(symbol)
min_amt = info["minOrderAmt"] or (info["minOrderQty"] * price)
if notional < min_amt:
return False, (f"${notional:.2f} is below the minimum order (~${min_amt:.2f}) "
f"for {symbol} — increase the amount"), None
tp_price = round_to(price * (1 + TAKE_PROFIT_PCT / 100.0), info["tickSize"])
sl_price = round_to(price * (1 - STOP_LOSS_PCT / 100.0), info["tickSize"])
def fmt(x):
return format(x, ".10f").rstrip("0").rstrip(".")
opened_ms = int(time.time() * 1000) - 2000
r = bybit_post("/v5/order/create", {
"category": "spot", "symbol": symbol, "side": "Buy",
"orderType": "Market", "qty": fmt(round_to(notional, info["quotePrecision"])),
"marketUnit": "quoteCoin",
"takeProfit": fmt(tp_price), "stopLoss": fmt(sl_price),
"tpOrderType": "Market", "slOrderType": "Market",
})
if r.get("retCode") != 0:
return False, f"order failed: {r.get('retMsg')}", None
# Read back the actual fill for accurate position tracking.
time.sleep(1.0)
fill = spot_fill(symbol, opened_ms)
if fill is None:
fill = {"qty": notional / price, "avg_price": price, "cost": notional}
entry = {
"symbol": symbol,
"qty": round(float(fill["qty"]), 8),
"entry_price": float(fill["avg_price"]),
"cost": round(float(fill["cost"]), 4),
"opened_ms": int(time.time() * 1000),
}
return True, (f"🟢 OPENED {_sym_link(symbol)} ${entry['cost']:.2f} spot "
f"(TP {fmt(tp_price)} / SL {fmt(sl_price)})"), entry
def linear_instrument(symbol):
d = {"tickSize": 0.01, "qtyStep": 0.001, "minOrderQty": 0.0, "minNotionalValue": 0.0}
try:
r = bybit_get("/v5/market/instruments-info",
{"category": "linear", "symbol": symbol})
for inst in r.get("result", {}).get("list", []):
pf = inst.get("priceFilter", {}) or {}
lot = inst.get("lotSizeFilter", {}) or {}
d["tickSize"] = float((pf.get("tickSize") or "0.01"))
d["qtyStep"] = float((lot.get("qtyStep") or "0.001"))
d["minOrderQty"] = float((lot.get("minOrderQty") or "0"))
d["minNotionalValue"] = float((inst.get("minNotionalValue") or "0"))
except Exception:
pass
return d
def _unified_available_usdt():
"""Free USDT available for futures orders in the UNIFIED account."""
try:
r = bybit_get("/v5/account/wallet-balance", {"accountType": "UNIFIED"})
lst = (r.get("result", {}) or {}).get("list") or []
if lst:
av = float(lst[0].get("totalAvailableBalance") or 0)
if av > 0:
return av
for c in lst[0].get("coin", []) or []:
if c.get("coin") == "USDT":
return float(c.get("availableToWithdraw") or 0)
except Exception:
pass
return 0.0
def _fund_transferable_usdt():
"""USDT transferable out of the Funding account."""
try:
r = bybit_get("/v5/asset/transfer/inter-transfer/transferable-amount",
{"accountType": "FUND", "coin": "USDT"})
amt = float((r.get("result") or {}).get("transferableAmount") or 0)
if amt > 0:
return amt
except Exception:
pass
# Fallback: plain Funding wallet balance.
try:
r = bybit_get("/v5/asset/transfer/query-account-coins-balance",
{"accountType": "FUND"})
for b in (r.get("result", {}) or {}).get("balance", []) or []:
if b.get("coin") == "USDT":
return float(b.get("walletBalance") or 0)
except Exception:
pass
return 0.0
def _fund_to_unified(amount):
"""Inter-transfer USDT from the Funding account into UNIFIED."""
import uuid
try:
r = bybit_post("/v5/asset/transfer/inter-transfer", {
"transferId": str(uuid.uuid4()),
"coin": "USDT", "amount": f"{amount:.2f}",
"fromAccountType": "FUND", "toAccountType": "UNIFIED"})
return r.get("retCode") == 0, str(r.get("retMsg"))
except Exception as e:
return False, str(e)
def _unified_transferable_usdt():
"""Free USDT transferable out of the UNIFIED account."""
try:
r = bybit_get("/v5/asset/transfer/inter-transfer/transferable-amount",
{"accountType": "UNIFIED", "coin": "USDT"})
return float((r.get("result") or {}).get("transferableAmount") or 0)
except Exception:
return 0.0
def _unified_to_fund(amount):
"""Inter-transfer USDT from UNIFIED back to the Funding account."""
import uuid
try:
r = bybit_post("/v5/asset/transfer/inter-transfer", {
"transferId": str(uuid.uuid4()),
"coin": "USDT", "amount": f"{amount:.2f}",
"fromAccountType": "UNIFIED", "toAccountType": "FUND"})
return r.get("retCode") == 0, str(r.get("retMsg"))
except Exception as e:
return False, str(e)
def sweep_to_fund(amount):
"""Sweep up to `amount` of released margin (UNIFIED) back to Funding."""
if DRY_RUN:
return f"💸 DRY-RUN: would sweep ${amount:.2f} UNIFIED → Funding"
trans = _unified_transferable_usdt()
if trans < 1.0:
return "💸 no free USDT to sweep to Funding"
amt = min(float(amount), trans)
ok, msg = _unified_to_fund(amt)
return (f"💸 swept ${amt:.2f} back to the Funding account" if ok
else f"💸 sweep failed: {msg}")
def ensure_funds(need_usdt):
"""Make sure the UNIFIED (futures) wallet has `need_usdt` available.
Futures/grid orders draw from the UNIFIED account; free USDT often sits
in the Funding account, causing 'ab not enough for new order' rejections.
Auto-transfers the shortfall (FUND → UNIFIED) before orders are placed.
Returns (ok, message).
"""
try:
need = float(need_usdt)
except (TypeError, ValueError):
need = 0.0
if need <= 0:
return True, ""
# 10% buffer: Bybit's "available" can overestimate orderable margin
# (unrealized P&L, fee buffers) right up to order placement.
need = need * 1.10
avail = _unified_available_usdt()
if avail >= need:
return True, ""
shortfall = round(need - avail, 2)
fund = _fund_transferable_usdt()
if fund < 1.0:
return False, (f"insufficient funds — UNIFIED ${avail:.2f}, funding "
f"transferable ${fund:.2f}, need ${need:.2f}")
transfer = min(shortfall, fund)
ok, msg = _fund_to_unified(transfer)
if not ok:
return False, f"auto-transfer failed: {msg}"
app.logger.info("auto-transferred $%.2f USDT FUND→UNIFIED", transfer)
time.sleep(2.5) # let Bybit settle the transfer before placing orders
return True, f"(auto-transferred ${transfer:.2f} FUND→UNIFIED)"
STABLE_COINS = {
"USDCUSDT", "USDTUSDT", "DAIUSDT", "TUSDUSDT", "FDUSDUSDT",
"PYUSDUSDT", "USD1USDT", "USDEUSDT", "USDDUSDT", "FRAXUSDT",
"LUSDUSDT", "USDJUSDT", "GEMINIUSDT", "EURUSDT",
}
def open_future_position(symbol, notional=ORDER_NOTIONAL, leverage=3,
tp_pct=None, sl_pct=None, trail_pct=None):
"""Combo futures: market BUY a linear USDT perpetual at `leverage`x.
Margin = `notional` ($100 default), position value = margin x leverage.
Native price-based TP/SL triggers attached to the order — the defaults
(+3% / -5%) or the caller's tp_pct/sl_pct (e.g. the riser rules);
leverage amplifies the return on margin, not the trigger distances.
"""
if str(symbol).upper() in STABLE_COINS:
return False, f"skip {symbol} — stablecoins are excluded from futures", None
if not tp_pct or not sl_pct:
# No caller-provided rules — use the admin-configured settings
cfg = load_state()
tp_pct = tp_pct or cfg.get("fut_tp") or TAKE_PROFIT_PCT
sl_pct = sl_pct or cfg.get("fut_sl") or STOP_LOSS_PCT
tp_use = float(tp_pct)
sl_use = float(sl_pct)
if DRY_RUN:
return True, (f"DRY-RUN: would buy {symbol} ${notional:.2f} futures at "
f"{leverage}x (TP +{tp_use:g}%, SL -{sl_use:g}%)"), None
fok, fmsg = ensure_funds(notional)
if not fok:
return False, f"cannot open {symbol} — {fmsg}", None
price = linear_price(symbol)
if price <= 0:
return False, f"no price for {symbol}", None
inst = linear_instrument(symbol)
step = inst["qtyStep"] or 0.001
raw_qty = float(notional) * int(leverage) / price
qty = round_to(math.floor(raw_qty / step) * step, step)
if (qty <= 0 or qty < inst["minOrderQty"]
or qty * price < inst["minNotionalValue"]):
return False, (f"${notional:.2f} at {leverage}x is below the minimum "
f"order size for {symbol} — increase the amount"), None
# Margin-based TP/SL: the trigger fires when P/L on the invested
# margin reaches +/- tp_pct/sl_pct percent. Since leverage amplifies
# the return on margin, the equivalent PRICE move is
# tp_pct / leverage (e.g. 3% at 3x = 1% price move).
lev = max(1, int(leverage))
tp_price = round_to(price * (1 + tp_use / 100.0 / lev), inst["tickSize"])
sl_price = round_to(price * (1 - sl_use / 100.0 / lev), inst["tickSize"])
# Trailing TP (native Bybit): instead of a fixed takeProfit, the
# position arms a trailing stop AT the TP level (activePrice) and
# then follows the price up, closing when it retraces by
# fut_trail% (settings page, default 1%). If Bybit rejects the
# trailing params we fall back to the fixed TP.
if trail_pct is None:
try:
_st = load_state()
trail_pct = float(_st.get("fut_trail", 1.0) or 1.0)
except Exception:
trail_pct = 1.0
trail_pct = float(trail_pct)
def fmt(x):
return format(x, ".10f").rstrip("0").rstrip(".")
# Best-effort leverage set (idempotent).
try:
bybit_post("/v5/position/set-leverage", {
"category": "linear", "symbol": symbol,
"buyLeverage": str(int(leverage)),
"sellLeverage": str(int(leverage))})
except Exception:
pass
r = bybit_post("/v5/order/create", {
"category": "linear", "symbol": symbol, "side": "Buy",
"orderType": "Market", "qty": fmt(qty),
"stopLoss": fmt(sl_price),
"tpslMode": "Full", "slOrderType": "Market",
})
if r.get("retCode") != 0:
return False, f"order failed: {r.get('retMsg')}", None
# Arm the native trailing TP. Bybit's trailingStop parameter is an
# absolute PRICE DISTANCE (not a percent), so convert our margin-based
# setting: fut_trail % of margin at `lev`x = (trail_pct/100/lev) of
# price, in dollars. At 3x, 1% of margin = 0.333% of price = ~$0.0034
# on a $1 coin. activePrice = the TP level. On failure, fall back to
# a fixed TP so the position is never left without an upside exit.
trail_dist = round_to(price * trail_pct / 100.0 / lev, inst["tickSize"])
if trail_dist <= 0:
trail_dist = inst["tickSize"]
ts = bybit_post("/v5/position/trading-stop", {
"category": "linear", "symbol": symbol,
"stopLoss": fmt(sl_price),
"trailingStop": fmt(trail_dist),
"activePrice": fmt(tp_price),
"tpslMode": "Full", "slOrderType": "Market",
})
trailing_ok = ts.get("retCode") == 0
if not trailing_ok:
bybit_post("/v5/position/trading-stop", {
"category": "linear", "symbol": symbol,
"takeProfit": fmt(tp_price), "stopLoss": fmt(sl_price),
"tpslMode": "Full", "tpOrderType": "Market",
"slOrderType": "Market",
})
# Read back the actual fill for accurate position tracking.
time.sleep(1.0)
entry_price = price
try:
e = bybit_get("/v5/execution/list",
{"category": "linear", "symbol": symbol, "limit": "10"})
for x in (e.get("result", {}) or {}).get("list", []):
if x.get("side") == "Buy":
entry_price = float(x.get("execPrice") or price) or price
break
except Exception:
pass
entry = {
"symbol": symbol,
"qty": round(float(qty), 8),
"entry_price": float(entry_price),
"cost": round(float(notional), 4),
"opened_ms": int(time.time() * 1000),
"category": "linear",
"leverage": int(leverage),
# Native trailing TP is already margin-consistent — don't let
# _retune_margin_tpsl overwrite it with a fixed TP on manage runs.
"tpsl_margin": True,
}
return True, (f"🟢 OPENED {_sym_link(symbol)} ${notional:.2f} futures {leverage}x "
+ (f"(trailing TP arms at {fmt(tp_price)}, "
f"retrench {trail_pct:g}% / SL {fmt(sl_price)})"
if trailing_ok else
f"(TP {fmt(tp_price)} / SL {fmt(sl_price)})")), entry
def closed_by(symbol, since_ms, category="spot"):
"""Return (kind, exit_price) if a native TP/SL close triggered since
`since_ms`, else None. kind is 'TP' or 'SL'."""
try:
r = bybit_get("/v5/order/history",
{"category": category, "symbol": symbol, "limit": "50"})
except Exception:
return None
for o in r.get("result", {}).get("list", []):
if o.get("orderStatus") != "Filled":
continue
if o.get("side") != "Sell":
continue
if int(o.get("updatedTime", 0) or 0) < since_ms:
continue
st = o.get("stopOrderType") or ""
# TrailingStop exits are the trailing-TP path (profit exits by
# design) — count them as TP so the close is detected, logged,
# compounded and reported to Telegram like any other TP.
if st in ("TakeProfit", "PartialTakeProfit", "TrailingStop"):
return "TP", float(o.get("avgPrice") or 0)
if st in ("StopLoss", "PartialStopLoss"):
return "SL", float(o.get("avgPrice") or 0)
return None
def _nan(v):
try:
f = float(v)
return f != f
except (TypeError, ValueError):
return False
# Separate Telegram channels for distinct notification sounds
TG_GRID_NEW = os.environ.get("TG_GRID_NEW", "-1004342501634")
TG_GRID_PROFIT = os.environ.get("TG_GRID_PROFIT", "-1003973879977")
TG_GRID_CLOSURE = os.environ.get("TG_GRID_CLOSURE", "-1003752631709")
TG_FUT_NEW = os.environ.get("TG_FUT_NEW", "-1004346678181")
TG_FUT_FUNDING = os.environ.get("TG_FUT_FUNDING", "-1003922967119")
TG_FUT_CLOSE = os.environ.get("TG_FUT_CLOSE", "-1004456360582")
TG_PROFIT = os.environ.get("TG_PROFIT", "-1004180764296") # "Ka-ching" (profit-only events)
TG_BOOHOO = os.environ.get("TG_BOOHOO", "") # "Boohoo" (loss-only events; empty = not set yet)
TG_BLIND_MONKEYS = os.environ.get("TG_BLIND_MONKEYS", "-1003957472064")
def _tg_green_open(text):
"""Highlight the words 'open' / 'opened' in scan-channel messages.
NOTE: Telegram's Bot API does not support colored text (<font> tags
make the whole message fail with HTTP 400), so emphasis is bold +
the 🟢 marker instead of a font color.
"""
import re as _re
return _re.sub(r"\b(open(?:ed)?)\b",
r'🟢 <b>\1</b>',
text, flags=_re.IGNORECASE)
def _sym_link(sym):
"""Symbol as a clickable link to its 24h thumbnail chart (Telegram-safe)."""
import urllib.parse as _up
s = str(sym)
return ('<a href="https://charts.blindmonkeys.org/grid/symbol-chart?symbol='
+ _up.quote(s) + '">' + s + '</a>')
def _tg_stamp(text):
"""Render every outbound Telegram message at ~1.5× normal text size
(Dean 2026-11-05): each line — including the green 🟢 timestamp heading
— becomes an H2 markdown heading in a Rich Message. Classic messages
have no font-size markup, so H2 headings are the only way to enlarge
text; inline HTML (<b>, <a>) still parses inside headings. Timestamp in
Yerevan time (UTC+4)."""
stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S")
lines = ["## 🟢 " + stamp]
for ln in text.split("\n"):
lines.append("## " + ln if ln.strip() else "")
out = "\n".join(lines)
# Rich messages allow 32768 chars; keep a safety margin
if len(out) > 32000:
out = out[:32000] + "…"
return out
def send_telegram(text, chat_id=None):
"""Send a Telegram message. Primary path: Rich Message with the H2
timestamp heading (~1.5× size); falls back to the classic bold-stamp
sendMessage if the Rich Message API rejects the message."""
cid = chat_id if chat_id else TELEGRAM_CHAT_ID
api = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}"
payload = json.dumps({"chat_id": cid,
"rich_message": {"markdown": _tg_stamp(text)}}).encode()
req = urllib.request.Request(api + "/sendRichMessage", data=payload,
headers={"Content-Type": "application/json"})
try:
urllib.request.urlopen(req, timeout=15)
return
except Exception:
pass # fall back to the classic format below
stamp = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d %H:%M:%S")
classic = f"🟢 <b>{stamp}</b>\n{text}"
if len(classic) > 4090:
classic = classic[:4090] + "…"
data = urllib.parse.urlencode({"chat_id": cid, "text": classic,
"parse_mode": "HTML"}).encode()
urllib.request.urlopen(urllib.request.Request(api + "/sendMessage", data=data), timeout=15)
# ---------------------------------------------------------------------------
# Server-side config/state (persisted in GCS so the hourly scheduler sees it)
# ---------------------------------------------------------------------------
def _default_state():
return {
"base_amount": ORDER_NOTIONAL,
"current_amount": ORDER_NOTIONAL,
"increase_pct": INCREASE_PCT,
"decrease_pct": DECREASE_PCT,
"daily_cap": MAX_DAILY_BUY,
"override_amount": None,
"positions": [],
"grid": {
"leverage": 1,
"range_percent": 3.0,
"amount": 500.0,
"grid_lines": 10,
"daily_cap": 500.0,
"tp_percent": 3.0,
"stop_loss_percent": 3.0,
"trailing_up_percent": 20.0,
"trailing_down_percent": 5.0,
"auto_min_score": 20.0,
"trailing_retrench": 1.0, # trailing-TP retrenchment %
# (app-side, 0.05–2.2)
"regime_pause_drift": -5.0, # pause new grids when BTC 7d
# drift <= this % (set -100 to off)
},
"combo_leverage": 3,
"fut_tp": 3.0, # futures take-profit % (settings page)
"fut_sl": 3.0, # futures stop-loss % (settings page)
"fut_auto_open": 1, # min score for futures auto-open (settings page)
"fut_trail": 1.0, # trailing-TP retrenchment % (0.1–10, settings page)
"upward_weights": {"rsi": 0.25, "momentum": 0.25, "zscore": 0.25, "volatility": 0.25},
"upward_outcomes": [],
"score_weights": {"osc": 0.25, "adx": 0.25, "drift": 0.25, "w24": 0.25},
"outcomes": [],
"grid_bots": [],
"grid_archive": [],
# Trading rules for coins flagged by the rising-coins scanner
"riser": {
"amount": 100.0, # $ per position
"leverage": 3.0, # x
"tp_percent": 3.0, # take-profit %
"stop_loss_percent": 3.0, # stop-loss %
"daily_cap": 1000.0, # max total invested per day
"min_funding": 0.0, # auto-open only when the coin's funding
# rate (%) is at/below this (0 = longs
# are paid; 99 = gate off)
},
}
def load_state():
s = _default_state()
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(STATE_OBJECT)
data = json.loads(blob.download_as_text())
except Exception:
return s
for k, v in s.items():
data.setdefault(k, v)
for k, v in s["grid"].items():
data.setdefault("grid", {}).setdefault(k, v)
return data
def save_state(s):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(STATE_OBJECT)
blob.upload_from_string(json.dumps(s), content_type="application/json")
except Exception as e:
app.logger.error(f"save_state failed: {e}")
def load_balance_history():
"""Daily balance snapshots ({"YYYY-MM-DD": {raw fields}}), or {} if none."""
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(BALANCE_HISTORY_OBJECT)
return json.loads(blob.download_as_text())
except Exception:
return {}
def save_balance_history(hist):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(BALANCE_HISTORY_OBJECT)
blob.upload_from_string(json.dumps(hist), content_type="application/json")
except Exception as e:
app.logger.error(f"save_balance_history failed: {e}")
def load_score_weights_history():
"""Daily score-weight snapshots ({"YYYY-MM-DD": {osc,adx,drift,w24}}), or {} if none."""
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(SCORE_WEIGHTS_HISTORY_OBJECT)
return json.loads(blob.download_as_text())
except Exception:
return {}
def save_score_weights_history(hist):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(SCORE_WEIGHTS_HISTORY_OBJECT)
blob.upload_from_string(json.dumps(hist), content_type="application/json")
except Exception as e:
app.logger.error(f"save_score_weights_history failed: {e}")
def load_upward_weights_history():
"""Daily upward(futures)-weight snapshots ({"YYYY-MM-DD": {rsi,momentum,zscore,volatility}})."""
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(UPWARD_WEIGHTS_HISTORY_OBJECT)
return json.loads(blob.download_as_text())
except Exception:
return {}
def save_upward_weights_history(hist):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob(UPWARD_WEIGHTS_HISTORY_OBJECT)
blob.upload_from_string(json.dumps(hist), content_type="application/json")
except Exception as e:
app.logger.error(f"save_upward_weights_history failed: {e}")
def clamp_amount(a, daily_cap):
return max(AMOUNT_FLOOR, min(float(a), float(daily_cap)))
def open_symbols(state):
return {p["symbol"] for p in state.get("positions", []) if p.get("symbol")}
def _retune_margin_tpsl(state, p):
"""Ensure an open LINEAR position's Bybit TP/SL triggers are
margin-based (P/L on invested margin), i.e. price distance =
pct / leverage. Positions opened before this rule had price-based
triggers; this converges them on the next manage run. One-shot:
marks the entry so it isn't retuned again."""
# entries opened by older code may lack "category" — riser/upward
# futures entries are always linear, so treat None as linear here
if p.get("category") not in (None, "linear") or p.get("tpsl_margin"):
return
sym = p.get("symbol")
try:
tp_pct = float(p.get("tp_pct") or state.get("fut_tp") or 3.0)
sl_pct = float(p.get("sl_pct") or state.get("fut_sl") or 3.0)
lev = max(1, int(p.get("leverage") or 3))
r = bybit_get("/v5/position/list", {"category": "linear",
"symbol": sym})
pos = (r.get("result", {}) or {}).get("list", [{}])[0]
entry = float(pos.get("avgPrice") or 0)
if entry <= 0:
return
inst = linear_instrument(sym)
tp_price = round_to(entry * (1 + tp_pct / 100.0 / lev),
inst["tickSize"])
sl_price = round_to(entry * (1 - sl_pct / 100.0 / lev),
inst["tickSize"])
d = bybit_post("/v5/position/trading-stop", {
"category": "linear", "symbol": sym,
"takeProfit": format(tp_price, ".10f").rstrip("0").rstrip("."),
"stopLoss": format(sl_price, ".10f").rstrip("0").rstrip("."),
"tpslMode": "Full", "tpOrderType": "Market",
"slOrderType": "Market",
})
print(f"retune {sym}: TP {tp_price} SL {sl_price} ret={d.get('retCode')} {d.get('retMsg')}")
if d.get("retCode") == 0:
p["tpsl_margin"] = True
except Exception as _e:
print(f"retune {sym} failed: {_e}")
def manage_positions(state):
"""Detect native TP/SL closes (Bybit triggers) and apply ± compounding.
TP hit -> current_amount *= (1 + increase_pct/100)
SL hit -> current_amount *= (1 - decrease_pct/100)
(floor $10, cap = daily_cap). No manual selling — Bybit's trigger already sold.
"""
positions = state.get("positions", [])
if not positions:
return state, []
# First, converge open linear positions to margin-based TP/SL.
for p in positions:
try:
_retune_margin_tpsl(state, p)
except Exception:
pass
remaining = []
events = []
for p in positions:
sym = p["symbol"]
since = int(p.get("opened_ms", 0) or 0)
cat = p.get("category") or "spot"
hit = closed_by(sym, since, cat)
if hit is None:
remaining.append(p) # still open (or undetectable) -> keep
continue
kind, exit_price = hit
qty = float(p.get("qty", 0) or 0)
cost = float(p.get("cost", 0) or 0)
entry = float(p.get("entry_price", 0) or 0)
if cat == "linear":
px = exit_price or linear_price(sym) or entry
pnl = qty * (px - entry)
else:
price = exit_price or spot_price(sym) or entry
pnl = qty * price - cost
if kind == "TP":
state["current_amount"] = clamp_amount(
round(state["current_amount"] * (1 + float(state["increase_pct"]) / 100.0), 2),
state["daily_cap"])
else:
state["current_amount"] = clamp_amount(
round(state["current_amount"] * (1 - float(state["decrease_pct"]) / 100.0), 2),
state["daily_cap"])
try:
_log_fut_close(state, sym, p.get("source") or "upward",
"upward", pnl, cost,
p.get("leverage") or 3,
p.get("tp_pct"), p.get("sl_pct"),
opened_ms=p.get("opened_ms"))
except Exception:
pass
events.append((sym, hit, pnl, state["current_amount"], True))
if cat == "linear" and not DRY_RUN:
mpct = (pnl / cost * 100.0) if cost else 0.0
wline = ""
if p.get("up_entry"):
try:
nw = _update_upward_weights(state, p["up_entry"], mpct)
wline = ("\n\u2696\ufe0f Upward weights: RSI "
+ f"{nw.get('rsi', 0.25):.2f}"
+ " \u00b7 Mom " + f"{nw.get('momentum', 0.25):.2f}"
+ " \u00b7 Z " + f"{nw.get('zscore', 0.25):.2f}"
+ " \u00b7 Vol " + f"{nw.get('volatility', 0.25):.2f}")
except Exception:
pass
try:
pnl_emoji = "🟢" if pnl > 0 else "🔴"
send_telegram(
f"🏁 <b>{_sym_link(sym)} futures closed</b> ({kind})\n"
f"P&L: {pnl_emoji} <b>${pnl:+.2f} "
f"({mpct:+.1f}% on margin)</b>\n"
f"Next order size: ${state['current_amount']:.2f}"
+ wline,
chat_id=TG_FUT_CLOSE)
except Exception:
pass
if pnl > 0 and not DRY_RUN:
try:
send_telegram(
f'💰 🟢 <b>{_sym_link(sym)} futures closed '
f'+${pnl:.2f}</b>',
chat_id=TG_PROFIT)
except Exception:
pass
elif pnl < 0 and TG_BOOHOO and not DRY_RUN:
try:
send_telegram(
f'😢 <b>{_sym_link(sym)} futures closed '
f'−${abs(pnl):.2f}</b>\n'
f'🔴 <a href="https://blindmonkeys.org/performance">'
f'blindmonkeys.org/performance</a>',
chat_id=TG_BOOHOO)
except Exception:
pass
state["positions"] = remaining
return state, events
def open_grid_bot(symbol, state, entry=None):
"""Open a Bybit Futures Grid Bot (neutral, arithmetic) on `symbol`.
Reads grid params from state["grid"]. Returns (ok, message, bot_record_or_None).
"""
g = state.get("grid", {})
rng = float(g.get("range_percent", 3.0))
lines = int(g.get("grid_lines", 10))
lev = int(g.get("leverage", 1))
# Order compounding: use the compounded chain amount (reset only when
# the Amount setting itself changes); fall back to the base amount.
amt = float(g.get("current_amount") or g.get("amount", 100.0))
amt = min(float(g.get("daily_cap", 5000.0) or 5000.0), max(10.0, amt))
# Fixed total-P&L take profit ("3" = close the bot at +3% P&L).
tp = float(g.get("tp_percent", 3.0))
# Fixed total-P&L stop loss ("3" = close the bot at -3% P&L).
sl = float(g.get("stop_loss_percent", 3.0))
up_pct = float(g.get("trailing_up_percent", 20.0))
down_pct = float(g.get("trailing_down_percent", 5.0))
if DRY_RUN:
return True, (f"DRY-RUN: would open {symbol} grid bot (±{rng}% range, "
f"{lines} lines, ${amt:.0f}, {lev}x)"), None
fok, fmsg = ensure_funds(amt)
if not fok:
return False, f"cannot open {symbol} grid — {fmsg}", None
price = linear_price(symbol)
if price <= 0:
return False, f"no price for {symbol}", None
tick = linear_tick(symbol)
min_price = round_to(price * (1 - rng / 100.0), tick)
max_price = round_to(price * (1 + rng / 100.0), tick)
def fmt(x):
return format(x, ".10f").rstrip("0").rstrip(".")
body = {
"symbol": symbol,
"grid_mode": 1, # neutral
"min_price": fmt(min_price),
"max_price": fmt(max_price),
"cell_number": lines,
"leverage": str(lev),
"grid_type": 1, # arithmetic
"total_investment": fmt(amt),
}
if tp or sl:
body["tp_sl_type"] = 1 # percentage-based TP/SL
# Bybit's *_per fields are percentages directly ("3" = 3%):
# they lock in a fixed total-P&L take profit / stop loss.
if tp:
body["take_profit_per"] = fmt(float(tp))
if sl:
body["stop_loss_per"] = fmt(float(sl))
# Grid range-following (Trailing Up/Down): stop prices where the grid stops
# shifting. Up is generous (ride breakouts); down is tight (let trailing stop exit).
body["move_up_price"] = fmt(round_to(price * (1 + up_pct / 100.0), tick))
body["move_down_price"] = fmt(round_to(price * (1 - down_pct / 100.0), tick))
r = bybit_post("/v5/fgridbot/create", body)
if r.get("retCode") != 0:
return False, f"grid bot failed: {r.get('retMsg')}", None
result = r.get("result", {})
bot_id = result.get("bot_id")
if not bot_id:
return False, f"grid bot failed: no bot_id ({result})", None
bot = {
"symbol": symbol,
"bot_id": str(bot_id),
"invested": amt,
"opened_ms": int(time.time() * 1000),
"entry": entry or {},
}
return True, f"🟢 OPENED grid bot {_sym_link(symbol)} (id {bot_id}, ${amt:.0f})", bot
def _scanner_candidates():
"""Fetch ranked grid candidates from the scanner (coins with a currently
running bot are excluded there). The scan takes ~30s, so use a generous
timeout."""
url = SCANNER_URL.rstrip("/") + "/grid/candidates.json"
with urllib.request.urlopen(url, timeout=120) as r:
return json.loads(r.read().decode())
def run_grid():
"""Auto-open grid bots for high-scoring range-bound candidates.
A bot is opened for any candidate whose composite score is >= the saved
auto_min_score setting (grid settings), using the saved grid settings and
respecting the daily cap. Currently running coins are excluded upstream
by the scanner's candidate list.
"""
lines_out = []
mode = "DRY-RUN (no real orders)" if DRY_RUN else "LIVE"
state = load_state()
g = state.get("grid", {})
daily_cap = float(g.get("daily_cap", 500.0))
# Keep the cap-check amount in sync with open_grid_bot's compounded chain.
amt = min(daily_cap, max(10.0, float(g.get("current_amount") or g.get("amount", 100.0))))
min_score = float(g.get("auto_min_score", 20.0))
today = day_start_ms()
invested_today = sum(
float(b.get("invested", 0) or 0)
for b in state.get("grid_bots", [])
if int(b.get("opened_ms", 0) or 0) >= today)
remaining = daily_cap - invested_today
# Regime gate: no new grids while BTC is clearly trending down over 7
# days — sideways tools don't work in a falling regime (backtested).
# regime_pause_drift = -100 disables the gate. Manual opens stay free.
pause_drift = float(g.get("regime_pause_drift", -5.0))
btc_drift = _btc_7d_drift()
if btc_drift is not None and btc_drift <= pause_drift:
lines_out.append(
f"Grid [{mode}] — PAUSED (downtrend regime): BTC 7d drift "
f"{btc_drift:+.2f}% <= {pause_drift:g}% threshold. No new grids.")
return "<br>".join(lines_out)
try:
cands = _scanner_candidates()
except Exception as e:
cands = []
lines_out.append(f"Grid [{mode}] — could not fetch candidates: {e}")
qual = [c for c in cands if float(c.get("score") or 0) >= min_score]
lines_out.append(f"Grid [{mode}] — {len(qual)}/{len(cands)} candidate(s) with score >= {min_score:g}; "
f"invested ${invested_today:.0f}/${daily_cap:.0f} today")
if not qual and cands is not None and not DRY_RUN:
try:
send_telegram(
"✅ <b>Grid Scan Complete</b> — No Grid Opportunities "
"Met the minimum score threshold",
chat_id=TG_BLIND_MONKEYS)
except Exception:
pass
opened = 0
opened_bots = []
for c in qual:
symbol = str(c.get("symbol") or "").upper()
if not (symbol.endswith("USDT") and len(symbol) > 4):
continue
if remaining < amt:
lines_out.append(f" skip {symbol} — daily cap reached")
continue
entry = {k: c.get(k) for k in
("width", "touches", "drift", "w24", "adx", "atr", "score",
"replay_total", "replay_gp", "replay_fills", "replay_worst",
"replay_max_dd", "replay_stopped")}
ok, msg, bot = open_grid_bot(symbol, state, entry=entry)
lines_out.append(f" {msg}")
if ok and bot is not None:
state.setdefault("grid_bots", []).append(bot)
opened_bots.append(bot)
opened += 1
remaining -= bot["invested"]
save_state(state)
result = "\n".join(lines_out) + "\n"
if opened_bots and not DRY_RUN:
tg = "\n".join(
f"🆕 <b>New grid</b>: {_sym_link(b.get('symbol'))} — funding "
f"${float(b.get('invested') or 0):.2f}"
for b in opened_bots)
send_telegram(f"🤖 <b>Grid bots</b>\n{tg}", chat_id=TG_GRID_NEW)
return result
# ---------------------------------------------------------------------------
# Main trading routine
# ---------------------------------------------------------------------------
def run_trader():
lines = []
mode = "DRY-RUN (no real orders)" if DRY_RUN else "LIVE"
state = load_state()
# 1. Manage existing positions: close on TP/SL and apply compounding.
state, events = manage_positions(state)
if events:
lines.append(f" closed {len(events)} position(s):")
for sym, kind, pnl, new_amt, ok in events:
tag = "close failed" if (not ok and not DRY_RUN) else ("DRY-RUN" if DRY_RUN else "closed")
lines.append(f" {sym} {kind} PnL {pnl:+.2f} → next order ${new_amt:.2f} [{tag}]")
daily_cap = float(state["daily_cap"])
algo_amount = clamp_amount(float(state["current_amount"]), daily_cap)
# One-time override for the next order (cleared once a trade fills).
override = state.get("override_amount")
if override is not None:
override = float(override)
lines.append(f" one-time override: next order ${override:.2f}")
strong = scan_strong()
lines.append(f"Trader [{mode}] — {len(strong)} strong coin(s), algo amount ${algo_amount:.2f}")
if not strong:
save_state(state)
return "\n".join(lines) + "\n"
today_bought = today_buy_notional()
remaining = daily_cap - today_bought
lines.append(f" daily bought ${today_bought:.2f} / ${daily_cap:.0f} cap → ${remaining:.2f} remaining")
open_syms = open_symbols(state)
available = MAX_POSITIONS - len(open_syms)
# Per-run cap (fixed at 1); fut_auto_open is now the score threshold,
# not a per-run cap.
per_run = 1
available = min(available, per_run)
opened = 0
for rank, sym, pct, vol, ratio, f, oi in strong:
symbol = sym + "USDT"
if symbol in open_syms:
continue
if available <= 0:
lines.append(f" skip {symbol} — max positions ({MAX_POSITIONS}) reached")
continue
amount = override if override is not None else algo_amount
if remaining < amount:
lines.append(f" skip {symbol} — daily buy cap reached")
continue
ok, msg, entry = open_future_position(
symbol, notional=amount,
leverage=int(state.get("combo_leverage", 3) or 3))
lines.append(f" {msg}")
if ok:
opened += 1
available -= 1
remaining -= amount
if entry is not None:
state.setdefault("positions", []).append(entry)
if not DRY_RUN:
try:
send_telegram(
f"🆕 <b>New futures</b>: {symbol} — "
f"${amount:.2f} margin at "
f"{int(state.get('combo_leverage', 3) or 3)}x",
chat_id=TG_FUT_NEW)
except Exception:
pass
if override is not None:
state["override_amount"] = None
override = None
if available <= 0 or remaining < amount:
break
save_state(state)
result = "\n".join(lines) + "\n"
if opened > 0 or events:
send_telegram(f"📈 <b>Trader {mode}</b>\n{result}")
return result
@app.get("/")
def index():
return run_trader().replace("\n", "<br>")
@app.get("/run")
def run():
return run_trader().replace("\n", "<br>")
@app.route("/buy", methods=["GET", "POST"])
def buy():
symbol = (request.args.get("symbol") or "").upper().strip()
if not (symbol.endswith("USDT") and len(symbol) > 4):
return "invalid symbol (expected e.g. BTCUSDT)", 400
try:
amount = float(request.args.get("amount", ORDER_NOTIONAL))
except (TypeError, ValueError):
amount = ORDER_NOTIONAL
if amount < 10 or amount > 500:
return "amount must be between $10 and $500", 400
category = (request.args.get("category") or "linear").strip().lower()
if category == "spot":
ok, msg, entry = open_position(symbol, notional=amount)
else:
s = load_state()
ok, msg, entry = open_future_position(
symbol, notional=amount,
leverage=int(s.get("combo_leverage", 3) or 3))
if ok and entry is not None:
s = load_state()
s.setdefault("positions", []).append(entry)
save_state(s)
if ok and not DRY_RUN:
send_telegram(f"🛒 <b>Manual buy</b>: {msg}",
chat_id=TG_FUT_NEW if category != "spot" else None)
return msg
@app.get("/positions")
def positions():
try:
s = load_state()
ps = s.get("positions", [])
if not ps:
return "Open positions: (none)"
out = []
for p in ps:
out.append(f"{p['symbol']} qty={p.get('qty')} entry={p.get('entry_price')}")
return "Open positions: " + " | ".join(out)
except Exception as e:
return f"error: {e}"
@app.get("/verify")
def verify():
"""Read-only auth check against Bybit."""
tag = "DRY-RUN (no orders will be placed)" if DRY_RUN else "LIVE"
out = [f"Mode: {tag}", f"Host: {BYBIT_HOST}", f"Category: {CATEGORY}", ""]
try:
r = bybit_get("/v5/account/wallet-balance", {"accountType": "UNIFIED"})
ret = r.get("retCode")
out.append(f"wallet-balance retCode: {ret} ({r.get('retMsg')})")
if ret == 0:
accounts = r.get("result", {}).get("list", [])
for a in accounts:
out.append(f" account: {a.get('accountType')} equity=${a.get('totalEquity', '?')}")
out.append("AUTHENTICATION: OK ✅")
else:
out.append("AUTHENTICATION: FAILED ❌ — check API key/secret and that IP is allowlisted")
except Exception as e:
out.append(f"error: {e}")
out.append("AUTHENTICATION: ERROR ❌")
# Account identity (UID) + key permissions to diagnose balance visibility
try:
q = bybit_get("/v5/user/query-api")
res = q.get("result", {}) or {}
perms = res.get("permissions", {}) or {}
out.append("")
out.append(f"Account UID: {res.get('userID')} (isMaster={res.get('isMaster')}, parentUid={res.get('parentUid')})")
out.append(f"Wallet perms: {', '.join(perms.get('Wallet') or []) or '(none)'}")
out.append(f"Fiat perms: {', '.join((perms.get('FiatP2P') or []) + (perms.get('FiatConvertBroker') or []) + (perms.get('FiatBitPay') or [])) or '(none)'}")
except Exception as e:
out.append(f"query-api error: {e}")
# Funding Account balance (raw) to see why fund_usdt shows 0
try:
f = bybit_get("/v5/asset/transfer/query-account-coins-balance", {"accountType": "FUND"})
out.append("")
out.append(f"FUND balance retCode: {f.get('retCode')} ({f.get('retMsg')})")
out.append(f"FUND balance result: {json.dumps(f.get('result'))}")
except Exception as e:
out.append(f"FUND balance error: {e}")
return "<br>".join(out)
def _futures_combo():
"""Total value of open linear (USDT) positions (Futures Combo Investment)."""
try:
r = bybit_get("/v5/position/list",
{"category": "linear", "settleCoin": "USDT", "limit": "200"})
pv = 0.0
for pos in (r.get("result", {}) or {}).get("list", []) or []:
pv += float(pos.get("positionValue") or 0.0)
return pv
except Exception:
return 0.0
@app.get("/balance")
def balance():
b = bybit_balance()
b["mode"] = "DRY-RUN" if DRY_RUN else "LIVE"
b["futures_combo"] = _futures_combo()
# Total Equity comes directly from Bybit (UNIFIED totalEquity field).
# Fall back to the account sum only if Bybit does not report one.
direct = b.get("total_equity_direct") or 0.0
if direct > 0:
b["total_equity"] = direct
else:
b["total_equity"] = (b.get("unified_total", 0.0)
+ b.get("fund_usdt", 0.0)
+ b.get("spot_total", 0.0)
+ b.get("contract_total", 0.0)
+ b.get("fiat_total", 0.0))
return json.dumps(b)
@app.get("/balance/history")
def balance_history():
"""Recorded daily balance snapshots ({"YYYY-MM-DD": {raw fields}})."""
return json.dumps(load_balance_history())
@app.get("/balance/snapshot")
def balance_snapshot():
"""Record today's balance snapshot (triggered daily by Cloud Scheduler).
Keyed by the Asia/Yerevan date: the cron fires at 00:05 Yerevan
(= 20:05 UTC of the previous day), so using the UTC date would
file every snapshot under the wrong day.
"""
from datetime import datetime, timezone, timedelta
b = bybit_balance()
today = datetime.now(timezone(timedelta(hours=4))).strftime("%Y-%m-%d")
hist = load_balance_history()
snap = {
"fund_usdt": b.get("fund_usdt", 0.0),
"unified_total": b.get("unified_total", 0.0),
"investment_total": b.get("investment_total", 0.0),
"spot_total": b.get("spot_total", 0.0),
"futures_combo": _futures_combo(),
}
hist = load_balance_history()
hist[today] = snap
save_balance_history(hist)
return json.dumps({"ok": True, "date": today, "snapshot": snap})
# ---------------------------------------------------------------------------
# Futures Combo bot P&L snapshot (ported from bybit_pnl_snapshot.py so it can
# run in the cloud with the Bybit credentials this service already holds).
# Triggered every 15 min by Cloud Scheduler; writes the bybit_pnl*.json files
# to the MAIN app's data bucket for /api/bot-pnl and /api/win-rate.
# ---------------------------------------------------------------------------
PNL_DATA_BUCKET = "portfolio-agent-data-388170800364"
PNL_RETENTION_DAYS = 35
PNL_THIN_SECONDS = 1800 # keep at most one history snapshot per bot per 30 min
def _is_closed_status(bybit_status):
s = str(bybit_status or "").upper()
return "COMPLETED" in s or "STOPPED" in s or "CLOSED" in s or "CANCEL" in s or "ENDED" in s
def _pnl_load(name, default):
try:
blob = storage.Client().bucket(PNL_DATA_BUCKET).blob(name)
return json.loads(blob.download_as_text())
except Exception:
return default
def _pnl_save(name, data):
blob = storage.Client().bucket(PNL_DATA_BUCKET).blob(name)
blob.upload_from_string(json.dumps(data), content_type="application/json")
def _prev_snap_load(bot_id):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob("bybit_pnl_prev/%s.json" % bot_id)
return json.loads(blob.download_as_text())
except Exception:
return None
def _prev_snap_save(bot_id, snap):
try:
blob = storage.Client().bucket(STATE_BUCKET).blob("bybit_pnl_prev/%s.json" % bot_id)
blob.upload_from_string(json.dumps(snap), content_type="application/json")
except Exception as e:
app.logger.warning("prev snap save failed for %s: %s", bot_id, e)
@app.get("/pnl/snapshot")
def pnl_snapshot():
"""Poll Futures Combo bots from Bybit and refresh the bybit_pnl files."""
now_ts = int(time.time())
# Bot IDs: every bot ever seen in history + manual additions
bots_history = _pnl_load("bybit_bots_history.json", {"bots": []})
bot_ids = []
for b in bots_history.get("bots", []):
mid = str(b.get("bot_id", "")).strip()
if mid and mid not in bot_ids:
bot_ids.append(mid)
for m in _pnl_load("manual_running_bots.json", {"bots": []}).get("bots", []):
mid = str(m.get("bot_id", "")).strip()
if mid and mid not in bot_ids:
bot_ids.append(mid)
if not bot_ids:
return json.dumps({"ok": False, "error": "no bot ids found"})
snapshots = []
for bot_id in bot_ids:
try:
d = bybit_post("/v5/fcombobot/detail", {"bot_id": bot_id})
except Exception as e:
app.logger.warning("pnl snapshot: fetch failed for %s: %s", bot_id, e)
continue
if d.get("retCode") != 0:
# Bot no longer on Bybit — mark it closed in history
for b in bots_history.get("bots", []):
if str(b.get("bot_id", "")) == bot_id and b.get("status") == "running":
b["status"] = "closed"
if not b.get("end_time"):
b["end_time"] = b.get("last_seen", now_ts)
continue
detail = d.get("result", {}).get("detail", {})
snap = {
"bot_id": bot_id,
"bot_name": detail.get("bot_name", ""),
"bot_status": detail.get("bot_display_status", ""),
"leverage": detail.get("leverage", ""),
"total_margin": detail.get("total_margin", ""),
"equity": detail.get("equity", ""),
"total_pnl": detail.get("total_pnl", ""),
"total_pnl_per": detail.get("total_pnl_per", ""),
"realized_pnl": detail.get("realized_pnl", ""),
"unrealized_pnl": detail.get("unrealized_pnl", ""),
"funding_fee": detail.get("funding_fee", ""),
"total_position_value": detail.get("total_position_value", ""),
"run_time_duration": detail.get("run_time_duration", ""),
"updated_at": now_ts,
"coins": [],
}
# Per-coin breakdown (kept on the latest snapshot only; stripped from
# history so bybit_pnl_history.json stays small)
total_pos_value = float(detail.get("total_position_value", 0) or 0)
prev = _prev_snap_load(bot_id) or {}
prev_coins = {}
if str(prev.get("bot_id", "")) == bot_id:
for pc in prev.get("coins", []):
prev_coins[pc.get("coin", "")] = pc
for ss in detail.get("symbol_settings", []):
base = ss.get("base_token", "")
if not base:
continue
symbol = base + "USDT"
weight = float(ss.get("target_position_percent", 0) or 0)
mark = linear_price(symbol) or None
coin_value = total_pos_value * weight if total_pos_value else None
size = (coin_value / mark) if (coin_value and mark) else None
prev_entry = prev_coins[base].get("entry_price") if base in prev_coins else None
entry = prev_entry if prev_entry is not None else mark
pnl_per = pnl = None
if entry and mark and float(entry) > 0:
pnl_per = round(((mark - float(entry)) / float(entry)) * 100, 4)
if prev_entry is not None and size is not None:
pnl = round((mark - float(entry)) * size, 4)
snap["coins"].append({
"coin": base,
"symbol": symbol,
"market": "Future",
"weight": weight,
"mark_price": mark,
"value_usd": round(coin_value, 4) if coin_value else None,
"size": round(size, 8) if size else None,
"entry_price": entry,
"pnl": pnl,
"pnl_per": pnl_per,
})
_prev_snap_save(bot_id, snap)
snapshots.append(snap)
# Bots-history upkeep (same fields as the original snapshot script)
found = False
for b in bots_history.get("bots", []):
if str(b.get("bot_id", "")) == bot_id:
b["bot_name"] = snap.get("bot_name", b.get("bot_name", ""))
b["final_pnl"] = float(snap.get("total_pnl", 0) or 0)
b["final_pnl_per"] = float(snap.get("total_pnl_per", 0) or 0)
b["equity"] = float(snap.get("equity", 0) or 0)
b["investment"] = float(snap.get("total_margin", 0) or 0)
if _is_closed_status(snap.get("bot_status")):
b["status"] = "closed"
if not b.get("end_time"):
b["end_time"] = now_ts
else:
b["last_seen"] = now_ts
b["status"] = "running"
found = True
break
if not found:
bots_history.setdefault("bots", []).append({
"bot_id": bot_id,
"bot_name": snap.get("bot_name", ""),
"create_time": now_ts - int(float(snap.get("run_time_duration", 0) or 0)),
"final_pnl": float(snap.get("total_pnl", 0) or 0),
"final_pnl_per": float(snap.get("total_pnl_per", 0) or 0),
"equity": float(snap.get("equity", 0) or 0),
"investment": float(snap.get("total_margin", 0) or 0),
"first_seen": now_ts,
"last_seen": now_ts,
"status": "closed" if _is_closed_status(snap.get("bot_status")) else "running",
"end_time": now_ts if _is_closed_status(snap.get("bot_status")) else None,
})
# Bots that were running but weren't seen this poll -> closed after 20 min
seen = {s.get("bot_id") for s in snapshots}
for b in bots_history.get("bots", []):
if b.get("status") == "running" and str(b.get("bot_id", "")) not in seen:
if now_ts - b.get("last_seen", 0) > 1200:
b["status"] = "closed"
if not b.get("end_time"):
b["end_time"] = b.get("last_seen", now_ts)
for b in bots_history.get("bots", []):
start = b.get("create_time", b.get("first_seen", 0))
end = b.get("end_time", start) if b.get("status") == "closed" else now_ts
b["duration_seconds"] = max(0, end - start)
_pnl_save("bybit_bots_history.json", bots_history)
# P&L history: append slim snapshots, thin to one per bot per 30 min,
# trim to 35 days (keeps the file small so /api/bot-pnl stays fast)
history = _pnl_load("bybit_pnl_history.json", {"snapshots": []})
history.setdefault("snapshots", []).extend(
{k: v for k, v in s.items() if k != "coins"} for s in snapshots
)
cutoff = now_ts - PNL_RETENTION_DAYS * 86400
kept = {}
for s in history["snapshots"]:
ts = s.get("updated_at", 0)
if ts < cutoff:
continue
s.pop("coins", None)
key = (str(s.get("bot_id", "")), ts // PNL_THIN_SECONDS)
cur = kept.get(key)
if cur is None or ts > cur.get("updated_at", 0):
kept[key] = s
history["snapshots"] = sorted(kept.values(), key=lambda x: x.get("updated_at", 0))
_pnl_save("bybit_pnl_history.json", history)
# Latest running snapshot (with coins) for /api/bot/<id> detail pages
running = [s for s in snapshots if not _is_closed_status(s.get("bot_status"))]
if running:
_pnl_save("bybit_pnl.json", running[0])
return json.dumps({
"ok": True,
"bots_polled": len(bot_ids),
"running": len(running),
"history_snapshots": len(history["snapshots"]),
"bots_tracked": len(bots_history.get("bots", [])),
})
@app.get("/score-weights/history")
def score_weights_history():
"""Recorded daily score-weight snapshots ({"YYYY-MM-DD": {osc,adx,drift,w24}})."""
return json.dumps(load_score_weights_history())
@app.get("/score-weights/snapshot")
def score_weights_snapshot():
"""Record today's score weights (triggered daily by Cloud Scheduler)."""
from datetime import datetime, timezone
s = load_state()
w = dict(s.get("score_weights")
or {"osc": 0.25, "adx": 0.25, "drift": 0.25, "w24": 0.25})
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
snap = {k: float(w.get(k, 0.25)) for k in ("osc", "adx", "drift", "w24")}
hist = load_score_weights_history()
hist[today] = snap
save_score_weights_history(hist)
return json.dumps({"ok": True, "date": today, "snapshot": snap})
def _public_state(s):
return {
"base_amount": s["base_amount"],
"current_amount": s["current_amount"],
"increase_pct": s["increase_pct"],
"decrease_pct": s["decrease_pct"],
"daily_cap": s["daily_cap"],
"override_amount": s["override_amount"],
"leverage": s.get("combo_leverage", 3),
"fut_tp": s.get("fut_tp", 3.0),
"fut_sl": s.get("fut_sl", 3.0),
"fut_auto_open": s.get("fut_auto_open", 1),
"fut_trail": s.get("fut_trail", 1.0),
}
@app.get("/upward/weights")
def upward_weights():
"""Current feedback-learned futures (upward) score weights."""
s = load_state()
w = dict(s.get("upward_weights") or _UP_W_DEFAULT)
return json.dumps({
"weights": {k: float(w.get(k, 0.25)) for k in _UP_W_DEFAULT},
"outcomes": len(s.get("upward_outcomes") or []),
})
@app.get("/upward/weights/history")
def upward_weights_history():
"""Daily upward(futures)-weight snapshots."""
return json.dumps(load_upward_weights_history())
@app.get("/upward/weights/snapshot")
def upward_weights_snapshot():
"""Record today's upward(futures) weights (triggered daily by Cloud Scheduler)."""
from datetime import datetime, timezone
s = load_state()
w = dict(s.get("upward_weights") or _UP_W_DEFAULT)
today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
snap = {k: float(w.get(k, 0.25)) for k in _UP_W_DEFAULT}
hist = load_upward_weights_history()
hist[today] = snap
save_upward_weights_history(hist)
return json.dumps({"ok": True, "date": today, "snapshot": snap})
@app.get("/config")
def get_config():
return json.dumps(_public_state(load_state()))
@app.post("/config")
def post_config():
s = load_state()
data = request.get_json(silent=True) or {}
float_fields = {"base_amount", "increase_pct", "decrease_pct", "daily_cap"}
for k in float_fields:
if k in data and data[k] is not None:
s[k] = float(data[k])
if "combo_leverage" in data and data["combo_leverage"] is not None:
s["combo_leverage"] = int(min(10, max(1, float(data["combo_leverage"]))))
if "fut_auto_open" in data and data["fut_auto_open"] is not None:
s["fut_auto_open"] = int(min(10, max(1, float(data["fut_auto_open"]))))
if "fut_trail" in data and data["fut_trail"] is not None:
s["fut_trail"] = float(min(10.0, max(0.1, float(data["fut_trail"]))))
for k, lo, hi in (("fut_tp", 3.0, 10.0), ("fut_sl", 3.0, 10.0)):
if k in data and data[k] is not None:
s[k] = float(min(hi, max(lo, float(data[k]))))
if "base_amount" in data and data["base_amount"] is not None:
new_base = float(data["base_amount"])
# ONLY an actual Amount change resets the compounding baseline —
# saving unrelated settings (TP/SL/trailing) must not wipe the
# current compounding chain.
if abs(new_base - float(s.get("base_amount") or 0)) > 0.005:
s["base_amount"] = new_base
s["current_amount"] = new_base
else:
s["base_amount"] = new_base
if "current_amount" in data and data["current_amount"] is not None:
# Direct set (admin/restore of the compounding chain)
s["current_amount"] = float(data["current_amount"])
if "override_amount" in data:
raw = data["override_amount"]
if raw in (None, "", "null", "None"):
s["override_amount"] = None
else:
s["override_amount"] = float(raw)
save_state(s)
return json.dumps(_public_state(s))
@app.route("/grid/run", methods=["GET", "POST"])
def grid_run():
# POST included: Cloud Scheduler HTTP jobs send POST requests.
return run_grid().replace("\n", "<br>")
@app.route("/grid/open", methods=["GET", "POST"])
def grid_open():
symbol = (request.args.get("symbol") or "").upper().strip()
if not (symbol.endswith("USDT") and len(symbol) > 4):
return "invalid symbol (expected e.g. BTCUSDT)", 400
s = load_state()
entry = {}
for k in ("width", "touches", "drift", "w24", "adx", "atr", "score"):
v = request.args.get(k)
if v not in (None, ""):
try:
entry[k] = float(v)
except ValueError:
pass
ok, msg, bot = open_grid_bot(symbol, s, entry=entry)
if ok and bot is not None:
s.setdefault("grid_bots", []).append(bot)
save_state(s)
if ok and bot is not None and not DRY_RUN:
send_telegram(
f"🆕 <b>New grid</b>: {symbol} — funding "
f"${float(bot.get('invested') or 0):.2f}", chat_id=TG_GRID_NEW)
return msg
@app.route("/grid/close", methods=["GET", "POST"])
def grid_close():
bot_id = (request.args.get("bot_id") or "").strip()
if not bot_id:
return "bot_id required", 400
if DRY_RUN:
return f"DRY-RUN: would close grid bot {bot_id}"
r = bybit_post("/v5/fgridbot/close", {"bot_id": bot_id})
if r.get("retCode") != 0:
return f"close failed: {r.get('retMsg')}"
s = load_state()
s["grid_bots"] = [b for b in s.get("grid_bots", []) if str(b.get("bot_id")) != bot_id]
save_state(s)
return f"closed {bot_id}"
@app.get("/grid/positions")
def grid_positions():
s = load_state()
gb = s.get("grid_bots", [])
if not gb:
return "Grid bots: (none)"
out = [f"{b['symbol']} id={b.get('bot_id')} ${float(b.get('invested', 0) or 0):.0f}" for b in gb]
return "Grid bots: " + " | ".join(out)
STATUS_MAP = {
"FUTURE_GRID_STATUS_RUNNING": "Running",
"FUTURE_GRID_STATUS_PAUSED": "Paused",
"FUTURE_GRID_STATUS_STOPPED": "Stopped",
"FUTURE_GRID_STATUS_COMPLETED": "Completed",
}
@app.get("/grid/bots")
def grid_bots():
"""Live grid bots with PnL pulled from Bybit (fgridbot/detail)."""
s = load_state()
status_map = STATUS_MAP
bots = []
for b in s.get("grid_bots", []):
bid = str(b.get("bot_id"))
row = {
"symbol": b.get("symbol"),
"bot_id": bid,
"opened_ms": b.get("opened_ms"),
"invested": float(b.get("invested", 0) or 0),
"status": None, "status_label": None,
"grid_profit": None, "pnl": None,
"realised_pnl": None, "unrealised_pnl": None,
"total_investment": None, "take_profit_per": None,
"trailing_stop_per": None, "leverage": None,
"liquidation_price": None, "last_price": None,
"min_price": None, "max_price": None,
"funding_rate": None,
}
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
st = det.get("status")
row["status"] = st
row["status_label"] = status_map.get(st, st)
row["grid_profit"] = det.get("grid_profit")
row["pnl"] = det.get("pnl")
row["realised_pnl"] = det.get("realised_pnl")
row["unrealised_pnl"] = det.get("unrealised_pnl")
row["total_investment"] = det.get("total_investment")
row["take_profit_per"] = det.get("take_profit_per")
row["trailing_stop_per"] = det.get("trailing_stop_per")
row["leverage"] = det.get("leverage")
row["liquidation_price"] = det.get("liquidation_price")
row["last_price"] = det.get("last_price")
row["min_price"] = det.get("min_price")
row["max_price"] = det.get("max_price")
except Exception as e:
row["error"] = str(e)
bots.append(row)
# Attach the current Bybit funding rate (per 8h) for each symbol.
try:
syms = sorted({r.get("symbol") for r in bots if r.get("symbol")})
fund = {}
for sym in syms:
t = bybit_get("/v5/market/tickers",
{"category": "linear", "symbol": sym})
lst = (t.get("result", {}) or {}).get("list", [])
if lst:
fund[sym] = lst[0].get("fundingRate")
for r in bots:
r["funding_rate"] = fund.get(r.get("symbol"))
except Exception:
pass
return json.dumps(bots)
def _update_score_weights(state, entry, ret_pct):
"""Refine score weights from a closed bot's realized grid return.
Bucketed attribution (per DeepSeek's plan): for each indicator, split all
recorded outcomes into favorable vs unfavorable halves around the median
and compare mean realized grid returns. The difference is the reward r_i;
weights update multiplicatively (w_i *= exp(eta * r_i)), then are
normalized and clamped to [0.10, 0.50]. eta = 0.3 (user-approved).
"""
import math
outs = state.setdefault("outcomes", [])
if entry:
outs.append({"entry": entry, "ret": float(ret_pct)})
del outs[:-200]
if not entry:
return state.get("score_weights") or {}
w = dict(state.get("score_weights")
or {"osc": 0.25, "adx": 0.25, "drift": 0.25, "w24": 0.25})
rows = [o for o in outs if o.get("entry") and o.get("ret") is not None]
fav_of = {
"osc": lambda e: float(e.get("touches") or 0), # more bounces better
"adx": lambda e: -float(e.get("adx") or 0), # lower ADX better
"drift": lambda e: -float(e.get("drift") or 0), # lower drift better
"w24": lambda e: -float(e.get("w24") or 0), # lower 24h width better
}
for k, fn in fav_of.items():
vals = sorted(fn(o["entry"]) for o in rows)
if len(vals) < 4:
continue
med = vals[len(vals) // 2]
fav = [o["ret"] for o in rows if fn(o["entry"]) >= med]
unf = [o["ret"] for o in rows if fn(o["entry"]) < med]
if not fav or not unf:
continue
r = (sum(fav) / len(fav)) - (sum(unf) / len(unf))
spread = (sum(abs(x) for x in (fav + unf)) / len(fav + unf)) or 1.0
r = max(-1.5, min(1.5, r / (spread + 0.5))) # normalized reward
w[k] = w.get(k, 0.25) * math.exp(0.3 * r)
tot = sum(w.values()) or 1.0
w = {k: max(0.10, min(0.50, v / tot)) for k, v in w.items()}
tot = sum(w.values()) or 1.0
w = {k: v / tot for k, v in w.items()}
state["score_weights"] = w
return w
@app.get("/grid/chart-data")
def grid_chart_data():
"""Raw grid data for the chart view: bot detail + grid orders.
Returns everything Bybit gives us so the scanner can draw the exact
grid lines, plus the bot record (opened_ms) for price-at-creation.
"""
bid = (request.args.get("bot_id") or "").strip()
if not bid:
return "missing bot_id", 400
s = load_state()
rec = next((b for b in s.get("grid_bots", [])
if str(b.get("bot_id")) == bid), None) or {}
out = {
"symbol": rec.get("symbol"),
"opened_ms": rec.get("opened_ms"),
"invested": rec.get("invested"),
"entry": rec.get("entry"),
}
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
out["detail"] = (d.get("result", {}) or {}).get("detail", {}) or {}
out["detail_ret"] = {"retCode": d.get("retCode"), "retMsg": d.get("retMsg")}
except Exception as e:
out["detail"] = {}
out["detail_ret"] = {"error": str(e)}
try:
o = bybit_get("/v5/fgridbot/orders", {"bot_id": bid, "limit": "50"})
out["orders"] = (o.get("result", {}) or {}).get("list", []) or []
out["orders_ret"] = {"retCode": o.get("retCode"), "retMsg": o.get("retMsg")}
except Exception as e:
out["orders"] = []
out["orders_ret"] = {"error": str(e)}
return json.dumps(out)
@app.get("/grid/check-events")
def grid_check_events():
"""Detect grid-bot events and send Telegram alerts.
1. A bot closed (TP / SL / manual) -> one message with final P&L.
2. Grid profit milestone -> message each time a bot's realised grid
profit crosses a new whole-dollar level ($1, $2, ...).
"""
state = load_state()
sl_pct = float(state.get("grid", {}).get("stop_loss_percent", 3.0) or 0)
msgs = []
grid_inv_now = 0.0
arch_to_remove = []
# 0. Futures closes (upward + rising-coin sources), near-real-time.
try:
state, _ = manage_positions(state)
except Exception:
pass
try:
riser_left = []
for p in (state.get("riser_positions") or []):
try:
_retune_margin_tpsl(state, p)
except Exception:
pass
sym = p.get("symbol")
since = int(p.get("opened_ms") or 0)
hit = closed_by(sym, since, "linear")
if hit is None:
riser_left.append(p)
continue
kind, exit_price = hit
qty = float(p.get("qty") or 0)
entry = float(p.get("entry_price") or 0)
px = exit_price or 0
pnl = qty * (px - entry) if px else 0.0
# Compounding: TP grows the next order, SL shrinks it
if kind == "TP":
state["current_amount"] = clamp_amount(
round(state["current_amount"]
* (1 + float(state["increase_pct"]) / 100.0), 2),
state["daily_cap"])
else:
state["current_amount"] = clamp_amount(
round(state["current_amount"]
* (1 - float(state["decrease_pct"]) / 100.0), 2),
state["daily_cap"])
try:
_log_fut_close(state, sym, p.get("source") or "riser",
"downward", pnl, float(p.get("cost") or 0),
p.get("leverage") or 3,
p.get("tp_pct"), p.get("sl_pct"),
opened_ms=p.get("opened_ms"))
except Exception:
pass
pnl_emoji = "🟢" if pnl > 0 else "🔴"
msgs.append((TG_FUT_CLOSE,
f"🏁 <b>{_sym_link(sym)} futures closed</b> ({kind}) — Rising Coin\n"
f"P&L: {pnl_emoji} <b>${pnl:+.2f}</b>\n"
f"Next order size: ${state['current_amount']:.2f}"))
if pnl > 0:
msgs.append((TG_PROFIT,
f'💰 🟢 <b>{_sym_link(sym)} futures closed '
f'+${pnl:.2f}</b>'))
elif pnl < 0 and TG_BOOHOO:
msgs.append((TG_BOOHOO,
f'😢 <b>{_sym_link(sym)} futures closed '
f'−${abs(pnl):.2f}</b>\n'
f'🔴 <a href="https://blindmonkeys.org/performance">'
f'blindmonkeys.org/performance</a>'))
state["riser_positions"] = riser_left
except Exception:
pass
released = 0.0
for b in state.get("grid_bots", []):
bid = str(b.get("bot_id"))
sym = b.get("symbol") or "?"
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
except Exception:
continue
st = det.get("status")
pnl = float(det.get("pnl") or 0.0)
# Grid-profit events must come ONLY from Bybit's actual grid_profit
# (pure buy-sell pair income). realised_pnl was previously used but
# it also includes funding/fee income — which produced phantom
# "grid profit" messages while a coin was out of range.
gpn = det.get("grid_profit")
gp = float(gpn) if (gpn not in (None, "") and not _nan(gpn)) else 0.0
# One-time resync of the baseline when the metric changes from the
# old realised_pnl basis, so no false event fires on the switch.
if b.get("gp_metric") != "grid":
b["gp_metric"] = "grid"
b["last_grid_profit"] = gp
inv = float(b.get("invested") or 0) or float(det.get("total_investment") or 0)
running = st in ("FUTURE_GRID_STATUS_RUNNING", "FUTURE_GRID_STATUS_PAUSED")
if running:
try:
grid_inv_now += float(det.get("total_investment") or 0.0)
except Exception:
pass
# 1. Closure notification (sent once per bot).
# (A previous "silent seeding" block here marked every closure as
# already-notified before the message could send — suppressing ALL
# closure messages, so only the generic auto-archive line ever
# reached Telegram. Removed 2026-11-05 per Dean's request for
# per-bot closure alerts with symbol + colored P&L.)
if not running:
# 100% automation: any completed/closed grid is auto-archived
# immediately (it skips straight to the archive list — no manual
# step, no Completed limbo), and its released margin is swept
# back to the Funding account afterwards.
state.setdefault("grid_archive", []).append({
"symbol": sym, "bot_id": bid,
"invested": float(b.get("invested", 0) or 0),
"status": st,
"status_label": STATUS_MAP.get(st, st) or "Archived",
"grid_profit": det.get("grid_profit"),
"pnl": det.get("pnl"),
"realised_pnl": det.get("realised_pnl"),
"unrealised_pnl": det.get("unrealised_pnl"),
"total_investment": det.get("total_investment"),
"take_profit_per": det.get("take_profit_per"),
"trailing_stop_per": det.get("trailing_stop_per"),
"leverage": det.get("leverage"),
"archived_ms": int(time.time() * 1000),
})
arch_to_remove.append(bid)
released += float(b.get("invested", 0) or 0)
if not running and not b.get("notified_closed"):
tp_per = float(det.get("take_profit_per") or 0)
pct = (pnl / inv * 100.0) if inv else 0.0
if tp_per and inv and pnl >= tp_per / 100.0 * inv * 0.999:
reason = "take profit"
elif sl_pct and inv and pnl <= -sl_pct / 100.0 * inv * 1.001:
reason = "stop loss"
else:
reason = "closed manually"
gl = ("🟢 gain" if pnl > 0 else "🔴 loss")
# Grid order compounding — same rule as futures: TP grows the
# next grid order, SL shrinks it (25%/25% from the shared
# increase_pct/decrease_pct settings). Manual closes don't change
# the chain.
grid_next = None
if state["grid"].get("compounding_deferred"):
pass # compounding paused until current cohort closes
elif reason == "take profit":
grid_next = round(float(state["grid"].get("current_amount")
or state["grid"].get("amount") or 100.0)
* (1 + float(state.get("increase_pct", 25.0)) / 100.0), 2)
elif reason == "stop loss":
grid_next = round(float(state["grid"].get("current_amount")
or state["grid"].get("amount") or 100.0)
* (1 - float(state.get("decrease_pct", 25.0)) / 100.0), 2)
if grid_next is not None:
grid_next = min(float(state["grid"].get("daily_cap") or 5000.0),
max(10.0, grid_next))
state["grid"]["current_amount"] = grid_next
msgs.append((TG_GRID_CLOSURE,
f"Next grid order: ${grid_next:.2f}"))
msgs.append((TG_GRID_CLOSURE,
f"🏁 <b>Grid {_sym_link(sym)} closed with a {gl} of "
f"${abs(pnl):.2f} ({pct:+.1f}%)</b> ({reason})\n"
f"Grid profit: ${gp:+.2f}"))
if pnl > 0:
msgs.append((TG_PROFIT,
f'💰 <b>{_sym_link(sym)} grid bot closed '
f'+${pnl:.2f} (+{pct:.1f}%)</b>'))
elif pnl < 0 and TG_BOOHOO:
msgs.append((TG_BOOHOO,
f'😢 <b>{_sym_link(sym)} grid bot closed '
f'−${abs(pnl):.2f} ({pct:+.1f}%)</b>\n'
f'🔴 <a href="https://blindmonkeys.org/performance">'
f'blindmonkeys.org/performance</a>'))
b["notified_closed"] = True
# Feedback loop: realized grid return refines the score weights.
try:
grid_ret = (gp / inv * 100.0) if inv else 0.0
new_w = _update_score_weights(state, b.get("entry") or {}, grid_ret)
msgs.append((TG_GRID_CLOSURE,
"⚖️ Score weights: osc "
+ f"{new_w.get('osc', 0.25):.2f} · ADX "
+ f"{new_w.get('adx', 0.25):.2f} · drift "
+ f"{new_w.get('drift', 0.25):.2f} · 24h "
+ f"{new_w.get('w24', 0.25):.2f}"))
except Exception:
pass
# 2. Every grid profit event (any increase in realised grid profit)
last = float(b.get("last_grid_profit") or 0.0)
gain = gp - last
if gain > 0.005:
msgs.append((TG_GRID_PROFIT,
f'💰 🟢 <b>{_sym_link(sym)} added a grid profit of '
f'${gain:.2f} (total ${gp:.2f})</b>'))
msgs.append((TG_PROFIT,
f'💰 🟢 <b>{_sym_link(sym)} added a grid profit of '
f'${gain:.2f} (total ${gp:.2f})</b>'))
b["last_grid_profit"] = max(last, gp)
# Auto-clear the compounding defer flag once every grid has closed —
# compounding re-enables itself for the next cohort.
if (state.get("grid", {}).get("compounding_deferred")
and not state.get("grid_bots")):
state["grid"]["compounding_deferred"] = False
msgs.append((TG_GRID_CLOSURE,
"⚖️ <b>Grid compounding re-enabled</b> — all grids closed; "
f"next grid order is ${float(state['grid'].get('current_amount') or 0):.2f}"))
if arch_to_remove:
gone = set(arch_to_remove)
state["grid_bots"] = [b for b in state.get("grid_bots", [])
if str(b.get("bot_id")) not in gone]
# (The "🗄 Archived: ..." bookkeeping line was removed per Dean
# 2026-11-05 — the per-bot closure message already names the grid
# and its P&L. The sweep's "no free USDT" variant is likewise
# channel noise: grid margin returns to the FUND account directly,
# so the UNIFIED account is almost always empty — only message when
# a transfer actually happened.)
if released > 0:
sweep_msg = sweep_to_fund(released)
if "swept" in sweep_msg or "sweep failed" in sweep_msg:
msgs.append((TG_GRID_CLOSURE, sweep_msg))
# 3. Futures funding-fee events (new Bybit funding entries since last
# check; first run only seeds the timestamp, no historical spam).
try:
t0 = state.get("last_funding_ms")
r = bybit_get("/v5/account/transaction-log",
{"type": "FUNDING", "limit": "20"})
entries = (r.get("result", {}) or {}).get("list", []) or []
newest = t0 or 0
for t in entries:
ts = int(t.get("transactionTime") or 0)
if ts > newest:
newest = ts
if t0 is not None:
try:
amt = float(t.get("funding") or 0)
except (TypeError, ValueError):
amt = 0.0
msgs.append((TG_FUT_FUNDING,
f"💸 <b>{t.get('symbol')}</b> funding fee "
f"{'received' if amt >= 0 else 'paid'}: "
f"${abs(amt):.4f}"))
state["last_funding_ms"] = newest
except Exception:
pass
# Equity snapshot: funding + unified + running grid investment,
# one point per 15 minutes (passive collection from the 90s check cycle).
try:
bal = bybit_balance()
eq = (float(bal.get("fund_usdt") or 0.0)
+ float(bal.get("unified_total") or 0.0)
+ grid_inv_now)
hist = state.setdefault("equity_history", [])
now_ms = int(time.time() * 1000)
if not hist or now_ms - int(hist[-1].get("ms") or 0) >= 15 * 60 * 1000:
hist.append({"ms": now_ms, "equity": round(eq, 2)})
del hist[:-2000]
except Exception:
pass
save_state(state)
sent = 0
for m in msgs:
cid, txt = m if isinstance(m, tuple) else (None, m)
try:
send_telegram(txt, chat_id=cid)
sent += 1
except Exception:
pass
return json.dumps({"events": len(msgs), "sent": sent})
@app.route("/price-change", methods=["GET"])
def price_change_api():
"""24h price change (%) for a symbol, live from Bybit's public ticker.
The trader runs in europe-west1, where Bybit does not geo-block
(unlike the main app's us-central1 egress) — the main site proxies
through this endpoint for its live BTC/ETH change displays.
"""
sym = (request.args.get("symbol") or "BTCUSDT").upper().strip()
if not _re_full.match(r"^[A-Z0-9]{1,20}USDT$", sym):
return json.dumps({"status": "error", "message": "bad symbol"}), 400
try:
r = bybit_get("/v5/market/tickers", {"category": "spot", "symbol": sym})
lst = (r.get("result", {}) or {}).get("list") or []
if not lst:
return json.dumps({"status": "error", "message": "no data"}), 502
t = lst[0]
return json.dumps({
"status": "ok",
"symbol": sym,
"last_price": t.get("lastPrice"),
"change_24h_pct": round(float(t.get("price24hPcnt") or 0) * 100, 2),
})
except Exception as e:
return json.dumps({"status": "error", "message": str(e)[:120]}), 502
@app.route("/grid/check-profit", methods=["GET", "POST"])
def grid_check_profit():
"""Fast grid-profit diff (2-minute cron): one Telegram message per bot
for every profit jump since the previous check — so individual round
trips arrive as separate messages instead of one 15-minute bundle.
Shares `last_grid_profit` with /grid/check-events, which keeps the
15-minute checker from double-reporting what this job already sent
(its delta will simply be zero for everything this job covered).
"""
state = load_state()
msgs = []
changed = False
for b in state.get("grid_bots", []):
bid = str(b.get("bot_id"))
sym = b.get("symbol") or "?"
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
except Exception:
continue
st = det.get("status")
if st not in ("FUTURE_GRID_STATUS_RUNNING", "FUTURE_GRID_STATUS_PAUSED"):
continue
gpn = det.get("grid_profit")
gp = float(gpn) if (gpn not in (None, "") and not _nan(gpn)) else 0.0
if b.get("gp_metric") != "grid":
# Metric-baseline resync — same rule as check-events: seed the
# baseline silently so no false event fires on the switch.
b["gp_metric"] = "grid"
b["last_grid_profit"] = gp
changed = True
continue
last = float(b.get("last_grid_profit") or 0.0)
gain = gp - last
if gain > 0.005:
msgs.append((TG_GRID_PROFIT,
f'💰 🟢 <b>{_sym_link(sym)} added a grid profit of '
f'${gain:.2f} (total ${gp:.2f})</b>'))
msgs.append((TG_PROFIT,
f'💰 🟢 <b>{_sym_link(sym)} added a grid profit of '
f'${gain:.2f} (total ${gp:.2f})</b>'))
if gp > last:
b["last_grid_profit"] = gp
changed = True
if changed:
save_state(state)
sent = 0
for m in msgs:
cid, txt = m if isinstance(m, tuple) else (None, m)
try:
send_telegram(txt, chat_id=cid)
sent += 1
except Exception:
pass
return json.dumps({"profit_events": len(msgs), "sent": sent})
@app.get("/grid/archive")
def grid_archive():
"""Move a completed bot from the active list into the archive.
Snapshots the bot's last-known stats so history is preserved without
hitting the Bybit API on every page load.
"""
bid = (request.args.get("bot_id") or "").strip()
if not bid:
return "missing bot_id", 400
s = load_state()
bots = s.get("grid_bots", [])
rec = next((b for b in bots if str(b.get("bot_id")) == bid), None)
if rec is None:
return "bot not found", 404
row = {
"symbol": rec.get("symbol"), "bot_id": bid,
"invested": float(rec.get("invested", 0) or 0),
"status": None, "status_label": "Archived",
"grid_profit": None, "pnl": None,
"realised_pnl": None, "unrealised_pnl": None,
"total_investment": None, "take_profit_per": None,
"trailing_stop_per": None, "leverage": None,
}
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
st = det.get("status")
row["status"] = st
row["status_label"] = STATUS_MAP.get(st, st) or "Archived"
row["grid_profit"] = det.get("grid_profit")
row["pnl"] = det.get("pnl")
row["realised_pnl"] = det.get("realised_pnl")
row["unrealised_pnl"] = det.get("unrealised_pnl")
row["total_investment"] = det.get("total_investment")
row["take_profit_per"] = det.get("take_profit_per")
row["trailing_stop_per"] = det.get("trailing_stop_per")
row["leverage"] = det.get("leverage")
except Exception:
pass
row["archived_ms"] = int(time.time() * 1000)
s.setdefault("grid_archive", []).append(row)
s["grid_bots"] = [b for b in bots if str(b.get("bot_id")) != bid]
save_state(s)
return f"ARCHIVED bot {bid}"
@app.get("/grid/archived")
def grid_archived():
return json.dumps(load_state().get("grid_archive", []))
@app.get("/grid/repair-archive")
def grid_repair_archive():
"""Re-snapshot archived bots whose stats are missing (a scoping bug in the
original archive code produced null PnL snapshots). Idempotent: only
touches entries with a missing pnl."""
s = load_state()
fixed = 0
for e in s.get("grid_archive", []):
if e.get("pnl") is not None:
continue
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": str(e.get("bot_id"))})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
st = det.get("status")
e["status"] = st
e["status_label"] = STATUS_MAP.get(st, st) or "Archived"
e["grid_profit"] = det.get("grid_profit")
e["pnl"] = det.get("pnl")
e["realised_pnl"] = det.get("realised_pnl")
e["unrealised_pnl"] = det.get("unrealised_pnl")
e["total_investment"] = det.get("total_investment")
e["take_profit_per"] = det.get("take_profit_per")
e["trailing_stop_per"] = det.get("trailing_stop_per")
e["leverage"] = det.get("leverage")
fixed += 1
except Exception:
continue
if fixed:
save_state(s)
return json.dumps({"status": "ok", "repaired": fixed})
@app.get("/grid/returns")
def grid_returns():
"""Aggregate realized return of completed grid bots (last 30 days).
Realized profit / total investment across bots that completed or were
archived within the window. Public aggregate only (no bot details).
"""
s = load_state()
cutoff_ms = time.time() * 1000 - 30 * 24 * 3600 * 1000
realized = 0.0
invested = 0.0
count = 0
wins = 0
closed = 0
for b in s.get("grid_bots", []):
if float(b.get("opened_ms", 0) or 0) < cutoff_ms:
continue
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": str(b.get("bot_id"))})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
if det.get("status") == "FUTURE_GRID_STATUS_COMPLETED":
p = float(det.get("pnl") or 0)
realized += p
invested += float(b.get("invested", 0) or 0)
count += 1
closed += 1
if p > 0:
wins += 1
except Exception:
continue
for e in s.get("grid_archive", []):
if float(e.get("archived_ms", 0) or 0) >= cutoff_ms:
p = float(e.get("pnl") or 0)
realized += p
invested += float(e.get("invested") or 0)
count += 1
closed += 1
if p > 0:
wins += 1
pct = (realized / invested * 100.0) if invested > 0 else 0.0
win_rate = (wins / closed * 100.0) if closed > 0 else 0.0
return json.dumps({"status": "ok", "realized": round(realized, 2),
"invested": round(invested, 2), "count": count,
"return_pct": round(pct, 2),
"wins": wins, "closed": closed,
"win_rate": round(win_rate, 1)})
@app.get("/telegram-stats")
def telegram_stats():
"""Three headline stats for the public /telegram page:
total realized GRID profit (30d) — the buy-low/sell-high pair profit,
distinct from total P/L — closed grid count (30d), and the number of
tracked futures closures (upward-regime outcomes ledger).
Public aggregate only (no positions or details).
"""
try:
grid = json.loads(grid_returns())
except Exception:
grid = {"realized": 0.0, "closed": 0, "win_rate": 0.0}
s = load_state()
cutoff_ms = time.time() * 1000 - 30 * 24 * 3600 * 1000
gp_total = 0.0
# Completed bots still in the active list (within 30d)
for b in s.get("grid_bots", []):
if float(b.get("opened_ms", 0) or 0) < cutoff_ms:
continue
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": str(b.get("bot_id"))})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
if det.get("status") == "FUTURE_GRID_STATUS_COMPLETED":
g = det.get("realised_pnl")
if g in (None, "") or _nan(g):
g = det.get("grid_profit") or 0.0
gp_total += float(g or 0.0)
except Exception:
continue
# Archived bots (within 30d)
for e in s.get("grid_archive", []):
if float(e.get("archived_ms", 0) or 0) >= cutoff_ms:
gp_total += float(e.get("grid_profit") or 0.0)
fut_closed = len(s.get("upward_outcomes") or [])
return json.dumps({
"grid_profits": round(gp_total, 2),
"closed_grids": int(grid.get("closed") or 0),
"grid_win_rate": float(grid.get("win_rate") or 0.0),
"closed_futures": int(fut_closed),
})
@app.route("/grid/trailing-check", methods=["GET", "POST"])
def grid_trailing_check():
"""App-side trailing TP for grid bots (runs on a fast cron).
Bybit's native grid trailing requires a 5% minimum retrenchment, so
tighter trailing (user setting `trailing_retrench`, default 1%) is
implemented here: track each running bot's peak total-P&L-% of its
invested amount; once the peak reaches the grid TP level (tp_percent)
the trailing is ARMED; if the P&L% then retraces by trailing_retrench
from the peak, the bot is closed at market and reported to Telegram.
"""
s = load_state()
g = s.get("grid", {})
tp_arm = float(g.get("tp_percent", 3.0) or 0)
retr = float(g.get("trailing_retrench", 1.0) or 1.0)
msgs = []
closed_bots = set()
checked = 0
for b in s.get("grid_bots", []):
bid = str(b.get("bot_id"))
sym = b.get("symbol") or "?"
try:
d = bybit_post("/v5/fgridbot/detail", {"bot_id": bid})
det = (d.get("result", {}) or {}).get("detail", {}) or {}
except Exception:
continue
if det.get("status") != "FUTURE_GRID_STATUS_RUNNING":
continue
checked += 1
try:
pnl = float(det.get("pnl") or 0)
except (TypeError, ValueError):
pnl = 0.0
inv = float(b.get("invested", 0) or 0) or float(det.get("total_investment") or 0)
if inv <= 0:
continue
pct = pnl / inv * 100.0
peak = max(float(b.get("trail_peak_pct") or pct), pct)
b["trail_peak_pct"] = peak
if not b.get("trail_armed") and pct >= tp_arm:
b["trail_armed"] = True
if b.get("trail_armed") and pct <= peak - retr:
r = bybit_post("/v5/fgridbot/close", {"bot_id": bid})
if r.get("retCode") == 0:
closed_bots.add(bid)
b["notified_closed"] = True # suppress the generic close msg
gl = ("🟢 gain" if pnl > 0 else "🔴 loss")
# Trailing-TP close is a profit close — compound the next
# grid order up like a TP (shared increase_pct), unless
# compounding is deferred until the cohort closes.
grid_next = None
if not s["grid"].get("compounding_deferred"):
grid_next = round(float(s["grid"].get("current_amount")
or s["grid"].get("amount") or 100.0)
* (1 + float(s.get("increase_pct", 25.0)) / 100.0), 2)
grid_next = min(float(s["grid"].get("daily_cap") or 5000.0),
max(10.0, grid_next))
s["grid"]["current_amount"] = grid_next
msgs.append((TG_GRID_CLOSURE,
f"Next grid order: ${grid_next:.2f}"))
msgs.append((TG_GRID_CLOSURE,
f"🏁 <b>Grid {_sym_link(sym)} closed with a {gl} of "
f"${abs(pnl):.2f} ({pct:+.1f}%)</b> (trailing TP)\n"
f"Peak: {peak:+.1f}% · retrench {retr:g}%"))
if pnl > 0:
msgs.append((TG_PROFIT,
f'💰 <b>{_sym_link(sym)} grid '
f'bot closed +${pnl:.2f}</b>'))
else:
msgs.append((TG_GRID_CLOSURE,
f"⚠️ trailing close failed for {sym}: "
f"{r.get('retMsg')}"))
if closed_bots:
s["grid_bots"] = [b for b in s.get("grid_bots", [])
if str(b.get("bot_id")) not in closed_bots]
save_state(s)
sent = 0
for cid, txt in msgs:
try:
send_telegram(txt, chat_id=cid)
sent += 1
except Exception:
pass
return json.dumps({"checked": checked, "closed": len(closed_bots),
"sent": sent})
@app.get("/grid/validate")
def grid_validate():
"""Call Bybit's /v5/fgridbot/validate with our current grid params.
Returns the allowable ranges (investment, trailing stop, move prices, ...)
so we can see exactly why a create call would be rejected.
"""
symbol = (request.args.get("symbol") or "BTCUSDT").strip().upper()
# Optional overrides for experimentation: trail=none omits the field,
# trail=<pct> sends that percentage instead of the saved config value.
trail_q = request.args.get("trail")
g = load_state().get("grid", {})
rng = float(g.get("range_percent", 3.0))
lines = int(g.get("grid_lines", 10))
lev = int(g.get("leverage", 1))
trail = (None if (trail_q or "").lower() == "none" else
(float(trail_q) if trail_q else None))
up_pct = float(g.get("trailing_up_percent", 20.0))
down_pct = float(g.get("trailing_down_percent", 5.0))
price = linear_price(symbol)
if price <= 0:
return json.dumps({"error": f"no price for {symbol}"})
tick = linear_tick(symbol)
min_price = round_to(price * (1 - rng / 100.0), tick)
max_price = round_to(price * (1 + rng / 100.0), tick)
def fmt(x):
return format(x, ".10f").rstrip("0").rstrip(".")
body = {
"symbol": symbol,
"grid_mode": 1, # neutral
"min_price": fmt(min_price),
"max_price": fmt(max_price),
"cell_number": lines,
"leverage": str(lev),
"grid_type": 1, # arithmetic
"move_up_price": fmt(round_to(price * (1 + up_pct / 100.0), tick)),
"move_down_price": fmt(round_to(price * (1 - down_pct / 100.0), tick)),
}
if trail:
body["trailing_stop_per"] = fmt(float(trail) / 100.0)
tp_v = g.get("tp_percent", 3.0)
if tp_v:
body["tp_sl_type"] = 1
body["take_profit_per"] = fmt(float(tp_v))
r = bybit_post("/v5/fgridbot/validate", body)
return json.dumps({"params_sent": body, "bybit": r.get("result", r)}, indent=2)
@app.get("/grid/config")
def grid_get_config():
s = load_state()
out = dict(s.get("grid", {}))
out["score_weights"] = s.get("score_weights") or {}
return json.dumps(out)
@app.post("/grid/config")
def grid_post_config():
s = load_state()
g = s["grid"]
data = request.get_json(silent=True) or {}
for k in ("leverage", "grid_lines"):
if k in data and data[k] is not None:
g[k] = int(data[k])
for k in ("range_percent", "amount", "daily_cap", "tp_percent",
"stop_loss_percent", "trailing_up_percent", "trailing_down_percent", "auto_min_score",
"regime_pause_drift", "trailing_retrench"):
if k in data and data[k] is not None:
if k == "amount":
new_amt = float(data[k])
# Surgical reset (same rule as futures): only an actual
# Amount change resets the grid compounding chain.
if abs(new_amt - float(g.get("amount") or 0)) > 0.005:
g["current_amount"] = new_amt
g[k] = new_amt
else:
g[k] = float(data[k])
if "current_amount" in data and data["current_amount"] is not None:
# Direct set (admin/restore of the grid compounding chain)
g["current_amount"] = float(data["current_amount"])
if "compounding_deferred" in data and data["compounding_deferred"] is not None:
g["compounding_deferred"] = bool(data["compounding_deferred"])
s["grid"] = g
save_state(s)
return json.dumps(g)
def _btc_7d_drift():
"""BTC 7-day price drift (%) from Bybit daily candles."""
try:
d = bybit_get("/v5/market/kline",
{"category": "linear", "symbol": "BTCUSDT",
"interval": "D", "limit": 8})
lst = (d.get("result", {}) or {}).get("list") or []
candles = sorted((int(k[0]), float(k[4])) for k in lst) # by time
if len(candles) < 8:
return None
first, last = candles[0][1], candles[-1][1]
if first <= 0:
return None
return round((last - first) / first * 100, 2)
except Exception:
return None
def _linear_position_size(symbol):
"""Current open linear position size for `symbol` (0 = none)."""
try:
r = bybit_get("/v5/position/list",
{"category": "linear", "symbol": symbol})
for p in (r.get("result", {}) or {}).get("list", []) or []:
sz = abs(float(p.get("size") or 0))
if sz > 0:
return sz
except Exception:
pass
return 0.0
@app.get("/riser/config")
def riser_get_config():
s = load_state()
rc = dict(_RISER_DEFAULTS)
rc.update(s.get("riser") or {})
return json.dumps(rc)
@app.post("/riser/config")
def riser_post_config():
"""Trading rules for rising-coins signals (settings page panel)."""
s = load_state()
r = s.setdefault("riser", dict(_RISER_DEFAULTS))
data = request.get_json(silent=True) or {}
for k in ("amount", "leverage", "tp_percent", "stop_loss_percent", "daily_cap",
"min_funding", "trailing_retrench"):
if k in data and data[k] is not None:
r[k] = float(data[k])
s["riser"] = r
save_state(s)
return json.dumps(r)
_RISER_DEFAULTS = {
"amount": 100.0, "leverage": 3.0, "tp_percent": 3.0,
"stop_loss_percent": 3.0, "daily_cap": 1000.0, "min_funding": 0.0,
"trailing_retrench": 1.0, # trailing-TP retrenchment % of margin
}
def _riser_rules(state):
rc = state.get("riser") or dict(_RISER_DEFAULTS)
return {
"amount": float(rc.get("amount", 100.0) or 100.0),
"leverage": int(rc.get("leverage", 3) or 3),
"tp": float(rc.get("tp_percent", 3.0) or 3.0),
"sl": float(rc.get("stop_loss_percent", 3.0) or 3.0),
"cap": float(rc.get("daily_cap", 1000.0) or 1000.0),
"min_funding": float(rc.get("min_funding", 0.0) or 0.0),
"trail": float(rc.get("trailing_retrench", 1.0) or 1.0),
}
def _riser_invested_today(state):
today = day_start_ms()
return sum(
float(p.get("cost", 0) or 0)
for p in state.get("riser_positions", [])
if int(p.get("opened_ms", 0) or 0) >= today)
@app.route("/riser/open", methods=["GET", "POST"])
def riser_open():
"""Open a rising-coin long using the saved riser rules.
Applies the configured amount (optional ?amount= override), leverage,
TP, SL and daily cap; skips symbols already held.
"""
symbol = (request.args.get("symbol") or "").upper().strip()
if not (symbol.endswith("USDT") and len(symbol) > 4):
return "invalid symbol (expected e.g. BTCUSDT)", 400
try:
override = float(request.args.get("amount") or 0)
except (TypeError, ValueError):
override = 0.0
s = load_state()
rc = _riser_rules(s)
# Order size follows the compounding chain (TP grows it, SL shrinks
# it — shared with the futures flow). An explicit ?amount= override
# still wins; the riser Amount setting is the fallback if the chain
# is somehow missing.
chain_amt = float(s.get("current_amount") or 0)
if chain_amt <= 0:
chain_amt = rc["amount"]
amount = override if override >= 10 else clamp_amount(chain_amt, rc["cap"])
invested = _riser_invested_today(s)
if invested + amount > rc["cap"]:
return (f"daily cap reached — invested ${invested:.0f} of ${rc['cap']:.0f} "
f"today, this order needs ${amount:.0f}"), 400
if _linear_position_size(symbol) > 0:
return f"already holding {symbol}", 400
ok, msg, entry = open_future_position(
symbol, notional=amount, leverage=rc["leverage"],
tp_pct=rc["tp"], sl_pct=rc["sl"], trail_pct=rc.get("trail"))
if ok and entry is not None:
entry["tp_pct"] = rc["tp"]
entry["sl_pct"] = rc["sl"]
entry["source"] = "riser"
s.setdefault("riser_positions", []).append(entry)
save_state(s)
if not DRY_RUN:
send_telegram(
f"🆕 <b>New futures (rising coin)</b>: {_sym_link(symbol)} — "
f"${amount:.2f} margin at {rc['leverage']}x (TP +{rc['tp']}% / SL −{rc['sl']}%)",
chat_id=TG_FUT_NEW)
return msg
# ---------------------------------------------------------------------------
# Upward-regime auto-trading (conservative + risk-taker buy signals -> futures)
# ---------------------------------------------------------------------------
MAIN_SITE = os.environ.get("MAIN_SITE", "https://blindmonkeys.org")
UPWARD_DROP_MAX = float(os.environ.get("UPWARD_DROP_MAX", "0.5"))
def _eth_drawdown_pct():
"""ETH % below its 24h high (Bybit public 1h klines, no auth)."""
try:
req = urllib.request.Request(
"https://api.bybit.com/v5/market/kline?category=linear"
"&symbol=ETHUSDT&interval=60&limit=24")
r = json.loads(urllib.request.urlopen(req, timeout=15).read())
ks = (r.get("result", {}) or {}).get("list", []) or []
if not ks:
return None
hi = max(float(k[2]) for k in ks)
last = float(ks[0][4]) # newest first
return (hi - last) / hi * 100.0 if hi > 0 else None
except Exception:
return None
def _upward_signals():
"""Union of conservative + risk-taker buy-signal coins (with factors)."""
out, seen = {}, set()
for mode in ("conservative", "risk"):
try:
url = f"{MAIN_SITE}/api/scan?mode={mode}&noalert=1"
req = urllib.request.Request(url, headers={"User-Agent": "bm-trader"})
d = json.loads(urllib.request.urlopen(req, timeout=300).read())
for c in d.get("results", []) or []:
if c.get("buy_signal") and c.get("symbol"):
sym = str(c["symbol"]).upper()
if not sym.endswith("USDT"):
sym = sym + "USDT"
if sym not in seen:
seen.add(sym)
c["symbol"] = sym
out[sym] = c
except Exception:
continue
return list(out.values())
_UP_W_DEFAULT = {"rsi": 0.25, "momentum": 0.25, "zscore": 0.25, "volatility": 0.25}
def _upward_score(w, c):
"""Weighted candidate score for an upward-regime buy signal.
Four factors (RSI, momentum, Z-score, volatility), each normalized to a
comparable 'goodness' scale where higher = better candidate:
RSI (50 - RSI) / 10 (lower RSI = more oversold = better)
momentum momentum / 5 (higher momentum = better)
Z-score -zscore (deeper below the mean = better)
volatility -volatility / 5 (calmer price action = better)
score = 4 * sum(weight_i * goodness_i); equal weights (0.25) reproduce
the plain average of the four goodness terms.
"""
rsi = float(c.get("rsi") or 50)
mom = float(c.get("momentum") or 0)
zs = float(c.get("zscore") or 0)
vol = float(c.get("volatility") or 0)
g = {
"rsi": (50.0 - rsi) / 10.0,
"momentum": mom / 5.0,
"zscore": -zs,
"volatility": -vol / 5.0,
}
score = 4.0 * sum(float(w.get(k, 0.25)) * g[k] for k in g)
return score, g
def _update_upward_weights(state, entry, ret_pct):
"""Feedback loop for upward-regime score weights (grid-style).
On each futures close, the realized margin return rewards the factors
that were favorable at entry (bucketed around the median, normalized,
eta = 0.3, weights clamped to [0.10, 0.50]).
"""
import math
outs = state.setdefault("upward_outcomes", [])
if entry:
outs.append({"entry": entry, "ret": float(ret_pct)})
del outs[:-200]
if not entry:
return dict(state.get("upward_weights") or _UP_W_DEFAULT)
w = dict(state.get("upward_weights") or _UP_W_DEFAULT)
rows = [o for o in outs if o.get("entry") and o.get("ret") is not None]
fav_of = {
"rsi": lambda e: -float(e.get("rsi") or 50), # lower better
"momentum": lambda e: float(e.get("momentum") or 0), # higher better
"zscore": lambda e: -float(e.get("zscore") or 0), # lower better
"volatility": lambda e: -float(e.get("volatility") or 0), # lower better
}
for k, fn in fav_of.items():
vals = sorted(fn(o["entry"]) for o in rows)
if len(vals) < 4:
continue
med = vals[len(vals) // 2]
fav = [o["ret"] for o in rows if fn(o["entry"]) >= med]
unf = [o["ret"] for o in rows if fn(o["entry"]) < med]
if not fav or not unf:
continue
r = (sum(fav) / len(fav)) - (sum(unf) / len(unf))
spread = (sum(abs(x) for x in (fav + unf)) / len(fav + unf)) or 1.0
r = max(-1.5, min(1.5, r / (spread + 0.5)))
w[k] = w.get(k, 0.25) * math.exp(0.3 * r)
tot = sum(w.values()) or 1.0
w = {k: max(0.10, min(0.50, v / tot)) for k, v in w.items()}
tot = sum(w.values()) or 1.0
w = {k: v / tot for k, v in w.items()}
state["upward_weights"] = w
return w
def run_upward():
"""Upward regime: place combo futures for coins with scan buy signals.
Regime-gated (ETH must hold near its 24h high), shares the position
pool (max 3), daily cap and compounding loop with the riser flow.
"""
mode = "DRY-RUN (no real orders)" if DRY_RUN else "LIVE"
drop = _eth_drawdown_pct()
if drop is None:
return "upward: could not read ETH price — skipped"
if drop >= UPWARD_DROP_MAX:
return (f"upward: regime gate closed — ETH {drop:.2f}% off 24h high "
f"(needs < {UPWARD_DROP_MAX}%)")
lines = [f"Upward regime open — ETH {drop:.2f}% off high [{mode}]"]
state = load_state()
# Manage existing positions first (shared compounding loop).
state, events = manage_positions(state)
coins = _upward_signals()
uw = dict(state.get("upward_weights") or _UP_W_DEFAULT)
scored = []
for c in coins:
sc, _g = _upward_score(uw, c)
scored.append((sc, c))
scored.sort(key=lambda x: -x[0])
lines.append(f"buy signals (conservative \u222a risk): {len(scored)} -> "
+ ", ".join(f"{c['symbol']} {sc:.1f}" for sc, c in scored[:8]))
lines.append("upward weights: RSI " + f"{uw.get('rsi', 0.25):.2f}"
+ " · Mom " + f"{uw.get('momentum', 0.25):.2f}"
+ " · Z " + f"{uw.get('zscore', 0.25):.2f}"
+ " · Vol " + f"{uw.get('volatility', 0.25):.2f}")
if not scored:
save_state(state)
if not DRY_RUN:
try:
send_telegram(
"✅ <b>Futures Scan Complete</b> — No Futures Met "
"the minimum score threshold",
chat_id=TG_BLIND_MONKEYS)
except Exception:
pass
return "\n".join(lines) + "\n"
daily_cap = float(state.get("daily_cap", 500.0))
algo_amount = clamp_amount(float(state.get("current_amount", ORDER_NOTIONAL)), daily_cap)
override = state.get("override_amount")
if override is not None:
override = float(override)
lines.append(f" one-time override: next order ${override:.2f}")
today_bought = today_buy_notional()
remaining = daily_cap - today_bought
lines.append(f" daily bought ${today_bought:.2f} / ${daily_cap:.0f} cap -> ${remaining:.2f} remaining")
open_syms = open_symbols(state)
grid_syms = {str(b.get("symbol") or "").upper()
for b in state.get("grid_bots", [])}
available = MAX_POSITIONS - len(open_syms)
# Per-run cap (fixed at 1); fut_auto_open is the score threshold, not a cap
per_run = 1
available = min(available, per_run)
# Auto-open score threshold (settings page, default 1): a futures
# position is auto-opened only for coins whose score is at or above
# this value.
min_score = float(state.get("fut_auto_open", 1) or 1)
lines.append(f" auto-open score threshold: {min_score:g}")
opened = 0
for sc, c in scored:
sym = c["symbol"]
if sc < min_score:
lines.append(f" skip {sym} — score {sc:.1f} below "
f"auto-open threshold {min_score:g}")
continue
if available <= 0:
lines.append(f" skip {sym} — max positions ({MAX_POSITIONS}) reached")
break
if sym in open_syms:
lines.append(f" skip {sym} — position already open")
continue
if sym in grid_syms:
lines.append(f" skip {sym} — grid bot running on this coin")
continue
amount = override if override is not None else algo_amount
if remaining < amount:
lines.append(f" skip {sym} — daily buy cap reached")
continue
ok, msg, entry = open_future_position(
sym, notional=amount,
leverage=int(state.get("combo_leverage", 3) or 3))
lines.append(f" {msg}")
if ok:
opened += 1
available -= 1
remaining -= amount
if entry is not None:
entry["source"] = "upward"
entry["up_entry"] = {
"rsi": c.get("rsi"),
"momentum": c.get("momentum"),
"zscore": c.get("zscore"),
"volatility": c.get("volatility"),
"score": round(sc, 2),
}
state.setdefault("positions", []).append(entry)
if override is not None:
state["override_amount"] = None
override = None
if not DRY_RUN:
try:
send_telegram(
f"\U0001f195 <b>New futures (upward signal)</b>: {_sym_link(sym)} — "
f"${amount:.2f} margin at "
f"{int(state.get('combo_leverage', 3) or 3)}x",
chat_id=TG_FUT_NEW)
except Exception:
pass
save_state(state)
result = "\n".join(lines) + "\n"
if opened > 0 or events:
send_telegram("\U0001f4c8 <b>Upward regime " + str(mode) + "</b>\n"
+ _tg_green_open(result))
return result
@app.route("/upward/run", methods=["GET", "POST"])
def upward_run():
return run_upward()
@app.get("/riser/run")
def riser_run():
"""Auto-open longs on rising-coin signals (hourly, Cloud Scheduler).
Only fires when the scanner flags a downward market (BTC + ETH both off
their 24h highs) with coins rising on real volume. Applies the riser
rules: amount, leverage, TP/SL, daily cap; skips held symbols.
"""
s = load_state()
rc = _riser_rules(s)
invested = _riser_invested_today(s)
remaining = rc["cap"] - invested
mode = "DRY-RUN (no real orders)" if DRY_RUN else "LIVE"
lines = [f"Riser [{mode}] — invested ${invested:.0f}/${rc['cap']:.0f} today"]
try:
with urllib.request.urlopen(
SCANNER_URL.rstrip("/") + "/rising.json", timeout=60) as r:
data = json.loads(r.read().decode())
except Exception as e:
return f"riser run: could not fetch rising coins: {e}"
if not data.get("market_down"):
lines.append("Market not flagged down — no riser signals.")
return "<br>".join(lines)
rows = data.get("rows") or []
if not rows:
lines.append("No rising coins flagged right now.")
if not DRY_RUN:
try:
send_telegram(
"✅ <b>Futures Scan Complete</b> — No Futures Met "
"the minimum score threshold",
chat_id=TG_BLIND_MONKEYS)
except Exception:
pass
return "<br>".join(lines)
# Order size follows the compounding chain (shared with futures);
# the riser Amount setting is only the fallback when the chain is
# somehow missing.
chain_amt = float(s.get("current_amount") or 0)
if chain_amt <= 0:
chain_amt = rc["amount"]
algo_amount = clamp_amount(chain_amt, rc["cap"])
opened = 0
for row in rows[:5]:
if remaining < algo_amount:
lines.append(" daily cap reached")
break
base = str(row.get("symbol") or "").upper()
sym = base if base.endswith("USDT") else base + "USDT"
# Funding gate (configurable): only auto-open longs whose funding rate
# is at/below min_funding — i.e. longs are being paid. Set min_funding
# to 99 (or more) in settings to turn the gate off.
if rc["min_funding"] < 99.0:
fr = row.get("funding_rate")
if fr is None or float(fr) > rc["min_funding"]:
lines.append(f" skip {sym} — funding {fr} exceeds "
f"{rc['min_funding']:g}% (longs would pay)")
continue
if _linear_position_size(sym) > 0:
lines.append(f" skip {sym} — already holding")
continue
ok, msg, entry = open_future_position(
sym, notional=algo_amount, leverage=rc["leverage"],
tp_pct=rc["tp"], sl_pct=rc["sl"], trail_pct=rc.get("trail"))
lines.append(f" {msg}")
if ok and entry is not None:
entry["tp_pct"] = rc["tp"]
entry["sl_pct"] = rc["sl"]
entry["source"] = "riser"
s.setdefault("riser_positions", []).append(entry)
opened += 1
remaining -= float(entry.get("cost", algo_amount) or algo_amount)
save_state(s)
if opened and not DRY_RUN:
send_telegram(
"🆕 <b>New futures (rising coin)</b>\n"
+ _tg_green_open("\n".join(lines[1:])),
chat_id=TG_FUT_NEW)
return "<br>".join(lines)
@app.get("/positions/closed")
def positions_closed():
"""Last 10 closed linear futures positions, newest first.
Combines the trader's closed-log (regime/source/TP-SL metadata kept
when the close was detected) with Bybit's /v5/position/closed-pnl for
any older history the log doesn't cover. Log rows win; Bybit-only
rows get regime '-'.
"""
s = load_state()
log = s.get("fut_closed_log") or []
out = []
try:
r = bybit_get("/v5/position/closed-pnl",
{"category": "linear", "limit": "30"})
rows = (r.get("result", {}) or {}).get("list") or []
except Exception:
rows = []
log_syms_ms = {(str(e.get("symbol")), int(e.get("closed_ms") or 0))
for e in log}
for e in log:
fp = 0.0
try:
oms = int(e.get("opened_ms") or 0)
cms = int(e.get("closed_ms") or 0)
if oms and cms and cms > oms:
fp = _funding_between(e.get("symbol"), oms, cms)
except Exception:
fp = 0.0
out.append({
"symbol": e.get("symbol"),
"source": e.get("source") or "—",
"regime": e.get("regime") or "—",
"leverage": e.get("leverage"),
"invested": round(float(e.get("invested") or 0), 2),
"funding_profit": fp,
"unrealised_pnl": 0.0,
"pnl": round(float(e.get("pnl") or 0), 2),
"closed_ms": int(e.get("closed_ms") or 0),
"in_log": True,
})
for p in rows:
try:
sym = p.get("symbol")
cms = int(p.get("updatedTime") or 0)
if (sym, cms) in log_syms_ms:
continue
lev = max(1, int(float(p.get("leverage") or 1)))
cum = float(p.get("cumEntryValue") or 0)
oms = int(p.get("createdTime") or 0)
fp = 0.0
try:
if oms and cms and cms > oms:
fp = _funding_between(sym, oms, cms)
except Exception:
fp = 0.0
out.append({
"symbol": sym,
"source": "—",
"regime": "—",
"leverage": lev,
"invested": round(cum / lev, 2),
"funding_profit": fp,
"unrealised_pnl": 0.0,
"pnl": round(float(p.get("closedPnl") or 0), 2),
"closed_ms": cms,
"in_log": False,
})
except Exception:
continue
out.sort(key=lambda x: -int(x.get("closed_ms") or 0))
return json.dumps(out[:10])
def _funding_between(symbol, start_ms, end_ms):
"""Sum funding settlements for `symbol` in [start_ms, end_ms]."""
total = 0.0
cursor = None
for _ in range(3):
params = {"type": "SETTLEMENT", "symbol": symbol,
"startTime": str(int(start_ms)), "endTime": str(int(end_ms)),
"limit": "50"}
if cursor:
params["cursor"] = cursor
try:
r = bybit_get("/v5/account/transaction-log", params)
except Exception:
break
res = (r.get("result", {}) or {})
entries = res.get("list") or []
cursor = res.get("nextPageCursor")
for e in entries:
try:
total += float(e.get("funding") or 0)
except (TypeError, ValueError):
continue
if not cursor or not entries:
break
return round(total, 4)
def _log_fut_close(state, symbol, source, regime, pnl, invested,
leverage, tp_pct, sl_pct, opened_ms=None):
"""Append a futures closure to the rolling closed-log (last 100)."""
log = state.setdefault("fut_closed_log", [])
log.append({
"symbol": symbol, "source": source, "regime": regime,
"pnl": round(float(pnl), 2), "invested": round(float(invested), 2),
"leverage": int(leverage or 3),
"tp_pct": tp_pct, "sl_pct": sl_pct,
"opened_ms": int(opened_ms) if opened_ms else None,
"closed_ms": int(time.time() * 1000),
})
del log[:-100]
@app.get("/positions/active")
def positions_active():
"""All open Bybit linear (USDT) futures positions.
Includes per-symbol funding profit from the last 7 days of funding
settlements (the transaction-log window cap) — enough to cover recent
riser/grid positions in full.
"""
now_ms = int(time.time() * 1000)
try:
r = bybit_get("/v5/position/list",
{"category": "linear", "settleCoin": "USDT", "limit": "200"})
lst = (r.get("result", {}) or {}).get("list") or []
except Exception:
lst = []
pos = [p for p in lst if abs(float(p.get("size") or 0)) > 0]
funding = {}
start = now_ms - 7 * 86400 * 1000
for p in pos:
sym = p.get("symbol")
if sym in funding:
continue
total = 0.0
cursor = None
for page in range(10):
params = {"accountType": "UNIFIED",
"startTime": str(start), "endTime": str(now_ms),
"limit": "50"}
if cursor:
params["cursor"] = cursor
try:
r2 = bybit_get("/v5/account/transaction-log", params)
except Exception:
break
res = r2.get("result", {}) or {}
entries = res.get("list") or []
cursor = res.get("nextPageCursor")
for e in entries:
if (e.get("type") == "SETTLEMENT"
and e.get("symbol") == sym):
total += float(e.get("funding") or 0)
if not cursor or not entries:
break
funding[sym] = round(total, 4)
# Join tracked entries to identify the source (riser / upward / manual)
try:
st = load_state()
except Exception:
st = {}
riser_map, pos_map = {}, {}
for t in (st.get("riser_positions") or []):
if t.get("symbol"):
riser_map[str(t["symbol"]).upper()] = t
for t in (st.get("positions") or []):
if t.get("symbol"):
pos_map[str(t["symbol"]).upper()] = t
out = []
for p in pos:
try:
unrl = float(p.get("unrealisedPnl") or 0)
real = float(p.get("curRealisedPnl") or 0)
except (TypeError, ValueError):
unrl = real = 0.0
sym_up = str(p.get("symbol") or "").upper()
if sym_up in riser_map:
src = "Rising Coin"
regime = "downward"
elif sym_up in pos_map:
raw_src = str(pos_map[sym_up].get("source") or "riser")
src = raw_src.title()
regime = "upward" if raw_src == "upward" else "downward"
else:
# Untracked positions are manual buys from the rising-coin page
# (the downward-regime flow) — the only manual entry point.
src = "Manual"
regime = "downward"
rec = riser_map.get(sym_up) or pos_map.get(sym_up) or {}
out.append({
"symbol": p.get("symbol"),
"source": src,
"regime": regime,
"tp_pct": rec.get("tp_pct"),
"sl_pct": rec.get("sl_pct"),
"take_profit_price": p.get("takeProfit"),
"stop_loss_price": p.get("stopLoss"),
"side": p.get("side"),
"leverage": p.get("leverage"),
"size": p.get("size"),
"invested": round(float(p.get("positionIM") or 0), 2),
"avg_price": p.get("avgPrice"),
"mark_price": p.get("markPrice"),
"funding_profit": funding.get(p.get("symbol"), 0.0),
"realised_pnl": round(real, 4),
"unrealised_pnl": round(unrl, 4),
"pnl": round(unrl + real, 4),
# Prefer our own trade record's open time: Bybit's position
# createdTime can persist from an earlier position on the
# same symbol (one-way mode re-entry), overstating duration.
"opened_ms": rec.get("opened_ms") or p.get("createdTime"),
})
return json.dumps(out)
@app.get("/funding/summary")
def funding_summary():
"""Funding fees received/paid over the last 7 and 30 days.
Reads SETTLEMENT entries from the Bybit transaction log (every 8-hour
funding settlement lands there with the amount in `funding`). The API
caps each query at a 7-day window, so 30 days = 5 windows, each paged
with the cursor.
"""
now_ms = int(time.time() * 1000)
out = {}
for label, days in (("d7", 7), ("d30", 30)):
by_sym = {}
received = paid = 0.0
n_settle = 0
for w in range(0, days, 7):
end_ms = now_ms - w * 86400 * 1000
start_ms = end_ms - 7 * 86400 * 1000
cursor = None
for page in range(20):
# NB: don't pass type=SETTLEMENT — Bybit silently returns
# nothing for it; filter client-side instead.
params = {"accountType": "UNIFIED",
"startTime": str(start_ms), "endTime": str(end_ms),
"limit": "50"}
if cursor:
params["cursor"] = cursor
try:
r = bybit_get("/v5/account/transaction-log", params)
except Exception:
break
res = r.get("result", {}) or {}
lst = res.get("list") or []
cursor = res.get("nextPageCursor")
for e in lst:
if e.get("type") != "SETTLEMENT":
continue
amt = float(e.get("funding") or 0)
if amt == 0:
continue
n_settle += 1
sym = e.get("symbol") or "?"
by_sym[sym] = round(by_sym.get(sym, 0.0) + amt, 4)
if amt > 0:
received += amt
else:
paid -= amt
if not cursor or not lst:
break
out[label] = {
"received": round(received, 4),
"paid": round(paid, 4),
"net": round(received - paid, 4),
"settlements": n_settle,
"by_symbol": {k: v for k, v in sorted(by_sym.items(),
key=lambda kv: -abs(kv[1]))},
}
return json.dumps(out)
@app.get("/grid/equity-history")
def grid_equity_history():
"""Recorded equity snapshots: [{ms, equity}, ...] (15-min cadence)."""
return json.dumps(load_state().get("equity_history", []))
@app.get("/healthz")
def healthz():
return "ok"
import os
import json
import math
import time
import hmac
import hashlib
import urllib.request
import urllib.parse
from flask import Flask, request
from google.cloud import storage
import re as _re_full
from datetime import datetime, timezone, timedelta
app = Flask(__name__)
# ---------------------------------------------------------------------------
# Config (env-driven; secrets injected by Cloud Run)
# ---------------------------------------------------------------------------
BYBIT_API_KEY = os.environ.get("BYBIT_API_KEY", "")
BYBIT_API_SECRET = os.environ.get("BYBIT_API_SECRET", "")
BYBIT_HOST = os.environ.get("BYBIT_HOST", "https://api.bybit.com") # mainnet
CATEGORY = os.environ.get("BYBIT_CATEGORY", "spot") # spot (no leverage)
DRY_RUN = os.environ.get("DRY_RUN", "true").lower() in ("1", "true", "yes")
SCANNER_URL = os.environ.get("SCANNER_URL", "https://blind-monkeys-scanner-353804379600.europe-west1.run.app")
ORDER_NOTIONAL = float(os.environ.get("ORDER_NOTIONAL", "100")) # $100 seed per trade
TAKE_PROFIT_PCT = float(os.environ.get("TAKE_PROFIT_PCT", "3")) # +3%
STOP_LOSS_PCT = float(os.environ.get("STOP_LOSS_PCT", "5")) # -5%
MAX_POSITIONS = int(os.environ.get("MAX_POSITIONS", "3"))
MAX_DAILY_BUY = float(os.environ.get("MAX_DAILY_BUY", "500"))
AMOUNT_FLOOR = float(os.environ.get("AMOUNT_FLOOR", "10")) # compounding floor
# Compounding feedback-loop defaults (seed amount is always $100)
INCREASE_PCT = float(os.environ.get("INCREASE_PCT", "25")) # +25% on TP
DECREASE_PCT = float(os.environ.get("DECREASE_PCT", "25")) # -25% on SL
STATE_BUCKET = os.environ.get("STATE_BUCKET", "blind-monkeys-trader-state")
STATE_OBJECT = "config.json"
BALANCE_HISTORY_OBJECT = "balance_history.json"
SCORE_WEIGHTS_HISTORY_OBJECT = "score_weights_history.json"
UPWARD_WEIGHTS_HISTORY_OBJECT = "upward_weights_history.json"
TELEGRAM_BOT_TOKEN = os.environ["TELEGRAM_BOT_TOKEN"]
TELEGRAM_CHAT_ID = os.environ["TELEGRAM_CHAT_ID"]
# Strong-tier constants (matches the "star" in the Rising Coins app)
STRONG_TOP_N = 100
STRONG_MIN_RISE = 2.0
STRONG_MIN_VOLUME = 5_000_000
STRONG_MIN_RATIO = 2.0
# Grid-opportunity scan constants (range-bound detection)
GRID_TOP_N = 100
GRID_MIN_WIDTH = 3.0 # % min 7d range width
GRID_MAX_WIDTH = 25.0 # % max 7d range width
GRID_MIN_OSC = 4 # min midpoint oscillations
GRID_DRIFT_RATIO = 0.6 # net drift must be < ratio * width
GRID_LOOKBACK_H = 168 # 7d hourly candles
GRID_SNAP_H = 24 # 24h snapshot
BINANCE_FUTURES = "https://fapi.binance.com"
COINGECKO = "https://api.coingecko.com/api/v3"
# ---------------------------------------------------------------------------
# HTTP helpers
# ---------------------------------------------------------------------------
def http_json(url, retries=3, timeout=20):
last = None
for i in range(retries):
try:
req = urllib.request.Request(url, headers={"User-Agent": "Mozilla/5.0"})
with urllib.request.urlopen(req, timeout=timeout) as r:
return json.loads(r.read().decode())
except Exception as e:
last = e
time.sleep(1.5 * (i + 1))
raise last
def top_symbols(n):
url = (f"{COINGECKO}/coins/markets?vs_currency=usd&order=market_cap_desc"
f"&per_page={n}&page=1&sparkline=false")
out = {}
for c in http_json(url):
s = (c.get("symbol") or "").upper()
out.setdefault(s, []).append(c.get("market_cap_rank"))
return {s: v[0] for s, v in out.items() if len(v) == 1 and v[0]}
def futures_symbols():
data = http_json(f"{BINANCE_FUTURES}/fapi/v1/exchangeInfo")
return {s["baseAsset"] for s in data["symbols"]
if s.get("contractType") == "PERPETUAL" and s.get("quoteAsset") == "USDT"
and s.get("status") == "TRADING"}
def one_hour(sym):
k = http_json(f"{BINANCE_FUTURES}/fapi/v1/klines?symbol={sym}USDT&interval=1h&limit=169")
if len(k) < 169: