feat: exp16-17 бэктесты (реалистичный Bybit, OHLC, объёмы)

- exp16: реалистичная симуляция Bybit spot margin
- exp16b: grid search stop_scale (0.75x лучший)
- exp16c-d: check frequency + time_exit analysis
- exp16e: комбо-тест stop_scale × time_exit (0.5x + no TE → Sharpe 4.15)
- exp16f: OHLC валидация (Close-only = production behavior)
- exp17: объёмы (VWAP +9% Sharpe, vol_filter WR 51%)

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-10 02:16:09 +10:00
co-authored by Claude Opus 4.6
parent acdcdba9d0
commit 536e32261a
17 changed files with 45425 additions and 0 deletions
@@ -0,0 +1,100 @@
{
"results": [
{
"stop_scale": 0.75,
"final_equity": 255.61,
"total_pnl": 141.61,
"total_ret": 124.2,
"trades": 802,
"wins": 357,
"wr": 44.5,
"sharpe": 3.34,
"max_dd": 7.6,
"stops": 436,
"time_exits": 364,
"monthly_pnl": 6.18,
"skipped_margin": 0,
"skipped_cooldown": 57
},
{
"stop_scale": 1.0,
"final_equity": 210.43,
"total_pnl": 96.43,
"total_ret": 84.6,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.47,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.21,
"skipped_margin": 0,
"skipped_cooldown": 44
},
{
"stop_scale": 1.25,
"final_equity": 177.01,
"total_pnl": 63.01,
"total_ret": 55.3,
"trades": 805,
"wins": 365,
"wr": 45.3,
"sharpe": 1.68,
"max_dd": 8.9,
"stops": 288,
"time_exits": 515,
"monthly_pnl": 2.75,
"skipped_margin": 0,
"skipped_cooldown": 35
},
{
"stop_scale": 1.5,
"final_equity": 159.27,
"total_pnl": 45.27,
"total_ret": 39.7,
"trades": 806,
"wins": 368,
"wr": 45.7,
"sharpe": 1.21,
"max_dd": 12.9,
"stops": 238,
"time_exits": 566,
"monthly_pnl": 1.98,
"skipped_margin": 0,
"skipped_cooldown": 26
},
{
"stop_scale": 2.0,
"final_equity": 131.85,
"total_pnl": 17.85,
"total_ret": 15.7,
"trades": 807,
"wins": 365,
"wr": 45.2,
"sharpe": 0.49,
"max_dd": 14.6,
"stops": 170,
"time_exits": 635,
"monthly_pnl": 0.78,
"skipped_margin": 0,
"skipped_cooldown": 23
},
{
"stop_scale": 2.5,
"final_equity": 119.01,
"total_pnl": 5.01,
"total_ret": 4.4,
"trades": 806,
"wins": 374,
"wr": 46.4,
"sharpe": 0.18,
"max_dd": 19.9,
"stops": 122,
"time_exits": 682,
"monthly_pnl": 0.22,
"skipped_margin": 0,
"skipped_cooldown": 17
}
]
}
@@ -0,0 +1,340 @@
{
"grid1_trailing": [
{
"final_equity": 210.01,
"total_pnl": 96.01,
"total_ret": 84.2,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.46,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.19,
"threshold": 0
},
{
"final_equity": 210.06,
"total_pnl": 96.06,
"total_ret": 84.3,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.45,
"max_dd": 7.8,
"stops": 343,
"time_exits": 458,
"monthly_pnl": 4.19,
"threshold": 0.1
},
{
"final_equity": 206.88,
"total_pnl": 92.88,
"total_ret": 81.5,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.38,
"max_dd": 7.8,
"stops": 341,
"time_exits": 460,
"monthly_pnl": 4.06,
"threshold": 0.25
},
{
"final_equity": 198.97,
"total_pnl": 84.97,
"total_ret": 74.5,
"trades": 803,
"wins": 360,
"wr": 44.8,
"sharpe": 2.22,
"max_dd": 7.8,
"stops": 329,
"time_exits": 472,
"monthly_pnl": 3.71,
"threshold": 0.5
},
{
"final_equity": 186.8,
"total_pnl": 72.8,
"total_ret": 63.9,
"trades": 804,
"wins": 360,
"wr": 44.8,
"sharpe": 1.97,
"max_dd": 7.9,
"stops": 317,
"time_exits": 485,
"monthly_pnl": 3.18,
"threshold": 0.75
},
{
"final_equity": 191.77,
"total_pnl": 77.77,
"total_ret": 68.2,
"trades": 805,
"wins": 367,
"wr": 45.6,
"sharpe": 2.04,
"max_dd": 7.9,
"stops": 302,
"time_exits": 501,
"monthly_pnl": 3.4,
"threshold": 1.0
},
{
"final_equity": 181.32,
"total_pnl": 67.32,
"total_ret": 59.1,
"trades": 805,
"wins": 362,
"wr": 45.0,
"sharpe": 1.81,
"max_dd": 8.1,
"stops": 299,
"time_exits": 504,
"monthly_pnl": 2.94,
"threshold": 1.5
}
],
"grid2_frequency": [
{
"final_equity": 210.01,
"total_pnl": 96.01,
"total_ret": 84.2,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.46,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.19,
"check_every": 1
},
{
"final_equity": 254.76,
"total_pnl": 140.76,
"total_ret": 123.5,
"trades": 798,
"wins": 367,
"wr": 46.0,
"sharpe": 3.04,
"max_dd": 8.5,
"stops": 369,
"time_exits": 427,
"monthly_pnl": 6.15,
"check_every": 2
},
{
"final_equity": 261.94,
"total_pnl": 147.94,
"total_ret": 129.8,
"trades": 797,
"wins": 378,
"wr": 47.4,
"sharpe": 3.12,
"max_dd": 9.9,
"stops": 348,
"time_exits": 447,
"monthly_pnl": 6.46,
"check_every": 3
},
{
"final_equity": 431.66,
"total_pnl": 317.66,
"total_ret": 278.7,
"trades": 653,
"wins": 331,
"wr": 50.7,
"sharpe": 4.78,
"max_dd": 7.4,
"stops": 320,
"time_exits": 331,
"monthly_pnl": 13.87,
"check_every": 4
},
{
"final_equity": 354.1,
"total_pnl": 240.1,
"total_ret": 210.6,
"trades": 794,
"wins": 393,
"wr": 49.5,
"sharpe": 4.29,
"max_dd": 7.3,
"stops": 238,
"time_exits": 554,
"monthly_pnl": 10.48,
"check_every": 5
},
{
"final_equity": 469.49,
"total_pnl": 355.49,
"total_ret": 311.8,
"trades": 780,
"wins": 406,
"wr": 52.1,
"sharpe": 5.12,
"max_dd": 7.7,
"stops": 327,
"time_exits": 451,
"monthly_pnl": 15.52,
"check_every": 7
}
],
"grid3_combos": [
{
"final_equity": 210.01,
"total_pnl": 96.01,
"total_ret": 84.2,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.46,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.19,
"threshold": 0,
"check_every": 1
},
{
"final_equity": 469.49,
"total_pnl": 355.49,
"total_ret": 311.8,
"trades": 780,
"wins": 406,
"wr": 52.1,
"sharpe": 5.12,
"max_dd": 7.7,
"stops": 327,
"time_exits": 451,
"monthly_pnl": 15.52,
"threshold": 0,
"check_every": 7
},
{
"final_equity": 431.66,
"total_pnl": 317.66,
"total_ret": 278.7,
"trades": 653,
"wins": 331,
"wr": 50.7,
"sharpe": 4.78,
"max_dd": 7.4,
"stops": 320,
"time_exits": 331,
"monthly_pnl": 13.87,
"threshold": 0,
"check_every": 4
},
{
"final_equity": 354.1,
"total_pnl": 240.1,
"total_ret": 210.6,
"trades": 794,
"wins": 393,
"wr": 49.5,
"sharpe": 4.29,
"max_dd": 7.3,
"stops": 238,
"time_exits": 554,
"monthly_pnl": 10.48,
"threshold": 0,
"check_every": 5
},
{
"final_equity": 293.72,
"total_pnl": 179.72,
"total_ret": 157.6,
"trades": 783,
"wins": 365,
"wr": 46.6,
"sharpe": 3.43,
"max_dd": 8.7,
"stops": 271,
"time_exits": 510,
"monthly_pnl": 7.85,
"threshold": 0.1,
"check_every": 7
},
{
"final_equity": 366.89,
"total_pnl": 252.89,
"total_ret": 221.8,
"trades": 644,
"wins": 314,
"wr": 48.8,
"sharpe": 4.13,
"max_dd": 9.1,
"stops": 287,
"time_exits": 355,
"monthly_pnl": 11.04,
"threshold": 0.1,
"check_every": 4
},
{
"final_equity": 281.94,
"total_pnl": 167.94,
"total_ret": 147.3,
"trades": 797,
"wins": 377,
"wr": 47.3,
"sharpe": 3.38,
"max_dd": 7.4,
"stops": 209,
"time_exits": 586,
"monthly_pnl": 7.33,
"threshold": 0.1,
"check_every": 5
},
{
"final_equity": 290.31,
"total_pnl": 176.31,
"total_ret": 154.7,
"trades": 783,
"wins": 365,
"wr": 46.6,
"sharpe": 3.4,
"max_dd": 8.7,
"stops": 268,
"time_exits": 513,
"monthly_pnl": 7.7,
"threshold": 0.25,
"check_every": 7
},
{
"final_equity": 356.0,
"total_pnl": 242.0,
"total_ret": 212.3,
"trades": 644,
"wins": 310,
"wr": 48.1,
"sharpe": 4.0,
"max_dd": 9.6,
"stops": 285,
"time_exits": 357,
"monthly_pnl": 10.57,
"threshold": 0.25,
"check_every": 4
},
{
"final_equity": 278.87,
"total_pnl": 164.87,
"total_ret": 144.6,
"trades": 797,
"wins": 377,
"wr": 47.3,
"sharpe": 3.34,
"max_dd": 7.4,
"stops": 205,
"time_exits": 590,
"monthly_pnl": 7.2,
"threshold": 0.25,
"check_every": 5
}
]
}
@@ -0,0 +1,160 @@
{
"results": [
{
"stop_scale": 1.0,
"time_exit": true,
"final_equity": 209.02,
"total_pnl": 95.02,
"total_ret": 83.4,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.45,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.15,
"avg_bars_held": 4.0,
"per_asset_pnl": {
"DOGE-USD": 23.58,
"SOL-USD": 22.22,
"BTC-USD": 17.55,
"XRP-USD": 10.21,
"DOT-USD": 9.58,
"ADA-USD": 7.59,
"ETH-USD": 4.29
},
"label": "A: BASELINE (scale=1.0, time_exit=ON)"
},
{
"stop_scale": 0.75,
"time_exit": true,
"final_equity": 253.91,
"total_pnl": 139.91,
"total_ret": 122.7,
"trades": 802,
"wins": 357,
"wr": 44.5,
"sharpe": 3.32,
"max_dd": 7.6,
"stops": 436,
"time_exits": 364,
"monthly_pnl": 6.11,
"avg_bars_held": 3.7,
"per_asset_pnl": {
"DOGE-USD": 32.5,
"SOL-USD": 25.27,
"DOT-USD": 19.61,
"BTC-USD": 17.59,
"ADA-USD": 16.69,
"ETH-USD": 16.53,
"XRP-USD": 11.71
},
"label": "B: scale=0.75, time_exit=ON"
},
{
"stop_scale": 1.0,
"time_exit": false,
"final_equity": 329.11,
"total_pnl": 215.11,
"total_ret": 188.7,
"trades": 634,
"wins": 267,
"wr": 42.1,
"sharpe": 3.0,
"max_dd": 10.6,
"stops": 632,
"time_exits": 0,
"monthly_pnl": 9.39,
"avg_bars_held": 9.7,
"per_asset_pnl": {
"ETH-USD": 58.38,
"SOL-USD": 51.97,
"DOGE-USD": 35.29,
"BTC-USD": 30.53,
"ADA-USD": 26.02,
"DOT-USD": 16.19,
"XRP-USD": -3.26
},
"label": "C: scale=1.0, time_exit=OFF"
},
{
"stop_scale": 0.75,
"time_exit": false,
"final_equity": 355.87,
"total_pnl": 241.87,
"total_ret": 212.2,
"trades": 682,
"wins": 287,
"wr": 42.1,
"sharpe": 3.4,
"max_dd": 7.9,
"stops": 680,
"time_exits": 0,
"monthly_pnl": 10.56,
"avg_bars_held": 7.1,
"per_asset_pnl": {
"DOGE-USD": 52.25,
"DOT-USD": 45.89,
"ETH-USD": 45.89,
"BTC-USD": 34.01,
"SOL-USD": 30.93,
"ADA-USD": 20.75,
"XRP-USD": 12.15
},
"label": "D: scale=0.75, time_exit=OFF \u2190 COMBO"
},
{
"stop_scale": 0.5,
"time_exit": false,
"final_equity": 416.32,
"total_pnl": 302.32,
"total_ret": 265.2,
"trades": 742,
"wins": 314,
"wr": 42.3,
"sharpe": 4.15,
"max_dd": 5.0,
"stops": 740,
"time_exits": 0,
"monthly_pnl": 13.2,
"avg_bars_held": 4.9,
"per_asset_pnl": {
"DOGE-USD": 72.76,
"DOT-USD": 69.01,
"BTC-USD": 51.44,
"ETH-USD": 43.44,
"ADA-USD": 25.64,
"SOL-USD": 22.29,
"XRP-USD": 17.73
},
"label": "E: scale=0.5, time_exit=OFF"
},
{
"stop_scale": 0.5,
"time_exit": true,
"final_equity": 279.36,
"total_pnl": 165.36,
"total_ret": 145.1,
"trades": 803,
"wins": 346,
"wr": 43.1,
"sharpe": 3.99,
"max_dd": 5.7,
"stops": 548,
"time_exits": 253,
"monthly_pnl": 7.22,
"avg_bars_held": 3.3,
"per_asset_pnl": {
"DOGE-USD": 34.93,
"DOT-USD": 29.4,
"BTC-USD": 24.37,
"SOL-USD": 23.5,
"ETH-USD": 23.07,
"ADA-USD": 17.22,
"XRP-USD": 12.87
},
"label": "F: scale=0.5, time_exit=ON"
}
]
}
@@ -0,0 +1,436 @@
{
"results": [
{
"stop_scale": 0.5,
"time_exit": false,
"use_ohlc": false,
"final_equity": 416.62,
"total_pnl": 302.62,
"total_ret": 265.5,
"trades": 742,
"wins": 314,
"wr": 42.3,
"sharpe": 4.16,
"max_dd": 5.0,
"stops": 740,
"time_exits": 0,
"monthly_pnl": 13.22,
"avg_bars_held": 4.9,
"per_asset_pnl": {
"DOGE-USD": 73.15,
"DOT-USD": 69.01,
"BTC-USD": 51.36,
"ETH-USD": 43.44,
"ADA-USD": 25.64,
"SOL-USD": 22.29,
"XRP-USD": 17.73
},
"label": "0.5x_close"
},
{
"stop_scale": 0.5,
"time_exit": false,
"use_ohlc": true,
"final_equity": 85.96,
"total_pnl": -28.04,
"total_ret": -24.6,
"trades": 805,
"wins": 265,
"wr": 32.9,
"sharpe": -2.08,
"max_dd": 27.4,
"stops": 803,
"time_exits": 0,
"monthly_pnl": -1.22,
"avg_bars_held": 1.2,
"per_asset_pnl": {
"DOT-USD": 0.01,
"DOGE-USD": -0.68,
"XRP-USD": -1.0,
"ADA-USD": -2.2,
"BTC-USD": -6.2,
"ETH-USD": -8.33,
"SOL-USD": -9.64
},
"label": "0.5x_OHLC"
},
{
"stop_scale": 0.75,
"time_exit": false,
"use_ohlc": false,
"final_equity": 356.13,
"total_pnl": 242.13,
"total_ret": 212.4,
"trades": 682,
"wins": 287,
"wr": 42.1,
"sharpe": 3.41,
"max_dd": 7.9,
"stops": 680,
"time_exits": 0,
"monthly_pnl": 10.57,
"avg_bars_held": 7.1,
"per_asset_pnl": {
"DOGE-USD": 52.57,
"DOT-USD": 45.89,
"ETH-USD": 45.89,
"BTC-USD": 33.94,
"SOL-USD": 30.93,
"ADA-USD": 20.75,
"XRP-USD": 12.15
},
"label": "0.75x_close"
},
{
"stop_scale": 0.75,
"time_exit": false,
"use_ohlc": true,
"final_equity": 51.05,
"total_pnl": -62.95,
"total_ret": -55.2,
"trades": 794,
"wins": 227,
"wr": 28.6,
"sharpe": -5.37,
"max_dd": 55.9,
"stops": 792,
"time_exits": 0,
"monthly_pnl": -2.75,
"avg_bars_held": 1.9,
"per_asset_pnl": {
"XRP-USD": -3.11,
"DOT-USD": -3.25,
"DOGE-USD": -8.54,
"ADA-USD": -9.66,
"BTC-USD": -11.49,
"ETH-USD": -12.45,
"SOL-USD": -14.46
},
"label": "0.75x_OHLC"
},
{
"stop_scale": 1.0,
"time_exit": false,
"use_ohlc": false,
"final_equity": 329.35,
"total_pnl": 215.35,
"total_ret": 188.9,
"trades": 634,
"wins": 267,
"wr": 42.1,
"sharpe": 3.0,
"max_dd": 10.6,
"stops": 632,
"time_exits": 0,
"monthly_pnl": 9.4,
"avg_bars_held": 9.7,
"per_asset_pnl": {
"ETH-USD": 58.38,
"SOL-USD": 51.97,
"DOGE-USD": 35.6,
"BTC-USD": 30.46,
"ADA-USD": 26.02,
"DOT-USD": 16.19,
"XRP-USD": -3.26
},
"label": "1.0x_close"
},
{
"stop_scale": 1.0,
"time_exit": false,
"use_ohlc": true,
"final_equity": 36.18,
"total_pnl": -77.82,
"total_ret": -68.3,
"trades": 772,
"wins": 205,
"wr": 26.6,
"sharpe": -6.77,
"max_dd": 68.7,
"stops": 770,
"time_exits": 0,
"monthly_pnl": -3.4,
"avg_bars_held": 2.9,
"per_asset_pnl": {
"XRP-USD": -3.86,
"BTC-USD": -8.74,
"DOT-USD": -8.86,
"ADA-USD": -9.93,
"ETH-USD": -15.2,
"SOL-USD": -15.52,
"DOGE-USD": -15.71
},
"label": "1.0x_OHLC"
},
{
"stop_scale": 1.25,
"time_exit": false,
"use_ohlc": false,
"final_equity": 276.95,
"total_pnl": 162.95,
"total_ret": 142.9,
"trades": 583,
"wins": 242,
"wr": 41.5,
"sharpe": 2.42,
"max_dd": 14.2,
"stops": 581,
"time_exits": 0,
"monthly_pnl": 7.12,
"avg_bars_held": 12.9,
"per_asset_pnl": {
"SOL-USD": 57.75,
"ETH-USD": 38.52,
"DOGE-USD": 33.58,
"BTC-USD": 25.22,
"ADA-USD": 18.37,
"DOT-USD": -2.77,
"XRP-USD": -7.71
},
"label": "1.25x_close"
},
{
"stop_scale": 1.25,
"time_exit": false,
"use_ohlc": true,
"final_equity": 30.25,
"total_pnl": -83.75,
"total_ret": -73.5,
"trades": 723,
"wins": 199,
"wr": 27.5,
"sharpe": -6.18,
"max_dd": 73.8,
"stops": 721,
"time_exits": 0,
"monthly_pnl": -3.66,
"avg_bars_held": 4.6,
"per_asset_pnl": {
"XRP-USD": -3.51,
"ADA-USD": -6.6,
"BTC-USD": -11.1,
"DOT-USD": -13.08,
"SOL-USD": -15.35,
"ETH-USD": -15.39,
"DOGE-USD": -18.7
},
"label": "1.25x_OHLC"
},
{
"stop_scale": 1.5,
"time_exit": false,
"use_ohlc": false,
"final_equity": 258.82,
"total_pnl": 144.82,
"total_ret": 127.0,
"trades": 536,
"wins": 213,
"wr": 39.7,
"sharpe": 2.03,
"max_dd": 20.8,
"stops": 534,
"time_exits": 0,
"monthly_pnl": 6.32,
"avg_bars_held": 16.5,
"per_asset_pnl": {
"SOL-USD": 35.9,
"ETH-USD": 31.53,
"ADA-USD": 28.05,
"BTC-USD": 25.74,
"DOGE-USD": 23.24,
"XRP-USD": 2.39,
"DOT-USD": -2.02
},
"label": "1.5x_close"
},
{
"stop_scale": 1.5,
"time_exit": false,
"use_ohlc": true,
"final_equity": 27.72,
"total_pnl": -86.28,
"total_ret": -75.7,
"trades": 670,
"wins": 187,
"wr": 27.9,
"sharpe": -5.7,
"max_dd": 76.0,
"stops": 668,
"time_exits": 0,
"monthly_pnl": -3.77,
"avg_bars_held": 6.9,
"per_asset_pnl": {
"ADA-USD": -3.87,
"XRP-USD": -5.12,
"SOL-USD": -11.5,
"BTC-USD": -14.33,
"DOT-USD": -16.06,
"DOGE-USD": -16.88,
"ETH-USD": -18.52
},
"label": "1.5x_OHLC"
},
{
"stop_scale": 1.0,
"time_exit": true,
"use_ohlc": true,
"final_equity": 44.9,
"total_pnl": -69.1,
"total_ret": -60.6,
"trades": 805,
"wins": 239,
"wr": 29.7,
"sharpe": -5.53,
"max_dd": 61.3,
"stops": 695,
"time_exits": 108,
"monthly_pnl": -3.02,
"avg_bars_held": 2.2,
"per_asset_pnl": {
"XRP-USD": -3.82,
"DOT-USD": -6.16,
"BTC-USD": -8.01,
"ADA-USD": -9.73,
"DOGE-USD": -11.86,
"ETH-USD": -14.53,
"SOL-USD": -15.0
},
"label": "BASELINE (1.0x, TE on, OHLC)"
},
{
"stop_scale": 0.75,
"time_exit": true,
"use_ohlc": true,
"final_equity": 55.81,
"total_pnl": -58.19,
"total_ret": -51.0,
"trades": 807,
"wins": 242,
"wr": 30.0,
"sharpe": -4.68,
"max_dd": 51.7,
"stops": 767,
"time_exits": 38,
"monthly_pnl": -2.54,
"avg_bars_held": 1.7,
"per_asset_pnl": {
"XRP-USD": -2.37,
"DOT-USD": -2.85,
"DOGE-USD": -7.65,
"ADA-USD": -9.94,
"BTC-USD": -10.83,
"ETH-USD": -10.95,
"SOL-USD": -13.59
},
"label": "0.75x, TE on, OHLC"
},
{
"stop_scale": 0.75,
"time_exit": false,
"use_ohlc": true,
"final_equity": 51.05,
"total_pnl": -62.95,
"total_ret": -55.2,
"trades": 794,
"wins": 227,
"wr": 28.6,
"sharpe": -5.37,
"max_dd": 55.9,
"stops": 792,
"time_exits": 0,
"monthly_pnl": -2.75,
"avg_bars_held": 1.9,
"per_asset_pnl": {
"XRP-USD": -3.11,
"DOT-USD": -3.25,
"DOGE-USD": -8.54,
"ADA-USD": -9.66,
"BTC-USD": -11.49,
"ETH-USD": -12.45,
"SOL-USD": -14.46
},
"label": "0.75x, TE off, OHLC"
},
{
"stop_scale": 1.0,
"time_exit": false,
"use_ohlc": true,
"final_equity": 36.18,
"total_pnl": -77.82,
"total_ret": -68.3,
"trades": 772,
"wins": 205,
"wr": 26.6,
"sharpe": -6.77,
"max_dd": 68.7,
"stops": 770,
"time_exits": 0,
"monthly_pnl": -3.4,
"avg_bars_held": 2.9,
"per_asset_pnl": {
"XRP-USD": -3.86,
"BTC-USD": -8.74,
"DOT-USD": -8.86,
"ADA-USD": -9.93,
"ETH-USD": -15.2,
"SOL-USD": -15.52,
"DOGE-USD": -15.71
},
"label": "1.0x, TE off, OHLC"
},
{
"stop_scale": 0.5,
"time_exit": false,
"use_ohlc": true,
"final_equity": 85.96,
"total_pnl": -28.04,
"total_ret": -24.6,
"trades": 805,
"wins": 265,
"wr": 32.9,
"sharpe": -2.08,
"max_dd": 27.4,
"stops": 803,
"time_exits": 0,
"monthly_pnl": -1.22,
"avg_bars_held": 1.2,
"per_asset_pnl": {
"DOT-USD": 0.01,
"DOGE-USD": -0.68,
"XRP-USD": -1.0,
"ADA-USD": -2.2,
"BTC-USD": -6.2,
"ETH-USD": -8.33,
"SOL-USD": -9.64
},
"label": "0.5x, TE off, OHLC"
},
{
"stop_scale": 0.5,
"time_exit": true,
"use_ohlc": true,
"final_equity": 86.05,
"total_pnl": -27.95,
"total_ret": -24.5,
"trades": 806,
"wins": 267,
"wr": 33.1,
"sharpe": -2.1,
"max_dd": 27.3,
"stops": 798,
"time_exits": 6,
"monthly_pnl": -1.22,
"avg_bars_held": 1.2,
"per_asset_pnl": {
"DOT-USD": 0.27,
"XRP-USD": -0.95,
"DOGE-USD": -1.16,
"ADA-USD": -2.42,
"BTC-USD": -5.73,
"ETH-USD": -8.33,
"SOL-USD": -9.65
},
"label": "0.5x, TE on, OHLC"
}
]
}
@@ -0,0 +1,571 @@
{
"results": [
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "close",
"final_equity": 416.69,
"total_pnl": 302.69,
"total_ret": 265.5,
"trades": 742,
"wins": 314,
"wr": 42.3,
"sharpe": 4.16,
"max_dd": 5.0,
"stops": 740,
"time_exits": 0,
"monthly_pnl": 13.22,
"avg_bars_held": 4.9,
"per_asset_pnl": {
"DOGE-USD": 73.17,
"DOT-USD": 69.01,
"BTC-USD": 51.41,
"ETH-USD": 43.44,
"ADA-USD": 25.64,
"SOL-USD": 22.29,
"XRP-USD": 17.73
},
"label": "0.5x_close"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 42.91,
"total_pnl": -71.09,
"total_ret": -62.4,
"trades": 800,
"wins": 189,
"wr": 23.6,
"sharpe": -7.52,
"max_dd": 62.9,
"stops": 798,
"time_exits": 0,
"monthly_pnl": -3.1,
"avg_bars_held": 1.8,
"per_asset_pnl": {
"XRP-USD": -3.79,
"DOT-USD": -7.13,
"DOGE-USD": -7.7,
"ADA-USD": -7.85,
"BTC-USD": -10.62,
"ETH-USD": -15.68,
"SOL-USD": -18.32
},
"label": "0.5x_hybrid"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "ohlc",
"final_equity": 85.97,
"total_pnl": -28.03,
"total_ret": -24.6,
"trades": 805,
"wins": 265,
"wr": 32.9,
"sharpe": -2.08,
"max_dd": 27.4,
"stops": 803,
"time_exits": 0,
"monthly_pnl": -1.22,
"avg_bars_held": 1.2,
"per_asset_pnl": {
"DOT-USD": 0.01,
"DOGE-USD": -0.68,
"XRP-USD": -1.0,
"ADA-USD": -2.2,
"BTC-USD": -6.19,
"ETH-USD": -8.33,
"SOL-USD": -9.64
},
"label": "0.5x_OHLC"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "close",
"final_equity": 356.19,
"total_pnl": 242.19,
"total_ret": 212.5,
"trades": 682,
"wins": 287,
"wr": 42.1,
"sharpe": 3.41,
"max_dd": 7.9,
"stops": 680,
"time_exits": 0,
"monthly_pnl": 10.58,
"avg_bars_held": 7.1,
"per_asset_pnl": {
"DOGE-USD": 52.59,
"DOT-USD": 45.89,
"ETH-USD": 45.89,
"BTC-USD": 33.98,
"SOL-USD": 30.93,
"ADA-USD": 20.75,
"XRP-USD": 12.15
},
"label": "0.75x_close"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 30.37,
"total_pnl": -83.63,
"total_ret": -73.4,
"trades": 773,
"wins": 187,
"wr": 24.2,
"sharpe": -8.72,
"max_dd": 73.7,
"stops": 771,
"time_exits": 0,
"monthly_pnl": -3.65,
"avg_bars_held": 3.1,
"per_asset_pnl": {
"XRP-USD": -4.11,
"DOT-USD": -8.75,
"BTC-USD": -9.67,
"ADA-USD": -12.01,
"DOGE-USD": -13.92,
"ETH-USD": -16.67,
"SOL-USD": -18.5
},
"label": "0.75x_hybrid"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "ohlc",
"final_equity": 51.06,
"total_pnl": -62.94,
"total_ret": -55.2,
"trades": 794,
"wins": 227,
"wr": 28.6,
"sharpe": -5.37,
"max_dd": 55.9,
"stops": 792,
"time_exits": 0,
"monthly_pnl": -2.75,
"avg_bars_held": 1.9,
"per_asset_pnl": {
"XRP-USD": -3.11,
"DOT-USD": -3.25,
"DOGE-USD": -8.54,
"ADA-USD": -9.66,
"BTC-USD": -11.49,
"ETH-USD": -12.45,
"SOL-USD": -14.46
},
"label": "0.75x_OHLC"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "close",
"final_equity": 329.41,
"total_pnl": 215.41,
"total_ret": 189.0,
"trades": 634,
"wins": 267,
"wr": 42.1,
"sharpe": 3.0,
"max_dd": 10.6,
"stops": 632,
"time_exits": 0,
"monthly_pnl": 9.41,
"avg_bars_held": 9.7,
"per_asset_pnl": {
"ETH-USD": 58.38,
"SOL-USD": 51.97,
"DOGE-USD": 35.62,
"BTC-USD": 30.5,
"ADA-USD": 26.02,
"DOT-USD": 16.19,
"XRP-USD": -3.26
},
"label": "1.0x_close"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 22.48,
"total_pnl": -91.52,
"total_ret": -80.3,
"trades": 735,
"wins": 177,
"wr": 24.1,
"sharpe": -8.31,
"max_dd": 80.6,
"stops": 733,
"time_exits": 0,
"monthly_pnl": -4.0,
"avg_bars_held": 4.6,
"per_asset_pnl": {
"XRP-USD": -4.28,
"ADA-USD": -6.76,
"BTC-USD": -12.0,
"DOT-USD": -14.35,
"SOL-USD": -16.76,
"ETH-USD": -17.85,
"DOGE-USD": -19.53
},
"label": "1.0x_hybrid"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "ohlc",
"final_equity": 36.19,
"total_pnl": -77.81,
"total_ret": -68.3,
"trades": 772,
"wins": 205,
"wr": 26.6,
"sharpe": -6.77,
"max_dd": 68.7,
"stops": 770,
"time_exits": 0,
"monthly_pnl": -3.4,
"avg_bars_held": 2.9,
"per_asset_pnl": {
"XRP-USD": -3.86,
"BTC-USD": -8.74,
"DOT-USD": -8.86,
"ADA-USD": -9.93,
"ETH-USD": -15.2,
"SOL-USD": -15.52,
"DOGE-USD": -15.71
},
"label": "1.0x_OHLC"
},
{
"stop_scale": 1.25,
"time_exit": false,
"stop_mode": "close",
"final_equity": 277.0,
"total_pnl": 163.0,
"total_ret": 143.0,
"trades": 583,
"wins": 242,
"wr": 41.5,
"sharpe": 2.42,
"max_dd": 14.2,
"stops": 581,
"time_exits": 0,
"monthly_pnl": 7.12,
"avg_bars_held": 12.9,
"per_asset_pnl": {
"SOL-USD": 57.75,
"ETH-USD": 38.52,
"DOGE-USD": 33.6,
"BTC-USD": 25.25,
"ADA-USD": 18.37,
"DOT-USD": -2.77,
"XRP-USD": -7.71
},
"label": "1.25x_close"
},
{
"stop_scale": 1.25,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 24.23,
"total_pnl": -89.77,
"total_ret": -78.7,
"trades": 663,
"wins": 171,
"wr": 25.8,
"sharpe": -5.98,
"max_dd": 79.1,
"stops": 661,
"time_exits": 0,
"monthly_pnl": -3.92,
"avg_bars_held": 7.4,
"per_asset_pnl": {
"XRP-USD": -4.89,
"ADA-USD": -8.07,
"SOL-USD": -12.8,
"BTC-USD": -13.63,
"DOT-USD": -15.83,
"DOGE-USD": -17.26,
"ETH-USD": -17.3
},
"label": "1.25x_hybrid"
},
{
"stop_scale": 1.25,
"time_exit": false,
"stop_mode": "ohlc",
"final_equity": 30.26,
"total_pnl": -83.74,
"total_ret": -73.5,
"trades": 723,
"wins": 199,
"wr": 27.5,
"sharpe": -6.18,
"max_dd": 73.8,
"stops": 721,
"time_exits": 0,
"monthly_pnl": -3.66,
"avg_bars_held": 4.6,
"per_asset_pnl": {
"XRP-USD": -3.51,
"ADA-USD": -6.6,
"BTC-USD": -11.09,
"DOT-USD": -13.08,
"SOL-USD": -15.35,
"ETH-USD": -15.39,
"DOGE-USD": -18.7
},
"label": "1.25x_OHLC"
},
{
"stop_scale": 1.5,
"time_exit": false,
"stop_mode": "close",
"final_equity": 258.87,
"total_pnl": 144.87,
"total_ret": 127.1,
"trades": 536,
"wins": 213,
"wr": 39.7,
"sharpe": 2.03,
"max_dd": 20.8,
"stops": 534,
"time_exits": 0,
"monthly_pnl": 6.33,
"avg_bars_held": 16.5,
"per_asset_pnl": {
"SOL-USD": 35.9,
"ETH-USD": 31.53,
"ADA-USD": 28.05,
"BTC-USD": 25.77,
"DOGE-USD": 23.25,
"XRP-USD": 2.39,
"DOT-USD": -2.02
},
"label": "1.5x_close"
},
{
"stop_scale": 1.5,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 23.77,
"total_pnl": -90.23,
"total_ret": -79.1,
"trades": 612,
"wins": 164,
"wr": 26.8,
"sharpe": -5.52,
"max_dd": 79.4,
"stops": 610,
"time_exits": 0,
"monthly_pnl": -3.94,
"avg_bars_held": 10.3,
"per_asset_pnl": {
"XRP-USD": -4.96,
"ADA-USD": -6.44,
"SOL-USD": -11.59,
"ETH-USD": -15.37,
"DOT-USD": -15.93,
"BTC-USD": -16.04,
"DOGE-USD": -19.9
},
"label": "1.5x_hybrid"
},
{
"stop_scale": 1.5,
"time_exit": false,
"stop_mode": "ohlc",
"final_equity": 27.72,
"total_pnl": -86.28,
"total_ret": -75.7,
"trades": 670,
"wins": 187,
"wr": 27.9,
"sharpe": -5.7,
"max_dd": 76.0,
"stops": 668,
"time_exits": 0,
"monthly_pnl": -3.77,
"avg_bars_held": 6.9,
"per_asset_pnl": {
"ADA-USD": -3.87,
"XRP-USD": -5.12,
"SOL-USD": -11.5,
"BTC-USD": -14.32,
"DOT-USD": -16.06,
"DOGE-USD": -16.88,
"ETH-USD": -18.52
},
"label": "1.5x_OHLC"
},
{
"stop_scale": 1.0,
"time_exit": true,
"stop_mode": "hybrid",
"final_equity": 32.46,
"total_pnl": -81.54,
"total_ret": -71.5,
"trades": 805,
"wins": 238,
"wr": 29.6,
"sharpe": -6.66,
"max_dd": 72.2,
"stops": 601,
"time_exits": 202,
"monthly_pnl": -3.56,
"avg_bars_held": 2.9,
"per_asset_pnl": {
"XRP-USD": -4.44,
"ADA-USD": -9.26,
"BTC-USD": -10.73,
"DOT-USD": -11.08,
"SOL-USD": -14.16,
"DOGE-USD": -15.91,
"ETH-USD": -15.95
},
"label": "BASELINE (1.0x, TE on)"
},
{
"stop_scale": 0.75,
"time_exit": true,
"stop_mode": "hybrid",
"final_equity": 36.54,
"total_pnl": -77.46,
"total_ret": -67.9,
"trades": 803,
"wins": 218,
"wr": 27.1,
"sharpe": -7.13,
"max_dd": 68.4,
"stops": 698,
"time_exits": 103,
"monthly_pnl": -3.38,
"avg_bars_held": 2.3,
"per_asset_pnl": {
"XRP-USD": -3.9,
"DOT-USD": -7.39,
"BTC-USD": -10.44,
"DOGE-USD": -11.25,
"ADA-USD": -11.52,
"ETH-USD": -15.66,
"SOL-USD": -17.3
},
"label": "0.75x, TE on"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 30.37,
"total_pnl": -83.63,
"total_ret": -73.4,
"trades": 773,
"wins": 187,
"wr": 24.2,
"sharpe": -8.72,
"max_dd": 73.7,
"stops": 771,
"time_exits": 0,
"monthly_pnl": -3.65,
"avg_bars_held": 3.1,
"per_asset_pnl": {
"XRP-USD": -4.11,
"DOT-USD": -8.75,
"BTC-USD": -9.67,
"ADA-USD": -12.01,
"DOGE-USD": -13.92,
"ETH-USD": -16.67,
"SOL-USD": -18.5
},
"label": "0.75x, TE off"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 22.48,
"total_pnl": -91.52,
"total_ret": -80.3,
"trades": 735,
"wins": 177,
"wr": 24.1,
"sharpe": -8.31,
"max_dd": 80.6,
"stops": 733,
"time_exits": 0,
"monthly_pnl": -4.0,
"avg_bars_held": 4.6,
"per_asset_pnl": {
"XRP-USD": -4.28,
"ADA-USD": -6.76,
"BTC-USD": -12.0,
"DOT-USD": -14.35,
"SOL-USD": -16.76,
"ETH-USD": -17.85,
"DOGE-USD": -19.53
},
"label": "1.0x, TE off"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "hybrid",
"final_equity": 42.91,
"total_pnl": -71.09,
"total_ret": -62.4,
"trades": 800,
"wins": 189,
"wr": 23.6,
"sharpe": -7.52,
"max_dd": 62.9,
"stops": 798,
"time_exits": 0,
"monthly_pnl": -3.1,
"avg_bars_held": 1.8,
"per_asset_pnl": {
"XRP-USD": -3.79,
"DOT-USD": -7.13,
"DOGE-USD": -7.7,
"ADA-USD": -7.85,
"BTC-USD": -10.62,
"ETH-USD": -15.68,
"SOL-USD": -18.32
},
"label": "0.5x, TE off"
},
{
"stop_scale": 0.5,
"time_exit": true,
"stop_mode": "hybrid",
"final_equity": 44.87,
"total_pnl": -69.13,
"total_ret": -60.6,
"trades": 808,
"wins": 196,
"wr": 24.3,
"sharpe": -7.3,
"max_dd": 61.2,
"stops": 773,
"time_exits": 33,
"monthly_pnl": -3.02,
"avg_bars_held": 1.7,
"per_asset_pnl": {
"XRP-USD": -3.88,
"DOGE-USD": -6.49,
"DOT-USD": -6.56,
"ADA-USD": -9.36,
"BTC-USD": -10.1,
"ETH-USD": -15.32,
"SOL-USD": -17.41
},
"label": "0.5x, TE on"
}
]
}
@@ -0,0 +1,571 @@
{
"results": [
{
"stop_scale": 0.5,
"time_exit": true,
"stop_mode": "production",
"final_equity": 79.47,
"total_pnl": -34.53,
"total_ret": -30.3,
"trades": 806,
"wins": 212,
"wr": 26.3,
"sharpe": -1.39,
"max_dd": 40.6,
"stops": 553,
"time_exits": 251,
"monthly_pnl": -1.51,
"avg_bars_held": 2.8,
"per_asset_pnl": {
"ADA-USD": 5.9,
"DOGE-USD": 1.95,
"XRP-USD": -3.44,
"DOT-USD": -5.81,
"SOL-USD": -9.26,
"ETH-USD": -11.17,
"BTC-USD": -12.7
},
"label": "0.5x_TEon_prod"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "production",
"final_equity": 50.91,
"total_pnl": -63.09,
"total_ret": -55.3,
"trades": 743,
"wins": 134,
"wr": 18.0,
"sharpe": -3.41,
"max_dd": 59.7,
"stops": 741,
"time_exits": 0,
"monthly_pnl": -2.76,
"avg_bars_held": 4.2,
"per_asset_pnl": {
"ADA-USD": 4.0,
"XRP-USD": -5.57,
"DOGE-USD": -6.25,
"BTC-USD": -10.4,
"DOT-USD": -13.59,
"ETH-USD": -14.59,
"SOL-USD": -16.69
},
"label": "0.5x_TEoff_prod"
},
{
"stop_scale": 0.75,
"time_exit": true,
"stop_mode": "production",
"final_equity": 78.14,
"total_pnl": -35.86,
"total_ret": -31.5,
"trades": 805,
"wins": 266,
"wr": 33.0,
"sharpe": -1.39,
"max_dd": 35.7,
"stops": 466,
"time_exits": 337,
"monthly_pnl": -1.57,
"avg_bars_held": 3.3,
"per_asset_pnl": {
"DOGE-USD": 0.31,
"ADA-USD": -1.55,
"XRP-USD": -2.46,
"DOT-USD": -5.67,
"ETH-USD": -8.2,
"SOL-USD": -8.23,
"BTC-USD": -10.05
},
"label": "0.75x_TEon_prod"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "production",
"final_equity": 46.43,
"total_pnl": -67.57,
"total_ret": -59.3,
"trades": 700,
"wins": 162,
"wr": 23.1,
"sharpe": -3.21,
"max_dd": 61.4,
"stops": 698,
"time_exits": 0,
"monthly_pnl": -2.95,
"avg_bars_held": 6.3,
"per_asset_pnl": {
"ADA-USD": -0.09,
"XRP-USD": -5.55,
"BTC-USD": -9.21,
"DOGE-USD": -10.61,
"SOL-USD": -11.83,
"DOT-USD": -13.68,
"ETH-USD": -16.6
},
"label": "0.75x_TEoff_prod"
},
{
"stop_scale": 1.0,
"time_exit": true,
"stop_mode": "production",
"final_equity": 83.65,
"total_pnl": -30.35,
"total_ret": -26.6,
"trades": 807,
"wins": 299,
"wr": 37.1,
"sharpe": -1.1,
"max_dd": 30.3,
"stops": 386,
"time_exits": 419,
"monthly_pnl": -1.33,
"avg_bars_held": 3.6,
"per_asset_pnl": {
"ADA-USD": -0.52,
"BTC-USD": -2.78,
"DOT-USD": -2.83,
"XRP-USD": -3.66,
"SOL-USD": -3.71,
"DOGE-USD": -5.31,
"ETH-USD": -11.53
},
"label": "1.0x_TEon_prod"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "production",
"final_equity": 46.33,
"total_pnl": -67.67,
"total_ret": -59.4,
"trades": 645,
"wins": 161,
"wr": 25.0,
"sharpe": -2.56,
"max_dd": 61.3,
"stops": 643,
"time_exits": 0,
"monthly_pnl": -2.95,
"avg_bars_held": 9.0,
"per_asset_pnl": {
"SOL-USD": -0.27,
"ADA-USD": -0.65,
"XRP-USD": -6.73,
"DOT-USD": -11.38,
"BTC-USD": -14.42,
"DOGE-USD": -16.36,
"ETH-USD": -17.87
},
"label": "1.0x_TEoff_prod"
},
{
"stop_scale": 1.25,
"time_exit": true,
"stop_mode": "production",
"final_equity": 87.67,
"total_pnl": -26.33,
"total_ret": -23.1,
"trades": 804,
"wins": 319,
"wr": 39.7,
"sharpe": -0.94,
"max_dd": 26.3,
"stops": 320,
"time_exits": 482,
"monthly_pnl": -1.15,
"avg_bars_held": 3.9,
"per_asset_pnl": {
"BTC-USD": 4.94,
"ADA-USD": -2.1,
"SOL-USD": -2.78,
"XRP-USD": -3.92,
"DOT-USD": -4.52,
"DOGE-USD": -4.78,
"ETH-USD": -13.17
},
"label": "1.25x_TEon_prod"
},
{
"stop_scale": 1.25,
"time_exit": false,
"stop_mode": "production",
"final_equity": 48.58,
"total_pnl": -65.42,
"total_ret": -57.4,
"trades": 587,
"wins": 147,
"wr": 25.0,
"sharpe": -2.07,
"max_dd": 59.4,
"stops": 585,
"time_exits": 0,
"monthly_pnl": -2.86,
"avg_bars_held": 12.4,
"per_asset_pnl": {
"SOL-USD": 1.04,
"ADA-USD": -5.36,
"XRP-USD": -7.37,
"ETH-USD": -10.21,
"BTC-USD": -11.53,
"DOGE-USD": -14.41,
"DOT-USD": -17.57
},
"label": "1.25x_TEoff_prod"
},
{
"stop_scale": 1.5,
"time_exit": true,
"stop_mode": "production",
"final_equity": 85.25,
"total_pnl": -28.75,
"total_ret": -25.2,
"trades": 805,
"wins": 336,
"wr": 41.7,
"sharpe": -0.93,
"max_dd": 27.4,
"stops": 273,
"time_exits": 530,
"monthly_pnl": -1.26,
"avg_bars_held": 4.1,
"per_asset_pnl": {
"BTC-USD": 3.38,
"ADA-USD": 0.2,
"XRP-USD": -0.48,
"SOL-USD": -2.66,
"DOT-USD": -7.74,
"DOGE-USD": -8.19,
"ETH-USD": -13.27
},
"label": "1.5x_TEon_prod"
},
{
"stop_scale": 1.5,
"time_exit": false,
"stop_mode": "production",
"final_equity": 49.08,
"total_pnl": -64.92,
"total_ret": -56.9,
"trades": 526,
"wins": 133,
"wr": 25.3,
"sharpe": -1.71,
"max_dd": 58.4,
"stops": 524,
"time_exits": 0,
"monthly_pnl": -2.83,
"avg_bars_held": 16.5,
"per_asset_pnl": {
"SOL-USD": -0.69,
"XRP-USD": -1.94,
"BTC-USD": -8.92,
"ADA-USD": -9.55,
"ETH-USD": -10.29,
"DOT-USD": -13.21,
"DOGE-USD": -20.31
},
"label": "1.5x_TEoff_prod"
},
{
"stop_scale": 1.0,
"time_exit": true,
"stop_mode": "close",
"final_equity": 209.5,
"total_pnl": 95.5,
"total_ret": 83.8,
"trades": 803,
"wins": 363,
"wr": 45.2,
"sharpe": 2.46,
"max_dd": 8.4,
"stops": 344,
"time_exits": 457,
"monthly_pnl": 4.17,
"avg_bars_held": 4.0,
"per_asset_pnl": {
"DOGE-USD": 23.9,
"SOL-USD": 22.22,
"BTC-USD": 17.71,
"XRP-USD": 10.21,
"DOT-USD": 9.58,
"ADA-USD": 7.59,
"ETH-USD": 4.29
},
"label": "close: 1.0x TE=on trail=1"
},
{
"stop_scale": 0.75,
"time_exit": true,
"stop_mode": "close",
"final_equity": 254.49,
"total_pnl": 140.49,
"total_ret": 123.2,
"trades": 802,
"wins": 357,
"wr": 44.5,
"sharpe": 3.33,
"max_dd": 7.6,
"stops": 436,
"time_exits": 364,
"monthly_pnl": 6.14,
"avg_bars_held": 3.7,
"per_asset_pnl": {
"DOGE-USD": 32.9,
"SOL-USD": 25.27,
"DOT-USD": 19.61,
"BTC-USD": 17.78,
"ADA-USD": 16.69,
"ETH-USD": 16.53,
"XRP-USD": 11.71
},
"label": "close: 0.75x TE=on trail=1"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "close",
"final_equity": 417.27,
"total_pnl": 303.27,
"total_ret": 266.0,
"trades": 742,
"wins": 314,
"wr": 42.3,
"sharpe": 4.16,
"max_dd": 5.0,
"stops": 740,
"time_exits": 0,
"monthly_pnl": 13.24,
"avg_bars_held": 4.9,
"per_asset_pnl": {
"DOGE-USD": 73.41,
"DOT-USD": 69.01,
"BTC-USD": 51.75,
"ETH-USD": 43.44,
"ADA-USD": 25.64,
"SOL-USD": 22.29,
"XRP-USD": 17.73
},
"label": "close: 0.5x TE=off trail=1"
},
{
"stop_scale": 1.0,
"time_exit": true,
"stop_mode": "production",
"final_equity": 83.65,
"total_pnl": -30.35,
"total_ret": -26.6,
"trades": 807,
"wins": 299,
"wr": 37.1,
"sharpe": -1.1,
"max_dd": 30.3,
"stops": 386,
"time_exits": 419,
"monthly_pnl": -1.33,
"avg_bars_held": 3.6,
"per_asset_pnl": {
"ADA-USD": -0.52,
"BTC-USD": -2.78,
"DOT-USD": -2.83,
"XRP-USD": -3.66,
"SOL-USD": -3.71,
"DOGE-USD": -5.31,
"ETH-USD": -11.53
},
"label": "PROD: 1.0x TE=on trail=7"
},
{
"stop_scale": 0.75,
"time_exit": true,
"stop_mode": "production",
"final_equity": 78.14,
"total_pnl": -35.86,
"total_ret": -31.5,
"trades": 805,
"wins": 266,
"wr": 33.0,
"sharpe": -1.39,
"max_dd": 35.7,
"stops": 466,
"time_exits": 337,
"monthly_pnl": -1.57,
"avg_bars_held": 3.3,
"per_asset_pnl": {
"DOGE-USD": 0.31,
"ADA-USD": -1.55,
"XRP-USD": -2.46,
"DOT-USD": -5.67,
"ETH-USD": -8.2,
"SOL-USD": -8.23,
"BTC-USD": -10.05
},
"label": "PROD: 0.75x TE=on trail=7"
},
{
"stop_scale": 0.5,
"time_exit": false,
"stop_mode": "production",
"final_equity": 50.91,
"total_pnl": -63.09,
"total_ret": -55.3,
"trades": 743,
"wins": 134,
"wr": 18.0,
"sharpe": -3.41,
"max_dd": 59.7,
"stops": 741,
"time_exits": 0,
"monthly_pnl": -2.76,
"avg_bars_held": 4.2,
"per_asset_pnl": {
"ADA-USD": 4.0,
"XRP-USD": -5.57,
"DOGE-USD": -6.25,
"BTC-USD": -10.4,
"DOT-USD": -13.59,
"ETH-USD": -14.59,
"SOL-USD": -16.69
},
"label": "PROD: 0.5x TE=off trail=7"
},
{
"stop_scale": 1.0,
"time_exit": false,
"stop_mode": "production",
"final_equity": 46.33,
"total_pnl": -67.67,
"total_ret": -59.4,
"trades": 645,
"wins": 161,
"wr": 25.0,
"sharpe": -2.56,
"max_dd": 61.3,
"stops": 643,
"time_exits": 0,
"monthly_pnl": -2.95,
"avg_bars_held": 9.0,
"per_asset_pnl": {
"SOL-USD": -0.27,
"ADA-USD": -0.65,
"XRP-USD": -6.73,
"DOT-USD": -11.38,
"BTC-USD": -14.42,
"DOGE-USD": -16.36,
"ETH-USD": -17.87
},
"label": "PROD: 1.0x TE=off trail=7"
},
{
"stop_scale": 0.75,
"time_exit": false,
"stop_mode": "production",
"final_equity": 46.43,
"total_pnl": -67.57,
"total_ret": -59.3,
"trades": 700,
"wins": 162,
"wr": 23.1,
"sharpe": -3.21,
"max_dd": 61.4,
"stops": 698,
"time_exits": 0,
"monthly_pnl": -2.95,
"avg_bars_held": 6.3,
"per_asset_pnl": {
"ADA-USD": -0.09,
"XRP-USD": -5.55,
"BTC-USD": -9.21,
"DOGE-USD": -10.61,
"SOL-USD": -11.83,
"DOT-USD": -13.68,
"ETH-USD": -16.6
},
"label": "PROD: 0.75x TE=off trail=7"
},
{
"stop_scale": 1.0,
"time_exit": true,
"stop_mode": "production",
"final_equity": 83.65,
"total_pnl": -30.35,
"total_ret": -26.6,
"trades": 807,
"wins": 299,
"wr": 37.1,
"sharpe": -1.1,
"max_dd": 30.3,
"stops": 386,
"time_exits": 419,
"monthly_pnl": -1.33,
"avg_bars_held": 3.6,
"per_asset_pnl": {
"ADA-USD": -0.52,
"BTC-USD": -2.78,
"DOT-USD": -2.83,
"XRP-USD": -3.66,
"SOL-USD": -3.71,
"DOGE-USD": -5.31,
"ETH-USD": -11.53
},
"label": "PROD: 1.0x FIXED stop"
},
{
"stop_scale": 1.5,
"time_exit": true,
"stop_mode": "production",
"final_equity": 85.25,
"total_pnl": -28.75,
"total_ret": -25.2,
"trades": 805,
"wins": 336,
"wr": 41.7,
"sharpe": -0.93,
"max_dd": 27.4,
"stops": 273,
"time_exits": 530,
"monthly_pnl": -1.26,
"avg_bars_held": 4.1,
"per_asset_pnl": {
"BTC-USD": 3.38,
"ADA-USD": 0.2,
"XRP-USD": -0.48,
"SOL-USD": -2.66,
"DOT-USD": -7.74,
"DOGE-USD": -8.19,
"ETH-USD": -13.27
},
"label": "PROD: 1.5x FIXED stop"
},
{
"stop_scale": 2.0,
"time_exit": true,
"stop_mode": "production",
"final_equity": 84.37,
"total_pnl": -29.63,
"total_ret": -26.0,
"trades": 805,
"wins": 352,
"wr": 43.7,
"sharpe": -0.91,
"max_dd": 30.5,
"stops": 191,
"time_exits": 612,
"monthly_pnl": -1.29,
"avg_bars_held": 4.4,
"per_asset_pnl": {
"BTC-USD": 3.95,
"SOL-USD": 0.97,
"XRP-USD": -0.44,
"ADA-USD": -1.32,
"DOT-USD": -10.8,
"DOGE-USD": -10.86,
"ETH-USD": -11.14
},
"label": "PROD: 2.0x FIXED stop"
}
]
}
+486
View File
@@ -0,0 +1,486 @@
"""Exp16: Realistic Bybit spot margin simulation.
Key differences from exp15:
- Single shared USDC pool (not per-asset equity)
- Margin requirement: pos_value / leverage locked as collateral
- Positions compete for same capital
- Interest on borrowed amount (~0.02%/day)
- Cooldown after stop (shift candles)
- Correlation groups (BTC+ETH, ADA+DOT+XRP)
- Chronological bar-by-bar processing across all assets
"""
import sys
from pathlib import Path
from dataclasses import dataclass
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import compute_metrics, save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAILING_STOP = True
TRAIN_RATIO = 0.3
SHIFT = 7
# Bybit spot margin
INTEREST_RATE_DAILY = 0.0002 # 0.02%/day on borrowed amount
COMMISSION = 0.001 # 0.1% per side
# Correlation groups — same as production
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
# Sharpe-optimal config from exp15
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
entry_date: str
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float # USDC locked as collateral
borrowed: float # amount borrowed from exchange
k_used: int
entry_bar: int
def check_correlation_conflict(open_positions: dict, ticker: str, direction: int) -> str | None:
"""Check if opening conflicts with correlated open position."""
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other == ticker:
continue
if other in open_positions and open_positions[other].direction == direction:
return f"correlated with {other} {'LONG' if direction == 1 else 'SHORT'} — SKIP"
return None
def main():
results_dir = Path(__file__).parent / "results"
# ══════════════════════════════════════════════════
# FETCH DATA + TRAIN MODELS
# ══════════════════════════════════════════════════
print(f"{'='*80}")
print("EXP16: REALISTIC BYBIT SPOT MARGIN SIMULATION")
print(f"{'='*80}")
print(f"Capital: ${TOTAL_CAPITAL} | Interest: {INTEREST_RATE_DAILY*100:.3f}%/day | "
f"Commission: {COMMISSION*100:.1f}%/side")
print()
asset_data = {} # ticker -> {prices, dates, tf, model, test_data, ws, leverage, weight}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws, leverage, weight = a["ws"], a["leverage"], a["weight"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
except Exception as e:
print(f"FETCH ERROR: {e}")
continue
if prices is None or len(prices) < ws + K + SHIFT + 30:
print("not enough data")
continue
data = signals.prepare_windows(prices, ws, SHIFT)
if len(data) < 30:
print(f"only {len(data)} windows")
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train_data = data[:n_train]
test_data = data[n_train:]
model_cfg = ModelConfig(
window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003,
)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
windows_arr = np.array([d["norm_input"] for d in train_data])
targets_arr = np.array([d["norm_target"] for d in train_data])
model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003)
asset_data[ticker] = {
"prices": prices, "dates": dates, "tf": tf,
"model": mdl, "test_data": test_data,
"ws": ws, "leverage": leverage, "weight": weight,
}
print(f"{len(prices)} bars, {len(test_data)} test windows")
if not asset_data:
print("No data!")
return
# ══════════════════════════════════════════════════
# BUILD CHRONOLOGICAL EVENT TIMELINE
# ══════════════════════════════════════════════════
# Each test window is a potential signal check point.
# Collect all (date, ticker, window_data) and sort by date.
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
price_idx = d["price_idx"]
date = str(ad["dates"][price_idx])
events.append((date, ticker, d))
events.sort(key=lambda x: x[0]) # chronological order
print(f"\n Total events: {len(events)} across {len(asset_data)} assets")
print(f" Date range: {events[0][0]} → {events[-1][0]}")
# ══════════════════════════════════════════════════
# SIMULATE WITH SHARED USDC POOL
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("SIMULATION")
print(f"{'='*80}\n")
free_usdc = TOTAL_CAPITAL
open_positions: dict[str, Position] = {}
all_trades = []
per_asset_trades: dict[str, list] = {t: [] for t in asset_data}
last_stop_date: dict[str, str] = {} # ticker -> date of last stop
skipped_no_margin = 0
skipped_cooldown = 0
skipped_correlation = 0
skipped_spot_short = 0
total_interest_paid = 0.0
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
# --- Check open position for this asset (every bar, not just windows) ---
if ticker in open_positions:
pos = open_positions[ticker]
bar_hours = tf_hours.get(ad["tf"], 4)
closed = False
# Check EVERY bar from last check to current price_idx
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_price = float(prices[bar_idx])
if TRAILING_STOP:
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
bars_held = bar_idx - pos.entry_bar
time_exit = bars_held >= (SHIFT - pos.k_used)
if stopped or time_exit:
exit_price = pos.stop_price if stopped else bar_price
exit_bar_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_held * bar_hours
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
total_interest_paid += trade_interest
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trade = {
"ticker": ticker, "pnl_net": pnl_net,
"pnl_gross": pnl_gross,
"commission": commission_cost, "interest": trade_interest,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
"bars_held": bars_held, "date": exit_bar_date,
"entry_price": pos.entry_price, "exit_price": exit_price,
"direction": pos.direction,
}
all_trades.append(trade)
per_asset_trades[ticker].append(trade)
if stopped:
last_stop_date[ticker] = exit_bar_date
# Track drawdown on realized equity
total_equity = free_usdc + sum(
p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
pass # position already handled
# --- Check for new signal (if no position) ---
if ticker not in open_positions and price_idx >= ws + K:
# Cooldown after stop
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
bar_h = tf_hours.get(ad["tf"], 4)
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
skipped_cooldown += 1
continue
# Signal generation
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None:
continue
# Spot mode: skip SHORT
if direction == -1:
skipped_spot_short += 1
continue
# Correlation filter
conflict = check_correlation_conflict(open_positions, ticker, direction)
if conflict:
skipped_correlation += 1
continue
# Position sizing: weight-based
total_equity = free_usdc + sum(
p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0: # Bybit minimum
continue
# Margin check: need pos_value / leverage as collateral
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
# Try reduced position with available margin
margin_needed = free_usdc * 0.95 # keep 5% buffer
pos_value = margin_needed * leverage
if pos_value < 5.0:
skipped_no_margin += 1
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed # borrowed from exchange
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult, current_price * 0.005)
# Lock margin
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price, entry_date=date,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close any remaining open positions at last price
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
last_bar = ad["test_data"][-1]["price_idx"]
bars_held = last_bar - pos.entry_bar
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
trade = {
"ticker": ticker, "pnl_net": pnl_net, "pnl_gross": pnl_gross,
"commission": commission_cost, "interest": trade_interest,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end", "bars_held": bars_held,
"date": str(ad["dates"][-1]),
"entry_price": pos.entry_price, "exit_price": last_price,
"direction": pos.direction,
}
all_trades.append(trade)
per_asset_trades[ticker].append(trade)
final_equity = free_usdc
# ══════════════════════════════════════════════════
# RESULTS
# ══════════════════════════════════════════════════
total_pnl = final_equity - TOTAL_CAPITAL
total_ret = total_pnl / TOTAL_CAPITAL * 100
total_commission = sum(t["commission"] for t in all_trades)
# Compute years from date range
if events:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = (last - first).days / 365.25
else:
years = 1.0
wins = [t for t in all_trades if t["pnl_net"] > 0]
losses = [t for t in all_trades if t["pnl_net"] <= 0]
print(f"\n{'='*80}")
print("RESULTS: REALISTIC BYBIT SIMULATION")
print(f"{'='*80}")
print(f"\n Capital: ${TOTAL_CAPITAL:.0f} → ${final_equity:.2f} "
f"(PnL: ${total_pnl:+.2f}, {total_ret:+.1f}%)")
print(f" Max Drawdown: {max_drawdown*100:.1f}%")
print(f" Trades: {len(all_trades)} ({len(wins)} wins, {len(losses)} losses)")
if all_trades:
wr = len(wins) / len(all_trades) * 100
print(f" Win Rate: {wr:.1f}%")
print(f" Total Commission: ${total_commission:.2f}")
print(f" Total Interest: ${total_interest_paid:.2f}")
print()
print(f" Skipped (no margin): {skipped_no_margin}")
print(f" Skipped (cooldown): {skipped_cooldown}")
print(f" Skipped (correlation): {skipped_correlation}")
print(f" Skipped (spot short): {skipped_spot_short}")
if len(all_trades) > 1 and years > 0:
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in all_trades if t["equity_at_entry"] > 0])
tpy = len(all_trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
monthly_pnl = total_pnl / months if months > 0 else 0
print(f"\n Sharpe: {sharpe:.2f}")
print(f" Monthly PnL: ${monthly_pnl:.2f}")
print(f" Period: {years:.1f} years")
# Per-asset breakdown
print(f"\n {'Asset':<10s} {'TF':>3s} {'WS':>4s} {'Lev':>4s} {'Wt%':>5s} "
f"{'Trds':>5s} {'Wins':>5s} {'WR%':>5s} {'PnL':>10s} {'Comm':>7s} {'Int':>6s}")
print(f" {'-'*75}")
for a in ASSETS:
ticker = a["ticker"]
trades = per_asset_trades.get(ticker, [])
if not trades:
print(f" {ticker:<10s} {a['tf']:>3s} {a['ws']:>4d} {a['leverage']:>3d}x "
f"{a['weight']*100:>4.1f}% {'':>5s} {'':>5s} {'':>5s} {'no trades':>10s}")
continue
w = [t for t in trades if t["pnl_net"] > 0]
pnl = sum(t["pnl_net"] for t in trades)
comm = sum(t["commission"] for t in trades)
intr = sum(t["interest"] for t in trades)
wr = len(w) / len(trades) * 100
print(f" {ticker:<10s} {a['tf']:>3s} {a['ws']:>4d} {a['leverage']:>3d}x "
f"{a['weight']*100:>4.1f}% {len(trades):>5d} {len(w):>5d} {wr:>4.1f}% "
f"${pnl:>+9.2f} ${comm:>6.2f} ${intr:>5.2f}")
# ══════════════════════════════════════════════════
# COMPARISON: exp15 (no margin) vs exp16 (realistic)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("IMPACT OF REALISTIC MARGIN SIMULATION")
print(f"{'='*80}")
print(f"\n {'Metric':<25s} {'exp15 (ideal)':>15s} {'exp16 (real)':>15s}")
print(f" {'-'*55}")
print(f" {'Margin model':<25s} {'per-asset':>15s} {'shared USDC':>15s}")
print(f" {'Interest':<25s} {'none':>15s} {'0.02%/day':>15s}")
print(f" {'Cooldown after stop':<25s} {'none':>15s} {f'{SHIFT} candles':>15s}")
print(f" {'Correlation filter':<25s} {'none':>15s} {'yes':>15s}")
print(f" {'Skipped (no margin)':<25s} {'0':>15s} {skipped_no_margin:>15d}")
print(f" {'Total interest paid':<25s} {'$0.00':>15s} ${total_interest_paid:>14.2f}")
print(f" {'Final equity':<25s} {'':>15s} ${final_equity:>14.2f}")
print(f" {'Max drawdown':<25s} {'':>15s} {max_drawdown*100:>14.1f}%")
# Save
save_data = {
"config": {
"total_capital": TOTAL_CAPITAL,
"interest_rate": INTEREST_RATE_DAILY,
"commission": COMMISSION,
"cooldown_candles": SHIFT,
"assets": ASSETS,
},
"results": {
"final_equity": round(final_equity, 2),
"total_pnl": round(total_pnl, 2),
"total_ret": round(total_ret, 1),
"max_drawdown": round(max_drawdown * 100, 1),
"total_trades": len(all_trades),
"wins": len(wins),
"wr": round(len(wins) / len(all_trades) * 100, 1) if all_trades else 0,
"total_commission": round(total_commission, 2),
"total_interest": round(total_interest_paid, 2),
"skipped_no_margin": skipped_no_margin,
"skipped_cooldown": skipped_cooldown,
"skipped_correlation": skipped_correlation,
"skipped_spot_short": skipped_spot_short,
"years": round(years, 2),
},
"trades": all_trades,
}
path = save_results(save_data, results_dir, "exp16_realistic")
print(f"\nSaved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,364 @@
"""Exp16d: Clean check frequency test — disable time_exit to isolate stop behavior.
Tests whether less frequent stop checking genuinely avoids false stops,
without time_exit masking the effect.
"""
import sys
from pathlib import Path
from dataclasses import dataclass
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
INTEREST_RATE_DAILY = 0.0002
COMMISSION = 0.001
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
def check_corr_conflict(open_positions, ticker, direction):
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
return True
return False
def run_sim(asset_data, events, check_every=1, use_time_exit=True):
"""Run simulation. check_every=N checks stop every N bars."""
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_price = float(prices[bar_idx])
bars_since_entry = bar_idx - pos.entry_bar
# Always update trailing stop (every bar)
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
# Check stop only every N bars
is_check_bar = (check_every <= 1) or (bars_since_entry % check_every == 0)
if not is_check_bar:
continue
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
time_exit = use_time_exit and bars_since_entry >= (SHIFT - pos.k_used)
if stopped or time_exit:
exit_price = pos.stop_price if stopped else bar_price
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_since_entry * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
"bars_held": bars_since_entry,
})
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# New signal
if ticker not in open_positions and price_idx >= ws + K:
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
continue
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
if check_corr_conflict(open_positions, ticker, direction):
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
bars_held = ad["test_data"][-1]["price_idx"] - pos.entry_bar
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
trades.append({"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end", "bars_held": bars_held})
final_equity = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
stops = [t for t in trades if t["exit_reason"] == "stop"]
time_exits = [t for t in trades if t["exit_reason"] == "time"]
avg_bars = np.mean([t["bars_held"] for t in trades]) if trades else 0
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = max((last - first).days / 365.25, 0.1)
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe, months = 0, 1
return {
"final_equity": round(final_equity, 2),
"total_pnl": round(final_equity - TOTAL_CAPITAL, 2),
"total_ret": round((final_equity - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades), "wins": len(wins),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"sharpe": round(sharpe, 2),
"max_dd": round(max_drawdown * 100, 1),
"stops": len(stops), "time_exits": len(time_exits),
"monthly_pnl": round((final_equity - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
"avg_bars_held": round(avg_bars, 1),
}
def main():
print(f"{'='*80}")
print("EXP16d: CLEAN CHECK FREQUENCY TEST")
print(f"{'='*80}\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
except Exception as e:
print(f"ERROR: {e}")
continue
if prices is None or len(prices) < ws + K + SHIFT + 30:
continue
data = signals.prepare_windows(prices, ws, SHIFT)
if len(data) < 30:
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
model_cfg = ModelConfig(window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
train_data = data[:n_train]
model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]),
np.array([d["norm_target"] for d in train_data]), 200, 0.003)
asset_data[ticker] = {
"prices": prices, "dates": dates, "tf": tf,
"model": mdl, "test_data": data[n_train:],
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(data[n_train:])} test")
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
events.append((str(ad["dates"][d["price_idx"]]), ticker, d))
events.sort(key=lambda x: x[0])
frequencies = [1, 2, 3, 5, 7]
# ══════════════════════════════════════════════════
# TEST A: WITH time_exit (production behavior)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("TEST A: check_every × WITH time_exit (current production)")
print(f"{'='*80}\n")
print(f" {'Every':>6s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} {'AvgBr':>6s} | {'$/mo':>7s}")
print(f" {'-'*90}")
for freq in frequencies:
r = run_sim(asset_data, events, check_every=freq, use_time_exit=True)
print(f" {freq:>4d} | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} "
f"{r['avg_bars_held']:>5.1f} | ${r['monthly_pnl']:>+6.2f}")
# ══════════════════════════════════════════════════
# TEST B: WITHOUT time_exit (isolate stop effect)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("TEST B: check_every × WITHOUT time_exit (pure stop behavior)")
print(f"{'='*80}\n")
print(f" {'Every':>6s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} {'AvgBr':>6s} | {'$/mo':>7s}")
print(f" {'-'*90}")
for freq in frequencies:
r = run_sim(asset_data, events, check_every=freq, use_time_exit=False)
print(f" {freq:>4d} | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} "
f"{r['avg_bars_held']:>5.1f} | ${r['monthly_pnl']:>+6.2f}")
# ══════════════════════════════════════════════════
# TEST C: No trailing stop at all (fixed stop only)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("TEST C: TRAILING ON vs OFF (check_every=1, with time_exit)")
print(f"{'='*80}\n")
# Test with trailing disabled by setting very high threshold
for label, check, time_ex in [
("baseline (every bar, trailing, time_exit)", 1, True),
("no time_exit (every bar, trailing, stop only)", 1, False),
("check_every=3 + time_exit", 3, True),
("check_every=3 no time_exit", 3, False),
]:
r = run_sim(asset_data, events, check_every=check, use_time_exit=time_ex)
print(f" {label:<45s} | Sharpe {r['sharpe']:>5.2f} | "
f"${r['final_equity']:>7.2f} | DD {r['max_dd']:>5.1f}% | "
f"{r['trades']:>4d} tr, {r['stops']:>3d} stops, {r['time_exits']:>3d} time, "
f"avg {r['avg_bars_held']:.1f} bars")
if __name__ == "__main__":
main()
@@ -0,0 +1,358 @@
"""Exp16e: Combination test — stop_scale × time_exit.
Tests all 4 combinations of validated improvements:
- stop_scale: 1.0 (current) vs 0.75 (exp16b winner)
- time_exit: on (current) vs off (exp16d winner)
Also tests stop_scale=0.5 to see if even tighter helps.
"""
import sys
from pathlib import Path
from dataclasses import dataclass
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
INTEREST_RATE_DAILY = 0.0002
COMMISSION = 0.001
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
def check_corr_conflict(open_positions, ticker, direction):
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
return True
return False
def run_sim(asset_data, events, stop_scale=1.0, use_time_exit=True):
"""Run simulation with stop_scale and time_exit options."""
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
per_asset_pnl = {}
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_price = float(prices[bar_idx])
bars_since_entry = bar_idx - pos.entry_bar
# Always update trailing stop every bar
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
# Check stop every bar (realistic — exchange checks every tick)
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
time_exit = use_time_exit and bars_since_entry >= (SHIFT - pos.k_used)
if stopped or time_exit:
exit_price = pos.stop_price if stopped else bar_price
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_since_entry * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
"bars_held": bars_since_entry,
})
per_asset_pnl[ticker] = per_asset_pnl.get(ticker, 0) + pnl_net
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# New signal
if ticker not in open_positions and price_idx >= ws + K:
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
continue
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
if check_corr_conflict(open_positions, ticker, direction):
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult * stop_scale, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
bars_held = ad["test_data"][-1]["price_idx"] - pos.entry_bar
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
per_asset_pnl[ticker] = per_asset_pnl.get(ticker, 0) + pnl_net
trades.append({"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end", "bars_held": bars_held})
final_equity = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
stops = [t for t in trades if t["exit_reason"] == "stop"]
time_exits = [t for t in trades if t["exit_reason"] == "time"]
avg_bars = np.mean([t["bars_held"] for t in trades]) if trades else 0
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = max((last - first).days / 365.25, 0.1)
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe, months = 0, 1
return {
"stop_scale": stop_scale,
"time_exit": use_time_exit,
"final_equity": round(final_equity, 2),
"total_pnl": round(final_equity - TOTAL_CAPITAL, 2),
"total_ret": round((final_equity - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades), "wins": len(wins),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"sharpe": round(sharpe, 2),
"max_dd": round(max_drawdown * 100, 1),
"stops": len(stops), "time_exits": len(time_exits),
"monthly_pnl": round((final_equity - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
"avg_bars_held": round(avg_bars, 1),
"per_asset_pnl": {k: round(v, 2) for k, v in sorted(per_asset_pnl.items(), key=lambda x: -x[1])},
}
def main():
print(f"{'='*80}")
print("EXP16e: COMBINATION TEST — stop_scale × time_exit")
print(f"{'='*80}\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
except Exception as e:
print(f"ERROR: {e}")
continue
if prices is None or len(prices) < ws + K + SHIFT + 30:
continue
data = signals.prepare_windows(prices, ws, SHIFT)
if len(data) < 30:
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
model_cfg = ModelConfig(window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
train_data = data[:n_train]
model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]),
np.array([d["norm_target"] for d in train_data]), 200, 0.003)
asset_data[ticker] = {
"prices": prices, "dates": dates, "tf": tf,
"model": mdl, "test_data": data[n_train:],
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(data[n_train:])} test")
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
events.append((str(ad["dates"][d["price_idx"]]), ticker, d))
events.sort(key=lambda x: x[0])
# ══════════════════════════════════════════════════
# 2×2 grid: stop_scale × time_exit
# ══════════════════════════════════════════════════
configs = [
{"label": "A: BASELINE (scale=1.0, time_exit=ON)", "scale": 1.0, "te": True},
{"label": "B: scale=0.75, time_exit=ON", "scale": 0.75, "te": True},
{"label": "C: scale=1.0, time_exit=OFF", "scale": 1.0, "te": False},
{"label": "D: scale=0.75, time_exit=OFF ← COMBO", "scale": 0.75, "te": False},
{"label": "E: scale=0.5, time_exit=OFF", "scale": 0.5, "te": False},
{"label": "F: scale=0.5, time_exit=ON", "scale": 0.5, "te": True},
]
print(f"\n{'='*80}")
print("RESULTS: stop_scale × time_exit (per-bar stop checking)")
print(f"{'='*80}\n")
results = []
for cfg in configs:
r = run_sim(asset_data, events, stop_scale=cfg["scale"], use_time_exit=cfg["te"])
results.append(r)
print(f" {cfg['label']}")
print(f" Sharpe {r['sharpe']:>5.2f} | ${r['final_equity']:>7.2f} "
f"(${r['total_pnl']:>+7.2f}, {r['total_ret']:>+6.1f}%) | "
f"DD {r['max_dd']:>4.1f}% | {r['trades']} trades "
f"(WR {r['wr']}%, {r['stops']} stops, {r['time_exits']} time) | "
f"avg {r['avg_bars_held']:.1f} bars | ${r['monthly_pnl']:>+.2f}/mo")
# Per-asset breakdown
for ticker, pnl in r["per_asset_pnl"].items():
print(f" {ticker:>8s}: ${pnl:>+7.2f}")
print()
# Summary table
print(f"\n{'='*80}")
print("SUMMARY")
print(f"{'='*80}\n")
print(f" {'Config':<42s} | {'Sharpe':>6s} | {'PnL':>8s} | {'DD%':>5s} | {'WR%':>5s} | {'Trds':>5s} | {'AvgBr':>5s} | {'$/mo':>7s}")
print(f" {'-'*100}")
for cfg, r in zip(configs, results):
print(f" {cfg['label']:<42s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | "
f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | "
f"{r['avg_bars_held']:>5.1f} | ${r['monthly_pnl']:>+6.2f}")
path = save_results({"results": [dict(r, label=c["label"]) for c, r in zip(configs, results)]},
Path(__file__).parent / "results", "exp16e_combo")
print(f"\n Saved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,446 @@
"""Exp16f: OHLC stop test — check stops against High/Low, not just Close.
Production stop orders on Bybit execute against ANY tick (including wicks).
Previous tests used Close prices only, potentially underestimating stop triggers.
This test uses Low (for longs) to check stops — realistic worst case.
Tests stop_scale grid with OHLC data to find truly reliable stop distance.
"""
import sys
from pathlib import Path
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig, ExchangeConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
INTEREST_RATE_DAILY = 0.0002
COMMISSION = 0.001
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
STOP_SCALES = [0.5, 0.75, 1.0, 1.25, 1.5]
def fetch_ohlcv(symbol, interval, period="max"):
"""Fetch OHLCV data from exchange. Returns closes, highs, lows, volumes, dates."""
from remizov_trader.core.signals import _get_exchange
exchange = _get_exchange(None)
if period == "max":
days = 1000
else:
days = int(period.rstrip("d"))
since = int((datetime.now(timezone.utc) - timedelta(days=days)).timestamp() * 1000)
all_ohlcv = []
batch_size = 1000
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
prev_since = None
while since < now_ms:
try:
ohlcv = exchange.fetch_ohlcv(symbol, interval, since=since, limit=batch_size)
except Exception as e:
print(f"ERROR fetching {symbol}: {e}")
return None, None, None, None, None
if not ohlcv:
break
all_ohlcv.extend(ohlcv)
since = ohlcv[-1][0] + 1
if since == prev_since:
break
prev_since = since
if not all_ohlcv:
return None, None, None, None, None
closes = np.array([c[4] for c in all_ohlcv], dtype=np.float64)
highs = np.array([c[2] for c in all_ohlcv], dtype=np.float64)
lows = np.array([c[3] for c in all_ohlcv], dtype=np.float64)
volumes = np.array([c[5] for c in all_ohlcv], dtype=np.float64)
dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date()
for c in all_ohlcv]
return closes, highs, lows, volumes, dates
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
def check_corr_conflict(open_positions, ticker, direction):
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
return True
return False
def run_sim(asset_data, events, stop_scale=1.0, use_time_exit=True, stop_mode="hybrid",
trail_every=1):
"""Run simulation.
stop_mode:
'close' = trailing on Close, check on Close (previous tests)
'hybrid' = trailing on Close, check on Low (realistic exchange behavior)
'ohlc' = trailing on High, check on Low (too aggressive)
trail_every: update trailing stop every N bars (production: SHIFT=7)
"""
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
per_asset_pnl = {}
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
highs = ad["highs"]
lows = ad["lows"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_close = float(prices[bar_idx])
bars_since_entry = bar_idx - pos.entry_bar
if stop_mode == "ohlc":
trail_price = float(highs[bar_idx]) if pos.direction == 1 else float(lows[bar_idx])
check_price = float(lows[bar_idx]) if pos.direction == 1 else float(highs[bar_idx])
elif stop_mode in ("hybrid", "production"):
trail_price = bar_close
check_price = float(lows[bar_idx]) if pos.direction == 1 else float(highs[bar_idx])
else: # "close"
trail_price = bar_close
check_price = bar_close
# Update trailing stop (respects trail_every frequency)
should_trail = (trail_every <= 1) or (bars_since_entry % trail_every == 0)
if should_trail:
pos.best_price, pos.stop_price = risk.update_trailing_stop(
trail_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
# Check stop (always — exchange checks every tick)
stopped = risk.is_stopped(check_price, pos.stop_price, pos.direction)
time_exit = use_time_exit and bars_since_entry >= (SHIFT - pos.k_used)
if stopped or time_exit:
# If stopped, exit at stop price; if time, exit at close
exit_price = pos.stop_price if stopped else bar_close
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_since_entry * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
"bars_held": bars_since_entry,
})
per_asset_pnl[ticker] = per_asset_pnl.get(ticker, 0) + pnl_net
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# New signal
if ticker not in open_positions and price_idx >= ws + K:
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
continue
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
if check_corr_conflict(open_positions, ticker, direction):
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult * stop_scale, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
bars_held = ad["test_data"][-1]["price_idx"] - pos.entry_bar
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
per_asset_pnl[ticker] = per_asset_pnl.get(ticker, 0) + pnl_net
trades.append({"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end", "bars_held": bars_held})
final_equity = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
stops = [t for t in trades if t["exit_reason"] == "stop"]
time_exits = [t for t in trades if t["exit_reason"] == "time"]
avg_bars = np.mean([t["bars_held"] for t in trades]) if trades else 0
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = max((last - first).days / 365.25, 0.1)
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe, months = 0, 1
return {
"stop_scale": stop_scale,
"time_exit": use_time_exit,
"stop_mode": stop_mode,
"final_equity": round(final_equity, 2),
"total_pnl": round(final_equity - TOTAL_CAPITAL, 2),
"total_ret": round((final_equity - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades), "wins": len(wins),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"sharpe": round(sharpe, 2),
"max_dd": round(max_drawdown * 100, 1),
"stops": len(stops), "time_exits": len(time_exits),
"monthly_pnl": round((final_equity - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
"avg_bars_held": round(avg_bars, 1),
"per_asset_pnl": {k: round(v, 2) for k, v in sorted(per_asset_pnl.items(), key=lambda x: -x[1])},
}
def main():
print(f"{'='*80}")
print("EXP16f: OHLC STOP TEST — High/Low vs Close-only")
print(f"{'='*80}\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
closes, highs, lows, volumes, dates = fetch_ohlcv(symbol, tf)
if closes is None or len(closes) < ws + K + SHIFT + 30:
print("not enough data")
continue
data = signals.prepare_windows(closes, ws, SHIFT)
if len(data) < 30:
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
model_cfg = ModelConfig(window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
train_data = data[:n_train]
model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]),
np.array([d["norm_target"] for d in train_data]), 200, 0.003)
asset_data[ticker] = {
"prices": closes, "highs": highs, "lows": lows,
"volumes": volumes, "dates": dates, "tf": tf,
"model": mdl, "test_data": data[n_train:],
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(closes)} bars, {len(data[n_train:])} test")
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
events.append((str(ad["dates"][d["price_idx"]]), ticker, d))
events.sort(key=lambda x: x[0])
# ══════════════════════════════════════════════════
# TEST 1: Three stop modes comparison
# ══════════════════════════════════════════════════
# ══════════════════════════════════════════════════
# TEST 1: Production-realistic — trail every SHIFT bars, check Low every bar
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("TEST 1: PRODUCTION-REALISTIC — trail every 7 bars (Close), check Low every bar")
print(f"{'='*80}\n")
print(f" {'Scale':>6s} {'TE':>3s} | {'Equity':>8s} {'PnL':>9s} | "
f"{'Sharpe':>6s} {'DD%':>5s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>5s} "
f"{'AvgBr':>5s} | {'$/mo':>7s}")
print(f" {'-'*85}")
all_results = []
for scale in STOP_SCALES:
for te, te_label in [(True, "on"), (False, "off")]:
r = run_sim(asset_data, events, stop_scale=scale,
use_time_exit=te, stop_mode="production",
trail_every=SHIFT)
r["label"] = f"{scale}x_TE{te_label}_prod"
all_results.append(r)
print(f" {scale:>5.2f}x {te_label:>3s} | ${r['final_equity']:>7.2f} "
f"${r['total_pnl']:>+8.2f} | {r['sharpe']:>6.2f} {r['max_dd']:>4.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>5d} "
f"{r['avg_bars_held']:>5.1f} | ${r['monthly_pnl']:>+6.2f}")
print()
# ══════════════════════════════════════════════════
# TEST 2: Comparison — close-only vs production-realistic for best configs
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("TEST 2: Close-only vs Production-realistic comparison")
print(f"{'='*80}\n")
configs = [
# Close-only (previous tests) — for comparison
{"label": "close: 1.0x TE=on trail=1", "scale": 1.0, "te": True, "mode": "close", "trail": 1},
{"label": "close: 0.75x TE=on trail=1", "scale": 0.75, "te": True, "mode": "close", "trail": 1},
{"label": "close: 0.5x TE=off trail=1", "scale": 0.5, "te": False, "mode": "close", "trail": 1},
# Production-realistic
{"label": "PROD: 1.0x TE=on trail=7", "scale": 1.0, "te": True, "mode": "production", "trail": SHIFT},
{"label": "PROD: 0.75x TE=on trail=7", "scale": 0.75, "te": True, "mode": "production", "trail": SHIFT},
{"label": "PROD: 0.5x TE=off trail=7", "scale": 0.5, "te": False, "mode": "production", "trail": SHIFT},
{"label": "PROD: 1.0x TE=off trail=7", "scale": 1.0, "te": False, "mode": "production", "trail": SHIFT},
{"label": "PROD: 0.75x TE=off trail=7", "scale": 0.75, "te": False, "mode": "production", "trail": SHIFT},
# No trailing at all — fixed stop
{"label": "PROD: 1.0x FIXED stop", "scale": 1.0, "te": True, "mode": "production", "trail": 9999},
{"label": "PROD: 1.5x FIXED stop", "scale": 1.5, "te": True, "mode": "production", "trail": 9999},
{"label": "PROD: 2.0x FIXED stop", "scale": 2.0, "te": True, "mode": "production", "trail": 9999},
]
print(f" {'Config':<35s} | {'Sharpe':>6s} | {'PnL':>8s} | {'DD%':>5s} | "
f"{'WR%':>5s} | {'Trds':>5s} | {'AvgBr':>5s} | {'$/mo':>7s}")
print(f" {'-'*95}")
for cfg in configs:
r = run_sim(asset_data, events, stop_scale=cfg["scale"],
use_time_exit=cfg["te"], stop_mode=cfg["mode"],
trail_every=cfg["trail"])
r["label"] = cfg["label"]
all_results.append(r)
print(f" {cfg['label']:<35s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | "
f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | "
f"{r['avg_bars_held']:>5.1f} | ${r['monthly_pnl']:>+6.2f}")
path = save_results({"results": all_results},
Path(__file__).parent / "results", "exp16f_ohlc")
print(f"\n Saved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,362 @@
"""Exp16b: Grid search for optimal stop multiplier scale.
Tests stop_scale=[1.0, 1.25, 1.5, 2.0, 2.5] applied on top of regime-adaptive stops.
Effective stop_mult = regime_mult × scale.
Per-bar stop checking (realistic).
"""
import sys
from pathlib import Path
from dataclasses import dataclass
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAILING_STOP = True
TRAIN_RATIO = 0.3
SHIFT = 7
INTEREST_RATE_DAILY = 0.0002
COMMISSION = 0.001
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
STOP_SCALES = [0.75, 1.0, 1.25, 1.5, 2.0, 2.5]
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
def check_corr_conflict(open_positions, ticker, direction):
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
return True
return False
def run_sim(asset_data, events, stop_scale):
"""Run full simulation with given stop_scale multiplier."""
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
skipped_margin = 0
skipped_cooldown = 0
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
# --- Check position (per-bar) ---
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_price = float(prices[bar_idx])
if TRAILING_STOP:
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
bars_held = bar_idx - pos.entry_bar
time_exit = bars_held >= (SHIFT - pos.k_used)
if stopped or time_exit:
exit_price = pos.stop_price if stopped else bar_price
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_held * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
})
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# --- New signal ---
if ticker not in open_positions and price_idx >= ws + K:
# Cooldown
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
skipped_cooldown += 1
continue
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1: # spot: long only
continue
if check_corr_conflict(open_positions, ticker, direction):
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
skipped_margin += 1
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
# Apply stop scale
stop_dist = max(atr * stop_mult * stop_scale, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
last_bar = ad["test_data"][-1]["price_idx"]
bars_held = last_bar - pos.entry_bar
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end",
})
final_equity = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
stops = [t for t in trades if t["exit_reason"] == "stop"]
time_exits = [t for t in trades if t["exit_reason"] == "time"]
# Sharpe
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = (last - first).days / 365.25
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years if years > 0 else 1
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe = 0
months = 1
return {
"stop_scale": stop_scale,
"final_equity": round(final_equity, 2),
"total_pnl": round(final_equity - TOTAL_CAPITAL, 2),
"total_ret": round((final_equity - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades),
"wins": len(wins),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"sharpe": round(sharpe, 2),
"max_dd": round(max_drawdown * 100, 1),
"stops": len(stops),
"time_exits": len(time_exits),
"monthly_pnl": round((final_equity - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
"skipped_margin": skipped_margin,
"skipped_cooldown": skipped_cooldown,
}
def main():
# Fetch data + train models (once)
print(f"{'='*80}")
print("EXP16b: STOP MULTIPLIER GRID SEARCH")
print(f"{'='*80}")
print(f"Scales: {STOP_SCALES}")
print(f"Effective stop = ATR × regime_mult × scale\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
except Exception as e:
print(f"ERROR: {e}")
continue
if prices is None or len(prices) < ws + K + SHIFT + 30:
print("not enough data")
continue
data = signals.prepare_windows(prices, ws, SHIFT)
if len(data) < 30:
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
train_data = data[:n_train]
test_data = data[n_train:]
model_cfg = ModelConfig(
window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003,
)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
windows_arr = np.array([d["norm_input"] for d in train_data])
targets_arr = np.array([d["norm_target"] for d in train_data])
model_mod.train(mdl, windows_arr, targets_arr, 200, 0.003)
asset_data[ticker] = {
"prices": prices, "dates": dates, "tf": tf,
"model": mdl, "test_data": test_data,
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(prices)} bars, {len(test_data)} test")
# Build events (once)
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
price_idx = d["price_idx"]
date = str(ad["dates"][price_idx])
events.append((date, ticker, d))
events.sort(key=lambda x: x[0])
# Run grid
print(f"\n{'='*80}")
print("RESULTS")
print(f"{'='*80}\n")
print(f" {'Scale':>6s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} | {'$/mo':>7s} {'NoMgn':>6s}")
print(f" {'-'*90}")
results = []
for scale in STOP_SCALES:
r = run_sim(asset_data, events, scale)
results.append(r)
print(f" {scale:>5.2f}x | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} | "
f"${r['monthly_pnl']:>+6.2f} {r['skipped_margin']:>6d}")
# Best by Sharpe
best = max(results, key=lambda x: x["sharpe"])
print(f"\n BEST (Sharpe): scale={best['stop_scale']}x → "
f"Sharpe {best['sharpe']}, ${best['final_equity']}, DD {best['max_dd']}%")
# Best by PnL
best_pnl = max(results, key=lambda x: x["total_pnl"])
print(f" BEST (PnL): scale={best_pnl['stop_scale']}x → "
f"PnL ${best_pnl['total_pnl']:+.2f}, Sharpe {best_pnl['sharpe']}")
path = save_results({"results": results}, Path(__file__).parent / "results", "exp16b_stop_grid")
print(f"\n Saved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,458 @@
"""Exp16c: Grid search for trailing stop aggressiveness and check frequency.
Two independent grids:
1. trailing_threshold: min price improvement (fraction of stop_dist) to move stop
2. check_every: check stops every N bars (1=every bar, 7=window boundary)
"""
import sys
from pathlib import Path
from dataclasses import dataclass, field
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
INTEREST_RATE_DAILY = 0.0002
COMMISSION = 0.001
CORRELATED_GROUPS = [
{"BTC-USD", "ETH-USD"},
{"ADA-USD", "DOT-USD", "XRP-USD"},
]
ASSETS = [
{"symbol": "BTC/USDC", "ticker": "BTC-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.241},
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.158},
{"symbol": "ADA/USDC", "ticker": "ADA-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.137},
{"symbol": "DOT/USDC", "ticker": "DOT-USD", "tf": "4h", "ws": 32, "leverage": 2, "weight": 0.137},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.127},
{"symbol": "SOL/USDC", "ticker": "SOL-USD", "tf": "2h", "ws": 128, "leverage": 2, "weight": 0.108},
{"symbol": "XRP/USDC", "ticker": "XRP-USD", "tf": "4h", "ws": 64, "leverage": 2, "weight": 0.092},
]
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
last_trail_price: float = 0.0 # last price at which trail was updated
def check_corr_conflict(open_positions, ticker, direction):
for g in CORRELATED_GROUPS:
if ticker not in g:
continue
for other in g:
if other != ticker and other in open_positions:
if open_positions[other].direction == direction:
return True
return False
def trailing_with_threshold(pos, current_price, threshold_frac):
"""Update trailing stop only if price improved by threshold_frac × stop_dist."""
direction = pos.direction
threshold = pos.stop_dist * threshold_frac
if direction == 1: # Long
if current_price > pos.best_price:
pos.best_price = current_price
# Only move stop if price exceeded last trail point by threshold
if current_price >= pos.last_trail_price + threshold:
new_stop = pos.best_price - pos.stop_dist
if new_stop > pos.stop_price:
pos.stop_price = new_stop
pos.last_trail_price = current_price
else: # Short
if current_price < pos.best_price:
pos.best_price = current_price
if current_price <= pos.last_trail_price - threshold:
new_stop = pos.best_price + pos.stop_dist
if new_stop < pos.stop_price:
pos.stop_price = new_stop
pos.last_trail_price = current_price
def run_sim(asset_data, events, trailing_threshold=0.0, check_every=1):
"""Run simulation with configurable trailing and check frequency."""
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
skipped_margin = 0
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
# --- Check position ---
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
# Check frequency: skip bars unless it's a check bar
bars_since_entry = bar_idx - pos.entry_bar
if check_every > 1 and bars_since_entry % check_every != 0:
# Still update best_price for trailing (but don't check stop)
bp = float(prices[bar_idx])
if pos.direction == 1 and bp > pos.best_price:
pos.best_price = bp
elif pos.direction == -1 and bp < pos.best_price:
pos.best_price = bp
continue
bar_price = float(prices[bar_idx])
# Trailing stop with threshold
if trailing_threshold > 0:
trailing_with_threshold(pos, bar_price, trailing_threshold)
else:
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
time_exit = bars_since_entry >= (SHIFT - pos.k_used)
if stopped or time_exit:
exit_price = pos.stop_price if stopped else bar_price
pnl_gross = pos.pos_size * (exit_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
hold_hours = bars_since_entry * bar_h
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * hold_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "stop" if stopped else "time",
})
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_equity)
dd = (peak_equity - total_equity) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# --- New signal ---
if ticker not in open_positions and price_idx >= ws + K:
# Cooldown
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
continue
w = prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy()
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
if check_corr_conflict(open_positions, ticker, direction):
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
skipped_margin += 1
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
stop_dist = max(atr * stop_mult, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
last_trail_price=current_price,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
last_bar = ad["test_data"][-1]["price_idx"]
bars_held = last_bar - pos.entry_bar
bar_hours = tf_hours.get(ad["tf"], 4)
trade_interest = pos.borrowed * INTEREST_RATE_DAILY * bars_held * bar_hours / 24
pnl_net = pnl_gross - commission_cost - trade_interest
free_usdc += pos.margin_locked + pnl_net
trades.append({
"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked,
"exit_reason": "end",
})
final_equity = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
stops = [t for t in trades if t["exit_reason"] == "stop"]
time_exits = [t for t in trades if t["exit_reason"] == "time"]
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = max((last - first).days / 365.25, 0.1)
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe, months = 0, 1
return {
"final_equity": round(final_equity, 2),
"total_pnl": round(final_equity - TOTAL_CAPITAL, 2),
"total_ret": round((final_equity - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades), "wins": len(wins),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"sharpe": round(sharpe, 2),
"max_dd": round(max_drawdown * 100, 1),
"stops": len(stops), "time_exits": len(time_exits),
"monthly_pnl": round((final_equity - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
}
def main():
print(f"{'='*80}")
print("EXP16c: TRAILING STOP AGGRESSIVENESS & CHECK FREQUENCY")
print(f"{'='*80}\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
try:
prices, dates = signals.fetch_prices_ccxt(symbol, tf, "max")
except Exception as e:
print(f"ERROR: {e}")
continue
if prices is None or len(prices) < ws + K + SHIFT + 30:
print("not enough data")
continue
data = signals.prepare_windows(prices, ws, SHIFT)
if len(data) < 30:
continue
n_train = max(int(len(data) * TRAIN_RATIO), 20)
model_cfg = ModelConfig(
window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003,
)
torch.manual_seed(42)
np.random.seed(42)
mdl = model_mod.create_model(model_cfg)
train_data = data[:n_train]
model_mod.train(mdl, np.array([d["norm_input"] for d in train_data]),
np.array([d["norm_target"] for d in train_data]), 200, 0.003)
asset_data[ticker] = {
"prices": prices, "dates": dates, "tf": tf,
"model": mdl, "test_data": data[n_train:],
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(data[n_train:])} test")
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
events.append((str(ad["dates"][d["price_idx"]]), ticker, d))
events.sort(key=lambda x: x[0])
# ══════════════════════════════════════════════════
# GRID 1: Trailing threshold (check_every=1)
# ══════════════════════════════════════════════════
thresholds = [0, 0.1, 0.25, 0.5, 0.75, 1.0, 1.5]
print(f"\n{'='*80}")
print("GRID 1: TRAILING STOP THRESHOLD (check_every=1)")
print(f"{'='*80}")
print(" threshold = min price improvement (fraction of stop_dist) to move trailing stop")
print(f" 0 = current behavior (move on any improvement)\n")
print(f" {'Thresh':>7s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} | {'$/mo':>7s}")
print(f" {'-'*85}")
grid1_results = []
for th in thresholds:
r = run_sim(asset_data, events, trailing_threshold=th, check_every=1)
r["threshold"] = th
grid1_results.append(r)
label = f"{th:.2f}×sd" if th > 0 else "any"
print(f" {label:>7s} | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} | "
f"${r['monthly_pnl']:>+6.2f}")
best1 = max(grid1_results, key=lambda x: x["sharpe"])
print(f"\n BEST: threshold={best1['threshold']}×sd → Sharpe {best1['sharpe']}, "
f"${best1['final_equity']}, DD {best1['max_dd']}%")
# ══════════════════════════════════════════════════
# GRID 2: Check frequency (trailing_threshold=0)
# ══════════════════════════════════════════════════
frequencies = [1, 2, 3, 4, 5, 7]
print(f"\n{'='*80}")
print("GRID 2: CHECK FREQUENCY (trailing_threshold=0)")
print(f"{'='*80}")
print(" check_every = check stop every N bars (1=every candle, 7=window boundary)\n")
print(f" {'Every':>6s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} | {'$/mo':>7s}")
print(f" {'-'*85}")
grid2_results = []
for freq in frequencies:
r = run_sim(asset_data, events, trailing_threshold=0, check_every=freq)
r["check_every"] = freq
grid2_results.append(r)
print(f" {freq:>4d} | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} | "
f"${r['monthly_pnl']:>+6.2f}")
best2 = max(grid2_results, key=lambda x: x["sharpe"])
print(f"\n BEST: check_every={best2['check_every']} → Sharpe {best2['sharpe']}, "
f"${best2['final_equity']}, DD {best2['max_dd']}%")
# ══════════════════════════════════════════════════
# GRID 3: Best combo (top from each grid)
# ══════════════════════════════════════════════════
print(f"\n{'='*80}")
print("GRID 3: BEST COMBINATIONS")
print(f"{'='*80}\n")
# Top 3 thresholds × top 3 frequencies
top_th = sorted(grid1_results, key=lambda x: x["sharpe"], reverse=True)[:3]
top_freq = sorted(grid2_results, key=lambda x: x["sharpe"], reverse=True)[:3]
combos = []
for th_r in top_th:
for freq_r in top_freq:
th = th_r["threshold"]
freq = freq_r["check_every"]
if th == 0 and freq == 1:
continue # already tested as baseline
combos.append((th, freq))
# Add baseline
combos = [(0, 1)] + combos
print(f" {'Thresh':>7s} {'Every':>6s} | {'Equity':>8s} {'PnL':>9s} {'Ret%':>7s} | "
f"{'Sharpe':>7s} {'DD%':>6s} | {'Trds':>5s} {'WR%':>5s} {'Stops':>6s} "
f"{'Time':>5s} | {'$/mo':>7s}")
print(f" {'-'*90}")
grid3_results = []
for th, freq in combos:
r = run_sim(asset_data, events, trailing_threshold=th, check_every=freq)
r["threshold"] = th
r["check_every"] = freq
grid3_results.append(r)
th_label = f"{th:.2f}×sd" if th > 0 else "any"
print(f" {th_label:>7s} {freq:>4d} | ${r['final_equity']:>7.2f} ${r['total_pnl']:>+8.2f} "
f"{r['total_ret']:>+6.1f}% | {r['sharpe']:>7.2f} {r['max_dd']:>5.1f}% | "
f"{r['trades']:>5d} {r['wr']:>4.1f}% {r['stops']:>6d} {r['time_exits']:>5d} | "
f"${r['monthly_pnl']:>+6.2f}")
best3 = max(grid3_results, key=lambda x: x["sharpe"])
print(f"\n WINNER: threshold={best3['threshold']}×sd, check_every={best3['check_every']} → "
f"Sharpe {best3['sharpe']}, ${best3['final_equity']}, DD {best3['max_dd']}%, "
f"${best3['monthly_pnl']}/mo")
path = save_results({
"grid1_trailing": grid1_results,
"grid2_frequency": grid2_results,
"grid3_combos": grid3_results,
}, Path(__file__).parent / "results", "exp16c_trailing_grid")
print(f"\n Saved: {path}")
if __name__ == "__main__":
main()
@@ -0,0 +1,64 @@
{
"results": [
{
"variant": "baseline",
"sharpe": 2.52,
"total_pnl": 713.11,
"total_ret": 625.5,
"trades": 323,
"wr": 40.9,
"max_dd": 14.8,
"monthly_pnl": 31.19,
"skipped_vol": 0,
"per_asset": {
"DOGE-USD": 497.9,
"ETH-USD": 215.21
}
},
{
"variant": "vol_filter",
"sharpe": 2.0,
"total_pnl": 272.94,
"total_ret": 239.4,
"trades": 76,
"wr": 51.3,
"max_dd": 5.4,
"monthly_pnl": 11.94,
"skipped_vol": 1388,
"per_asset": {
"DOGE-USD": 225.91,
"ETH-USD": 47.03
}
},
{
"variant": "vol_stop",
"sharpe": 2.49,
"total_pnl": 591.79,
"total_ret": 519.1,
"trades": 324,
"wr": 40.4,
"max_dd": 14.4,
"monthly_pnl": 25.88,
"skipped_vol": 0,
"per_asset": {
"DOGE-USD": 373.74,
"ETH-USD": 218.05
}
},
{
"variant": "vwap",
"sharpe": 2.74,
"total_pnl": 1581.3,
"total_ret": 1387.1,
"trades": 281,
"wr": 43.1,
"max_dd": 12.4,
"monthly_pnl": 69.15,
"skipped_vol": 0,
"per_asset": {
"DOGE-USD": 1098.35,
"ETH-USD": 482.95
}
}
]
}
+389
View File
@@ -0,0 +1,389 @@
"""Exp17: Volume integration tests.
Variant A: VWAP as model input (instead of Close)
Variant B: Volume filter — only trade when volume > 1.5× avg
Variant C: Volume-weighted stop (wider stop on high volume = conviction)
Tests on ETH (2h, ws=64) and DOGE (4h, ws=48) — best performers from exp16e.
"""
import sys
from pathlib import Path
from dataclasses import dataclass
from datetime import datetime, timedelta, timezone
sys.path.insert(0, str(Path(__file__).parent.parent.parent / "src"))
sys.path.insert(0, str(Path(__file__).parent.parent))
import numpy as np
import torch
from remizov_trader.core import model as model_mod, signals, risk
from remizov_trader.config import ModelConfig
from common.metrics import save_results
TOTAL_CAPITAL = 114.0
K = 2
CORR_THRESH = 0.5
TRAIN_RATIO = 0.3
SHIFT = 7
COMMISSION = 0.001
STOP_SCALE = 0.5 # exp16e winner
ASSETS = [
{"symbol": "ETH/USDC", "ticker": "ETH-USD", "tf": "2h", "ws": 64, "leverage": 2, "weight": 0.5},
{"symbol": "DOGE/USDC", "ticker": "DOGE-USD", "tf": "4h", "ws": 48, "leverage": 2, "weight": 0.5},
]
def fetch_ohlcv(symbol, interval, period="max"):
"""Fetch OHLCV data."""
from remizov_trader.core.signals import _get_exchange
exchange = _get_exchange(None)
if period == "max":
days = 1000
else:
days = int(period.rstrip("d"))
since = int((datetime.now(timezone.utc) - timedelta(days=days)).timestamp() * 1000)
all_ohlcv = []
batch_size = 1000
now_ms = int(datetime.now(timezone.utc).timestamp() * 1000)
prev_since = None
while since < now_ms:
try:
ohlcv = exchange.fetch_ohlcv(symbol, interval, since=since, limit=batch_size)
except Exception as e:
print(f"ERROR: {e}")
return None, None, None, None, None
if not ohlcv:
break
all_ohlcv.extend(ohlcv)
since = ohlcv[-1][0] + 1
if since == prev_since:
break
prev_since = since
if not all_ohlcv:
return None, None, None, None, None
closes = np.array([c[4] for c in all_ohlcv], dtype=np.float64)
highs = np.array([c[2] for c in all_ohlcv], dtype=np.float64)
lows = np.array([c[3] for c in all_ohlcv], dtype=np.float64)
volumes = np.array([c[5] for c in all_ohlcv], dtype=np.float64)
dates = [datetime.fromtimestamp(c[0] / 1000, tz=timezone.utc).date()
for c in all_ohlcv]
return closes, highs, lows, volumes, dates
def compute_vwap(closes, highs, lows, volumes, period=20):
"""Compute VWAP using typical price × volume."""
typical = (highs + lows + closes) / 3.0
vwap = np.full_like(closes, np.nan)
for i in range(period, len(closes)):
w = volumes[i-period:i]
tp = typical[i-period:i]
total_vol = w.sum()
if total_vol > 0:
vwap[i] = (tp * w).sum() / total_vol
else:
vwap[i] = closes[i]
# Fill initial with close
vwap[:period] = closes[:period]
return vwap
@dataclass
class Position:
ticker: str
direction: int
entry_price: float
stop_price: float
stop_dist: float
best_price: float
pos_size: float
pos_value: float
margin_locked: float
borrowed: float
k_used: int
entry_bar: int
def run_sim(asset_data, events, variant="baseline"):
"""Run simulation with volume variant.
variant:
'baseline' — standard (Close input, no filter)
'vwap' — VWAP as model input
'vol_filter' — only trade when volume > 1.5x rolling avg
'vol_stop' — wider stop on high volume (conviction trade)
"""
free_usdc = TOTAL_CAPITAL
open_positions = {}
trades = []
last_stop_date = {}
peak_equity = TOTAL_CAPITAL
max_drawdown = 0.0
per_asset = {}
skipped_vol = 0
tf_hours = {"1h": 1, "2h": 2, "4h": 4, "6h": 6, "12h": 12, "1d": 24}
for date, ticker, window in events:
ad = asset_data[ticker]
prices = ad["prices"] # always Close for stop/entry
model_prices = ad.get("vwap", prices) if variant == "vwap" else prices
volumes = ad["volumes"]
price_idx = window["price_idx"]
current_price = float(prices[price_idx])
ws = ad["ws"]
leverage = ad["leverage"]
weight = ad["weight"]
bar_h = tf_hours.get(ad["tf"], 4)
# Check position
if ticker in open_positions:
pos = open_positions[ticker]
closed = False
check_from = max(pos.entry_bar + 1, price_idx - SHIFT + 1)
for bar_idx in range(check_from, price_idx + 1):
if bar_idx >= len(prices):
break
bar_price = float(prices[bar_idx])
bars_since = bar_idx - pos.entry_bar
pos.best_price, pos.stop_price = risk.update_trailing_stop(
bar_price, pos.best_price, pos.stop_price,
pos.stop_dist, pos.direction)
stopped = risk.is_stopped(bar_price, pos.stop_price, pos.direction)
if stopped:
pnl_gross = pos.pos_size * (pos.stop_price - pos.entry_price) * pos.direction
commission_cost = pos.pos_value * COMMISSION * 2
pnl_net = pnl_gross - commission_cost
free_usdc += pos.margin_locked + pnl_net
del open_positions[ticker]
trades.append({"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked})
per_asset[ticker] = per_asset.get(ticker, 0) + pnl_net
if stopped:
exit_date = str(ad["dates"][bar_idx]) if bar_idx < len(ad["dates"]) else date
last_stop_date[ticker] = exit_date
total_eq = free_usdc + sum(p.margin_locked for p in open_positions.values())
peak_equity = max(peak_equity, total_eq)
dd = (peak_equity - total_eq) / peak_equity if peak_equity > 0 else 0
max_drawdown = max(max_drawdown, dd)
closed = True
break
if closed:
continue
# New signal
if ticker not in open_positions and price_idx >= ws + K:
# Cooldown
if ticker in last_stop_date:
from datetime import date as d
days_since = (d.fromisoformat(date[:10]) -
d.fromisoformat(last_stop_date[ticker][:10])).days
candles_since = days_since * 24 // bar_h
if candles_since < SHIFT:
continue
# Volume filter (variant B)
if variant == "vol_filter":
vol_window = 50
if price_idx >= vol_window:
avg_vol = volumes[price_idx-vol_window:price_idx].mean()
current_vol = volumes[price_idx]
if avg_vol > 0 and current_vol < avg_vol * 1.5:
skipped_vol += 1
continue
# Use model_prices for prediction input
w = model_prices[price_idx - ws - K:price_idx - K].copy()
confirm = prices[price_idx - K:price_idx].copy() # always Close for confirmation
mu, std = w.mean(), w.std()
if std < 1e-10:
continue
norm_input = (w - mu) / std
pred = model_mod.predict(ad["model"], norm_input)
pred_new = pred[-SHIFT:]
corr, confirmed = signals.check_shape_confirmation(
pred_new, confirm, mu, std, K, CORR_THRESH)
if not confirmed:
continue
direction = signals.get_direction(pred_new, K)
if direction is None or direction == -1:
continue
total_equity = free_usdc + sum(p.margin_locked for p in open_positions.values())
pos_value = total_equity * weight * leverage
if pos_value < 5.0:
continue
margin_needed = pos_value / leverage
if free_usdc < margin_needed:
margin_needed = free_usdc * 0.95
pos_value = margin_needed * leverage
if pos_value < 5.0:
continue
pos_size = pos_value / current_price
borrowed = pos_value - margin_needed
k_adj, stop_mult = risk.regime_adaptive_params(prices, price_idx, K)
atr = risk.compute_atr(prices, price_idx)
# Volume-weighted stop (variant C)
scale = STOP_SCALE
if variant == "vol_stop" and price_idx >= 50:
avg_vol = volumes[price_idx-50:price_idx].mean()
vol_ratio = volumes[price_idx] / avg_vol if avg_vol > 0 else 1.0
if vol_ratio > 2.0:
scale *= 1.5 # wider stop on high volume (conviction)
elif vol_ratio < 0.5:
scale *= 0.7 # tighter stop on low volume (less conviction)
stop_dist = max(atr * stop_mult * scale, current_price * 0.005)
free_usdc -= margin_needed
open_positions[ticker] = Position(
ticker=ticker, direction=direction,
entry_price=current_price,
stop_price=current_price - direction * stop_dist,
stop_dist=stop_dist, best_price=current_price,
pos_size=pos_size, pos_value=pos_value,
margin_locked=margin_needed, borrowed=borrowed,
k_used=k_adj, entry_bar=price_idx,
)
# Close remaining
for ticker, pos in list(open_positions.items()):
ad = asset_data[ticker]
last_price = float(ad["prices"][-1])
pnl_gross = pos.pos_size * (last_price - pos.entry_price) * pos.direction
pnl_net = pnl_gross - pos.pos_value * COMMISSION * 2
free_usdc += pos.margin_locked + pnl_net
per_asset[ticker] = per_asset.get(ticker, 0) + pnl_net
trades.append({"ticker": ticker, "pnl_net": pnl_net,
"equity_at_entry": pos.margin_locked})
final = free_usdc
wins = [t for t in trades if t["pnl_net"] > 0]
if len(trades) > 1:
from datetime import date as d
first = d.fromisoformat(events[0][0][:10])
last = d.fromisoformat(events[-1][0][:10])
years = max((last - first).days / 365.25, 0.1)
returns = np.array([t["pnl_net"] / t["equity_at_entry"]
for t in trades if t["equity_at_entry"] > 0])
tpy = len(trades) / years
sharpe = float(np.mean(returns) / np.std(returns) * np.sqrt(tpy)) if np.std(returns) > 0 else 0
months = years * 12
else:
sharpe, months = 0, 1
return {
"variant": variant,
"sharpe": round(sharpe, 2),
"total_pnl": round(final - TOTAL_CAPITAL, 2),
"total_ret": round((final - TOTAL_CAPITAL) / TOTAL_CAPITAL * 100, 1),
"trades": len(trades),
"wr": round(len(wins) / len(trades) * 100, 1) if trades else 0,
"max_dd": round(max_drawdown * 100, 1),
"monthly_pnl": round((final - TOTAL_CAPITAL) / months, 2) if months > 0 else 0,
"skipped_vol": skipped_vol,
"per_asset": {k: round(v, 2) for k, v in sorted(per_asset.items(), key=lambda x: -x[1])},
}
def main():
print(f"{'='*80}")
print("EXP17: VOLUME INTEGRATION TESTS")
print(f"{'='*80}\n")
asset_data = {}
for a in ASSETS:
ticker, symbol, tf = a["ticker"], a["symbol"], a["tf"]
ws = a["ws"]
print(f" {ticker} ({tf}, ws={ws})...", end=" ", flush=True)
closes, highs, lows, volumes, dates = fetch_ohlcv(symbol, tf)
if closes is None or len(closes) < ws + K + SHIFT + 30:
print("not enough data")
continue
# Compute VWAP
vwap = compute_vwap(closes, highs, lows, volumes)
# Train model on Close (baseline) — same model for all variants
data_close = signals.prepare_windows(closes, ws, SHIFT)
if len(data_close) < 30:
continue
n_train = max(int(len(data_close) * TRAIN_RATIO), 20)
model_cfg = ModelConfig(window_size=ws, n_steps=20, total_time=0.5,
shift=SHIFT, epochs=200, finetune_epochs=50, lr=0.003)
torch.manual_seed(42)
np.random.seed(42)
mdl_close = model_mod.create_model(model_cfg)
train_close = data_close[:n_train]
model_mod.train(mdl_close, np.array([d["norm_input"] for d in train_close]),
np.array([d["norm_target"] for d in train_close]), 200, 0.003)
# Train model on VWAP (variant A)
data_vwap = signals.prepare_windows(vwap, ws, SHIFT)
torch.manual_seed(42)
np.random.seed(42)
mdl_vwap = model_mod.create_model(model_cfg)
train_vwap = data_vwap[:n_train]
model_mod.train(mdl_vwap, np.array([d["norm_input"] for d in train_vwap]),
np.array([d["norm_target"] for d in train_vwap]), 200, 0.003)
asset_data[ticker] = {
"prices": closes, "highs": highs, "lows": lows,
"volumes": volumes, "vwap": vwap, "dates": dates, "tf": tf,
"model": mdl_close, "model_vwap": mdl_vwap,
"test_data": data_close[n_train:],
"ws": ws, "leverage": a["leverage"], "weight": a["weight"],
}
print(f"{len(closes)} bars, {len(data_close[n_train:])} test")
# Build events
events = []
for ticker, ad in asset_data.items():
for d in ad["test_data"]:
events.append((str(ad["dates"][d["price_idx"]]), ticker, d))
events.sort(key=lambda x: x[0])
# Run variants
variants = ["baseline", "vol_filter", "vol_stop"]
print(f"\n{'='*80}")
print("RESULTS")
print(f"{'='*80}\n")
print(f" {'Variant':<15s} | {'Sharpe':>6s} | {'PnL':>8s} | {'DD%':>5s} | "
f"{'WR%':>5s} | {'Trds':>5s} | {'$/mo':>7s} | {'Skip':>5s}")
print(f" {'-'*75}")
all_results = []
for v in variants:
r = run_sim(asset_data, events, variant=v)
all_results.append(r)
print(f" {v:<15s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | "
f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | "
f"${r['monthly_pnl']:>+6.2f} | {r['skipped_vol']:>5d}")
for t, pnl in r["per_asset"].items():
print(f" {t}: ${pnl:>+7.2f}")
# VWAP variant — needs separate model
print(f"\n --- VWAP variant (separate model trained on VWAP) ---")
# Swap models for VWAP test
for ticker, ad in asset_data.items():
ad["model"], ad["_orig_model"] = ad["model_vwap"], ad["model"]
r = run_sim(asset_data, events, variant="vwap")
all_results.append(r)
print(f" {'vwap':<15s} | {r['sharpe']:>6.2f} | ${r['total_pnl']:>+7.2f} | "
f"{r['max_dd']:>4.1f}% | {r['wr']:>4.1f}% | {r['trades']:>5d} | "
f"${r['monthly_pnl']:>+6.2f} | {r['skipped_vol']:>5d}")
for t, pnl in r["per_asset"].items():
print(f" {t}: ${pnl:>+7.2f}")
# Restore models
for ticker, ad in asset_data.items():
ad["model"] = ad.pop("_orig_model")
path = save_results({"results": all_results},
Path(__file__).parent / "results", "exp17_volume")
print(f"\n Saved: {path}")
if __name__ == "__main__":
main()