OPEN-SOURCE SCRIPT
AetherEdge - Transformer-Inspired Attention Bias

🖊️ Overview
A Transformer-style attention mechanism rendered in Pine — an engine for the selective focus of memory. Just as a Transformer attends selectively to the most relevant elements of a sequence, this engine treats the current bar as a query and every recent bar as a key/value. It scores each past bar's relevance via scaled dot-product (Q·Kᵀ/√d), normalizes the scores with softmax, and forms a weighted blend of those bars' directional signals — automatically focusing on the past patterns that matter most right now to compute the current bias (bullish/bearish). Several heads run in parallel, each learning a different notion of relevance, then merge into one directional bias. Visualization: an Attention Heatbar across the top of the chart (a horizontal strip whose brightness shows how much attention each point in recent time receives) plus one main bias arrow — a Transformer-style "selective focus of memory" in Pine.
🔶 Key Features
Multi-head attention — scaled dot-product attention (Q·Kᵀ/√d → softmax → ·V) reproduced in Pine
Selective focus of memory — automatically focuses on important past bars while suppressing noisy ones
Multiple heads — heads learn different relevance notions in parallel, merging into one bias
Positional encoding — an optional recency signal so the model knows how far back each bar is
Attention Heatbar — visualizes time-axis importance as a horizontal strip above price (brighter = more attention, tinted by bias)
Main bias arrow — the post-attention directional bias shown as one arrow (with glow)
Temperature parameter — softmax temperature tunes between sharp focus on a single bar and diffuse attention
Intelligence panel — attention bias, focus sharpness and distance (how far back focus sits), head count, context length, and more
🧠 Technical Architecture
Each bar is encoded into a small feature "token": momentum, RSI deviation, one-bar return, and range width (all normalized). Each bar is also assigned a directional "value" value = tanh(...) capturing its bullish/bearish lean.
The core is multi-head attention. The current bar's token is projected by Wq into a d-dim query q; each of the past ctxLen bars' tokens is projected by Wk into kᵢ. Attention scores are the scaled dot-product score_i = (q·kᵢ)/√d / temperature, where √d scaling ensures gradient stability. With positional encoding enabled, a recency signal is added to the keys. The scores are normalized by softmax into weights wᵢ, and the past bars' values are blended as Σ wᵢ·valueᵢ — that head's bias. Since each head has distinct projection weights, each captures a different relevance, merged via head output weights Wo.
A key implementation detail: Pine's [] history operator cannot take a loop variable, so past tokens are accumulated into rolling arrays and accessed dynamically via array.get(idx). Attention weights are aggregated into time-axis buckets and shown, normalized, as the Attention Heatbar (a brighter cell = stronger attention to that bar). The final bias is EMA-smoothed, and the main arrow fires when it clears the gate.
⚙️ Recommended Settings & Tuning Guide
BTC (1H–4H): Context Window 40, Heads 3, Key Dim 4, Temperature 1.0. Standard settings fit well
ETH (1H–4H): As BTC, with Context Window 50 for slightly longer memory
SOL (15m–1H): High volatility favors Temperature ≈ 0.7 for sharp focus, Heads 4 to capture diverse relevance
XRP (1H–4H): Spike-prone; Context Window ≈ 30 to emphasize recency, Position Encoding ON
Context Window: longer references further back but is heavier; 30–60 is practical
Heads: more captures more relevance notions but adds compute; 2–4 is readable
Temperature: low (0.5–0.8) sharply focuses on the single most relevant bar; high (1.5–3) gives diffuse, smooth attention
Min |Bias| to Signal: higher makes arrows more selective — tune to your trade frequency
💡 How to Use in Practice
Reading the Heatbar: a bright cell means that bar strongly drives the current bias. Bright on the right (recent) = short-term pattern leads; bright on the left (older) = a past important moment is recurring
Reacting to the main arrow: the arrow is the verdict where multi-head attention's merged bias clears the gate — a core basis for trend-following entries
Using focus distance: small panel "Focus Distance" = recency-driven; large = attending to far-back patterns, suggesting recurrence of a past analog
Focus sharpness: high = attention concentrated on one point (clear pattern recognition); low = diffuse (ambiguous)
Pairing with temperature: if the heatbar is wide and faint, lower the temperature to sharpen focus and clarify what the engine attends to
Multi-timeframe usage: confirm the big-picture bias on the higher timeframe (4H), then refine timing on arrows on the lower one (15m–1H)
⚠️ Important Notes
Initial context period: attention is incomplete until the context window (ctxLen) fills; treat the bias as low-confidence until enough past bars accumulate
Effect of setting changes: changing parameters, switching symbol/timeframe, or recompiling reinitializes the projection weights and token history
On learning: the projection weights are seed-initialized fixed weights used to compute attention patterns; this tool does not update weights from reward — it focuses on visualizing the attention mechanism itself
Heatbar placement: the heatbar draws above price, so adjust Heatbar Height to avoid overlapping the candles
Adaptive-system nature: historical and live behavior can differ — always forward-test
Constraints: this is a lightweight implementation operating within Pine's compute budget; Context × Heads × Key Dim drives compute load, so extreme settings affect performance
🚨 Disclaimer
This indicator is an analytical and educational visualization tool. The attention mechanism, multi-head attention, positional encoding, bias computation, and Attention Heatbar are quantitative heuristics computed on-chart from price data — they are not financial advice, buy/sell signals, or any guarantee of future performance. Always combine any tool with your own analysis and disciplined risk management.
A Transformer-style attention mechanism rendered in Pine — an engine for the selective focus of memory. Just as a Transformer attends selectively to the most relevant elements of a sequence, this engine treats the current bar as a query and every recent bar as a key/value. It scores each past bar's relevance via scaled dot-product (Q·Kᵀ/√d), normalizes the scores with softmax, and forms a weighted blend of those bars' directional signals — automatically focusing on the past patterns that matter most right now to compute the current bias (bullish/bearish). Several heads run in parallel, each learning a different notion of relevance, then merge into one directional bias. Visualization: an Attention Heatbar across the top of the chart (a horizontal strip whose brightness shows how much attention each point in recent time receives) plus one main bias arrow — a Transformer-style "selective focus of memory" in Pine.
🔶 Key Features
Multi-head attention — scaled dot-product attention (Q·Kᵀ/√d → softmax → ·V) reproduced in Pine
Selective focus of memory — automatically focuses on important past bars while suppressing noisy ones
Multiple heads — heads learn different relevance notions in parallel, merging into one bias
Positional encoding — an optional recency signal so the model knows how far back each bar is
Attention Heatbar — visualizes time-axis importance as a horizontal strip above price (brighter = more attention, tinted by bias)
Main bias arrow — the post-attention directional bias shown as one arrow (with glow)
Temperature parameter — softmax temperature tunes between sharp focus on a single bar and diffuse attention
Intelligence panel — attention bias, focus sharpness and distance (how far back focus sits), head count, context length, and more
🧠 Technical Architecture
Each bar is encoded into a small feature "token": momentum, RSI deviation, one-bar return, and range width (all normalized). Each bar is also assigned a directional "value" value = tanh(...) capturing its bullish/bearish lean.
The core is multi-head attention. The current bar's token is projected by Wq into a d-dim query q; each of the past ctxLen bars' tokens is projected by Wk into kᵢ. Attention scores are the scaled dot-product score_i = (q·kᵢ)/√d / temperature, where √d scaling ensures gradient stability. With positional encoding enabled, a recency signal is added to the keys. The scores are normalized by softmax into weights wᵢ, and the past bars' values are blended as Σ wᵢ·valueᵢ — that head's bias. Since each head has distinct projection weights, each captures a different relevance, merged via head output weights Wo.
A key implementation detail: Pine's [] history operator cannot take a loop variable, so past tokens are accumulated into rolling arrays and accessed dynamically via array.get(idx). Attention weights are aggregated into time-axis buckets and shown, normalized, as the Attention Heatbar (a brighter cell = stronger attention to that bar). The final bias is EMA-smoothed, and the main arrow fires when it clears the gate.
⚙️ Recommended Settings & Tuning Guide
BTC (1H–4H): Context Window 40, Heads 3, Key Dim 4, Temperature 1.0. Standard settings fit well
ETH (1H–4H): As BTC, with Context Window 50 for slightly longer memory
SOL (15m–1H): High volatility favors Temperature ≈ 0.7 for sharp focus, Heads 4 to capture diverse relevance
XRP (1H–4H): Spike-prone; Context Window ≈ 30 to emphasize recency, Position Encoding ON
Context Window: longer references further back but is heavier; 30–60 is practical
Heads: more captures more relevance notions but adds compute; 2–4 is readable
Temperature: low (0.5–0.8) sharply focuses on the single most relevant bar; high (1.5–3) gives diffuse, smooth attention
Min |Bias| to Signal: higher makes arrows more selective — tune to your trade frequency
💡 How to Use in Practice
Reading the Heatbar: a bright cell means that bar strongly drives the current bias. Bright on the right (recent) = short-term pattern leads; bright on the left (older) = a past important moment is recurring
Reacting to the main arrow: the arrow is the verdict where multi-head attention's merged bias clears the gate — a core basis for trend-following entries
Using focus distance: small panel "Focus Distance" = recency-driven; large = attending to far-back patterns, suggesting recurrence of a past analog
Focus sharpness: high = attention concentrated on one point (clear pattern recognition); low = diffuse (ambiguous)
Pairing with temperature: if the heatbar is wide and faint, lower the temperature to sharpen focus and clarify what the engine attends to
Multi-timeframe usage: confirm the big-picture bias on the higher timeframe (4H), then refine timing on arrows on the lower one (15m–1H)
⚠️ Important Notes
Initial context period: attention is incomplete until the context window (ctxLen) fills; treat the bias as low-confidence until enough past bars accumulate
Effect of setting changes: changing parameters, switching symbol/timeframe, or recompiling reinitializes the projection weights and token history
On learning: the projection weights are seed-initialized fixed weights used to compute attention patterns; this tool does not update weights from reward — it focuses on visualizing the attention mechanism itself
Heatbar placement: the heatbar draws above price, so adjust Heatbar Height to avoid overlapping the candles
Adaptive-system nature: historical and live behavior can differ — always forward-test
Constraints: this is a lightweight implementation operating within Pine's compute budget; Context × Heads × Key Dim drives compute load, so extreme settings affect performance
🚨 Disclaimer
This indicator is an analytical and educational visualization tool. The attention mechanism, multi-head attention, positional encoding, bias computation, and Attention Heatbar are quantitative heuristics computed on-chart from price data — they are not financial advice, buy/sell signals, or any guarantee of future performance. Always combine any tool with your own analysis and disciplined risk management.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.
Script de código aberto
Em verdadeiro espírito do TradingView, o criador deste script o tornou de código aberto, para que os traders possam revisar e verificar sua funcionalidade. Parabéns ao autor! Embora você possa usá-lo gratuitamente, lembre-se de que a republicação do código está sujeita às nossas Regras da Casa.
Aviso legal
As informações e publicações não se destinam a ser, e não constituem, conselhos ou recomendações financeiras, de investimento, comerciais ou de outro tipo fornecidos ou endossados pela TradingView. Leia mais nos Termos de Uso.