is_strategyCorrection-Adaptive Trend Strategy (Open-Source)
Core Advantage: Designed specifically for the is_correction indicator, with full transparency and customization options.
Key Features:
Open-Source Code:
✅ Full access to the strategy logic – study how every trade signal is generated.
✅ Freedom to customize – modify entry/exit rules, risk parameters, or add new indicators.
✅ No black boxes – understand and trust every decision the strategy makes.
Built for is_correction:
Filters out false signals during market noise.
Works only in confirmed trends (is_correction = false).
Adaptable for Your Needs:
Change Take Profit/Stop Loss ratios directly in the code.
Add alerts, notifications, or integrate with other tools (e.g., Volume Profile).
For Developers/Traders:
Use the code as a template for your own strategies.
Test modifications risk-free on historical data.
How the Strategy Works:
Main Goal:
Automatically buys when the price starts rising and sells when it starts falling, but only during confirmed trends (ignoring temporary pullbacks).
What You See on the Chart:
📈 Up arrows ▼ (below the candle) = Buy signal.
📉 Down arrows ▲ (above the candle) = Sell signal.
Gray background = Market is in a correction (no trades).
Key Mechanics:
Buy Condition:
Price closes higher than the previous candle + is_correction confirms the main trend (not a pullback).
Example: Red candle → green candle → ▼ arrow → buy.
Sell Condition:
Price closes lower than the previous candle + is_correction confirms the trend (optional: turn off short-selling in settings).
Exit Rules:
Closes trades automatically at:
+0.5% profit (adjustable in settings).
-0.5% loss (adjustable).
Or if a reverse signal appears (e.g., sell signal after a buy).
User-Friendly Settings:
Sell – On (default: ON):
ON → Allows short-selling (selling when price falls).
OFF → Strategy only buys and closes positions.
Revers (default: OFF):
ON → Inverts signals (▼ = sell, ▲ = buy).
%Profit & %Loss:
Adjust these values (0-30%) to increase/decrease profit targets and risk.
Example Scenario:
Buy Signal:
Price rises for 3 days → green ▼ arrow → strategy buys.
Stop loss set 0.5% below entry price.
If price keeps rising → trade closes at +0.5% profit.
Correction Phase:
After a rally, price drops for 1 day → gray background → strategy ignores the drop (no action).
Stop Loss Trigger:
If price drops 0.5% from entry → trade closes automatically.
Key Features:
Correction Filter (is_correction):
Acts as a “noise filter” → avoids trades during temporary pullbacks.
Flexibility:
Disable short-selling, flip signals, or tweak profit/loss levels in seconds.
Transparency:
Open-source code → see exactly how every signal is generated (click “Source” in TradingView).
Tips for Beginners:
Test First:
Run the strategy on historical data (click the “Chart” icon in TradingView).
See how it performed in the past.
Customize It:
Increase %Profit to 2-3% for volatile assets like crypto.
Turn off Sell – On if short-selling confuses you.
Trust the Stop Loss:
Even if you think the price will rebound, the strategy will close at -0.5% to protect your capital.
Where to Find Settings:
Click the strategy name on the top-left of your chart → adjust sliders/toggles in the menu.
Русская Версия
Трендовая стратегия с открытым кодом
Главное преимущество: Полная прозрачность логики и адаптация под ваши нужды.
Особенности:
Открытый исходный код:
✅ Видите всю «кухню» стратегии – как формируются сигналы, когда открываются сделки.
✅ Меняйте правила – корректируйте тейк-профит, стоп-лосс или добавляйте новые условия.
✅ Никаких секретов – вы контролируете каждое правило.
Заточка под is_correction:
Игнорирует ложные сигналы в коррекциях.
Работает только в сильных трендах (is_correction = false).
Гибкая настройка:
Подстройте параметры под свой риск-менеджмент.
Добавьте свои индикаторы или условия для входа.
Для трейдеров и разработчиков:
Используйте код как основу для своих стратегий.
Тестируйте изменения на истории перед реальной торговлей.
Простыми словами:
Почему это удобно:
Открытый код = полный контроль. Вы можете:
Увидеть, как именно стратегия решает купить или продать.
Изменить правила закрытия сделок (например, поставить TP=2% вместо 1.5%).
Добавить новые условия (например, торговать только при высоком объёме).
Примеры кастомизации:
Новички: Меняйте только TP/SL в настройках (без кодинга).
Продвинутые: Добавьте RSI-фильтр, чтобы избегать перекупленности.
Разработчики: Встройте стратегию в свою торговую систему.
Как начать:
Скачайте код из TradingView.
Изучите логику в разделе strategy.entry/exit.
Меняйте параметры в блоке input.* (безопасно!).
Тестируйте изменения и оптимизируйте под свои цели.
Как работает стратегия:
Главная задача:
Автоматически покупает, когда цена начинает расти, и продаёт, когда падает. Но делает это «умно» — только когда рынок в основном тренде, а не во временном откате (коррекции).
Что видно на графике:
📈 Стрелки вверх ▼ (под свечой) — сигнал на покупку.
📉 Стрелки вниз ▲ (над свечой) — сигнал на продажу.
Серый фон — рынок в коррекции (не торгуем).
Как это работает:
Когда покупаем:
Если цена закрылась выше предыдущей и индикатор is_correction показывает «основной тренд» (не коррекция).
Пример: Была красная свеча → стала зелёная → появилась стрелка ▼ → покупаем.
Когда продаём:
Если цена закрылась ниже предыдущей и is_correction подтверждает тренд (опционально, можно отключить в настройках).
Когда закрываем сделку:
Автоматически при достижении:
+0.5% прибыли (можно изменить в настройках).
-0.5% убытка (можно изменить).
Или если появился противоположный сигнал (например, после покупки пришла стрелка продажи).
Настройки для чайников:
«Sell – On» (включено по умолчанию):
Если включено → стратегия будет продавать в шорт.
Если выключено → только покупки и закрытие позиций.
«Revers» (выключено по умолчанию):
Если включить → стратегия будет работать наоборот (стрелки ▼ = продажа, ▲ = покупка).
«%Profit» и «%Loss»:
Меняйте эти цифры (от 0 до 30), чтобы увеличить/уменьшить прибыль и риски.
Пример работы:
Сигнал на покупку:
Цена 3 дня растет → появляется зелёная стрелка ▼ → стратегия покупает.
Стоп-лосс ставится на 0.5% ниже цены входа.
Если цена продолжает расти → сделка закрывается при +0.5% прибыли.
Коррекция:
После роста цена падает на 1 день → фон становится серым → стратегия игнорирует это падение (не закрывает сделку).
Стоп-лосс:
Если цена упала на 0.5% от точки входа → сделка закрывается автоматически.
Важные особенности:
Фильтр коррекций (is_correction):
Это «защита от шума» — стратегия не реагирует на мелкие откаты, работая только в сильных трендах.
Гибкие настройки:
Можно запретить шорты, перевернуть сигналы или изменить уровни прибыли/убытка за 2 клика.
Прозрачность:
Весь код открыт → вы можете увидеть, как формируется каждый сигнал (меню «Исходник» в TradingView).
Советы для новичков:
Начните с теста:
Запустите стратегию на исторических данных (кнопка «Свеча» в окне TradingView).
Посмотрите, как она работала в прошлом.
Настройте под себя:
Увеличьте %Profit до 2-3%, если торгуете валюты.
Отключите «Sell – On», если не понимаете шорты.
Доверяйте стоп-лоссу:
Даже если кажется, что цена развернётся — стратегия закроет сделку при -0.5%, защитив ваш депозит.
Где найти настройки:
Кликните на название стратегии в верхнем левом углу графика → откроется меню с ползунками и переключателями.
Важно: Стратегия предоставляет «рыбу» – чтобы она стала «уловистой», адаптируйте её под свой стиль торговли!
Narzędzia Pine
200 EMA AlertHow It Works:
The 200 EMA calculates the average price over the last 200 periods, giving more weight to recent price movements for a smoother and more responsive trend line.
It helps traders determine whether the market is in a bullish (above 200 EMA) or bearish (below 200 EMA) phase.
Why Traders Use the 200 EMA:
✅ Trend Confirmation – If the price is above the 200 EMA, the trend is bullish; if below, the trend is bearish.
✅ Dynamic Support & Resistance – Price often reacts around the 200 EMA, making it a key level for entries and exits.
✅ Works on All Timeframes – Whether on the 1-minute chart or the daily timeframe, the 200 EMA is effective for scalping, swing trading, and long-term investing.
✅ Easy to Combine with Other Indicators – Traders pair it with RSI, MACD, or price action for stronger confirmation.
How to Use It in Trading:
📌 Trend Trading – Buy when price pulls back to the 200 EMA in an uptrend; sell when price retests it in a downtrend.
📌 Breakout Strategy – A strong candle breaking above/below the 200 EMA signals a possible trend reversal.
📌 Filtering Trades – Many traders only take long trades above and short trades below the 200 EMA to align with the overall market trend.
Conclusion:
The 200 EMA is an essential indicator for traders of all levels, offering clear trend direction, strong support/resistance zones, and trade filtering for better decision-making. Whether you're trading forex, stocks, or crypto, mastering the 200 EMA can give you a significant edge in the markets. 🚀📈
Day Counter with Custom RulesRelease Notes – Day Counter with Custom Rules Indicator
Version 1.0
New Features:
Day Counter Calculation
The indicator calculates the number of days elapsed from a user‑specified start date.
The start date is provided as an input (in milliseconds), with a default set to January 1, 2023.
Customizable Appearance
Users can choose the text color and background color for the day counter label.
There is an option to remove the table background (making it transparent).
The table’s position on the chart is fully configurable via standard position options (top‑left, top‑center, top‑right, etc.).
Custom Trading Rules Table
Users can define up to 20 custom rule texts.
Each rule has its own customizable text color.
The rules are displayed in a table below the day counter.
Combined Table Display
The indicator combines the day counter and the custom trading rules into a single table.
Table layout settings such as border width, frame width, text size, and position are fully configurable.
The table is updated on the last bar, ensuring the most recent day count and custom rules are shown.
Responsive Design
The table automatically adjusts its row count based on the number of custom rules defined.
User-Friendly Interface
All input parameters are organized into logical groups (such as "Table Settings" and "Custom Rules"), making it easy to customize the indicator.
Consecutive Bullish/Bearish Candles🔍 Overview:
This indicator detects market manipulation and deception by identifying sequences of consecutive bullish or bearish candles. It highlights potential reversal zones where trends may exhaust or trap traders before reversing.
📌 How It Works:
The user can set a custom number of consecutive bullish or bearish candles (default: 5).
If the set number of consecutive green (bullish) or red (bearish) candles appears, the indicator plots a signal on the chart.
This pattern often signals exhaustion, stop hunts, or market traps, making it useful for traders looking for reversal opportunities.
📊 Features:
✅ Customizable candle count for detection
✅ Visual signals (✅ for bullish, ❌ for bearish)
✅ Alerts support for automated notifications
✅ Works on all timeframes and all markets (crypto, stocks, forex)
⚠️ Note:
This indicator does not guarantee reversals but helps identify areas where traders may be trapped and a trend shift is likely. Always use it with other confluence factors like volume, support/resistance, and market sentiment.
🚀 Use this tool to spot market deception and trade smart!
Anari Gold Circuit BacktestUses Neural net weights from a trained strategy. Volume, price, time, and value area high/low go into the decision making.
Wave Modulation Demo█ OVERVIEW
This script demonstrates Stacked Wave Modulation by visualizing four interconnected waves. Wave 1 is the base wave, influencing Wave 2's frequency, which in turn modulates Wave 3's amplitude, and finally, Wave 3 modulates Wave 4's phase. Explore the fascinating effects of wave modulation by adjusting the inputs for each wave and their modulation scales.
══════════════════════════════════════════════════
█ CONCEPTS
This script visualizes a cascade of wave modulations:
1 — Base Wave (Wave 1): This is the foundational wave. Its parameters (type, frequency, amplitude, phase, vertical shift) are directly controlled and serve as the basis for subsequent modulations.
2 — Frequency Modulation (Wave 2): Wave 2's frequency is modulated by Wave 1 . As Wave 1 oscillates, it dynamically changes the frequency of Wave 2 , creating interesting frequency variations. The Frequency Mod Scale input controls the intensity of this modulation.
3 — Amplitude Modulation (Wave 3): Building upon the cascade, Wave 3 's amplitude is modulated by Wave 2 . The peaks and troughs of Wave 2 influence the amplitude of Wave 3 , resulting in amplitude variations. The Amplitude Mod Scale input adjusts the strength of this amplitude modulation.
4 — Phase Modulation (Wave 4): Finally, Wave 4 's phase is modulated by Wave 3 . Wave 3 's oscillations shift the phase of Wave 4 , leading to phase-related distortions and dynamic wave patterns. The Phase Mod Scale input determines the extent of phase modulation.
5 — Stacked Wave (Average): The script calculates and plots the average of all four waves, providing a composite view of the combined modulation effects.
══════════════════════════════════════════════════
█ FEATURES
The script is organized into input groups for each wave, allowing for detailed customization:
1 — Wave 1: Base Wave
• Type : Select the waveform type for Wave 1 (Sine, Cosine, Triangle, Square).
• Frequency (Hz) : Sets the base frequency of Wave 1 in Hertz (cycles per second).
• Amplitude : Controls the vertical amplitude or height of Wave 1.
• Phase Shift (deg) : Adjusts the phase shift of Wave 1 in degrees, shifting the wave horizontally.
• Vertical Shift : Sets the vertical position of Wave 1 on the chart.
2 — Wave 2: Frequency Modulation
• Type : Select the waveform type for Wave 2.
• Base Frequency (Hz) : Sets the base frequency of Wave 2, before modulation.
• Amplitude : Controls the amplitude of Wave 2.
• Phase Shift (deg) : Adjusts the phase shift of Wave 2.
• Vertical Shift : Sets the vertical position of Wave 2.
• Frequency Mod Scale : Determines the degree to which Wave 1 modulates Wave 2's frequency. Higher values increase the modulation effect.
3 — Wave 3: Amplitude Modulation
• Type : Select the waveform type for Wave 3.
• Base Frequency (Hz) : Sets the base frequency of Wave 3.
• Amplitude : Controls the base amplitude of Wave 3, before modulation.
• Phase Shift (deg) : Adjusts the phase shift of Wave 3.
• Vertical Shift : Sets the vertical position of Wave 3.
• Amplitude Mod Scale : Determines the degree to which Wave 2 modulates Wave 3's amplitude. Higher values increase the modulation effect.
4 — Wave 4: Phase Modulation
• Type : Select the waveform type for Wave 4.
• Base Frequency (Hz) : Sets the base frequency of Wave 4.
• Amplitude : Controls the amplitude of Wave 4.
• Phase Shift (deg) : Sets the base phase shift of Wave 4, before modulation.
• Vertical Shift : Sets the vertical position of Wave 4.
• Phase Mod Scale : Determines the degree to which Wave 3 modulates Wave 4's phase. Higher values increase the modulation effect.
══════════════════════════════════════════════════
█ HOW TO USE
1. Add the "Stacked Wave Modulation Demo" script to your TradingView chart.
2. Explore the input settings. Each wave has its own group of customizable parameters.
3. Adjust the Type , Frequency , Amplitude , Phase Shift , and Vertical Shift for each wave to define their base characteristics.
4. Experiment with the modulation scales ( Frequency Mod Scale , Amplitude Mod Scale , Phase Mod Scale ) to control the intensity of the modulation effects between the waves.
5. Observe how the waves interact and how the modulations shape their forms and the final stacked wave (average).
══════════════════════════════════════════════════
█ NOTES
* This script utilizes the `waves` and `hsvColor` libraries. Look for other scripts on my profile.
* The frequencies are set in Hertz (cycles per second), which relate to bars on the chart. A frequency of 0.5 Hz means 0.5 cycles per bar, or 1 cycle every 2 bars.
* Adjusting the modulation scales allows you to fine-tune the visual impact of the modulation effects.
* The color of each wave plot is dynamically generated based on its value using the HSV color model for visual distinction.
* Feel free to modify and experiment with the script to create different modulation schemes or stacking methods.
Let me know if you have any other questions or would like further refinements!
MACD Color Shift//@version=5
// Title: MACD with Color Intensity
indicator("MACD Color Shift", overlay = false)
// MACD Inputs
fast_length = input.int(12, "Fast Length", minval=1)
slow_length = input.int(26, "Slow Length", minval=1)
signal_length = input.int(9, "Signal Length", minval=1)
// MACD Calculation
= ta.macd(close, fast_length, slow_length, signal_length)
// Calculate momentum (rate of change) to determine color intensity
macdMomentum = ta.change(macdLine)
histMomentum = ta.change(hist)
// Define color conditions
// For Histogram
lightGreen = hist > 0 and histMomentum >= 0
darkGreen = hist > 0 and histMomentum < 0
lightRed = hist < 0 and histMomentum <= 0
darkRed = hist < 0 and histMomentum > 0
// Plot MACD Line
plot(macdLine, "MACD", color=color.blue, linewidth=1)
// Plot Signal Line
plot(signalLine, "Signal", color=color.orange, linewidth=1)
// Plot Histogram with conditional colors
plot(hist, "Histogram", style=plot.style_histogram,
color=lightGreen ? #90EE90 : darkGreen ? #006400 : lightRed ? #FFB6C1 : #8B0000)
// Plot zero line
plot(0, "Zero", color=color.gray, linewidth=1)
Volume Flow Indicator Signals | iSolani
Volume Flow Indicator Signals | iSolani: Decoding Trend Momentum with Volume Precision
In markets where trends are fueled by institutional participation, discerning genuine momentum from false moves is critical. The Volume Flow Indicator Signals | iSolani cuts through this noise by synthesizing price action with volume dynamics, generating high-confidence signals when capital flows align with directional bias. This tool reimagines traditional volume analysis by incorporating volatility-adjusted thresholds and dual-layer smoothing, offering traders a laser-focused approach to trend identification.
Core Methodology
The indicator employs a multi-stage calculation to quantify volume-driven momentum:
Volatility-Adjusted Filter: Measures price changes via log returns, scaling significance using a 30-bar standard deviation multiplied by user-defined sensitivity (default: 2x).
Volume Normalization: Caps extreme volume spikes at 3x the 50-bar moving average, preventing distortion from anomalous trades.
Directional Volume Flow: Assigns positive/negative values to volume based on whether price movement exceeds volatility-derived thresholds.
Dual Smoothing: Applies consecutive SMA (3-bar) and EMA (14-bar) to create the Volume Flow Indicator (VFI) and its signal line, filtering out transient fluctuations.
Breaking New Ground
This implementation introduces three key innovations:
Adaptive Noise Gates: Unlike static volume oscillators, the sensitivity coefficient dynamically adjusts to market volatility, reducing false signals during choppy conditions.
Institutional Volume Capping: The vcoef parameter limits the influence of outlier volume spikes, focusing on sustained institutional activity rather than one-off trades.
Non-Repainting Signals: Generates single-per-trend labels (buy below bars, sell above) to avoid chart clutter while maintaining visual clarity.
Engine Under the Hood
The script executes through five systematic stages:
Data Preparation: Computes HLC3 typical price and its logarithmic rate of change.
Threshold Calculation: Derives dynamic cutoff levels using 30-period volatility scaled by user sensitivity.
Volume Processing: Filters raw volume through a 50-bar SMA, capping extremes at 3x average.
VFI Construction: Sums directional volume flow over 50 bars, smoothed with a 3-bar SMA.
Signal Generation: Triggers alerts when VFI crosses zero, confirmed by a 14-bar EMA crossover.
Standard Configuration
Optimized defaults balance responsiveness and reliability:
Volume MA: 50-bar smoothing window
Sensitivity: 2.0 (doubles volatility threshold)
Signal Smoothing: 14-bar EMA
Volume Cap: 3x average (hidden parameter)
VFI Smoothing: Enabled (3-bar SMA)
By fusing adaptive volume filtering with price confirmation logic, the Volume Flow Indicator Signals | iSolani transforms raw market data into institutional-grade trend signals. Its ability to mute choppy price action while amplifying high-conviction volume moves makes it particularly effective for spotting early trend reversals in equities, forex, and futures markets.
Combined IndicatorThis script merges the features of the RSI Volatility Suppression Zones , Twin Range Filter, and Zero-Lag MA Trend Levels into a single indicator while maintaining their core functionalities.
It includes:
RSI-based volatility detection
Twin Range Filter for buy/sell signals
Zero-Lag MA Trend Levels for trend identification
Unified signal plotting for easier visualization
Trendicator EMA17This indicator is to follow the trend in the short term when the price goes below the EMA17 it shows that the short term is not favour for longs and vice versa.
SMA Strategy Builder: Create & Prove Profitability📄 Pine Script Strategy Description (For Publishing on TradingView)
🎯 Strategy Title:
SMA Strategy Builder: Create & Prove Profitability
✨ Description:
This tool is designed for traders who want to build, customize, and prove their own SMA-based trading strategies. The strategy tracks capital growth in real-time, providing clear evidence of profitability after each trade. Users can adjust key parameters such as SMA period, take profit levels, and initial capital, making it a flexible solution for backtesting and strategy validation.
🔍 Key Features:
✅ SMA-Based Logic:
Core trading logic revolves around the Simple Moving Average (SMA).
SMA period is fully adjustable to suit various trading styles.
🎯 Customizable Take Profit (TP):
User-defined TP percentages per position.
TP line displayed as a Step Line with Breaks for clear segmentation.
Visual 🎯TP label for quick identification of profit targets.
💵 Capital Tracking (Proof of Profitability):
Initial capital is user-defined.
Capital balance updates after each closed trade.
Shows both absolute profit/loss and percentage changes for every position.
Darker green profit labels for better readability and dark red for losses.
📈 Capital Curve (Performance Visualization):
Capital growth curve available (hidden by default, can be enabled via settings).
📏 Dynamic Label Positioning:
Label positions adjust dynamically based on the price range.
Ensures consistent visibility across low and high-priced assets.
⚡ How It Works:
Long Entry:
Triggered when the price crosses above the SMA.
TP level is calculated as a user-defined percentage above the entry price.
Short Entry:
Triggered when the price crosses below the SMA.
TP level is calculated as a user-defined percentage below the entry price.
TP Execution:
Positions close immediately once the TP level is reached (no candle close confirmation needed).
🔔 Alerts:
🟩 Long Signal Alert: When the price crosses above the SMA.
🟥 Short Signal Alert: When the price crosses below the SMA.
🎯 TP Alert: When the TP target is reached.
⚙️ Customization Options:
📅 SMA Period: Choose the moving average period that best fits your strategy.
🎯 Take Profit (%): Adjust TP percentages for flexible risk management.
💵 Initial Capital: Set the starting capital for realistic backtesting.
📈 Capital Curve Toggle: Enable or disable the capital curve to track overall performance.
🌟 Why Use This Tool?
🔧 Flexible Strategy Creation: Adjust core parameters and create tailored SMA-based strategies.
📈 Performance Proof: Capital tracking acts as real proof of profitability after each trade.
🎯 Immediate TP Execution: No waiting for candle closures; profits lock in as soon as targets are hit.
💹 Comprehensive Performance Insights: Percentage-based and absolute capital tracking with dynamic visualization.
🏦 Clean Visual Indicators: Strategy insights made clear with dynamic labeling and adjustable visuals.
⚠️ Disclaimer:
This script is provided for educational and informational purposes only. Trading financial instruments carries risk, and past performance does not guarantee future results. Always perform your own due diligence before making any trading decisions.
Liquidity Grab [crypticmaster]Test Strat Liquidity Grab by CrypticMaster.
How It Works
Liquidity Zones: The script identifies recent highs and lows using the ta.highest and ta.lowest functions.
Liquidity Grab Detection: It detects when price breaks a recent high/low and then reverses (closes below/above the high/low).
Confirmation: A simple moving average (SMA) crossover is used to confirm the reversal.
Signals: Buy/sell signals are generated when the conditions are met.
Heikin Ashi Option: You can toggle Heikin Ashi candles for smoother price action analysis.
Stock Earnings Viewer for Pine ScreenerThe script, titled "Stock Earnings Viewer with Surprise", fetches actual and estimated earnings, calculates absolute and percent surprise values, and presents them for analysis. It is intended to use in Pine Screener, as on chart it is redundant.
How to Apply to Pine Screener
Favorite this script
Open pine screener www.tradingview.com
Select "Stock Earnings Viewer with Surprise" in "Choose indicator"
Click "Scan"
Data
Actual Earnings: The reported earnings per share (EPS) for the stock, sourced via request.earnings().
Estimated Earnings: Analyst-predicted EPS, accessed with field=earnings.estimate.
Absolute Surprise: The difference between actual and estimated earnings (e.g., actual 1.2 - estimated 1.0 = 0.2).
Percent Surprise (%): The absolute surprise as a percentage of estimated earnings (e.g., (0.2 / 1.0) * 100 = 20%). Note: This may return NaN or infinity if estimated earnings are zero, due to division by zero.
Practical Use
This screener script allows users to filter stocks based on earnings metrics. For example, you could screen for stocks where Percent Surprise > 15 to find companies exceeding analyst expectations significantly, or use Absolute Surprise < -0.5 to identify underperformers.
Astro R4.0Regarding the code that has a significant impact on Pine Community and many feel helped by it, this is the code that I ported from VBA to PineScript which comes from simontelescopium owner of astroexcel dot wordpress dot com and "astrofnc" by Keith Burnett, previously I used it personally but I forgot to give a citation to those who are entitled to them both so that when I shared it for community use and it has been shared by brother @BarefootJoey with the additions made by him personally, there was no citation for them.
Apologies for my negligence because I am only human.
Hopefully with this script it can help the community to see the potential for implementation in the trading world as a significant variable.
Finally, I publish this script as a reference to find out astronomical charts presented in table form to make it easier to visualize and debug as long as the input.timestamp() allow it.
Future updates for optimization using library of brother @BarefootJoey
Thank you.
Mon to Fri + LSE and NYSE📌 Highlight Custom Days & Market Hours Indicator 📌
🔹 Overview:
This script allows traders to visually highlight specific weekdays and market sessions directly on their TradingView charts. With customizable checkboxes, you can choose which days of the week to highlight, along with session times for the New York Stock Exchange (NYSE) and London Stock Exchange (LSE).
🔹 Features:
✅ Select individual weekdays (Monday–Friday) to highlight in blue
✅ Highlight NYSE open hours (2:30 PM – 9:30 PM UK time) in green
✅ Highlight LSE open hours (8:00 AM – 4:30 PM UK time) in orange
✅ Ensures NYSE & LSE sessions are only highlighted on weekdays (no weekends)
✅ Clean and simple visualization for enhanced market awareness
🔹 How to Use:
1️⃣ Add the indicator to your TradingView chart
2️⃣ Use the settings panel to enable/disable specific weekdays
3️⃣ Toggle NYSE or LSE session highlights based on your trading preference
🚀 Perfect for traders who follow institutional sessions and want better time-based confluence in their strategies!
Auto Levels Test RHAuto Levels Test RH is an indicator that automatically draws support and resistance levels based on local extremes and the ZigZag pattern. It helps traders identify key levels for entering and exiting trades. The indicator analyzes the last 100 bars and determines significant price zones.
Cash And Carry Arbitrage BTC Compare Month 6 by SeoNo1Detailed Explanation of the BTC Cash and Carry Arbitrage Script
Script Title: BTC Cash And Carry Arbitrage Month 6 by SeoNo1
Short Title: BTC C&C ABT Month 6
Version: Pine Script v5
Overlay: True (The indicators are plotted directly on the price chart)
Purpose of the Script
This script is designed to help traders analyze and track arbitrage opportunities between the spot market and futures market for Bitcoin (BTC). Specifically, it calculates the spread and Annual Percentage Yield (APY) from a cash-and-carry arbitrage strategy until a specific expiry date (in this case, June 27, 2025).
The strategy helps identify profitable opportunities when the futures price of BTC is higher than the spot price. Traders can then buy BTC in the spot market and short BTC futures contracts to lock in a risk-free profit.
1. Input Settings
Spot Symbol: The real-time BTC spot price from Binance (BTCUSDT).
Futures Symbol: The BTC futures contract that expires in June 2025 (BTCUSDM2025).
Expiry Date: The expiration date of the futures contract, set to June 27, 2025.
These inputs allow users to adjust the symbols or expiry date according to their trading needs.
2. Price Data Retrieval
Spot Price: Fetches the latest closing price of BTC from the spot market.
Futures Price: Fetches the latest closing price of BTC futures.
Spread: The difference between the futures price and the spot price (futures_price - spot_price).
The spread indicates how much higher (or lower) the futures price is compared to the spot market.
3. Time to Maturity (TTM) and Annual Percentage Yield (APY) Calculation
Current Date: Gets the current timestamp.
Time to Maturity (TTM): The number of days left until the futures contract expires.
APY Calculation:
Formula:
APY = ( Spread / Spot Price ) x ( 365 / TTM Days ) x 100
This represents the annualized return from holding a cash-and-carry arbitrage position if the trader buys BTC at the spot price and sells BTC futures.
4. Display Information Table on the Chart
A table is created on the chart's top-right corner showing the following data:
Metric: Labels such as Spread and APY
Value: Displays the calculated spread and APY
The table automatically updates at the latest bar to display the most recent data.
5. Alert Condition
This sets an alert condition that triggers every time the script runs.
In practice, users can modify this alert to trigger based on specific conditions (e.g., APY exceeds a threshold).
6. Plotting the APY and Spread
APY Plot: Displays the annualized yield as a blue line on the chart.
Spread Plot: Visualizes the futures-spot spread as a red line.
This helps traders quickly identify arbitrage opportunities when the spread or APY reaches desirable levels.
How to Use the Script
Monitor Arbitrage Opportunities:
A positive spread indicates a potential cash-and-carry arbitrage opportunity.
The larger the APY, the more profitable the arbitrage opportunity could be.
Timing Trades:
Execute a buy on the BTC spot market and simultaneously sell BTC futures when the APY is attractive.
Close both positions upon futures contract expiry to realize profits.
Risk Management:
Ensure you have sufficient margin to hold both positions until expiry.
Monitor funding rates and volatility, which could affect returns.
Conclusion
This script is an essential tool for traders looking to exploit price discrepancies between the BTC spot market and futures market through a cash-and-carry arbitrage strategy. It provides real-time data on spreads, annualized returns (APY), and visual alerts, helping traders make informed decisions and maximize their profit potential.
Oblique StrategiesHi, this is a fun script that will print an Oblique Strategy to help you think laterally for the day of trading ahead of you.
Oblique Strategies are a concept conceived by Brian Eno the Music Producer, Artist, and modern-day philosopher. Oblique Strategies are a pack of 52 cards that have a creative suggestion on each one. When Brian was at a point at which he could not see a clear way forward in his creations, he would pick out a random card out of the Oblique Strategies pack, to help him think differently as to how to move forward. They are specifically devised for music creators, but i find the help in a multitude of situations.
Enjoy!
Advanced Averaged Momentum Indicator (AAMI)Key Features of AAMI:
Combination of Momentum Indicators: It averages normalized values from RSI, MACD histogram, raw Momentum, and Stochastic oscillator to give a comprehensive view of momentum.
Normalization: Each component is normalized to a scale from -1 to 1 to ensure they contribute equally to the AMI calculation.
Visual Cues: The indicator includes visual levels for neutral, overbought, and oversold conditions to aid in quick decision-making.
Alerts: Basic alert conditions are included for when AMI moves into overbought or oversold territory, which traders can customize further.
Customizable: All parameters can be adjusted within TradingView to tailor the indicator to different market conditions or trading strategies.
Smoothing: Included an SMA for AMI to reduce noise and give smoother signals.
Divergence Detection: Implemented a basic divergence detection mechanism to spot potential reversals.
Usage Tips:
Overbought/Oversold: When AMI goes above 0.7, it might suggest an overbought condition, potentially signaling a sell or take profit. Below -0.7 might indicate oversold conditions, suggesting a buy opportunity.
Divergence: Watch for divergences between the AMI and price action for signals of potential trend reversals.
Crossing Zero: The AMI crossing from negative to positive might be used as a buy signal, and vice versa for a sell signal.
This script provides a new way to view momentum by consolidating multiple traditional indicators into one, potentially offering clearer signals in complex market environments.
Boilerplate Configurable Strategy [Yosiet]This is a Boilerplate Code!
Hello! First of all, let me introduce myself a little bit. I don't come from the world of finance, but from the world of information and communication technologies (ICT) where we specialize in data processing with the aim of automating it and eliminating all human factors and actors in the processes. You could say that I am an algotrader.
That said, in my journey through trading in recent years I have understood that this world is often shown to be incomplete. All those who want to learn about trading only end up learning a small part of what it really entails, they only seek to learn how to read candlesticks. Therefore, I want to share with the entire community a fraction of what I have really understood it to be.
As a computer scientist, the most important thing is the data, it is the raw material of our work and without data you simply cannot do anything. Entropy is simple: Data in -> Data is transformed -> Data out.
The quality of the outgoing data will directly depend on the incoming data, there is no greater mystery or magic in the process. In trading it is no different, because at the end of the day it is nothing more than data. As we often say, if garbage comes in, garbage comes out.
Most people focus on the results only, on the outgoing data, because in the end we all want the same thing, to make easy money. Very few pay attention to the input data, much less to the process.
Now, I am not here to delude you, because there is no bigger lie than easy money, but I am here to give you a boilerplate code that will help you create strategies where you only have to concentrate on the quality of the incoming data.
To the Point
The code is a strategy boilerplate that applies the technique that you decide to customize for the criteria for opening a position. It already has the other factors involved in trading programmed and automated.
1. The Entry
This section of the boilerplate is the one that each individual must customize according to their needs and knowledge. The code is offered with two simple, well-known strategies to exemplify how the code can be reused for your own benefits.
For the purposes of this post on tradingview, I am going to use the simplest of the known strategies in trading for entries: SMA Crossing
// SMA Cross Settings
maFast = ta.sma(close, length)
maSlow = ta.sma(open, length)
The Strategy Properties for all cases published here:
For Stock TSLA H1 From 01/01/2025 To 02/15/2025
For Crypto XMR-USDT 30m From 01/01/2025 To 02/15/2025
For Forex EUR-USD 5m From 01/01/2025 To 02/15/2025
But the goal of this post is not to sell you a dream, else to show you that the same Entry decision works very well for some and does not for others and with this boilerplate code you only have to think of entries, not exits.
2. Schedules, Days, Sessions
As you know, there are an infinite number of markets that are susceptible to the sessions of each country and the news that they announce during those sessions, so the code already offers parameters so that you can condition the days and hours of operation, filter the best time parameters for a specific market and time frame.
3. Data Filtering
The data offered in trading are numerical series presented in vectors on a time axis where an endless number of mathematical equations can be applied to process them, with matrix calculation and non-linear regressions being the best, in my humble opinion.
4. Read Fundamental Macroeconomic Events, News
The boilerplate has integration with the tradingview SDK to detect when news will occur and offers parameters so that you can enable an exclusion time margin to not operate anything during that time window.
5. Direction and Sense
In my experience I have found the peculiarity that the same algorithm works very well for a market in a time frame, but for the same market in another time frame it is only a waste of time and money. So now you can easily decide if you only want to open LONG, SHORT or both side positions and know how effective your strategy really is.
6. Reading the money, THE PURPOSE OF EVERYTHING
The most important section in trading and the reason why many clients usually hire me as a financial programmer, is reading and controlling the money, because in the end everyone wants to win and no one wants to lose. Now they can easily parameterize how the money should flow and this is the genius of this boilerplate, because it is what will really decide if an algorithm (Indicator: A bunch of math equations) for entries will really leave you good money over time.
7. Managing the Risk, The Ego Destroyer
Many trades, little money. Most traders focus on making money and none of them know about statistics and the few who do know something about it, only focus on the winrate. Well, with this code you can unlock what really matters, the true success criteria to be able to live off of trading: Profit Factor, Sortino Ratio, Sharpe Ratio and most importantly, will you really make money?
8. Managing Emotions
Finally, the main reason why many lose money is because they are very bad at managing their emotions, because with this they will no longer need to do so because the boilerplate has already programmed criteria to chase the price in a position, cut losses and maximize profits.
In short, this is a boilerplate code that already has the data processing and data output ready, you only have to worry about the data input.
“And so the trader learned: the greatest edge was not in predicting the storm, but in building a boat that could not sink.”
DISCLAIMER
This post is intended for programmers and quantitative traders who already have a certain level of knowledge and experience. It is not intended to be financial advice or to sell you any money-making script, if you use it, you do so at your own risk.