OPEN-SOURCE SCRIPT

[alert-custome] direction-ema-dca-rsi-security

257

Below is a detailed description of the Pine Script v5 strategy titled [alert-custome] direction-ema-dca-rsi-security. This strategy automates Long or Short trading on cryptocurrency pairs (e.g., BTCUSDT.P), leveraging technical indicators such as EMA, RSI, and ATR, combined with a Dollar Cost Averaging (DCA) approach. It integrates with OKX via alerts for automated trading execution.

Overview
Strategy Name: [alert-custome] direction-ema-dca-rsi-security
Objective: Automate Long or Short trades using EMA, RSI, and ATR signals, with DCA to improve average position price when the market moves against the position. The strategy allows customization of trade direction (Long or Short) and integrates with OKX for automated execution.
Type: Supports both Long and Short trades, using leverage and flexible capital management.
Target Market: Designed for high-volatility cryptocurrency markets, particularly perpetual futures pairs like BTCUSDT.P.
Key Features:
Uses Fast and Slow EMAs to identify trends and entry points.
Combines RSI from the current timeframe and a user-defined timeframe (security RSI) to detect overbought/oversold conditions.
Implements DCA to add to positions when prices move unfavorably.
Integrates with OKX via JSON alerts for automated trading.
Supports Take Profit (TP) and Stop Loss (SL) based on ATR or percentage values.
Structure and Key Components
1. Strategy Configuration
Basic Settings:
Initial Capital: $1,000.
Leverage: Default 6x, adjustable from 1x to 10x.
Order Type: Cash-based, with a default quantity of 10.
Commission: 0.1% per trade.
Pyramiding: Allows up to 100 concurrent orders.
Slippage: 3 pips.
Backtest Fill Limits Assumption: 3 pips, ensuring limit orders are filled within a price range.
Calculate on Order Fills: Enabled (calc_on_order_fills = true).
Use Bar Magnifier: Enabled for detailed candle data calculations.
Fill Orders on Standard OHLC: Enabled, ensuring orders match standard open, high, low, close prices.
2. Input Parameters
The strategy offers customizable inputs, grouped as follows:

Strategy:
Fast/Slow EMA Length: Fast EMA (default 9), Slow EMA (default 21) for trend detection.
ATR Length: Default 14 for volatility measurement.
RSI Length: Default 14 for overbought/oversold detection.
RSI Security Timeframe: Default 15 minutes (options: 5m, 15m, 30m, 1h, 4h, D, W, M).
Direction Security Timeframe: Default daily (options: 4h, D, W, M).
Strategy Size:
Init Webhook Balance ($): Initial balance for webhook (default 0, uses strategy balance if unset).
Leverage: Financial leverage (default 6x).
Init Size Equity (%): Initial position size as a percentage of equity (default 2%).
Size Increase (%): Position size increase per DCA order (default 15%).
Max DCA Orders: Maximum DCA orders (default 15).
Strategy DCA:
Init Percent to DCA (%): Initial price drop/rise for DCA (default 2%).
Increase Step Percent to DCA (%): Incremental DCA price adjustment (default 1%).
Decrease DCA with ATR: ATR multiplier for DCA price (default 0, disabled).
Strategy DCA RSI:
RSI to DCA: RSI threshold for DCA (default 50, below for Long, above for Short).
Security RSI to DCA: RSI threshold for security timeframe (default 50).
Strategy Delay:
Off-Time Delays / Order (s): Delay between orders (default 1000 seconds).
Off-Time Active Stop Loss (Hour): Delay for activating Stop Loss (default 0, disabled).
Strategy TPSL (Take Profit/Stop Loss):
ATR Multiplier TP: ATR multiplier for Take Profit (default 2x).
Init TP (%): Initial Take Profit percentage (default 2%).
ATR Multiplier SL: ATR multiplier for Stop Loss (default 0, disabled).
Init SL (%): Initial Stop Loss percentage (default 0%, disabled).
Strategy Direction:
Trade Direction: Trade direction (default Long, options: Long, Short).
Strategy OKX:
OKX Signal Key: Signal key for OKX API integration.
3. Market Data
Technical Indicators:
EMA: Fast EMA (9) and Slow EMA (21) on the current timeframe for trend identification.
RSI: RSI (14) on the current timeframe and a user-defined timeframe (rsiSecurityTimeframe) for overbought/oversold signals.
ATR: ATR (14) for volatility-based calculations of TP, SL, and DCA prices.
External Library: Uses jason5480/chrono_utils/6 for time-related functions.
4. Entry Conditions
Long Position:
Condition 1: Fast EMA crosses above Slow EMA (ta.crossover(fastMA, slowMA)), or
Condition 2: RSI ≤ rsiTrigger (default 50), Fast EMA ≤ Slow EMA, and RSI security ≤ rsiSecurityTrigger (default 50).
Short Position:
Condition 1: Fast EMA crosses below Slow EMA (ta.crossunder(fastMA, slowMA)), or
Condition 2: RSI ≥ rsiTrigger, Fast EMA ≥ Slow EMA, and RSI security ≥ rsiSecurityTrigger.
Constraints:
Entries are allowed only if tradeDirection matches the signal (Long or Short).
Open trades ≤ maxDCAOrders (default 15).
Current price meets DCA conditions (if positions exist).
Time since last order ≥ offTimeMsOpen (default 1000 seconds).
5. Dollar Cost Averaging (DCA)
DCA Conditions:
Long: Current price ≤ DCA price, calculated as:
strategy.position_avg_price - (atrValue * decreaseDCAWithATR), or
strategy.position_avg_price * (1 - currentUnderPercentDCA) (default 2%, increasing by 1% per DCA).
Short: Current price ≥ DCA price, calculated similarly but for price increases.
DCA Management:
Position size increases by 15% per DCA (stepSizePercent).
DCA price distance increases by 1% per order (stepDecreasePercentDCA).
Maximum 15 DCA orders (maxDCAOrders).
6. Position Management
Position Size:
Initial size: 2% of equity (initSizeEquity).
Increases by 15% per DCA order.
Limited by leverage and current balance (currentBalance).
Current Balance:
If webhookInitBalance = 0, uses initial_capital + netprofit + openprofit.
If webhookInitBalance > 0, uses this value plus net and open profits.
Order Delay: Ensures a minimum gap of 1000 seconds between orders (offTimeMsOpen).
7. Exit Conditions
Take Profit (TP):
Long: strategy.position_avg_price + (atrValue * atrMultiplierTP) (default 2x ATR), or strategy.position_avg_price * (1 + initTP) (default 2%).
Short: strategy.position_avg_price - (atrValue * atrMultiplierTP), or strategy.position_avg_price * (1 - initTP).
Stop Loss (SL):
Long: strategy.position_avg_price - (atrValue * atrMultiplierSL), or strategy.position_avg_price * (1 - initSL).
Short: strategy.position_avg_price + (atrValue * atrMultiplierSL), or strategy.position_avg_price * (1 + initSL).
Currently, atrMultiplierSL and initSL = 0, meaning Stop Loss is disabled.
Exit Execution:
Uses strategy.order for Long TP and strategy.exit for Short TP, closing the entire position when TP is reached.
Sends OKX alerts for exits (EXIT_LONG or EXIT_SHORT).
8. Visualization
Plots:
Fast EMA: Red.
Slow EMA: Aqua.
Take Profit Price: Lime.
Position Average Price: Gray.
Background Color: Commented out, but can display green for Long or red for Short.
9. OKX Integration
Alerts:
Sends JSON alerts for entries (ENTER_LONG, ENTER_SHORT) and exits (EXIT_LONG, EXIT_SHORT), including:
Market position, size, order type (market), and investment percentage.
OKX signal key (okxSignalKeyInput) for API integration.
How the Strategy Works
Market Analysis:
Uses EMA (9, 21) for trend detection (crossover/crossunder).
Combines RSI from the current and security timeframes to confirm overbought/oversold conditions.
ATR measures volatility for TP, SL, and DCA price calculations.
Entry:
Long: Triggers on EMA crossover or RSI in oversold territory with a bearish trend.
Short: Triggers on EMA crossunder or RSI in overbought territory with a bullish trend.
Entries are restricted by tradeDirection setting.
DCA:
Adds positions when price moves against the trade (down for Long, up for Short) based on RSI or ATR conditions.
Increases position size and DCA price distance per order.
Exit:
Closes positions when price hits TP (ATR or percentage-based).
Stop Loss is currently disabled, posing a risk.
Risk Management:
Limits DCA orders to 15.
Enforces time delays between orders.
Caps leverage at 10x.
Strengths
Flexible Direction: Supports both Long and Short trades.
Effective DCA: Improves average position price in volatile markets.
OKX Integration: Automates trading via OKX API.
Multi-Timeframe Analysis: Uses RSI from a secondary timeframe for confirmation.
Customizable Capital Management: Adjustable position sizes and leverage.
Weaknesses
No Stop Loss: Disabled SL increases risk of large losses.
OKX Dependency: Requires accurate API configuration.
Simple Conditions: Relies primarily on EMA and RSI, potentially lacking depth.
Fixed Timeframes: Commented-out EMA security logic limits trend analysis flexibility.
Practical Applications
Target Market: High-volatility crypto markets, especially perpetual futures like BTCUSDT.P.
Trading Style: Suitable for short- to medium-term traders using DCA for risk management.
Optimization: Adjust fastMALen, slowMALen, rsiTrigger, or maxDCAOrders for specific markets.
Improvement Suggestions
Enable Stop Loss: Set atrMultiplierSL or initSL > 0 to protect capital.
Use EMA Security: Uncomment fastDirectionEMA and slowDirectionEMA code to enhance trend accuracy.
Optimize Parameters: Use TradingView’s optimization tool to fine-tune rsiTrigger, atrMultiplierTP, or maxDCAOrders.
Add Indicators: Incorporate Volume, ADX, or other indicators for robust entry signals.
Leverage Alerts: Add warnings for high-leverage risks in volatile conditions.
If you need further analysis, code optimization, or additional strategy development, let me know!

Declinazione di responsabilità

Le informazioni ed i contenuti pubblicati non costituiscono in alcun modo una sollecitazione ad investire o ad operare nei mercati finanziari. Non sono inoltre fornite o supportate da TradingView. Maggiori dettagli nelle Condizioni d'uso.