PINE LIBRARY
Zaktualizowano

TimeframeAlign

50
THE PROBLEM THIS LIBRARY SOLVES

When you use `request.security()` to get data from a Higher Timeframe (HTF) and try to draw objects like boxes, lines, or labels, they appear at the wrong horizontal position. This is the "floating in space" problem.

Why does this happen?
The `bar_index` in Pine Script refers to where data was RECEIVED, not where the event OCCURRED.

Consider this scenario:
• You're on a 5-minute chart
• You request 1-hour data for drawing an FVG (Fair Value Gap)
• A 1H candle spans 12 chart bars (60min / 5min = 12)
• But your code draws at `bar_index - 1` or `bar_index - 3`
• The result: your FVG box is only 2-3 bars wide instead of spanning the correct 12-36 bars

This library solves that by tracking where HTF bars actually start and end on your chart timeframe.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

HOW TO USE THIS LIBRARY

Step 1: Import the Library
```
import ArunaReborn/TimeframeAlign/1 as tfa
```

Step 2: Create a Tracker for Each HTF
```
var tfa.HTFTracker tracker1H = tfa.createTracker("60")
```

Step 3: Update the Tracker Every Bar
```
tfa.updateTracker(tracker1H, "60")
```

Step 4: Use Synced Drawing Functions
```
if tfa.htfBarChanged(tracker1H)
tfa.syncedBox(tracker1H, 3, 1, topPrice, bottomPrice, color.new(color.green, 80))
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

EXPORTED TYPES

TimeframePair
Stores metadata about the relationship between source and chart timeframes.
• sourceTimeframe - The HTF/LTF being compared
• chartTimeframe - Current chart timeframe
• isHTF - True if source is higher than chart
• isLTF - True if source is lower than chart
• barRatio - Chart bars per source bar
• secondsRatio - Time ratio between timeframes

MTFEventData
Stores synchronized event data with correct bar positions.
• price - Price level of the event
• eventTime - Unix timestamp of the event
• chartBarStart - Chart bar_index where event's TF bar started
• chartBarEnd - Chart bar_index where event's TF bar ended
• htfOffset - The HTF offset used
• isValid - True if synchronization succeeded

HTFTracker
Tracks HTF bar boundaries. Create one per timeframe you need to track.
• htfTimeframe - The timeframe being tracked
• currentStartBar - Where current HTF bar started
• currentEndBar - Where current HTF bar ends (provisional)
• startHistory - Array of historical start positions
• endHistory - Array of historical end positions
• lastUpdateBar - Last bar_index when updated
• barJustChanged - True if HTF bar changed on this chart bar (set by updateTracker)

SyncedBox
Managed box with synchronization metadata.
• bx - The Pine Script box object
• htfTimeframe - Source timeframe
• leftHtfOffset / rightHtfOffset - HTF offsets for edges
• topPrice / bottomPrice - Price boundaries
• extendRight - Auto-extend flag

SyncedLine
Managed line with synchronization metadata.
• ln - The Pine Script line object
• htfTimeframe - Source timeframe
• htfOffset - Anchor offset
• price - Price level (horizontal lines)
• isHorizontal - Line orientation
• extendRight - Auto-extend flag

SyncedLabel
Managed label with synchronization metadata.
• lbl - The Pine Script label object
• htfTimeframe - Source timeframe
• htfOffset - Anchor offset
• price - Price level
• anchorPoint - "start", "end", or "middle"

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

EXPORTED FUNCTIONS

━━ CORE FUNCTIONS ━━

getTimeframeInfo(sourceTimeframe)
Analyzes relationship between a source TF and chart TF.
Returns: TimeframePair with comparison metadata

createTracker(htfTimeframe)
Creates a new HTF tracker. Call once per timeframe, store with `var`.
Returns: HTFTracker instance

updateTracker(tracker, htfTimeframe, historyDepth)
Updates tracker with current bar data. Call on every bar.
• htfTimeframe: The timeframe string (must match createTracker)
• historyDepth: Max HTF bars to track (default 500)
Returns: Updated tracker

getStartBar(tracker, htfOffset)
Gets chart bar_index where a specific HTF bar started.
• htfOffset: 0=current, 1=previous, 2=two bars ago, etc.
Returns: bar_index or na

getEndBar(tracker, htfOffset)
Gets chart bar_index where a specific HTF bar ended.
Returns: bar_index or na

htfBarChanged(tracker)
Detects when HTF bar just changed.
Returns: True on first chart bar of new HTF bar

findBarAtTime(timestamp, maxLookback)
Searches backward to find chart bar containing a timestamp.
• maxLookback: How far back to search (default 500)
Returns: bar_index or na

syncEventToChart(tracker, eventPrice, eventTime, anchorPoint)
Generic sync function mapping any event to correct chart position.
• anchorPoint: "start", "end", or "middle"
Returns: MTFEventData

━━ DRAWING CREATION FUNCTIONS ━━

syncedBox(tracker, leftHtfOffset, rightHtfOffset, topPrice, bottomPrice, bgcolor, ...)
Creates a box at correct HTF-aligned position.
• leftHtfOffset: HTF bars back for left edge
• rightHtfOffset: HTF bars back for right edge
• extendRight: Auto-extend to current bar
Returns: SyncedBox or na

syncedHLine(tracker, htfOffset, price, lineColor, lineStyle, lineWidth, extendRight)
Creates horizontal line anchored to HTF bar start.
• extendRight: If true, extends to current bar (default true)
Returns: SyncedLine or na

syncedVLine(tracker, htfOffset, atStart, lineColor, lineStyle, lineWidth)
Creates vertical line at HTF bar boundary.
• atStart: True=start of HTF bar, False=end
Returns: SyncedLine or na

syncedLabel(tracker, htfOffset, price, labelText, anchorPoint, ...)
Creates label at correct HTF-aligned position.
• anchorPoint: "start", "end", or "middle"
Returns: SyncedLabel or na

syncedPlotValue(tracker, value, htfOffset)
Returns value for plotting only at synced positions.
Returns: value if current bar is within HTF range, otherwise na

━━ UPDATE FUNCTIONS ━━

updateSyncedBox(syncedBox, extendToCurrentBar)
Extends existing box's right edge to current bar.
Returns: Updated SyncedBox

updateSyncedLine(syncedLine, extendToCurrentBar)
Extends existing horizontal line to current bar.
Returns: Updated SyncedLine

updateSyncedLabel(syncedLabel, tracker, newText, newPrice)
Updates label text/price while maintaining sync.
Returns: Updated SyncedLabel

━━ CONVENIENCE FUNCTIONS ━━

htfBarStartIndex(htfTimeframe, htfOffset, historyDepth)
Simple function to get HTF bar start without explicit tracker.
⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern.
Returns: bar_index or na

htfBarEndIndex(htfTimeframe, htfOffset, historyDepth)
Simple function to get HTF bar end without explicit tracker.
⚠️ Only tracks ONE timeframe. For multiple TFs, use createTracker pattern.
Returns: bar_index or na

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

COMPLETE USAGE EXAMPLES

Example 1: FVG Box with Auto-Extend
```
//version=6
indicator("FVG with Synced Drawing", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa

htfInput = input.timeframe("60", "HTF for FVG")

// Create tracker for chosen timeframe
var tfa.HTFTracker fvgTracker = tfa.createTracker(htfInput)
tfa.updateTracker(fvgTracker, htfInput)

// Get FVG data from HTF (confirmed bars with [1] offset)
[fvgTop, fvgBot, fvgDetected] = request.security(syminfo.tickerid, htfInput,
[low[1], high[3], low[1] > high[3]],
lookahead=barmerge.lookahead_off)

// Store managed box
var tfa.SyncedBox fvgBox = na

// Create synced box when FVG detected
if fvgDetected and tfa.htfBarChanged(fvgTracker)
fvgBox := tfa.syncedBox(fvgTracker, 3, 1, fvgTop, fvgBot,
color.new(color.green, 85), color.green, 1, "FVG", color.white, true)

// Extend box to current bar each tick
if not na(fvgBox)
tfa.updateSyncedBox(fvgBox, true)
```

Example 2: HTF Support/Resistance Lines
```
//version=6
indicator("HTF S/R Lines", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa

htfInput = input.timeframe("240", "HTF for S/R")

// Create and update tracker
var tfa.HTFTracker srTracker = tfa.createTracker(htfInput)
tfa.updateTracker(srTracker, htfInput)

// Get HTF high/low (confirmed with [1] offset)
[htfHigh, htfLow] = request.security(syminfo.tickerid, htfInput,
[high[1], low[1]], lookahead=barmerge.lookahead_off)

// Track lines
var tfa.SyncedLine resistanceLine = na
var tfa.SyncedLine supportLine = na

// Create new lines when HTF bar changes
if tfa.htfBarChanged(srTracker)
resistanceLine := tfa.syncedHLine(srTracker, 1, htfHigh, color.red, line.style_solid, 2, true)
supportLine := tfa.syncedHLine(srTracker, 1, htfLow, color.green, line.style_solid, 2, true)

// Auto-extend lines each bar
if not na(resistanceLine)
tfa.updateSyncedLine(resistanceLine, true)
if not na(supportLine)
tfa.updateSyncedLine(supportLine, true)
```

Example 3: Multiple Timeframes
```
//version=6
indicator("Multi-TF Boxes", overlay=true)
import ArunaReborn/TimeframeAlign/1 as tfa

// Create separate tracker for each timeframe
var tfa.HTFTracker tracker1H = tfa.createTracker("60")
var tfa.HTFTracker tracker4H = tfa.createTracker("240")
var tfa.HTFTracker trackerD = tfa.createTracker("1D")

// Update ALL trackers every bar (pass the same TF string)
tfa.updateTracker(tracker1H, "60")
tfa.updateTracker(tracker4H, "240")
tfa.updateTracker(trackerD, "1D")

// Now use each tracker independently for drawing
// Each tracker maintains its own separate boundary history
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

NON-REPAINTING COMPLIANCE

To ensure non-repainting behavior, always use this pattern with request.security:
```
[value1, value2] = request.security(syminfo.tickerid, htfTimeframe,
[value1[1], value2[1]], // Use [1] offset for confirmed data
lookahead=barmerge.lookahead_off) // Never use lookahead_on
```

The `[1]` offset ensures you're using the previous completed HTF bar, not the current forming bar.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

HISTORY DEPTH PARAMETER

The `historyDepth` parameter controls how many HTF bars are tracked:
• Default: 500 HTF bars
• Maximum: Limited by Pine Script's array constraints
• Higher values = more historical accuracy but more memory usage
• Lower values = less memory but may return `na` for older offsets

Adjust based on your needs:
```
tfa.updateTracker(tracker, 100) // Track 100 HTF bars (light)
tfa.updateTracker(tracker, 1000) // Track 1000 HTF bars (heavier)
```

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

IMPORTANT NOTES

1. One Tracker Per Timeframe: If you need multiple HTFs, create separate trackers for each. The convenience functions (htfBarStartIndex, htfBarEndIndex) only track one TF.

2. Update Every Bar: Always call updateTracker() unconditionally on every bar, not inside conditionals.

3. HTF Only: This library is designed for Higher Timeframe data. For LTF aggregation, use findBarAtTime() for time-based lookups.

4. Drawing Limits: Pine Script has limits on drawing objects. Use box.delete(), line.delete(), label.delete() to clean up old objects.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

TROUBLESHOOTING

Q: My boxes/lines still appear at wrong positions
A: Make sure you're calling updateTracker() on every bar (not inside an if statement) and using the correct htfOffset values.

Q: Functions return na
A: The htfOffset might be larger than available history. Increase historyDepth or use a smaller offset.

Q: Multiple timeframes don't work correctly
A: Don't use the convenience functions for multiple TFs. Create separate HTFTracker instances with createTracker() for each timeframe.

━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

CHANGELOG

v1 - Initial release
• HTFTracker pattern for reliable multi-TF tracking
• Synced drawing functions for boxes, lines, labels
• Update functions for extending drawings
• Convenience functions for simple single-TF use cases
Informacje o Wersji
v2

Wyłączenie odpowiedzialności

Informacje i publikacje nie stanowią i nie powinny być traktowane jako porady finansowe, inwestycyjne, tradingowe ani jakiekolwiek inne rekomendacje dostarczane lub zatwierdzone przez TradingView. Więcej informacji znajduje się w Warunkach użytkowania.