本页源码来自 TradingView 公开发布的开源脚本,版权归原作者所有, 请遵循其原始许可(Pine 脚本常见 CC BY-NC-SA / MPL-2.0 / MIT)。 本项目仅用于研究检索与许可范围内的移植。
// This Pine Script® code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © GoofyFarmer
//
// Appreciation to Ata Sabanci (@ata_sabanci) for sharing his work on the Isotropic
// Coordinate System (ICS) on TradingView, providing a solid launchpad to bounce ideas
// off of and extend scale-invariant geometry into multi-dimensional state space.
//
//@version=6
// @description Provides 4-dimensional unit-sphere vector normalization, scale-invariant isotropic angle conversion,
// algebraic sigmoid mapping, and a zero-sqrt cosine similarity associative memory bank for Pine Script v6.
// Each 4D state vector is normalized to unit length (L2 norm = 1.0) once upon insertion so that historical
// similarity queries execute as fast dot products inside the loop.
library("IsotropicVectorSpace", overlay = true)
// ============================================================================
// 1. EXPORTED DATA STRUCTURE (4D UNIT-SPHERE RECORD)
// ============================================================================
// @type Pre-normalized 4-dimensional unit vector memory record.
// Stored coordinates (u1..u4) satisfy sqrt(u1^2 + u2^2 + u3^2 + u4^2) == 1.0.
// @field u1 Unit-normalized coordinate 1.
// @field u2 Unit-normalized coordinate 2.
// @field u3 Unit-normalized coordinate 3.
// @field u4 Unit-normalized coordinate 4.
// @field ev Primary scalar value associated with this state vector (e.g., structural score or response metric).
// @field mfe Optional auxiliary scalar 1 (pass 0.0 if unused).
// @field mae Optional auxiliary scalar 2 (pass 0.0 if unused).
export type VectorMem
float u1
float u2
float u3
float u4
float ev
float mfe
float mae
// ============================================================================
// 2. EXPORTED GEOMETRIC NORMALIZATION UTILITIES
// ============================================================================
// @function Converts a price displacement into local volatility units and a zoom-invariant isotropic angle in degrees.
// A displacement of ±(atr_mult * atr_val) maps to exactly ±45 degrees, independent of chart zoom or aspect ratio.
// @param delta_price Net price displacement over the chosen lookback window.
// @param atr_val Local volatility reference (e.g., ta.atr(14)).
// @param atr_mult Volatility multiplier defining the ±45° reference threshold (default = 2.0).
// @returns Tuple: [z_volatility_units, theta_degrees, f_bounded_in_neg1_to_pos1].
export to_isotropic(series float delta_price, series float atr_val, simple float atr_mult = 2.0) =>
float safe_atr = math.max(not na(atr_val) ? atr_val : syminfo.mintick * 10.0, syminfo.mintick)
float z = delta_price / (atr_mult * safe_atr)
float ang = math.atan(z)
float theta_deg = ang * (180.0 / math.pi)
float f_norm = ang / (0.5 * math.pi)
[z, theta_deg, f_norm]
// @function Fast algebraic sigmoid x / sqrt(1 + x^2). Smoothly maps any unbounded value into (-1.0, +1.0)
// without transcendental exponential calls.
// @param x Raw unbounded input value.
// @returns Bounded float in the range (-1.0, +1.0).
export sigmoid_fast(series float x) =>
float val = not na(x) ? x : 0.0
val / math.sqrt(1.0 + val * val)
// @function Zero-centered bipolar standardization: centers a raw metric around its neutral midpoint and maps it into (-1.0, +1.0).
// Prevents all-positive features from clustering in the positive orthant during cosine similarity comparisons.
// @param raw_val Raw input metric.
// @param center Neutral midpoint of the metric (e.g., 50.0 for RSI, 1.0 for relative volume).
// @param scale Sensitivity gain applied prior to algebraic squashing.
// @returns Zero-centered bipolar coordinate in (-1.0, +1.0).
export bipolar_norm(series float raw_val, simple float center = 0.0, simple float scale = 1.0) =>
float z = (not na(raw_val) ? raw_val - center : 0.0) * scale
z / math.sqrt(1.0 + z * z)
// ============================================================================
// 3. EXPORTED 4D VECTOR MEMORY & COSINE SIMILARITY METHODS
// ============================================================================
// @function Normalizes a 4D feature vector (f1..f4) onto the unit 3-sphere S^3 and appends it to the FIFO memory bank.
// Because vectors are normalized once upon insertion, subsequent similarity queries require no square roots per row.
// @param self Target `array<VectorMem>` memory bank instance.
// @param f1 Raw or bounded feature 1.
// @param f2 Raw or bounded feature 2.
// @param f3 Raw or bounded feature 3.
// @param f4 Raw or bounded feature 4 (pass 0.0 for 3D vectors).
// @param ev Primary scalar value to associate with this vector.
// @param mfe Optional auxiliary scalar 1 (default = 0.0).
// @param mae Optional auxiliary scalar 2 (default = 0.0).
// @param cap Maximum FIFO capacity of the memory bank (default = 200).
// @returns void (mutates `self` in place).
export method insert(array<VectorMem> self, series float f1, series float f2, series float f3, series float f4, series float ev, series float mfe = 0.0, series float mae = 0.0, simple int cap = 200) =>
if not (na(f1) or na(f2) or na(f3) or na(f4))
float inv_norm = 1.0 / math.sqrt(f1 * f1 + f2 * f2 + f3 * f3 + f4 * f4 + 1e-12)
array.push(self, VectorMem.new(f1 * inv_norm, f2 * inv_norm, f3 * inv_norm, f4 * inv_norm, ev, mfe, mae))
while array.size(self) > cap
array.shift(self)
// @function Searches the memory bank for stored 4D vectors whose cosine similarity with the query vector (f1..f4)
// exceeds `sim_thresh`. Returns the cubic-cosine kernel-weighted scalar average, mean similarity, and match count.
// @param self Target `array<VectorMem>` memory bank instance.
// @param f1 Query coordinate 1.
// @param f2 Query coordinate 2.
// @param f3 Query coordinate 3.
// @param f4 Query coordinate 4.
// @param sim_thresh Minimum cosine similarity cutoff in [-1.0, 1.0] required to count as a match (default = 0.15).
// @returns Tuple: [kernel_weighted_val, mean_cosine_similarity, matched_twins_count].
export method query(array<VectorMem> self, series float f1, series float f2, series float f3, series float f4, simple float sim_thresh = 0.15) =>
int n_rows = array.size(self)
float weighted_val = 0.0
float mean_sim = 0.0
int matches = 0
if n_rows > 0
float inv_q = 1.0 / math.sqrt(f1 * f1 + f2 * f2 + f3 * f3 + f4 * f4 + 1e-12)
float q1 = f1 * inv_q
float q2 = f2 * inv_q
float q3 = f3 * inv_q
float q4 = f4 * inv_q
float sum_w = 0.0
float sum_val = 0.0
float sum_sim = 0.0
for r = 0 to n_rows - 1
VectorMem m = array.get(self, r)
float cos_s = q1 * m.u1 + q2 * m.u2 + q3 * m.u3 + q4 * m.u4
if cos_s > sim_thresh
matches += 1
sum_sim += cos_s
float kw = cos_s * cos_s * cos_s
sum_w += kw
sum_val += kw * m.ev
if matches > 0 and sum_w > 0.0
weighted_val := sum_val / sum_w
mean_sim := sum_sim / float(matches)
[weighted_val, mean_sim, matches]
// @function Identifies which of the 4 coordinates (1..4) has the largest value (when `find_max` is true) or smallest value (when false).
// @param f1 Coordinate 1.
// @param f2 Coordinate 2.
// @param f3 Coordinate 3.
// @param f4 Coordinate 4.
// @param find_max Pass true to find the maximum coordinate, false to find the minimum (default = true).
// @returns Tuple: [dominant_index_1_to_4, dominant_coordinate_value].
export rank_features(series float f1, series float f2, series float f3, series float f4, series bool find_max = true) =>
int best_i = 1
float best_v = f1
if (find_max and f2 > best_v) or (not find_max and f2 < best_v)
best_i := 2
best_v := f2
if (find_max and f3 > best_v) or (not find_max and f3 < best_v)
best_i := 3
best_v := f3
if (find_max and f4 > best_v) or (not find_max and f4 < best_v)
best_i := 4
best_v := f4
[best_i, best_v]
// ============================================================================
// 4. LIBRARY VISUAL DEMONSTRATION (ON-CHART PIVOT SIMILARITY & TELEMETRY)
// ============================================================================
// Demonstrates all exported functions by indexing 5-bar structural swing pivots
// into a 4D unit-sphere memory bank and displaying their cosine similarity twins.
var array<VectorMem> state_bank = array.new<VectorMem>()
var array<label> piv_labels = array.new<label>()
float atr14 = math.max(nz(ta.atr(14), syminfo.mintick * 10.0), syminfo.mintick)
float vol_sma20 = math.max(nz(ta.sma(volume, 20), 1.0), 1.0)
float ema20 = ta.ema(close, 20)
float bar_rng = math.max(high - low, syminfo.mintick)
// Compute 4 normalized coordinates at the pivot candidate bar (offset 5)
float disp_5 = close[5] - nz(close[10], open[5])
[z_iso, theta_deg, c1_theta] = to_isotropic(disp_5, atr14[5], 1.5)
float c2_body = bipolar_norm((close[5] - open[5]) / math.max(high[5] - low[5], syminfo.mintick), 0.0, 1.5)
float c3_wick = bipolar_norm(((math.min(open[5], close[5]) - low[5]) - (high[5] - math.max(open[5], close[5]))) / math.max(high[5] - low[5], syminfo.mintick), 0.0, 1.5)
float c4_rvol = sigmoid_fast((nz(volume[5], vol_sma20[5]) / math.max(vol_sma20[5], 1.0)) - 1.0)
float ph = ta.pivothigh(high, 5, 5)
float pl = ta.pivotlow(low, 5, 5)
bool is_piv = not na(ph) or not na(pl)
var float last_sim = 0.0
var int last_twins = 0
var float last_score = 0.0
var float last_theta = 0.0
var int dom_idx = 1
if is_piv
float dir_s = not na(pl) ? 1.0 : -1.0
float q1 = c1_theta * dir_s
float q2 = c2_body * dir_s
float q3 = c3_wick * dir_s
float q4 = c4_rvol
float state_mag = 0.25 * (math.abs(q1) + math.abs(q2) + math.abs(q3) + math.abs(q4))
[w_val, m_sim, twins] = state_bank.query(q1, q2, q3, q4, 0.70)
[d_i, d_v] = rank_features(math.abs(q1), math.abs(q2), math.abs(q3), math.abs(q4), true)
last_sim := m_sim
last_twins := twins
last_score := w_val
last_theta := theta_deg
dom_idx := d_i
state_bank.insert(q1, q2, q3, q4, state_mag, 0.0, 0.0, 200)
bool is_low = not na(pl)
float piv_y = is_low ? pl : ph
color badge_c = is_low ? color.new(#00E5FF, 82) : color.new(#F43F5E, 82)
color text_c = is_low ? #22D3EE : #FB7185
string badge_txt = (is_low ? "▲ " : "▼ ") + "θ:" + str.tostring(theta_deg, "#") + "° | " + str.tostring(twins) + " Twins"
string tip_txt = "4D Unit-Sphere Pivot Record\n• Isotropic Angle (θ): " + str.tostring(theta_deg, "#.1") + "°\n• Matched Twins (cos ≥ 0.70): " + str.tostring(twins) + "\n• Mean Cosine Similarity: " + str.tostring(m_sim, "#.##")
label lbl = label.new(bar_index - 5, piv_y, badge_txt, color = badge_c, textcolor = text_c, style = is_low ? label.style_label_up : label.style_label_down, size = size.small, tooltip = tip_txt)
array.push(piv_labels, lbl)
while array.size(piv_labels) > 40
label.delete(array.shift(piv_labels))
// Plot Isotropic Volatility Reference Corridor (±1.5 ATR = ±45° Isotropic Reference)
p_mid = plot(ema20, "EMA 20 Reference", color = color.new(#6366F1, 45), linewidth = 1, display = display.pane)
p_up = plot(ema20 + 1.5 * atr14, "+45° Isotropic Corridor (+1.5 ATR)", color = color.new(#00E5FF, 75), linewidth = 1, display = display.pane)
p_dn = plot(ema20 - 1.5 * atr14, "-45° Isotropic Corridor (-1.5 ATR)", color = color.new(#F43F5E, 75), linewidth = 1, display = display.pane)
fill(p_up, p_dn, color = color.new(#6366F1, 93), title = "Isotropic ±45° Reference Zone")
// Compact Library Telemetry HUD
var table hud = table.new(position.top_right, 2, 6, bgcolor = color.new(#0F172A, 12), border_color = color.new(#334155, 40), border_width = 1)
if barstate.islast
string dom_name = dom_idx == 1 ? "f1 (Isotropic θ)" : (dom_idx == 2 ? "f2 (Body Ratio)" : (dom_idx == 3 ? "f3 (Wick Balance)" : "f4 (Rel Volume)"))
table.cell(hud, 0, 0, "IsotropicVectorSpace v1", text_color = #F8FAFC, bgcolor = color.new(#1E293B, 10), text_size = size.small)
table.cell(hud, 1, 0, "4D Unit Sphere (S³)", text_color = #38BDF8, bgcolor = color.new(#1E293B, 10), text_size = size.small)
table.cell(hud, 0, 1, "Memory Bank Size", text_color = #94A3B8, text_size = size.small, text_halign = text.align_left)
table.cell(hud, 1, 1, str.tostring(array.size(state_bank)) + " / 200 Vectors", text_color = #E2E8F0, text_size = size.small, text_halign = text.align_right)
table.cell(hud, 0, 2, "Last Pivot Angle (θ)", text_color = #94A3B8, text_size = size.small, text_halign = text.align_left)
table.cell(hud, 1, 2, str.tostring(last_theta, "#.1") + "°", text_color = #22D3EE, text_size = size.small, text_halign = text.align_right)
table.cell(hud, 0, 3, "Matched Twins (≥0.70)", text_color = #94A3B8, text_size = size.small, text_halign = text.align_left)
table.cell(hud, 1, 3, str.tostring(last_twins) + " (Sim: " + str.tostring(last_sim, "#.##") + ")", text_color = #10B981, text_size = size.small, text_halign = text.align_right)
table.cell(hud, 0, 4, "Dominant Coordinate", text_color = #94A3B8, text_size = size.small, text_halign = text.align_left)
table.cell(hud, 1, 4, dom_name, text_color = #F59E0B, text_size = size.small, text_halign = text.align_right)
table.cell(hud, 0, 5, "Unit Vector Norm ||u||", text_color = #94A3B8, text_size = size.small, text_halign = text.align_left)
table.cell(hud, 1, 5, "1.0000 (Zero-Sqrt k-NN)", text_color = #A855F7, text_size = size.small, text_halign = text.align_right)