OPEN-SOURCE SCRIPT
EMA Stack Strategy (DCA or Single Entry, HTF Logic)

This strategy implements a multi-moving-average (MA) stacking system combined with flexible execution modes, allowing traders to test both trend-following entries and position management techniques within a single framework.
Core concept
The strategy uses up to four configurable moving averages to define directional bias. A valid trend is identified when the averages are properly stacked (e.g., faster MAs above slower MAs for long trades). Entries can optionally require multiple confirmed closes in a valid stack, which helps reduce noise and avoid premature signals.
Higher timeframe logic and non-repainting behavior
The script supports running MA calculations on a higher timeframe while executing on a lower chart timeframe. Signals are only updated on confirmed higher timeframe closes using request.security() with lookahead disabled, which prevents repainting and ensures that historical results reflect confirmed data.
Dual trading modes
Two execution modes are available:
* DCA / Grid mode: builds a position through multiple entries as price moves against the initial trade. Spacing between entries can be based on fixed units, percentage, or ATR, and can expand progressively using a scaling factor.
* Single Entry mode: places one position per signal and manages it using a selectable exit system.
DCA system design
The DCA module is not a simple averaging tool. It includes:
* Configurable spacing using Units, Percent, or ATR
* Optional geometric spacing expansion (step scaling)
* Position sizing growth (volume scaling) or manual ladder sizing
* Maximum total capital cap to limit exposure
* Choice between anchoring to first entry price or average position price
This structure allows users to test different grid-style risk distributions rather than relying on fixed averaging.
Exit logic
Exit behavior differs by mode:
* DCA mode:
* Take profit is calculated from the average entry (breakeven) plus an offset
* Optional trailing stop activates after price moves in favor
* Optional “after last DCA” exit logic targets a move from the final entry instead of the average price
* Optional MA-based kill switch to close positions when trend structure breaks
* Single Entry mode:
* Multiple exit types including MA cross, ATR-based bracket, risk-reward bracket, percent-based bracket, and time stop
* Optional break-even adjustment
* Optional independent trailing stop
Risk and position management
The strategy includes controls to:
* Limit total capital deployed in DCA mode
* Adjust position sizing per entry
* Configure stop distances using ATR, percent, or structure
* Prevent new trades or DCA adds during specific time windows
These tools are intended to help simulate more realistic position management conditions rather than fixed, static strategies.
Visualization and usability
The script provides:
* Clear MA overlays for trend structure
* Optional plotting of average entry, take profit, and next DCA level
* Trade summary labels including P/L, number of entries, and drawdown in units
* Optional status table showing real-time strategy state
Notes on backtesting and usage
* Results depend heavily on parameter selection, market conditions, and timeframe
* DCA/grid strategies can increase exposure during adverse price movement and should be tested carefully
* Default settings use zero commission and slippage; users should adjust these to better reflect real trading conditions
* Past performance does not guarantee future results
This script is intended as a configurable framework for testing MA-based trend entries combined with different position management techniques, rather than a fixed or optimized trading system.
Core concept
The strategy uses up to four configurable moving averages to define directional bias. A valid trend is identified when the averages are properly stacked (e.g., faster MAs above slower MAs for long trades). Entries can optionally require multiple confirmed closes in a valid stack, which helps reduce noise and avoid premature signals.
Higher timeframe logic and non-repainting behavior
The script supports running MA calculations on a higher timeframe while executing on a lower chart timeframe. Signals are only updated on confirmed higher timeframe closes using request.security() with lookahead disabled, which prevents repainting and ensures that historical results reflect confirmed data.
Dual trading modes
Two execution modes are available:
* DCA / Grid mode: builds a position through multiple entries as price moves against the initial trade. Spacing between entries can be based on fixed units, percentage, or ATR, and can expand progressively using a scaling factor.
* Single Entry mode: places one position per signal and manages it using a selectable exit system.
DCA system design
The DCA module is not a simple averaging tool. It includes:
* Configurable spacing using Units, Percent, or ATR
* Optional geometric spacing expansion (step scaling)
* Position sizing growth (volume scaling) or manual ladder sizing
* Maximum total capital cap to limit exposure
* Choice between anchoring to first entry price or average position price
This structure allows users to test different grid-style risk distributions rather than relying on fixed averaging.
Exit logic
Exit behavior differs by mode:
* DCA mode:
* Take profit is calculated from the average entry (breakeven) plus an offset
* Optional trailing stop activates after price moves in favor
* Optional “after last DCA” exit logic targets a move from the final entry instead of the average price
* Optional MA-based kill switch to close positions when trend structure breaks
* Single Entry mode:
* Multiple exit types including MA cross, ATR-based bracket, risk-reward bracket, percent-based bracket, and time stop
* Optional break-even adjustment
* Optional independent trailing stop
Risk and position management
The strategy includes controls to:
* Limit total capital deployed in DCA mode
* Adjust position sizing per entry
* Configure stop distances using ATR, percent, or structure
* Prevent new trades or DCA adds during specific time windows
These tools are intended to help simulate more realistic position management conditions rather than fixed, static strategies.
Visualization and usability
The script provides:
* Clear MA overlays for trend structure
* Optional plotting of average entry, take profit, and next DCA level
* Trade summary labels including P/L, number of entries, and drawdown in units
* Optional status table showing real-time strategy state
Notes on backtesting and usage
* Results depend heavily on parameter selection, market conditions, and timeframe
* DCA/grid strategies can increase exposure during adverse price movement and should be tested carefully
* Default settings use zero commission and slippage; users should adjust these to better reflect real trading conditions
* Past performance does not guarantee future results
This script is intended as a configurable framework for testing MA-based trend entries combined with different position management techniques, rather than a fixed or optimized trading system.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.
오픈 소스 스크립트
트레이딩뷰의 진정한 정신에 따라, 이 스크립트의 작성자는 이를 오픈소스로 공개하여 트레이더들이 기능을 검토하고 검증할 수 있도록 했습니다. 작성자에게 찬사를 보냅니다! 이 코드는 무료로 사용할 수 있지만, 코드를 재게시하는 경우 하우스 룰이 적용된다는 점을 기억하세요.
면책사항
해당 정보와 게시물은 금융, 투자, 트레이딩 또는 기타 유형의 조언이나 권장 사항으로 간주되지 않으며, 트레이딩뷰에서 제공하거나 보증하는 것이 아닙니다. 자세한 내용은 이용 약관을 참조하세요.