OPEN-SOURCE SCRIPT
EMA20 Cross Strategy with countertrades and signals

EMA20 Cross Strategy Documentation
Overview
The EMA20 Cross Strategy with Counter-Trades and Instant Signals is a Pine Script (version 6) trading strategy designed for the TradingView platform. It implements an Exponential Moving Average (EMA) crossover system to generate buy and sell signals, with optional trend filtering, session-based trading, instant signal processing, and visual/statistical feedback. The strategy supports counter-trades (closing opposing positions before entering new ones) and operates with a fixed trade size in EUR.
Features
EMA Crossover Mechanism:
Uses a short-term EMA (configurable length, default: 1) and a long-term EMA (default: 20) to detect crossovers.
A buy signal is generated when the short EMA crosses above the long EMA.
A sell signal is generated when the short EMA crosses below the long EMA.
Instant Signals:
If enabled (useInstantSignals), signals are based on the current price crossing the short EMA, rather than waiting for the candle close.
This allows faster trade execution but may increase sensitivity to price fluctuations.
Trend Filter:
Optionally filters trades based on the trend direction (useTrendFilter).
Long trades are allowed only when the short EMA (or price, for instant signals) is above the long EMA.
Short trades are allowed only when the short EMA (or price) is below the long EMA.
Session Filter:
Restricts trading to specific market hours (sessionStart, default: 09:00–17:00) if enabled (useSessionFilter).
Ensures trades occur only during active market sessions, reducing exposure to low-liquidity periods.
Customizable Timeframe:
The EMA calculations can use a higher timeframe (e.g., 5m, 15m, 1H, 4H, 1D, default: 1H) via request.security.
This allows the strategy to base signals on longer-term trends while operating on a shorter-term chart.
Trade Management:
Fixed trade size of €100,000 per trade (tradeAmount), with a maximum quantity cap (maxQty = 10,000) to prevent oversized trades.
Counter-trades: Closes short positions before entering a long position and vice versa.
Trades are executed with a minimum quantity of 1 to ensure valid orders.
Visualization:
EMA Lines: The short EMA is colored based on the last signal (green for buy, red for sell, gray for neutral), and the long EMA is orange.
Signal Markers: Displays buy/sell signals as arrows (triangles) above/below candles if enabled (showSignalShapes).
Background/Candle Coloring: Optionally colors the chart background or candles green (bullish) or red (bearish) based on the trend (useColoredBars).
Statistics Display:
If enabled (useStats), a label on the chart shows:
Total closed trades
Open trades
Win rate (%)
Number of winning/losing trades
Profit factor (gross profit / gross loss)
Net profit
Maximum drawdown
Configuration Inputs
EMA Short Length (emaLength): Length of the short-term EMA (default: 1).
Trend EMA Length (trendLength): Length of the long-term EMA (default: 20).
Enable Trend Filter (useTrendFilter): Toggles trend-based filtering (default: true).
Color Candles (useColoredBars): Colors candles instead of the background (default: true).
Enable Session Filter (useSessionFilter): Restricts trading to specified hours (default: false).
Trading Session (sessionStart): Defines trading hours (default: 09:00–17:00).
Show Statistics (useStats): Displays performance stats on the chart (default: true).
Show Signal Arrows (showSignalShapes): Displays buy/sell signals as arrows (default: true).
Use Instant Signals (useInstantSignals): Generates signals based on live price action (default: false).
EMA Timeframe (emaTimeframe): Timeframe for EMA calculations (options: 5m, 15m, 1H, 4H, 1D; default: 1H).
Strategy Logic
Signal Generation:
Standard Mode: Signals are based on EMA crossovers (short EMA crossing long EMA) at candle close.
Instant Mode: Signals are based on the current price crossing the short EMA, enabling faster reactions.
Trade Execution:
On a buy signal, closes any short position and opens a long position.
On a sell signal, closes any long position and opens a short position.
Position size is calculated as the minimum of €100,000 or available equity, divided by the current price, capped at 10,000 units.
Filters:
Trend Filter: Ensures trades align with the trend direction (if enabled).
Session Filter: Restricts trades to user-defined market hours (if enabled).
Visual Feedback
EMA Lines: Provide a clear view of the short and long EMAs, with the short EMA’s color reflecting the latest signal.
Signal Arrows: Large green triangles (buy) below candles or red triangles (sell) above candles for easy signal identification.
Chart Coloring: Highlights bullish (green) or bearish (red) trends via background or candle colors.
Statistics Label: Displays key performance metrics in a label above the chart for quick reference.
Usage Notes
Initial Capital: €100,000 (configurable via initial_capital).
Currency: EUR (set via currency).
Order Processing: Orders are processed at candle close (process_orders_on_close=true) unless instant signals are enabled.
Dynamic Requests: Allows dynamic timeframe adjustments for EMA calculations (dynamic_requests=true).
Platform: Designed for TradingView, compatible with any market supported by the platform (e.g., stocks, forex, crypto).
Example Use Case
Scenario: Trading on a 5-minute chart with a 1-hour EMA timeframe, trend filter enabled, and session filter set to 09:00–17:00.
Behavior: The strategy will:
Calculate EMAs on the 1-hour timeframe.
Generate buy signals when the short EMA crosses above the long EMA (and price is above the long EMA).
Generate sell signals when the short EMA crosses below the long EMA (and price is below the long EMA).
Execute trades only during 09:00–17:00.
Display green/red candles and performance stats on the chart.
Limitations
Instant Signals: May lead to more frequent signals, increasing the risk of false positives in volatile markets.
Fixed Trade Size: Does not adjust dynamically based on market conditions beyond equity and max quantity limits.
Session Filter: Simplified and may not account for complex session rules or holidays.
Statistics: Displayed on-chart, which may clutter the view in smaller charts.
Customization
Adjust emaLength and trendLength to suit different market conditions (e.g., shorter for scalping, longer for swing trading).
Toggle useInstantSignals for faster or more stable signal generation.
Modify sessionStart to align with specific market hours.
Disable useStats or showSignalShapes for a cleaner chart.
This strategy is versatile for both manual and automated trading, offering flexibility for various markets and trading styles while providing clear visual and statistical feedback.
Overview
The EMA20 Cross Strategy with Counter-Trades and Instant Signals is a Pine Script (version 6) trading strategy designed for the TradingView platform. It implements an Exponential Moving Average (EMA) crossover system to generate buy and sell signals, with optional trend filtering, session-based trading, instant signal processing, and visual/statistical feedback. The strategy supports counter-trades (closing opposing positions before entering new ones) and operates with a fixed trade size in EUR.
Features
EMA Crossover Mechanism:
Uses a short-term EMA (configurable length, default: 1) and a long-term EMA (default: 20) to detect crossovers.
A buy signal is generated when the short EMA crosses above the long EMA.
A sell signal is generated when the short EMA crosses below the long EMA.
Instant Signals:
If enabled (useInstantSignals), signals are based on the current price crossing the short EMA, rather than waiting for the candle close.
This allows faster trade execution but may increase sensitivity to price fluctuations.
Trend Filter:
Optionally filters trades based on the trend direction (useTrendFilter).
Long trades are allowed only when the short EMA (or price, for instant signals) is above the long EMA.
Short trades are allowed only when the short EMA (or price) is below the long EMA.
Session Filter:
Restricts trading to specific market hours (sessionStart, default: 09:00–17:00) if enabled (useSessionFilter).
Ensures trades occur only during active market sessions, reducing exposure to low-liquidity periods.
Customizable Timeframe:
The EMA calculations can use a higher timeframe (e.g., 5m, 15m, 1H, 4H, 1D, default: 1H) via request.security.
This allows the strategy to base signals on longer-term trends while operating on a shorter-term chart.
Trade Management:
Fixed trade size of €100,000 per trade (tradeAmount), with a maximum quantity cap (maxQty = 10,000) to prevent oversized trades.
Counter-trades: Closes short positions before entering a long position and vice versa.
Trades are executed with a minimum quantity of 1 to ensure valid orders.
Visualization:
EMA Lines: The short EMA is colored based on the last signal (green for buy, red for sell, gray for neutral), and the long EMA is orange.
Signal Markers: Displays buy/sell signals as arrows (triangles) above/below candles if enabled (showSignalShapes).
Background/Candle Coloring: Optionally colors the chart background or candles green (bullish) or red (bearish) based on the trend (useColoredBars).
Statistics Display:
If enabled (useStats), a label on the chart shows:
Total closed trades
Open trades
Win rate (%)
Number of winning/losing trades
Profit factor (gross profit / gross loss)
Net profit
Maximum drawdown
Configuration Inputs
EMA Short Length (emaLength): Length of the short-term EMA (default: 1).
Trend EMA Length (trendLength): Length of the long-term EMA (default: 20).
Enable Trend Filter (useTrendFilter): Toggles trend-based filtering (default: true).
Color Candles (useColoredBars): Colors candles instead of the background (default: true).
Enable Session Filter (useSessionFilter): Restricts trading to specified hours (default: false).
Trading Session (sessionStart): Defines trading hours (default: 09:00–17:00).
Show Statistics (useStats): Displays performance stats on the chart (default: true).
Show Signal Arrows (showSignalShapes): Displays buy/sell signals as arrows (default: true).
Use Instant Signals (useInstantSignals): Generates signals based on live price action (default: false).
EMA Timeframe (emaTimeframe): Timeframe for EMA calculations (options: 5m, 15m, 1H, 4H, 1D; default: 1H).
Strategy Logic
Signal Generation:
Standard Mode: Signals are based on EMA crossovers (short EMA crossing long EMA) at candle close.
Instant Mode: Signals are based on the current price crossing the short EMA, enabling faster reactions.
Trade Execution:
On a buy signal, closes any short position and opens a long position.
On a sell signal, closes any long position and opens a short position.
Position size is calculated as the minimum of €100,000 or available equity, divided by the current price, capped at 10,000 units.
Filters:
Trend Filter: Ensures trades align with the trend direction (if enabled).
Session Filter: Restricts trades to user-defined market hours (if enabled).
Visual Feedback
EMA Lines: Provide a clear view of the short and long EMAs, with the short EMA’s color reflecting the latest signal.
Signal Arrows: Large green triangles (buy) below candles or red triangles (sell) above candles for easy signal identification.
Chart Coloring: Highlights bullish (green) or bearish (red) trends via background or candle colors.
Statistics Label: Displays key performance metrics in a label above the chart for quick reference.
Usage Notes
Initial Capital: €100,000 (configurable via initial_capital).
Currency: EUR (set via currency).
Order Processing: Orders are processed at candle close (process_orders_on_close=true) unless instant signals are enabled.
Dynamic Requests: Allows dynamic timeframe adjustments for EMA calculations (dynamic_requests=true).
Platform: Designed for TradingView, compatible with any market supported by the platform (e.g., stocks, forex, crypto).
Example Use Case
Scenario: Trading on a 5-minute chart with a 1-hour EMA timeframe, trend filter enabled, and session filter set to 09:00–17:00.
Behavior: The strategy will:
Calculate EMAs on the 1-hour timeframe.
Generate buy signals when the short EMA crosses above the long EMA (and price is above the long EMA).
Generate sell signals when the short EMA crosses below the long EMA (and price is below the long EMA).
Execute trades only during 09:00–17:00.
Display green/red candles and performance stats on the chart.
Limitations
Instant Signals: May lead to more frequent signals, increasing the risk of false positives in volatile markets.
Fixed Trade Size: Does not adjust dynamically based on market conditions beyond equity and max quantity limits.
Session Filter: Simplified and may not account for complex session rules or holidays.
Statistics: Displayed on-chart, which may clutter the view in smaller charts.
Customization
Adjust emaLength and trendLength to suit different market conditions (e.g., shorter for scalping, longer for swing trading).
Toggle useInstantSignals for faster or more stable signal generation.
Modify sessionStart to align with specific market hours.
Disable useStats or showSignalShapes for a cleaner chart.
This strategy is versatile for both manual and automated trading, offering flexibility for various markets and trading styles while providing clear visual and statistical feedback.
オープンソーススクリプト
TradingViewの精神に則り、この作者はスクリプトのソースコードを公開しているので、その内容を理解し検証することができます。作者に感謝です!無料でお使いいただけますが、このコードを投稿に再利用する際にはハウスルールに従うものとします。
免責事項
これらの情報および投稿は、TradingViewが提供または保証する金融、投資、取引、またはその他の種類のアドバイスや推奨を意図したものではなく、またそのようなものでもありません。詳しくは利用規約をご覧ください。
オープンソーススクリプト
TradingViewの精神に則り、この作者はスクリプトのソースコードを公開しているので、その内容を理解し検証することができます。作者に感謝です!無料でお使いいただけますが、このコードを投稿に再利用する際にはハウスルールに従うものとします。
免責事項
これらの情報および投稿は、TradingViewが提供または保証する金融、投資、取引、またはその他の種類のアドバイスや推奨を意図したものではなく、またそのようなものでもありません。詳しくは利用規約をご覧ください。