# Adapted from DOMENEC UNIFICADO, © IbraShipping. # This Source Code Form is subject to the Mozilla Public License, v. 2.0. # https://mozilla.org/MPL/2.0/ """Closed-candle implementation. No orders are submitted by this application.""" import math from collections import deque DEFAULTS = dict(ema=8, williams=40, adx=7, pivot=5, trailing=2, ticks=2, fallback=10, filter_genial=False, two_closes=True, reference='Zona completa', window=500, fvg_mode='Cierre', fvg_max=35) def ema(values, period): out, prev = [], None for value in values: if value is not None: prev = value if prev is None else prev + 2 / (period + 1) * (value - prev) out.append(prev) return out def sma(values, period): out, q = [], deque() for value in values: q.append(value) if len(q) > period: q.popleft() out.append(sum(q) / period if len(q) == period and None not in q else None) return out def rma(values, period): out, seed, prev = [], [], None for value in values: if value is not None: if prev is None: seed.append(value) if len(seed) >= period: prev = sum(seed[-period:]) / period else: prev = (prev * (period - 1) + value) / period out.append(prev) return out def dema(values, period): first = ema(values, period) return [2 * a - b if a is not None and b is not None else None for a, b in zip(first, ema(first, period))] def stddev(values, period): avg = sma(values, period) return [math.sqrt(sum((v - avg[i]) ** 2 for v in values[i-period+1:i+1]) / period) if avg[i] is not None else None for i in range(len(values))] def alma(values, period, offset=.85, sigma=4): weights = [math.exp(-((k - offset * (period - 1)) ** 2) / (2 * (period / sigma) ** 2)) for k in range(period)] total = sum(weights) return [sum(v * w for v, w in zip(values[i-period+1:i+1], weights)) / total if i >= period - 1 else None for i in range(len(values))] def pivot(values, i, width, high): j = i - width if j < width: return None # Pine resolves equal pivots in favour of the rightmost occurrence. left, right, v = values[j-width:j], values[j+1:i+1], values[j] ok = all(v >= x for x in left) and all(v > x for x in right) if high else all(v <= x for x in left) and all(v < x for x in right) return v if ok else None def genial(bars, macro=False): close = [b['close'] for b in bars] if not close: return [] smooth, sp = [], close[0] for i, value in enumerate(close): if macro and i > 0 or not macro and i > 1: sp = (sp * 19 + value) / 20 smooth.append(sp) return [(a + b) / 2 if b is not None else None for a, b in zip(smooth, sma(close, 34))] def macro_summary(bars): g = genial(bars, True) if len(g) < 2 or g[-1] is None or g[-2] is None: return dict(value=None, direction='Sin datos', position='—', asof=None) return dict(value=g[-1], direction='Sube' if g[-1] > g[-2] else 'Baja' if g[-1] < g[-2] else 'Lateral', position='Encima' if bars[-1]['close'] > g[-1] else 'Debajo' if bars[-1]['close'] < g[-1] else 'En línea', asof=bars[-1]['time']) def calculate(bars, settings=None, tick=.01): cfg = DEFAULTS | (settings or {}) c, h, l = ([b[k] for b in bars] for k in ('close', 'high', 'low')) size = len(c) if not size: raise ValueError('No hay velas') gen = genial(bars) fast = ema(c, cfg['ema']) wilder, prev = [], 0 smooth_range, sr = [], 0 for i, value in enumerate(c): prev = (prev * 7 + value) / 8 wilder.append(prev) if i > 1: sr = (sr * 19 + h[i] - l[i]) / 20 smooth_range.append(sr) sp, p = [], c[0] for i, value in enumerate(c): if i > 1: p = (p * 19 + value) / 20 sp.append(p) upper = dema([a + b * math.pi for a, b in zip(sp, smooth_range)], 20) lower = dema([a - b * math.pi for a, b in zip(sp, smooth_range)], 20) ribbons = {str(n): ema(c, n) for n in (21, 34, 55, 89, 120, 160)} tr = [None if not i else max(h[i] - l[i], abs(h[i] - c[i-1]), abs(l[i] - c[i-1])) for i in range(size)] plus, minus = [None], [None] for i in range(1, size): up, down = h[i] - h[i-1], l[i-1] - l[i] plus.append(up if up > down and up > 0 else 0) minus.append(down if down > up and down > 0 else 0) rt, rp, rm = rma(tr, cfg['adx']), rma(plus, cfg['adx']), rma(minus, cfg['adx']) dx, lastp, lastm = [], None, None for a, b, t in zip(rp, rm, rt): if a is not None and t: lastp, lastm = 100 * a / t, 100 * b / t dx.append(abs(lastp-lastm) / ((lastp+lastm) or 1) if lastp is not None else None) adx = [100 * v if v is not None else None for v in rma(dx, cfg['adx'])] wpr = [] for i in range(size): hi, lo = max(h[max(0, i-cfg['williams']+1):i+1]), min(l[max(0, i-cfg['williams']+1):i+1]) wpr.append(-100 * (hi-c[i]) / (hi-lo) if hi != lo else None) osc = [] for i in range(size): hi, lo = max(h[max(0, i-7):i+1]), min(l[max(0, i-7):i+1]) osc.append((c[i]-lo) / (hi-lo) * 100 if hi != lo else 50) osc = dema(osc, 3) af, slow = alma(c, 15), alma(c, 25) alma_values = [a-b if a is not None and b is not None else None for a, b in zip(af, slow)] cond1 = [(max(c[max(0,i-29):i+1])-c[i]) / max(c[max(0,i-29):i+1]) for i in range(size)] cond2 = sma(c, 30) av1, sd1, av2, sd2 = sma(cond1, 120), stddev(cond1, 120), sma(cond2, 120), stddev(cond2, 120) pos, entry, entry_bar, stop, count, bias = 0, None, -1, None, 0, 0 support = resistance = last_low = last_high = None trades, events, gaps, rows, divergences = [], [], [], [], [] event = 'Esperando ruptura válida' margin = cfg['ticks'] * tick for i, bar in enumerate(bars): close, high, low = c[i], h[i], l[i] n, t = cfg['pivot'], cfg['trailing'] ph, pl = pivot(h, i, n, True), pivot(l, i, n, False) phs, pls = pivot(h, i, t, True), pivot(l, i, t, False) if pls is not None: last_low = pls if phs is not None: last_high = phs zhi, zlo = max(fast[i], wilder[i]), min(fast[i], wilder[i]) ready = i > 0 and gen[i-1] is not None if ready and gen[i] != gen[i-1]: bias = 1 if gen[i] > gen[i-1] else -1 phase = 'Esperando datos' if ready: phase = ('Impulso alcista' if close > zhi else 'Corrección del sesgo alcista') if bias == 1 and close > gen[i] else ('Impulso bajista' if close < zlo else 'Corrección del sesgo bajista') if bias == -1 and close < gen[i] else 'Transición / sin alineación' refl = refc = None if cfg['reference'] == 'EMA 8': refl = refc = fast[i] elif cfg['reference'] == 'Wilder 8': refl = refc = wilder[i] elif cfg['reference'] == 'Genial': refl = refc = gen[i] else: refl, refc = zlo, zhi signal = None oldstop = stop if pos: contrary = ready and (close < refl if pos == 1 else close > refc) count = count + 1 if contrary else 0 hit = low <= stop if pos == 1 else high >= stop if hit or cfg['two_closes'] and count >= 2: exit_price = stop if hit else close ret = (exit_price / entry - 1) * 100 if pos == 1 else (entry / exit_price - 1) * 100 trades.append(dict(entry_time=bars[entry_bar]['time'], time=bar['time'], bar=i, side=pos, entry=entry, exit=exit_price, pct=ret, reason='Stop' if hit else 'Dos cierres')) signal = 'exit_long' if pos == 1 else 'exit_short' event = ('Stop largo' if pos == 1 else 'Stop corto') + ' tocado' if hit else 'Salida por dos cierres' pos, stop, entry = 0, None, None else: pv = pls if pos == 1 else phs if pv is not None and i-t > entry_bar: candidate = pv-margin if pos == 1 else pv+margin if (stop < candidate < close) if pos == 1 else (close < candidate < stop): stop = candidate signal = 'stop' event = 'Subir stop' if pos == 1 else 'Bajar stop' if cfg['two_closes'] and count == 1 and signal is None: signal = 'warning' event = 'Primer cierre contrario' else: count = 0 up = resistance is not None and i > 0 and close > resistance and c[i-1] <= resistance down = support is not None and i > 0 and close < support and c[i-1] >= support allow_l = not cfg['filter_genial'] or ready and close > gen[i] and gen[i] > gen[i-1] allow_s = not cfg['filter_genial'] or ready and close < gen[i] and gen[i] < gen[i-1] if ready and up and not down and close > zhi and allow_l: pos, entry, entry_bar = 1, close, i stop = last_low-margin if last_low is not None and last_low-margin < close else min(l[max(0,i-cfg['fallback']+1):i+1])-margin signal, event = 'long', 'Entrada larga orientativa' elif ready and down and not up and close < zlo and allow_s: pos, entry, entry_bar = -1, close, i stop = last_high+margin if last_high is not None and last_high+margin > close else max(h[max(0,i-cfg['fallback']+1):i+1])+margin signal, event = 'short', 'Entrada corta orientativa' if ph is not None: resistance = ph if pl is not None: support = pl if signal: events.append(dict(time=bar['time'], type=signal, price=close, text=event, stop=stop)) gaps = [g for g in gaps if not ((close if cfg['fvg_mode'] == 'Cierre' else low) < g['bottom'] if g['side'] == 1 else (close if cfg['fvg_mode'] == 'Cierre' else high) > g['top'])] if i >= 2: side = 1 if low-h[i-2] >= tick else -1 if l[i-2]-high >= tick else 0 if side: gaps.append(dict(time=bars[i-2]['time'], side=side, top=low if side == 1 else l[i-2], bottom=h[i-2] if side == 1 else high)) gaps = gaps[-cfg['fvg_max']:] if i > 36: prior_o, prior_c = osc[i-26:i-1], c[i-26:i-1] bearish = osc[i-1] > osc[i] and osc[i-1] > osc[i-2] and osc[i-1] < max(prior_o) and c[i-1] > max(prior_c) bullish = osc[i-1] < osc[i] and osc[i-1] < osc[i-2] and osc[i-1] > min(prior_o) and c[i-1] < min(prior_c) if bearish or bullish: target = max(prior_c) if bearish else min(prior_c) j = next(j for j in range(i-2, i-27, -1) if c[j] == target) divergences.append(dict(start=bars[j]['time'], end=bars[i-1]['time'], a=target, b=c[i-1], side=-1 if bearish else 1)) color = '#808080' if i and None not in (wpr[i], wpr[i-1], adx[i], adx[i-1]): w, wp, a, ap = wpr[i], wpr[i-1], adx[i], adx[i-1] rules = [(w < -50 and a >= ap and w > wp, '#00ff00'), (w > -50 and w < -27 and a >= ap and w > wp, '#78b946'), (w > -27 and a >= ap and w > wp, '#466446'), (w > -50 and a <= ap and w < wp, '#fffa00'), (w < -50 and a <= ap and w < wp, '#fa8c00'), (w > -50 and a >= ap and w < wp, '#ff0000'), (w < -50 and w > -72 and a >= ap and w < wp, '#d23c82'), (w < -72 and a >= ap and w < wp, '#642832'), (w < -50 and a <= ap and w > wp, '#00ffff'), (w > -50 and a <= ap and w > wp, '#1eb4e6'), (w < -50 <= wp, '#ff00ff'), (w > -50 >= wp, '#000096')] for condition, clr in rules: if condition: color = clr exhausted = av1[i] is not None and av2[i] is not None and cond1[i] > av1[i]+sd1[i] and cond2[i] < av2[i]-sd2[i] rows.append(dict(**bar, genial=gen[i], ema=fast[i], wilder=wilder[i], upper=upper[i], lower=lower[i], middle=sp[i], ribbons={k:v[i] for k,v in ribbons.items()}, color=color, stop=oldstop, next_stop=stop, signal=signal, exhausted=exhausted, alma=alma_values[i])) recent = [t for t in trades if t['bar'] > size-1-cfg['window']] wins = sum(t['pct'] > 0 for t in recent) profit, loss = sum(max(t['pct'], 0) for t in recent), -sum(min(t['pct'], 0) for t in recent) return dict(bars=rows, gaps=gaps, divergences=divergences[-100:], events=events[-100:], trades=recent, stats=dict(total=len(recent), wins=wins, win_rate=wins/len(recent)*100 if recent else None, average=sum(t['pct'] for t in recent)/len(recent) if recent else None, total_pct=sum(t['pct'] for t in recent), factor=profit/loss if loss else None, window=cfg['window']), state=dict(phase=phase, bias=bias, position=pos, entry=entry, stop=stop, contrary=count, event=event, support=support, resistance=resistance), settings=cfg)