PROTECTED SOURCE SCRIPT
[Kpt-Ahab] Simple AlgoPilot Riskmgt and Backtest

[Kpt-Ahab] Simple AlgoPilot Riskmgt and Backtest
This script provides a compact solution for automated risk management and backtesting within TradingView.
It offers the following core functionalities:
Risk Management:
The system integrates various risk limitation mechanisms:
Percentage-based or trailing stop-loss
Maximum losing streak limitation
Maximum drawdown limitation relative to account equity
Flexible position sizing control (based on equity, fixed size, or contracts)
Dynamic repurchasing of positions ("Repurchase") during losses with adjustable size scaling
Supports multi-stage take-profit targets (TP1/TP2) and automatic stop-loss adjustment to breakeven
External Signal Processing for Backtesting:
In addition to its own moving average crossovers, the script can process external trading signals:
External signals are received via a source input variable (e.g., from other indicators or signal generators)
Positive values (+1) trigger long positions, negative values (–1) trigger short positions
This allows for easy integration of other indicator-based strategies into backtests
Additional Backtesting Features:
Selection between different MA types (SMA, EMA, WMA, VWMA, HMA)
Flexible time filtering (trade only within defined start and end dates)
Simulation of commission costs, slippage, and leverage
Optional alert functions for moving average crossovers
Visualization of liquidation prices and portfolio development in an integrated table
Note: This script is primarily intended for strategic backtesting and risk setting optimization.
Real-time applications should be tested with caution. All order executions, alerts, and risk calculations are purely simulation-based.
Explanation of Calculations and Logics:
1. Risk Management and Position Sizing:
The position size is calculated based on the user’s choice using three possible methods:
Percentage of Equity:
The position size is a defined fraction of the available capital, dynamically adjusted based on market price (riskPerc / close).
Fixed Size (in currency): The user defines a fixed monetary amount to be used per trade.
Contracts: A fixed number of contracts is traded regardless of the current price.
Leverage: The selected leverage multiplies the position size for margin calculations.
2. Trade Logic and Signal Triggering:
Trades can be triggered through two mechanisms:
Internal Signals:
When a fast moving average crosses above or below a slower moving average (ta.crossover, ta.crossunder). The type of moving averages (SMA, EMA, WMA, VWMA, HMA) can be freely selected.

External Signals:
Signals from other indicators can be received via an input source field.
+1 triggers a long entry, –1 triggers a short entry.

Position Management:
Once entered, the position is actively managed.
Multiple take-profit targets are set.
Upon reaching a profit target, the stop-loss can optionally be moved to breakeven.
3. Stop-Loss and Take-Profit Logic:
Stop-Loss Types:
Fixed Percentage Stop:
A fixed distance below/above the entry price.
Trailing Stop:
Dynamically adjusts as the trade moves into profit.
Fast Trailing Stop:
A more aggressive variant of trailing that reacts quicker to price changes.
Take-Profit Management:
Two take-profit targets (TP1 and TP2) are supported, allowing partial exits at different stages.
Remaining positions can either reach the second target or be closed by the stop-loss.
4. Repurchase Strategy ("Scaling In" on Losses):
If a position reaches a specified loss threshold (e.g., –15%), an automatic additional purchase can occur.
The position size is increased by a configurable percentage.
Repurchases happen only if an initial position is already open.
5. Backtesting Control and Filters:
Time Filters:
A trading period can be defined (start and end date).
All trades outside the selected period are ignored.
Risk Filters: Trading is paused if:
A maximum losing streak is reached.
A maximum allowed drawdown is exceeded.
6. Liquidation Calculation (Simulation Only):
The script simulates liquidation prices based on the account balance and position size.
Liquidation lines are drawn on the chart to better visualize potential risk exposure.
This is purely a visual aid — no real broker-side liquidation is performed.
This script provides a compact solution for automated risk management and backtesting within TradingView.
It offers the following core functionalities:
Risk Management:
The system integrates various risk limitation mechanisms:
Percentage-based or trailing stop-loss
Maximum losing streak limitation
Maximum drawdown limitation relative to account equity
Flexible position sizing control (based on equity, fixed size, or contracts)
Dynamic repurchasing of positions ("Repurchase") during losses with adjustable size scaling
Supports multi-stage take-profit targets (TP1/TP2) and automatic stop-loss adjustment to breakeven
External Signal Processing for Backtesting:
In addition to its own moving average crossovers, the script can process external trading signals:
External signals are received via a source input variable (e.g., from other indicators or signal generators)
Positive values (+1) trigger long positions, negative values (–1) trigger short positions
This allows for easy integration of other indicator-based strategies into backtests
Additional Backtesting Features:
Selection between different MA types (SMA, EMA, WMA, VWMA, HMA)
Flexible time filtering (trade only within defined start and end dates)
Simulation of commission costs, slippage, and leverage
Optional alert functions for moving average crossovers
Visualization of liquidation prices and portfolio development in an integrated table
Note: This script is primarily intended for strategic backtesting and risk setting optimization.
Real-time applications should be tested with caution. All order executions, alerts, and risk calculations are purely simulation-based.
Explanation of Calculations and Logics:
1. Risk Management and Position Sizing:
The position size is calculated based on the user’s choice using three possible methods:
Percentage of Equity:
The position size is a defined fraction of the available capital, dynamically adjusted based on market price (riskPerc / close).
Fixed Size (in currency): The user defines a fixed monetary amount to be used per trade.
Contracts: A fixed number of contracts is traded regardless of the current price.
Leverage: The selected leverage multiplies the position size for margin calculations.
2. Trade Logic and Signal Triggering:
Trades can be triggered through two mechanisms:
Internal Signals:
When a fast moving average crosses above or below a slower moving average (ta.crossover, ta.crossunder). The type of moving averages (SMA, EMA, WMA, VWMA, HMA) can be freely selected.
External Signals:
Signals from other indicators can be received via an input source field.
+1 triggers a long entry, –1 triggers a short entry.
Position Management:
Once entered, the position is actively managed.
Multiple take-profit targets are set.
Upon reaching a profit target, the stop-loss can optionally be moved to breakeven.
3. Stop-Loss and Take-Profit Logic:
Stop-Loss Types:
Fixed Percentage Stop:
A fixed distance below/above the entry price.
Trailing Stop:
Dynamically adjusts as the trade moves into profit.
Fast Trailing Stop:
A more aggressive variant of trailing that reacts quicker to price changes.
Take-Profit Management:
Two take-profit targets (TP1 and TP2) are supported, allowing partial exits at different stages.
Remaining positions can either reach the second target or be closed by the stop-loss.
4. Repurchase Strategy ("Scaling In" on Losses):
If a position reaches a specified loss threshold (e.g., –15%), an automatic additional purchase can occur.
The position size is increased by a configurable percentage.
Repurchases happen only if an initial position is already open.
5. Backtesting Control and Filters:
Time Filters:
A trading period can be defined (start and end date).
All trades outside the selected period are ignored.
Risk Filters: Trading is paused if:
A maximum losing streak is reached.
A maximum allowed drawdown is exceeded.
6. Liquidation Calculation (Simulation Only):
The script simulates liquidation prices based on the account balance and position size.
Liquidation lines are drawn on the chart to better visualize potential risk exposure.
This is purely a visual aid — no real broker-side liquidation is performed.
Skrip dilindungi
Skrip ini diterbitkan sebagai sumber tertutup. Akan tetapi, anda boleh menggunakannya dengan percuma dan tanpa had – ketahui lebih lanjut di sini.
Penafian
Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.
Skrip dilindungi
Skrip ini diterbitkan sebagai sumber tertutup. Akan tetapi, anda boleh menggunakannya dengan percuma dan tanpa had – ketahui lebih lanjut di sini.
Penafian
Maklumat dan penerbitan adalah tidak dimaksudkan untuk menjadi, dan tidak membentuk, nasihat untuk kewangan, pelaburan, perdagangan dan jenis-jenis lain atau cadangan yang dibekalkan atau disahkan oleh TradingView. Baca dengan lebih lanjut di Terma Penggunaan.