OPEN-SOURCE SCRIPT
BTC Risk Metric DCA Adapter (3Commas Webhook Strategy)

Risk Metric DCA Adapter (3Commas Webhook Strategy) - WORK IN PROGRESS
This Pine Script strategy, originally inspired by the Risk Metric Indicator, is fundamentally engineered as an Adapter to interface with external trading bots like 3Commas via Webhooks. It calculates a dynamic market risk score and translates that score into specific dollar-cost averaging (DCA) entry levels and tiered profit-taking exits.
Key Features & Logic
Risk Metric Calculation (Credit to The Trading Parrot):
The strategy incorporates a complex, multi-timeframe Risk Metric calculation based on daily and weekly moving averages (SMA) and standard deviation (StDev). This metric aims to quantify the current market overextension or compression relative to long-term historical data. The resulting score dictates the level of conviction for a new trade.
Tiered DCA Entry Sizing:
The strategy defines three distinct Buy Levels (L1, L2, L3) corresponding to increasingly favorable (lower) Risk Metric scores.
L1 (Base): Risk is moderate, initiating the minimum defined trade amount.
L2 (Scaled): Risk is low, initiating L1 amount + L2 amount.
L3 (Aggressive): Risk is very low, initiating L1 + L2 + L3 amounts.
Tiered Profit-Taking Exits:
The strategy implements a staggered, partial profit-taking approach based on the Risk Metric rising:
Sell L1 & L2: Closes a percentage of the current position when the Risk Metric reaches defined high thresholds, locking in partial profits.
Sell L3 (Full Exit): Closes the remaining position when the Risk Metric reaches the highest defined threshold.
The Adapter Function (Webhook Integration)
This script is unique because it uses the Pine Script strategy() function to trigger Order Fills, which are necessary to access powerful placeholders in the TradingView alert system.
Trigger Type: The alert must be set to trigger on Any order fill.
Dynamic Webhook Data: Instead of using fixed alert() commands, the strategy generates dynamic labels (e.g., BUY_ENTRY_L3_USD_1000 or SELL_L1_PCT_25) using the strategy.entry and strategy.close commands.
Data Transfer: The alert message then uses the placeholder {{strategy.order.comment}} to pass these dynamic labels to the 3Commas bot, allowing the bot to execute the precise action (e.g., start_deal_with_volume_in_quote_currency or close_deal_at_market_percentage).
Full Strategy Webhook payload
{
"secret": "YOUR_3COMMAS_SECRET_KEY",
"max_lag": "300",
"timestamp": "{{timenow}}",
"trigger_price": "{{close}}",
"tv_exchange": "{{exchange}}",
"tv_instrument": "{{ticker}}",
"action": "{{strategy.order.action}}",
"bot_uuid": "YOUR_BOT_UUID",
"strategy_info": {
"market_position": "{{strategy.market_position}}",
"market_position_size": "{{strategy.market_position_size}}",
"prev_market_position": "{{strategy.prev_market_position}}",
"prev_market_position_size": "{{strategy.prev_market_position_size}}"
},
"order": {
"amount": "{{strategy.order.contracts}}",
"currency_type": "base",
"comment": "{{strategy.order.comment}}"
}
}
Disclaimer: This script is an adapter tool and does not guarantee profit. Trading requires manual configuration of risk settings, bot parameters, and adherence to platform-specific setup instructions.
This Pine Script strategy, originally inspired by the Risk Metric Indicator, is fundamentally engineered as an Adapter to interface with external trading bots like 3Commas via Webhooks. It calculates a dynamic market risk score and translates that score into specific dollar-cost averaging (DCA) entry levels and tiered profit-taking exits.
Key Features & Logic
Risk Metric Calculation (Credit to The Trading Parrot):
The strategy incorporates a complex, multi-timeframe Risk Metric calculation based on daily and weekly moving averages (SMA) and standard deviation (StDev). This metric aims to quantify the current market overextension or compression relative to long-term historical data. The resulting score dictates the level of conviction for a new trade.
Tiered DCA Entry Sizing:
The strategy defines three distinct Buy Levels (L1, L2, L3) corresponding to increasingly favorable (lower) Risk Metric scores.
L1 (Base): Risk is moderate, initiating the minimum defined trade amount.
L2 (Scaled): Risk is low, initiating L1 amount + L2 amount.
L3 (Aggressive): Risk is very low, initiating L1 + L2 + L3 amounts.
Tiered Profit-Taking Exits:
The strategy implements a staggered, partial profit-taking approach based on the Risk Metric rising:
Sell L1 & L2: Closes a percentage of the current position when the Risk Metric reaches defined high thresholds, locking in partial profits.
Sell L3 (Full Exit): Closes the remaining position when the Risk Metric reaches the highest defined threshold.
The Adapter Function (Webhook Integration)
This script is unique because it uses the Pine Script strategy() function to trigger Order Fills, which are necessary to access powerful placeholders in the TradingView alert system.
Trigger Type: The alert must be set to trigger on Any order fill.
Dynamic Webhook Data: Instead of using fixed alert() commands, the strategy generates dynamic labels (e.g., BUY_ENTRY_L3_USD_1000 or SELL_L1_PCT_25) using the strategy.entry and strategy.close commands.
Data Transfer: The alert message then uses the placeholder {{strategy.order.comment}} to pass these dynamic labels to the 3Commas bot, allowing the bot to execute the precise action (e.g., start_deal_with_volume_in_quote_currency or close_deal_at_market_percentage).
Full Strategy Webhook payload
{
"secret": "YOUR_3COMMAS_SECRET_KEY",
"max_lag": "300",
"timestamp": "{{timenow}}",
"trigger_price": "{{close}}",
"tv_exchange": "{{exchange}}",
"tv_instrument": "{{ticker}}",
"action": "{{strategy.order.action}}",
"bot_uuid": "YOUR_BOT_UUID",
"strategy_info": {
"market_position": "{{strategy.market_position}}",
"market_position_size": "{{strategy.market_position_size}}",
"prev_market_position": "{{strategy.prev_market_position}}",
"prev_market_position_size": "{{strategy.prev_market_position_size}}"
},
"order": {
"amount": "{{strategy.order.contracts}}",
"currency_type": "base",
"comment": "{{strategy.order.comment}}"
}
}
Disclaimer: This script is an adapter tool and does not guarantee profit. Trading requires manual configuration of risk settings, bot parameters, and adherence to platform-specific setup instructions.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.
Скрипт с открытым кодом
В истинном духе TradingView, создатель этого скрипта сделал его открытым исходным кодом, чтобы трейдеры могли проверить и убедиться в его функциональности. Браво автору! Вы можете использовать его бесплатно, но помните, что перепубликация кода подчиняется нашим Правилам поведения.
Отказ от ответственности
Информация и публикации не предназначены для предоставления и не являются финансовыми, инвестиционными, торговыми или другими видами советов или рекомендаций, предоставленных или одобренных TradingView. Подробнее читайте в Условиях использования.