TimeframeAlignTHE 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 offset)
= request.security(syminfo.tickerid, htfInput,
[low , high , low > high ],
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 offset)
= request.security(syminfo.tickerid, htfInput,
[high , low ], 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:
```
= request.security(syminfo.tickerid, htfTimeframe,
[value1 , value2 ], // Use offset for confirmed data
lookahead=barmerge.lookahead_off) // Never use lookahead_on
```
The ` ` 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
Display
Plan Limit TimerA Pine Script library that helps developers monitor script execution time against TradingView's plan-specific timeout limits. Displays a visual debug table with runtime metrics, percentage of limit consumed, and color-coded status warnings.
WHAT THIS LIBRARY DOES
TradingView enforces different script timeout limits based on subscription tier:
• Basic : 20 seconds
• Essential / Plus / Premium : 40 seconds
• Ultimate : 100 seconds
This library measures your script's total execution time and displays it relative to these limits, helping you optimize indicators for users on different plans.
THE DEBUG TABLE
When enabled, a table appears on your chart showing:
• Plan : The selected TradingView subscription tier
• Limit : Maximum allowed execution time for that plan
• Runtime : Measured script execution time
• Per Bar : Average time spent per bar
• Bars : Number of bars processed
• % Used : Percentage of timeout limit consumed (color-coded)
• Status : OK (green), WARNING (yellow), DANGER (orange), or EXCEEDED (red)
HOW IT WORKS
The library captures a timestamp at the start of your script using timenow, then calculates the elapsed time at the end. It compares this against the selected plan's timeout limit to determine percentage used and status.
Technical Note : Pine Script's timenow variable has approximately 1-second precision. Scripts that execute in under 1 second may display 0ms. This is a platform limitation, not a library issue. For detailed per-function profiling, use TradingView's built-in Pine Profiler (More → Profiler mode in the Editor).
EXPORTED FUNCTIONS
startTimer()
Call at the very beginning of your script. Returns a timestamp.
getStats(startTime, plan)
Calculates timing statistics. Returns a TimingStats object with all metrics.
showTimingTable(stats, plan, tablePosition, showOnlyOnLast)
Renders the debug table on the chart.
debugTiming(startTime, plan, tablePosition)
Convenience function combining getStats() and showTimingTable() in one call.
isApproachingLimit(stats, threshold)
Returns true if execution time has reached the specified percentage of the limit.
getRemainingMs(stats)
Returns milliseconds remaining before timeout.
formatSummary(stats)
Returns a compact single-line string for labels or tooltips.
addTimingLabel(stats, barIdx, price, labelStyle, textSize)
Creates a color-coded chart label displaying timing statistics. Useful for visual debugging without the full table. Returns the label object for further customization.
EXPORTED CONSTANTS
• LIMIT_BASIC = 20
• LIMIT_ESSENTIAL = 40
• LIMIT_PLUS = 40
• LIMIT_PREMIUM = 40
• LIMIT_ULTIMATE = 100
EXPORTED TYPE: TimingStats
Object containing:
• totalTimeMs (float): Total execution time in milliseconds
• timePerBarMs (float): Average time per bar
• barsTimed (int): Number of bars measured
• barsSkipped (int): Bars excluded from measurement
• planLimitMs (int): Plan timeout in milliseconds
• percentUsed (float): Percentage of limit consumed
• status (string): "OK", "WARNING", "DANGER", or "EXCEEDED"
HOW TO USE IN YOUR INDICATOR
//@version=6
indicator("My Indicator", overlay = true)
import YourUsername/PlanLimitTimer/1 as timer
// User selects their TradingView plan
planInput = input.string("basic", "Your Plan", options = )
// START TIMING - must be first
startTime = timer.startTimer()
// Your indicator calculations here
sma20 = ta.sma(close, 20)
rsi14 = ta.rsi(close, 14)
plot(sma20)
// END TIMING - must be last
timer.debugTiming(startTime, planInput)
ADVANCED USAGE EXAMPLE
//@version=6
indicator("Advanced Example", overlay = true)
import YourUsername/PlanLimitTimer/1 as timer
planInput = input.string("basic", "Plan", options = )
startTime = timer.startTimer()
// Your calculations...
sma = ta.sma(close, 200)
plot(sma)
// Get stats for programmatic use
stats = timer.getStats(startTime, planInput)
// Option 1: Use addTimingLabel for a quick visual indicator
if barstate.islast
timer.addTimingLabel(stats, bar_index, high)
// Option 2: Show custom warning label if approaching limit
if timer.isApproachingLimit(stats, 70.0) and barstate.islast
label.new(bar_index, low, "Warning: " + timer.formatSummary(stats),
color = color.orange, textcolor = color.white, style = label.style_label_up)
// Display the debug table
timer.showTimingTable(stats, planInput, position.bottom_right)
IMPORTANT LIMITATIONS
1. Precision : Timing precision is approximately 1 second due to timenow behavior. Fast scripts show 0ms.
2. Variability : Results vary based on TradingView server load. The same script may show different times across runs.
3. Total Time Only : This library measures total script execution time, not individual function timing. For per-function analysis, use the Pine Profiler in the Editor.
4. Historical Bars : On historical bars, timenow reflects when the script loaded, not individual bar processing times.
USE CASES
• Optimization Debugging : See how close your script is to timeout limits
• Multi-Plan Support : Help users select appropriate settings for their subscription tier
• Performance Regression : Detect when changes increase execution time
• Documentation : Show users the performance characteristics of your indicator
News2026H2Library "News2026H2" - 2026 News Events Support Lib
f_loadNewsRows()
f_loadExcSevByTypeId()
f_loadExcTagByTypeId()
f_loadExcDelayAfterNewsMins()
T5_TradeEngineLibrary "T5_TradeEngine"
tick(close_, high_, low_, ema21, ema50, ema200, atrPct, emaGapPct, btcEma50, btcEma200, btcFilterEffective, isBarClose, crossUp21_50, crossDown21_50, allowEntries, exitOnOppositeCross, feeBps, useSR_TPSL, srLeft, srRight, srLookbackPivots, srBufferPct, srMinDistPct, srMinNetAfterFeesPct, srFallbackToATR, tp1CapPct, slCapPct, useTP2Trail, trailExitOnCloseOnly, tp2CapPct, trailCapPct, holdBars)
Parameters:
close_ (float)
high_ (float)
low_ (float)
ema21 (float)
ema50 (float)
ema200 (float)
atrPct (float)
emaGapPct (float)
btcEma50 (float)
btcEma200 (float)
btcFilterEffective (bool)
isBarClose (bool)
crossUp21_50 (bool)
crossDown21_50 (bool)
allowEntries (bool)
exitOnOppositeCross (bool)
feeBps (float)
useSR_TPSL (bool)
srLeft (int)
srRight (int)
srLookbackPivots (int)
srBufferPct (float)
srMinDistPct (float)
srMinNetAfterFeesPct (float)
srFallbackToATR (bool)
tp1CapPct (float)
slCapPct (float)
useTP2Trail (bool)
trailExitOnCloseOnly (bool)
tp2CapPct (float)
trailCapPct (float)
holdBars (int)
ZigZag ATRZigZag ATR Library
A volatility-adaptive ZigZag indicator that uses Average True Range (ATR) instead of fixed percentage deviation to detect pivot points. This makes the ZigZag dynamically adjust to market conditions — tighter during low volatility, wider during high volatility.
Why ATR instead of Percentage?
The standard ZigZag uses a fixed percentage threshold (e.g., 5%) to determine when price has reversed enough to form a new pivot. This approach has limitations:
A 5% move means very different things for a $10 stock vs a $500 stock
During high volatility, fixed percentages create too many pivots (noise)
During low volatility, fixed percentages may miss significant structure
ATR-based deviation solves these issues by measuring reversals in terms of actual volatility , not arbitrary percentages.
Key Features
Volatility-adaptive pivot detection using ATR × multiplier threshold
Automatic adjustment to changing market conditions
Full customization of ATR length and multiplier
Optional line extension to current price
Pivot labels showing price, volume, and price change
Clean library structure for easy integration
Settings
ATR Length — Period for ATR calculation (default: 14)
ATR Multiplier — How many ATRs price must move to confirm a new pivot (default: 2.0)
Depth — Bars required for pivot detection (default: 10)
Extend to Last Bar — Draw provisional line to current price
Display options — Toggle price, volume, and change labels
How to Use
import YourUsername/ZigZagATR/1 as zz
// Create settings
var zz.Settings settings = zz.Settings.new(
14, // ATR length
2.0, // ATR multiplier
10 // Depth
)
// Create ZigZag instance
var zz.ZigZag zigZag = zz.newInstance(settings)
// Calculate ATR and update on each bar
float atrValue = ta.atr(14)
zigZag.update(atrValue)
Exported Types
Settings — Configuration for calculation and display
Pivot — Stores pivot point data, lines, and labels
ZigZag — Main object maintaining state and pivot history
Exported Functions
newInstance(settings) — Creates a new ZigZag object
update(atrValue) — Updates the ZigZag with current ATR (call once per bar)
lastPivot() — Returns the most recent pivot point
Recommended Multiplier Values
1.0 - 1.5 → More sensitive, more pivots, better for scalping
2.0 - 2.5 → Balanced, good for swing trading (default)
3.0+ → Less sensitive, major pivots only, better for position trading
Based on TradingView's official ZigZag library, modified to use ATR-based deviation threshold.
demark_poolLibrary "demark_pool"
f_labelArrayClear(pool, run)
Parameters:
pool (array)
run (bool)
f_labelPushCap(pool, l, cap)
Parameters:
pool (array)
l (label)
cap (int)
f_labelTrimCap(pool, run, cap)
Parameters:
pool (array)
run (bool)
cap (int)
demark_uiLibrary "demark_ui"
f_dashUpdate6x2(dash, c00, c10, c01, c11, c02, c12, c12TextColor, c03, c13, c04, c14, c05, c15, bg, tc, ts)
Parameters:
dash (table)
c00 (string)
c10 (string)
c01 (string)
c11 (string)
c02 (string)
c12 (string)
c12TextColor (color)
c03 (string)
c13 (string)
c04 (string)
c14 (string)
c05 (string)
c15 (string)
bg (color)
tc (color)
ts (string)
demark_renderLibrary "demark_render"
f_renderMaxBack(lookbackBars)
Parameters:
lookbackBars (float)
f_renderExtendBars(levelLineExtendBarsMax)
Parameters:
levelLineExtendBarsMax (int)
f_upsertLevelLine(lnIn, show, y, col, width, style, levelLineExtendBarsMax)
Parameters:
lnIn (line)
show (bool)
y (float)
col (color)
width (int)
style (string)
levelLineExtendBarsMax (int)
f_upsertZoneBox(bxIn, show, x1, lo, hi, bg, brd, brdW, lookbackBars, levelLineExtendBarsMax)
Parameters:
bxIn (box)
show (bool)
x1 (int)
lo (float)
hi (float)
bg (color)
brd (color)
brdW (int)
lookbackBars (float)
levelLineExtendBarsMax (int)
f_upsertTdLine(lnIn, show, p1Idx, p1Price, p0Idx, p0Price, col, width, style, lookbackBars, levelLineExtendBarsMax)
Parameters:
lnIn (line)
show (bool)
p1Idx (int)
p1Price (float)
p0Idx (int)
p0Price (float)
col (color)
width (int)
style (string)
lookbackBars (float)
levelLineExtendBarsMax (int)
f_levelTagX(levelLineExtendBarsMax)
Parameters:
levelLineExtendBarsMax (int)
f_stackY(baseY, step, idx, stackUp)
Parameters:
baseY (float)
step (float)
idx (int)
stackUp (bool)
f_upsertLevelTag(lbIn, show, y, txt, bg, tc, sz, levelLineExtendBarsMax)
Parameters:
lbIn (label)
show (bool)
y (float)
txt (string)
bg (color)
tc (color)
sz (string)
levelLineExtendBarsMax (int)
f_upsertPointTag(lbIn, show, x, y, txt, bg, tc, sz, sty)
Parameters:
lbIn (label)
show (bool)
x (int)
y (float)
txt (string)
bg (color)
tc (color)
sz (string)
sty (string)
HelperScriptA Personal Helper Script based on FFriZz/Holiday/2
Only change the font size and language
ArgentinaBondsLib - Argentina Sovereign Bonds Cashflow LibraryArgentinaBondsLib
A Pine Script v6 library providing cashflow data and financial calculation functions for Argentine sovereign bonds (Bonares and Globales).
## Supported Bonds
**Bonares** (Argentina legislation, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
**Globales** (Foreign legislation, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
## Exported Functions
### Cashflow Data
- `getCashflows_ ()` - Returns timestamps, cashflows, and count for each bond
### Bond Identification
- `getBondType(ticker)` - Returns BONAR() or GLOBAL()
- `getBaseTicker(ticker)` - Extracts base ticker without prefix/suffix
- `getCurrencyType(ticker)` - Returns 0=ARS, 1=MEP, 2=Cable
- `isSupported(baseTicker)` - Checks if bond is supported
### Financial Calculations
- `calcPV()` - Present Value calculation
- `calcIRR()` - Internal Rate of Return using Newton-Raphson method
- `calcPriceFromIRR()` - Calculate price from target IRR
### Currency Conversion
- `convertToNativeCurrency()` - Converts price to cashflow currency (MEP for Bonares, Cable for Globales)
### Utilities
- `getSettlementDate()` - Returns T+1 timestamp
- `BONAR()` / `GLOBAL()` - Bond type constants
## Methodology
- Day count convention: Actual/365
- Settlement: T+1
- IRR solver: Newton-Raphson iterative method
## Usage Example
```
import EcoValores/ArgentinaBondsLib/1 as Bonds
= Bonds.getCashflows_AL30()
settlementDate = Bonds.getSettlementDate()
irr = Bonds.calcIRR(ts, cf, count, settlementDate, close)
```
---
## Español
Librería Pine Script v6 con datos de flujos de fondos y funciones de cálculo financiero para bonos soberanos argentinos.
### Bonos Soportados
- **Bonares** (Legislación argentina, USD MEP): AE38, AL29, AL30, AL35, AL41, AN29
- **Globales** (Legislación extranjera, USD Cable): GD29, GD30, GD35, GD38, GD41, GD46
### Metodología
- Convención de días: Actual/365
- Liquidación: T+1
- Solver TIR: Método iterativo Newton-Raphson
---
**DISCLAIMER**: This library is for informational and educational purposes only. Eco Valores S.A. does NOT provide investment advice or recommendations. Consult a qualified financial advisor before making investment decisions.
**AVISO LEGAL**: Esta librería es solo para fines informativos y educativos. Eco Valores S.A. NO brinda asesoramiento ni recomendaciones de inversión. Consulte con un asesor financiero calificado antes de invertir.
CoreLibrary "Core"
inRTH()
gapFlags(prevDayClose, gapPct)
Parameters:
prevDayClose (float)
gapPct (float)
gapInfo(prevClose)
Parameters:
prevClose (float)
relativeVolume(len)
Parameters:
len (int)
barSeconds()
barSecondsOpt(rthSecondsDefault)
Parameters:
rthSecondsDefault (int)
relVolRealtime(len)
Parameters:
len (int)
mtfAlign(htfEma, tol)
Parameters:
htfEma (float)
tol (float)
htfDistanceAbs(htfEma, fallback)
Parameters:
htfEma (float)
fallback (float)
mtfState(htfEma, tol)
Parameters:
htfEma (float)
tol (float)
adaptiveLength(rocLen, minSmooth, maxSmooth, useAdaptive, baseSmoothing, speedLookback)
Parameters:
rocLen (int)
minSmooth (int)
maxSmooth (int)
useAdaptive (bool)
baseSmoothing (int)
speedLookback (int)
adaptiveTrend(src, adaptiveLen)
Parameters:
src (float)
adaptiveLen (float)
atrBands(atrLen, atrMult, basis)
Parameters:
atrLen (simple int)
atrMult (float)
basis (float)
calcTrendStrength(closePrice, fastEMA, slowEMA, volumeConfirmed, speedConfirmed)
Parameters:
closePrice (float)
fastEMA (float)
slowEMA (float)
volumeConfirmed (bool)
speedConfirmed (bool)
calcMovementPotential(inExpansionZone, trendStrength, speedConfirmed)
Parameters:
inExpansionZone (bool)
trendStrength (int)
speedConfirmed (bool)
combineSignalScore(trendStrength, movementPotential, mtfBonus, volumeSurgeBonus)
Parameters:
trendStrength (int)
movementPotential (int)
mtfBonus (int)
volumeSurgeBonus (int)
strength10(dirLong, volRatio, htfDistance, isTraditional, isAltPattern, bodySize, rsi)
Parameters:
dirLong (bool)
volRatio (float)
htfDistance (float)
isTraditional (bool)
isAltPattern (bool)
bodySize (float)
rsi (float)
sessionProfile()
microstructure(lookback)
Parameters:
lookback (int)
normalizePressure(pressure, lookback)
Parameters:
pressure (float)
lookback (int)
tickPressureNorm(lb)
Parameters:
lb (int)
zscore(x, lb)
Parameters:
x (float)
lb (int)
tickPressureZ(lb)
Parameters:
lb (int)
strength10DayTrade(dirLong, volRatio, htfDistance, isTraditional, isAltPattern, bodySize, rsi, sessionBonus, tickPressure)
Parameters:
dirLong (bool)
volRatio (float)
htfDistance (float)
isTraditional (bool)
isAltPattern (bool)
bodySize (float)
rsi (float)
sessionBonus (bool)
tickPressure (float)
vwapBands(vwap, length)
Parameters:
vwap (float)
length (int)
vwapChop(vwap, dev, atrPct, rsi)
Parameters:
vwap (float)
dev (float)
atrPct (float)
rsi (float)
calcRiskReward(entry, stop, tp1, tp2, tp3, shares)
Parameters:
entry (float)
stop (float)
tp1 (float)
tp2 (float)
tp3 (float)
shares (float)
squeezeBBKC()
marketRegime(lookback)
Parameters:
lookback (int)
squeezeBucket(ratio)
Parameters:
ratio (float)
dynamicCooldown(baseBars, atrPct, inChop, maxBars)
Parameters:
baseBars (int)
atrPct (float)
inChop (bool)
maxBars (int)
vwapMode(inChop)
Parameters:
inChop (bool)
toPctStr(x)
Parameters:
x (float)
yesNo(b)
Parameters:
b (bool)
trendLabel(state)
Parameters:
state (int)
minRByPct(price, pct)
Parameters:
price (float)
pct (float)
vwapChopScore(vwap, dev, atrPct, rsi)
Parameters:
vwap (float)
dev (float)
atrPct (float)
rsi (float)
strengthGateSuggest(isQualityTime, inChop, baseGate)
Parameters:
isQualityTime (bool)
inChop (bool)
baseGate (int)
cooldownReason(atrPct, inChop)
Parameters:
atrPct (float)
inChop (bool)
readyGates(isQualityTime, inChop, relVol, atrPct, baseGate)
Parameters:
isQualityTime (bool)
inChop (bool)
relVol (float)
atrPct (float)
baseGate (int)
readyVerdict(isLong, mtfStateVal, relVol, atrPercent, strengthScore, strengthGate)
Parameters:
isLong (bool)
mtfStateVal (int)
relVol (float)
atrPercent (float)
strengthScore (int)
strengthGate (int)
structuralStops(isLong, sigLow, sigHigh, vwap, dev, atr, stopBufAtr)
Parameters:
isLong (bool)
sigLow (float)
sigHigh (float)
vwap (float)
dev (float)
atr (float)
stopBufAtr (float)
emaSlopePct(ema, bars)
Parameters:
ema (float)
bars (int)
atrPct(len)
Parameters:
len (simple int)
cooldownStatus(lastSigBar, cooldownBars)
Parameters:
lastSigBar (int)
cooldownBars (int)
emaSlopeSign(ema, bars)
Parameters:
ema (float)
bars (int)
barProgress()
rthMarkers()
badge(ok)
Parameters:
ok (bool)
triBadge(x)
Parameters:
x (int)
priceAcceptanceAdaptive(minBodyFrac)
Parameters:
minBodyFrac (float)
speedConfirmed(rocLen, emaLen, smaLen)
Parameters:
rocLen (int)
emaLen (simple int)
smaLen (int)
setupScore(isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, microOK, cooldownOK)
Parameters:
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
microOK (bool)
cooldownOK (bool)
setupTier(score)
Parameters:
score (int)
setupQuality(score)
Parameters:
score (int)
setupQualityColor(score)
Parameters:
score (int)
setupScoreDir(isLong, isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, priceAccept, tickNorm, cooldownOK)
Parameters:
isLong (bool)
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
priceAccept (bool)
tickNorm (float)
cooldownOK (bool)
setupScoresBoth(isLoose, isNormal, vwapTrend, emaUp, mtfBull, relVolOK, priceAccept, tickNorm, cooldownOK)
Parameters:
isLoose (bool)
isNormal (bool)
vwapTrend (bool)
emaUp (bool)
mtfBull (bool)
relVolOK (bool)
priceAccept (bool)
tickNorm (float)
cooldownOK (bool)
ruleGatesDir(isLong, squeezeTight, emaUp, vwapTrend, relVol, relVolThresh, tickNorm, useSqzGate, useEmaGate, useVwapGate, useVolGate, useMicroGate)
Parameters:
isLong (bool)
squeezeTight (bool)
emaUp (bool)
vwapTrend (bool)
relVol (float)
relVolThresh (float)
tickNorm (float)
useSqzGate (bool)
useEmaGate (bool)
useVwapGate (bool)
useVolGate (bool)
useMicroGate (bool)
ruleGates(squeezeTight, emaUp, vwapTrend, relVol, relVolThresh, tickNorm, useSqzGate, useVwapGate, useVolGate, useMicroGate)
Parameters:
squeezeTight (bool)
emaUp (bool)
vwapTrend (bool)
relVol (float)
relVolThresh (float)
tickNorm (float)
useSqzGate (bool)
useVwapGate (bool)
useVolGate (bool)
useMicroGate (bool)
arrowColor(bucket, baseColor, useRegimeColor)
Parameters:
bucket (string)
baseColor (color)
useRegimeColor (bool)
orbHiLo(minutes)
Parameters:
minutes (int)
prevDayHL()
EMTIA_MASTER_LIBLibrary "EMTIA_MASTER_LIB"
trendUp(emaFast, emaSlow)
Parameters:
emaFast (float)
emaSlow (float)
rsiHealthy(rsi)
Parameters:
rsi (float)
adxStrong(adx, diPlus, diMinus)
Parameters:
adx (float)
diPlus (float)
diMinus (float)
macroSlope(emaFast, emaSlow)
Parameters:
emaFast (float)
emaSlow (float)
structureBull(hh, hl)
Parameters:
hh (bool)
hl (bool)
calcScore(weeklyTrend, dailyTrend, adxOk, rsiOk, structureOk, macroOk)
Parameters:
weeklyTrend (bool)
dailyTrend (bool)
adxOk (bool)
rsiOk (bool)
structureOk (bool)
macroOk (bool)
ZigZag forceLibrary "ZigZag"
method lastPivot(this)
Retrieves the last `Pivot` object's reference from a `ZigZag` object's `pivots`
array if it contains at least one element, or `na` if the array is empty.
Callable as a method or a function.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) The `ZigZag` object's reference.
Returns: (Pivot) The reference of the last `Pivot` instance in the `ZigZag` object's
`pivots` array, or `na` if the array is empty.
method update(this)
Updates a `ZigZag` object's pivot information, volume data, lines, and
labels when it detects new pivot points.
NOTE: This function requires a single execution on each bar for accurate
calculations.
Callable as a method or a function.
Namespace types: ZigZag
Parameters:
this (ZigZag) : (series ZigZag) The `ZigZag` object's reference.
Returns: (bool) `true` if the function detects a new pivot point and updates the
`ZigZag` object's data, `false` otherwise.
newInstance(settings)
Creates a new `ZigZag` instance with optional settings.
Parameters:
settings (Settings) : (series Settings) Optional. A `Settings` object's reference for the new
`ZigZag` instance's `settings` field. If `na`, the `ZigZag` instance
uses a new `Settings` object with default properties. The default is `na`.
Returns: (ZigZag) A new `ZigZag` object's reference.
Settings
A structure for objects that store calculation and display properties for `ZigZag` instances.
Fields:
devThreshold (series float) : The minimum percentage deviation from a previous pivot point required to change the Zig Zag's direction.
depth (series int) : The number of bars required for pivot point detection.
lineColor (series color) : The color of each line in the Zig Zag drawing.
extendLast (series bool) : Specifies whether the Zig Zag drawing includes a line connecting the most recent pivot point to the latest bar's `close`.
displayReversalPrice (series bool) : Specifies whether the Zig Zag drawing shows pivot prices in its labels.
displayCumulativeVolume (series bool) : Specifies whether the Zig Zag drawing shows the cumulative volume between pivot points in its labels.
displayReversalPriceChange (series bool) : Specifies whether the Zig Zag drawing shows the reversal amount from the previous pivot point in each label.
differencePriceMode (series string) : The reversal amount display mode. Possible values: `"Absolute"` for price change or `"Percent"` for percentage change.
draw (series bool) : Specifies whether the Zig Zag drawing displays its lines and labels.
allowZigZagOnOneBar (series bool) : Specifies whether the Zig Zag calculation can register a pivot high *and* pivot low on the same bar.
Pivot
A structure for objects that store chart point references, drawing references, and volume information for `ZigZag` instances.
Fields:
ln (series line) : References a `line` object that connects the coordinates from the `start` and `end` chart points.
lb (series label) : References a `label` object that displays pivot data at the `end` chart point's coordinates.
isHigh (series bool) : Specifies whether the pivot at the `end` chart point's coordinates is a pivot high.
vol (series float) : The cumulative volume across the bars between the `start` and `end` chart points.
start (chart.point) : References a `chart.point` object containing the coordinates of the previous pivot point.
end (chart.point) : References a `chart.point` object containing the coordinates of the current pivot point.
ZigZag
A structure for objects that maintain Zig Zag drawing settings, pivots, and cumulative volume data.
Fields:
settings (Settings) : References a `Settings` object that specifies the Zig Zag drawing's calculation and display properties.
pivots (array) : References an array of `Pivot` objects that store pivot point, drawing, and volume information.
sumVol (series float) : The cumulative volume across bars covered by the latest `Pivot` object's line segment.
extend (Pivot) : References a `Pivot` object that projects a line from the last confirmed pivot point to the current bar's `close`.
PineML_v6Library "PineML_v6"
ML Library for lightweight strategies. Implements k-NN with matrix storage.
method new_model(k, history, features)
Създава нов модел
Namespace types: series int, simple int, input int, const int
Parameters:
k (int) : Брой съседи (напр. 5)
history (int) : Дълбочина на паметта (напр. 1000 бара)
features (int) : Брой променливи, които ще следим
method train(model, feature_array, label)
Добавя нови данни към паметта на модела
Namespace types: KNN_Model
Parameters:
model (KNN_Model) : Инстанцията на модела
feature_array (array) : Масив с текущите стойности на индикаторите
label (float) : Резултатът (класът), свързан с тези данни
method predict(model, query_features)
Изчислява прогноза на база текущите данни
Namespace types: KNN_Model
Parameters:
model (KNN_Model)
query_features (array)
KNN_Model
Fields:
k_neighbors (series int)
max_history (series int)
features (matrix)
labels (array)
feature_count (series int)
StrategyMatrixLibLibrary "StrategyMatrixLib"
render_matrix(posStr, digits, bgCol, headBg, headTxt, valCol, valTxt)
Renders a strategy performance matrix (table) using strategy.* and strategy.closedtrades.*
Parameters:
posStr (string) : Table anchor position: "Top Left" | "Top Right" | "Bottom Left" | "Bottom Right"
digits (int) : Decimal places for numeric formatting
bgCol (color) : Background color for non-header cells
headBg (color) : Background for header rows
headTxt (color) : Text color for header rows
valCol (color) : Background for value cells
valTxt (color) : Text color for value cells
Returns: table id The created/updated table ID
SlopeUtilsLibrary "SlopeUtils"
calcSlope(src, atr_series, length)
Calculates a normalized slope based on price change relative to ATR.
Parameters:
src (float) : (series float) The source input (e.g., close).
atr_series (float) : (series float) The ATR value for normalization.
length (simple int) : (simple int) The lookback period for the slope calculation.
Returns: (float) The normalized slope value.
BoxesLibLibrary "BoxesLib"
isOverlappingBox(_boxes, _top, _bottom)
Parameters:
_boxes (array)
_top (float)
_bottom (float)
isTooCloseBox(_boxes, _top, _bottom, zoneProximityPct)
Parameters:
_boxes (array)
_top (float)
_bottom (float)
zoneProximityPct (float)
createBox(_boxes, _top, _bottom, _leftBarIndex, _color, _txt, _is_breakout, numberLimit, zoneProximityPct, currentClose, isConfirmed)
Parameters:
_boxes (array)
_top (float)
_bottom (float)
_leftBarIndex (int)
_color (color)
_txt (string)
_is_breakout (bool)
numberLimit (int)
zoneProximityPct (float)
currentClose (float)
isConfirmed (bool)
manageBoxes(_boxes, _is_breakout, currentClose, isConfirmed)
Parameters:
_boxes (array)
_is_breakout (bool)
currentClose (float)
isConfirmed (bool)
TradingSystems_AlphaLib_v1_FinalLibrary "TradingSystems_AlphaLib_v1_Final"
Master Library for Institutional Analysis v1
@author jmcanovelles
calc_ema(len)
Calculates standardized EMA
Parameters:
len (simple int)
calc_adx(len)
Calculates precise ADX and DI
Parameters:
len (simple int)
TradingSystems_AlphaLib_v6//@version=6
// @description Master Library for Institutional Grade Analysis v1
// @author jmcanovelles
library("TradingSystems_AlphaLib_v6")
// @function Calculates standardized EMA
// @param len Period for the average
export calc_ema(int len) =>
ta.ema(close, len)
// @function Calculates precise ADX and DI
// @param len Calculation period
export calc_adx(int len) =>
= ta.dmi(len, len)
OKXJsonLibrary "OKXJson"
f_buildId(prefix, instrument)
Parameters:
prefix (string)
instrument (string)
f_utcTimestamp()
f_investmentType(internalAction, entryType, closeType)
Parameters:
internalAction (string)
entryType (string)
closeType (string)
f_build(id, okxAction, marketPosition, prevMarketPosition, instrument, signalToken, timestampUtc, investmentType, amount, maxLagSeconds)
Parameters:
id (string)
okxAction (string)
marketPosition (string)
prevMarketPosition (string)
instrument (string)
signalToken (string)
timestampUtc (string)
investmentType (string)
amount (string)
maxLagSeconds (string)
SharelineUI_LibraryLibrary "SharelineUI_Library"
get_text_size(opt)
Parameters:
opt (string)
status_color(val)
Parameters:
val (float)
trend_color(trend_cat)
Parameters:
trend_cat (string)
momentum_color(score, bullTh, bearTh)
Parameters:
score (float)
bullTh (float)
bearTh (float)
create_standard_hud(pos, cols, rows)
Parameters:
pos (string)
cols (int)
rows (int)
Mirpapa_Lib_StructLibrary "Mirpapa_Lib_Struct"
ICT 구조 변화 감지 라이브러리 (BOS, CHoCH, MSS, Sweep)
initStructState()
StructState 초기화
checkBOS(_trend, _currentClose, _lastHHPrice, _lastLLPrice)
BOS 체크 (추세 지속) - 종가 기준
Parameters:
_trend (string) : 현재 추세
_currentClose (float) : 현재 종가
_lastHHPrice (float) : 마지막 HH 가격
_lastLLPrice (float) : 마지막 LL 가격
Returns:
checkCHoCH(_trend, _currentClose, _lastHHPrice, _lastLLPrice)
CHoCH 체크 (추세 전환) - 종가 기준
Parameters:
_trend (string) : 현재 추세
_currentClose (float) : 현재 종가
_lastHHPrice (float) : 마지막 HH 가격
_lastLLPrice (float) : 마지막 LL 가격
Returns:
checkSweep(_currentHigh, _currentLow, _currentClose, _lastHHPrice, _lastLLPrice)
Sweep 체크 (유동성 수집) 설명
Parameters:
_currentHigh (float) : 현재 고가
_currentLow (float) : 현재 저가
_currentClose (float) : 현재 종가
_lastHHPrice (float) : 마지막 HH 가격
_lastLLPrice (float) : 마지막 LL 가격
Returns:
checkMSS(_hadCHoCH, _chochDir, _currentHigh, _currentLow, _chochPrice)
MSS 체크 (CHoCH + 리테스트 확인)
Parameters:
_hadCHoCH (bool) : CHoCH 발생 여부
_chochDir (string) : CHoCH 방향
_currentHigh (float) : 현재 고가
_currentLow (float) : 현재 저가
_chochPrice (float) : CHoCH 발생 가격
Returns:
drawStructLabel(_price, _time, _type, _dir, _lblColor)
구조 변화 라벨 그리기
Parameters:
_price (float) : 가격
_time (int) : 시간
_type (string) : 구조 타입
_dir (string) : 방향
_lblColor (color) : 라벨 색상
drawStructLine(_price, _startTime, _endTime, _lineColor, _lineWidth)
구조 변화 라인 그리기
Parameters:
_price (float) : 가격
_startTime (int) : 시작 시간
_endTime (int) : 끝 시간
_lineColor (color) : 라인 색상
_lineWidth (int) : 라인 두께
StructType
구조 타입 상수
Fields:
BOS (series string)
CHOCH (series string)
MSS (series string)
SWEEP (series string)
TrendDir
추세 방향 상수
Fields:
UP (series string)
DOWN (series string)
NONE (series string)
StructState
구조 변화 상태
Fields:
_trend (series string) : 현재 추세 방향
_lastHHPrice (series float) : 마지막 HH 가격
_lastHHTime (series int) : 마지막 HH 시간
_lastLLPrice (series float) : 마지막 LL 가격
_lastLLTime (series int) : 마지막 LL 시간
_peakHHPrice (series float) : 최고 HH 가격 (BOS 레벨용)
_peakHHTime (series int) : 최고 HH 시간
_peakLLPrice (series float) : 최저 LL 가격 (BOS 레벨용)
_peakLLTime (series int) : 최저 LL 시간
_bosLevelHH (series float) : BOS 체크용 HH 레벨 (확정된 최고 HH)
_bosLevelHHTime (series int) : BOS 체크용 HH 시간
_bosLevelLL (series float) : BOS 체크용 LL 레벨 (확정된 최저 LL)
_bosLevelLLTime (series int) : BOS 체크용 LL 시간
Mirpapa_Lib_UnicornLibrary "Mirpapa_Lib_Unicorn"
유니콘 패턴 라이브러리 (Unicorn Pattern Library)
유니콘 모델 전략 로직, 데이터 구조체 및 상태 관리를 구현합니다.
initUnicornData(_isBull, _createTime, _createBar, _timeframe)
UnicornData 초기화
@description 새로운 UnicornData 객체를 생성하고 초기화합니다.
Parameters:
_isBull (bool) : 방향 (True: 상승, False: 하락)
_createTime (int) : 생성 시간
_createBar (int) : 생성 Bar Index
_timeframe (string) : 시간대
calculateOverlap(_obTop, _obBot, _fvgTop, _fvgBot)
중첩 영역(Overlap Zone) 계산
@description OB와 FVG 사이의 겹치는 영역을 계산합니다.
Parameters:
_obTop (float) : OB 상단
_obBot (float) : OB 하단
_fvgTop (float) : FVG 상단
_fvgBot (float) : FVG 하단
Returns: 겹침 영역 상단, 하단, 겹침 여부
updateUnicornStatus(_data, _currentHigh, _currentLow, _time)
유니콘 상태 업데이트
@description 가격 움직임에 따라 유니콘 패턴의 상태를 업데이트합니다.
active: 진입 대기 (리테스트 대기) -> triggered: 진입 (TP/SL 대기) -> win/loss: 결과 확정
Parameters:
_data (UnicornData) : UnicornData 객체
_currentHigh (float) : 현재 고가
_currentLow (float) : 현재 저가
_time (int) : 현재 시간
Returns: UnicornData 업데이트된 객체
activateUnicorn(_data)
유니콘 활성화 (Active 전환)
@description Pending 상태인 유니콘 데이터를 Active 상태로 전환합니다. (보통 CHoCH 발생 시 호출)
Parameters:
_data (UnicornData) : UnicornData 객체
setTradeLevels(_data, _entry, _stop, _target)
트레이딩 레벨 설정
@description 진입가, 목표가, 손절가를 설정합니다.
Parameters:
_data (UnicornData) : UnicornData 객체
_entry (float) : 진입가
_stop (float) : 손절가
_target (float) : 목표가
UnicornData
유니콘 데이터 (UnicornData)
Fields:
_isBull (series bool) : // 상승/하락 방향 (True: Long, False: Short)
_status (series string) : // "pending", "active", "triggered", "win", "loss", "cancelled"
_createTime (series int) : // 생성 시간
_createBar (series int) : // 생성 bar_index
_obTop (series float) : // OB 상단
_obBot (series float) : // OB 하단
_obTime (series int) : // OB 캔들 시간
_obBox (series box) : // OB 박스 객체
_fvgTop (series float) : // FVG 상단
_fvgBot (series float) : // FVG 하단
_fvgTime (series int) : // FVG 시간
_fvgBox (series box) : // FVG 박스 객체
_zoneTop (series float) : // 겹침 영역 상단 (Unicorn Zone)
_zoneBot (series float) : // 겹침 영역 하단 (Unicorn Zone)
_zoneBox (series box) : // Unicorn Zone 박스 객체
_chochConfirmed (series bool) : // CHoCH 확정 여부
_chochTime (series int) : // CHoCH 발생 시간
_chochPrice (series float) : // CHoCH 돌파 가격
_entryPrice (series float) : // 진입가
_targetPrice (series float) : // 목표가 (다음 유동성 레벨)
_stopPrice (series float) : // 손절가 (Zone 반대편)
_result (series string) : // "none", "win", "loss"
_resultTime (series int) : // 결과 확정 시간
_resultPrice (series float) : // 결과 확정 가격
_profitPips (series float) : // 수익 pips (양수)
_lossPips (series float) : // 손실 pips (음수)
_profitPercent (series float) : // 수익 %
_lossPercent (series float) : // 손실 %
_rrRatio (series float) : // Risk:Reward 비율
_timeframe (series string) : // 시간대 (HTF/MTF/CTF)
_triggerTime (series int) : // 진입 트리거 시간 (리테스트)
_triggerPrice (series float) : // 진입 트리거 가격
_isRetested (series bool) : // 리테스트 여부
_retestCount (series int) : // 리테스트 횟수
_maxDrawdown (series float) : // 최대 손실폭 (진입 후)
_maxProfit (series float) : // 최대 수익폭 (진입 후)






















