Spaces:
Running
Running
File size: 45,811 Bytes
4cc1098 2460914 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 39ee783 4cc1098 39ee783 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 39ee783 4cc1098 1364132 4cc1098 1364132 4cc1098 39ee783 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 39ee783 4cc1098 1a7814e 4cc1098 1364132 4cc1098 b1ba858 1cdb139 4cc1098 1364132 4cc1098 b1ba858 1cdb139 4cc1098 1364132 4cc1098 b1ba858 1cdb139 4cc1098 1364132 4cc1098 711cb1e 4cc1098 1364132 4cc1098 1364132 4cc1098 1364132 4cc1098 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 | <!DOCTYPE html>
<html lang="id">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Asset Trading Simulator</title>
<style>
:root {
--bg-main: #0b0e11;
--bg-card: #181a20;
--text-main: #eaecef;
--text-muted: #848e9c;
--up-color: #0ecb81;
--down-color: #f6465d;
--accent: #f0b90b;
}
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
-webkit-tap-highlight-color: transparent;
}
html, body {
height: 100%;
}
body {
background-color: #000;
color: var(--text-main);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
min-height: 100dvh;
}
.phone-container {
width: 100%;
max-width: 412px;
height: 100vh;
height: 100dvh;
max-height: 892px;
background-color: var(--bg-main);
display: flex;
flex-direction: column;
overflow: hidden;
position: relative;
box-shadow: 0 0 20px rgba(0, 0, 0, 0.8);
}
.header {
background-color: var(--bg-card);
padding: 12px;
border-bottom: 1px solid #2b3139;
}
/* ====== Baris judul: teks kiri + link kanan ====== */
.header-title-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 4px;
}
.header-title {
font-size: 14px;
color: var(--text-muted);
}
.mode-link {
font-size: 12px;
font-weight: 700;
color: var(--accent);
text-decoration: none;
padding: 2px 8px;
border: 1px solid var(--accent);
border-radius: 4px;
transition: background-color 0.2s, color 0.2s;
}
.mode-link:hover,
.mode-link:active {
background-color: var(--accent);
color: #000;
}
.balance-row {
display: flex;
justify-content: space-between;
align-items: baseline;
margin-bottom: 8px;
}
.balance-value {
font-size: 24px;
font-weight: 700;
color: var(--text-main);
}
.pnl-badge {
font-size: 14px;
font-weight: 600;
padding: 2px 8px;
border-radius: 4px;
transition: background-color .2s, color .2s;
}
.stats-grid {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 12px;
margin-top: 12px;
font-size: 12px;
}
.stat-box {
background: rgba(255, 255, 255, 0.03);
padding: 8px;
border-radius: 6px;
}
.stat-label {
color: var(--text-muted);
margin-bottom: 2px;
}
.stat-val {
font-weight: 600;
}
.ticker-bar {
display: flex;
justify-content: space-between;
padding: 8px 12px;
background: #12161a;
font-size: 13px;
border-bottom: 1px solid #2b3139;
}
/* ====== Bar berisi 4 dropdown ====== */
.indicator-bar {
display: flex;
gap: 6px;
padding: 6px 8px;
background: #12161a;
border-bottom: 1px solid #2b3139;
}
.ind-select {
flex: 1 1 0;
min-width: 0;
background-color: #2b3139;
color: var(--text-main);
border: 1px solid #3a4048;
border-radius: 5px;
padding: 5px 16px 5px 6px;
font-size: 11px;
font-family: inherit;
cursor: pointer;
outline: none;
-webkit-appearance: none;
-moz-appearance: none;
appearance: none;
background-image: url("data:image/svg+xml;utf8,<svg xmlns='http://www.w3.org/2000/svg' width='8' height='8' viewBox='0 0 8 8'><path d='M0 2 L4 6 L8 2 Z' fill='%23848e9c'/></svg>");
background-repeat: no-repeat;
background-position: right 5px center;
}
.ind-select:focus {
border-color: var(--accent);
}
/* ====== Baris input fee ====== */
.fee-row {
display: flex;
gap: 12px;
padding: 6px 12px;
background: #12161a;
border-bottom: 1px solid #2b3139;
font-size: 12px;
color: var(--text-muted);
align-items: center;
}
.fee-row label {
display: flex;
align-items: center;
gap: 6px;
flex: 1;
}
.fee-row input {
width: 60px;
background-color: #2b3139;
color: var(--text-main);
border: 1px solid #3a4048;
border-radius: 4px;
padding: 4px 6px;
font-size: 12px;
font-family: inherit;
outline: none;
}
.fee-row input:focus {
border-color: var(--accent);
}
/* ====== Grafik utama ====== */
.chart-container {
flex: 1.8 1 0;
position: relative;
background-color: var(--bg-main);
width: 100%;
min-height: 100px;
overflow: hidden;
}
/* ====== Grafik bawah ====== */
.subchart-container {
flex: 0.9 1 0;
position: relative;
background-color: var(--bg-main);
width: 100%;
min-height: 50px;
border-top: 1px solid #2b3139;
overflow: hidden;
}
canvas {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
display: block;
}
.control-panel {
background-color: var(--bg-card);
padding: 12px;
border-top: 1px solid #2b3139;
}
.playback-controls {
display: flex;
gap: 8px;
margin-bottom: 10px;
}
.btn {
flex: 1;
border: none;
padding: 10px;
font-size: 14px;
font-weight: 600;
border-radius: 8px;
cursor: pointer;
display: flex;
justify-content: center;
align-items: center;
gap: 6px;
transition: opacity 0.2s;
user-select: none;
}
.btn:active {
opacity: 0.8;
}
.btn:disabled {
opacity: 0.4;
cursor: not-allowed;
}
.btn-secondary {
background-color: #2b3139;
color: var(--text-main);
}
.btn-buy {
background-color: var(--up-color);
color: #fff;
font-size: 16px;
}
.btn-sell {
background-color: var(--down-color);
color: #fff;
font-size: 16px;
}
.trade-actions {
display: flex;
gap: 12px;
}
.pos-indicator {
text-align: center;
font-size: 12px;
color: var(--text-muted);
margin-bottom: 8px;
min-height: 15px;
}
</style>
</head>
<body>
<div class="phone-container">
<div class="header">
<div class="header-title-row">
<span class="header-title">Total Kekayaan (Equity)</span>
<a class="mode-link" href="https://lynk.id/readthefuture" target="_blank" rel="noopener noreferrer">MODE: PEMULA</a>
</div>
<div class="balance-row">
<span class="balance-value" id="equity-val">1.000.000</span>
<span class="pnl-badge" id="pnl-pct" style="background: rgba(255,255,255,0.1);">+0.00%</span>
</div>
<div class="stats-grid">
<div class="stat-box">
<div class="stat-label">Saldo Tunai (Cash)</div>
<div class="stat-val" id="cash-val">1.000.000</div>
</div>
<div class="stat-box">
<div class="stat-label">Nilai Aset</div>
<div class="stat-val" id="asset-val">0</div>
</div>
</div>
</div>
<div class="ticker-bar">
<div>
<strong style="color:var(--accent)">SIMULASI-UNIT</strong>
<span id="bar-progress" style="color:var(--text-muted)">0/250</span>
</div>
<div id="ticker-price" style="font-weight:700; color:var(--text-main)">0</div>
</div>
<!-- ====== Baris dropdown indikator utama + sub-chart ====== -->
<div class="indicator-bar">
<select id="ind1" class="ind-select" title="Indikator utama 1">
<option value="">Kosong</option>
<option value="ma5">MA 5</option>
<option value="ma10">MA 10</option>
<option value="ma20">MA 20</option>
<option value="ma50">MA 50</option>
<option value="ma100">MA 100</option>
<option value="ma200">MA 200</option>
<option value="ema5">EMA 5</option>
<option value="ema10">EMA 10</option>
<option value="ema20">EMA 20</option>
<option value="ema50">EMA 50</option>
<option value="ema100">EMA 100</option>
<option value="ema200">EMA 200</option>
<option value="wma5">WMA 5</option>
<option value="wma10">WMA 10</option>
<option value="wma20">WMA 20</option>
<option value="wma50">WMA 50</option>
<option value="wma100">WMA 100</option>
<option value="wma200">WMA 200</option>
<option value="wilders5">Wilders 5</option>
<option value="wilders10">Wilders 10</option>
<option value="wilders20">Wilders 20</option>
<option value="wilders50">Wilders 50</option>
<option value="wilders100">Wilders 100</option>
<option value="wilders200">Wilders 200</option>
<option value="bollinger">Bollinger</option>
<option value="squeeze">Squeeze</option>
<option value="mahir" disabled>== MODE:MAHIR ==</option>
<option value="supnresv01" disabled>Sup & Res V01</option>
</select>
<select id="ind2" class="ind-select" title="Indikator utama 2">
<option value="">Kosong</option>
<option value="ma5">MA 5</option>
<option value="ma10">MA 10</option>
<option value="ma20">MA 20</option>
<option value="ma50">MA 50</option>
<option value="ma100">MA 100</option>
<option value="ma200">MA 200</option>
<option value="ema5">EMA 5</option>
<option value="ema10">EMA 10</option>
<option value="ema20">EMA 20</option>
<option value="ema50">EMA 50</option>
<option value="ema100">EMA 100</option>
<option value="ema200">EMA 200</option>
<option value="wma5">WMA 5</option>
<option value="wma10">WMA 10</option>
<option value="wma20">WMA 20</option>
<option value="wma50">WMA 50</option>
<option value="wma100">WMA 100</option>
<option value="wma200">WMA 200</option>
<option value="wilders5">Wilders 5</option>
<option value="wilders10">Wilders 10</option>
<option value="wilders20">Wilders 20</option>
<option value="wilders50">Wilders 50</option>
<option value="wilders100">Wilders 100</option>
<option value="wilders200">Wilders 200</option>
<option value="bollinger">Bollinger</option>
<option value="squeeze">Squeeze</option>
<option value="mahir" disabled>== MODE:MAHIR ==</option>
<option value="supnresv01" disabled>Sup & Res V01</option>
</select>
<select id="ind3" class="ind-select" title="Indikator utama 3">
<option value="">Kosong</option>
<option value="ma5">MA 5</option>
<option value="ma10">MA 10</option>
<option value="ma20">MA 20</option>
<option value="ma50">MA 50</option>
<option value="ma100">MA 100</option>
<option value="ma200">MA 200</option>
<option value="ema5">EMA 5</option>
<option value="ema10">EMA 10</option>
<option value="ema20">EMA 20</option>
<option value="ema50">EMA 50</option>
<option value="ema100">EMA 100</option>
<option value="ema200">EMA 200</option>
<option value="wma5">WMA 5</option>
<option value="wma10">WMA 10</option>
<option value="wma20">WMA 20</option>
<option value="wma50">WMA 50</option>
<option value="wma100">WMA 100</option>
<option value="wma200">WMA 200</option>
<option value="wilders5">Wilders 5</option>
<option value="wilders10">Wilders 10</option>
<option value="wilders20">Wilders 20</option>
<option value="wilders50">Wilders 50</option>
<option value="wilders100">Wilders 100</option>
<option value="wilders200">Wilders 200</option>
<option value="bollinger">Bollinger</option>
<option value="squeeze">Squeeze</option>
<option value="mahir" disabled>== MODE:MAHIR ==</option>
<option value="supnresv01" disabled>Sup & Res V01</option>
</select>
<select id="subchart" class="ind-select" title="Grafik bawah">
<option value="rsi">RSI</option>
<option value="macd">MACD+Signal</option>
</select>
</div>
<!-- ====== Input Fee Beli & Jual ====== -->
<div class="fee-row">
<label>Fee Beli (%): <input type="number" id="fee-buy-input" value="0.3" step="0.01" min="0" max="10"></label>
<label>Fee Jual (%): <input type="number" id="fee-sell-input" value="0.3" step="0.01" min="0" max="10"></label>
</div>
<div class="chart-container" id="chart-parent">
<canvas id="tradingChart"></canvas>
</div>
<!-- ====== Grafik bawah (RSI / MACD) ====== -->
<div class="subchart-container" id="subchart-parent">
<canvas id="subChart"></canvas>
</div>
<div class="control-panel">
<div class="pos-indicator" id="pos-info">Posisi saat ini: 0 Unit (Rata-rata: 0)</div>
<div class="playback-controls">
<button class="btn btn-secondary" id="btn-pause">⏸ Pause</button>
<button class="btn btn-secondary" id="btn-restart">🔄 Restart</button>
</div>
<div class="trade-actions">
<button class="btn btn-buy" id="btn-buy">BELI</button>
<button class="btn btn-sell" id="btn-sell">JUAL</button>
</div>
</div>
</div>
<script>
(function () {
'use strict';
/* ==================== KONFIGURASI ==================== */
const INITIAL_CASH = 1000000;
const WARMUP_BARS = 30; // candle pemanasan sebelum trading
const TOTAL_BARS = 250; // jumlah candle yang disimulasikan
const END_INDEX = WARMUP_BARS + TOTAL_BARS; // 280
const VISIBLE_BARS = 30; // candle yang tampil di layar
const INTERVAL_TIME = 1000; // ms per candle
// === FEE: variabel agar bisa diubah dari UI ===
let feeBeli = 0.003; // 0.3%
let feeJual = 0.003; // 0.3%
// Warna per slot indikator utama
const SLOT_COLORS = ['#f0b90b', '#4fc3f7', '#e91e63'];
/* ==================== STATE ==================== */
let fullData = [];
let currentIndex = WARMUP_BARS;
let isPaused = false;
let finished = false;
let timer = null;
let cash = INITIAL_CASH;
let positionVolume = 0;
let avgBuyPrice = 0;
let dpr = 1;
let viewW = 0, viewH = 0;
let subViewW = 0, subViewH = 0;
/* ==================== DOM ==================== */
const canvas = document.getElementById('tradingChart');
const ctx = canvas.getContext('2d');
const equityValEl = document.getElementById('equity-val');
const cashValEl = document.getElementById('cash-val');
const assetValEl = document.getElementById('asset-val');
const pnlPctEl = document.getElementById('pnl-pct');
const tickerPriceEl = document.getElementById('ticker-price');
const barProgressEl = document.getElementById('bar-progress');
const posInfoEl = document.getElementById('pos-info');
const subCanvas = document.getElementById('subChart');
const sctx = subCanvas.getContext('2d');
const ind1El = document.getElementById('ind1');
const ind2El = document.getElementById('ind2');
const ind3El = document.getElementById('ind3');
const subSelectEl = document.getElementById('subchart');
const feeBuyInput = document.getElementById('fee-buy-input');
const feeSellInput = document.getElementById('fee-sell-input');
const btnPause = document.getElementById('btn-pause');
const btnRestart = document.getElementById('btn-restart');
const btnBuy = document.getElementById('btn-buy');
const btnSell = document.getElementById('btn-sell');
/* ==================== UTILITAS ==================== */
function getTickSize(price) {
if (price < 200) return 1;
if (price < 500) return 2;
if (price < 2000) return 5;
if (price < 5000) return 10;
return 25;
}
function bulatkanFraksi(price, up) {
const tick = getTickSize(price);
return up
? Math.ceil(price / tick) * tick
: Math.floor(price / tick) * tick;
}
function formatUnit(num) {
if (!isFinite(num)) num = 0;
return Math.round(num).toLocaleString('id-ID');
}
/* ==================== GENERATOR DATA ==================== */
function generateSyntheticData(totalBars) {
const data = [];
let currentPrice = 1000;
for (let i = 0; i < totalBars; i++) {
const changePercent = (Math.random() - 0.48) * 0.04;
let newPrice = currentPrice * (1 + changePercent);
if (newPrice < 50) newPrice = 50;
const open = bulatkanFraksi(currentPrice, false);
const close = bulatkanFraksi(newPrice, false);
let high = bulatkanFraksi(Math.max(open, close) * (1 + Math.random() * 0.015), false);
let low = bulatkanFraksi(Math.min(open, close) * (1 - Math.random() * 0.015), true);
high = Math.max(high, open, close);
low = Math.min(low, open, close);
if (low <= 0) low = Math.max(1, Math.round(open * 0.9));
data.push({ open, high, low, close });
currentPrice = close;
}
return data;
}
/* ==================== KALKULASI INDIKATOR ==================== */
function calcSMA(values, period) {
const out = new Array(values.length).fill(null);
let sum = 0;
for (let i = 0; i < values.length; i++) {
sum += values[i];
if (i >= period) sum -= values[i - period];
if (i >= period - 1) out[i] = sum / period;
}
return out;
}
function calcEMA(values, period) {
const out = new Array(values.length).fill(null);
if (period < 1) return out;
const k = 2 / (period + 1);
let prev = null;
for (let i = 0; i < values.length; i++) {
if (i < period - 1) continue;
if (prev === null) {
let s = 0;
for (let j = i - period + 1; j <= i; j++) s += values[j];
prev = s / period;
} else {
prev = values[i] * k + prev * (1 - k);
}
out[i] = prev;
}
return out;
}
function calcWMA(values, period) {
const out = new Array(values.length).fill(null);
const denom = period * (period + 1) / 2;
for (let i = period - 1; i < values.length; i++) {
let s = 0;
for (let j = 0; j < period; j++) {
s += values[i - period + 1 + j] * (j + 1);
}
out[i] = s / denom;
}
return out;
}
function calcWilders(values, period) {
const out = new Array(values.length).fill(null);
let prev = null;
for (let i = 0; i < values.length; i++) {
if (i < period - 1) continue;
if (prev === null) {
let s = 0;
for (let j = i - period + 1; j <= i; j++) s += values[j];
prev = s / period;
} else {
prev = (prev * (period - 1) + values[i]) / period;
}
out[i] = prev;
}
return out;
}
function calcBollinger(closes, period, mult) {
period = period || 20;
mult = mult || 2;
const middle = calcSMA(closes, period);
const upper = new Array(closes.length).fill(null);
const lower = new Array(closes.length).fill(null);
for (let i = period - 1; i < closes.length; i++) {
let s = 0;
for (let j = i - period + 1; j <= i; j++) {
const d = closes[j] - middle[i];
s += d * d;
}
const sd = Math.sqrt(s / period);
upper[i] = middle[i] + mult * sd;
lower[i] = middle[i] - mult * sd;
}
return { upper, middle, lower };
}
function calcATR(data, period) {
const tr = new Array(data.length).fill(0);
for (let i = 0; i < data.length; i++) {
if (i === 0) {
tr[i] = data[i].high - data[i].low;
} else {
tr[i] = Math.max(
data[i].high - data[i].low,
Math.abs(data[i].high - data[i - 1].close),
Math.abs(data[i].low - data[i - 1].close)
);
}
}
return calcWilders(tr, period);
}
function calcSqueeze(data) {
const closes = data.map(d => d.close);
const bb = calcBollinger(closes, 20, 2);
const atrArr = calcATR(data, 20);
const kcMid = calcEMA(closes, 20);
const squeezeOn = new Array(closes.length).fill(null);
for (let i = 0; i < closes.length; i++) {
if (bb.upper[i] === null || atrArr[i] === null || kcMid[i] === null) continue;
const kcUp = kcMid[i] + 1.5 * atrArr[i];
const kcLo = kcMid[i] - 1.5 * atrArr[i];
squeezeOn[i] = (bb.upper[i] < kcUp && bb.lower[i] > kcLo) ? 1 : 0;
}
return squeezeOn;
}
function calcRSI(closes, period) {
period = period || 14;
const out = new Array(closes.length).fill(null);
let avgGain = 0, avgLoss = 0;
for (let i = 1; i < closes.length; i++) {
const ch = closes[i] - closes[i - 1];
const g = Math.max(ch, 0);
const l = Math.max(-ch, 0);
if (i <= period) {
avgGain += g;
avgLoss += l;
if (i === period) {
avgGain /= period;
avgLoss /= period;
out[i] = avgLoss === 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss);
}
} else {
avgGain = (avgGain * (period - 1) + g) / period;
avgLoss = (avgLoss * (period - 1) + l) / period;
out[i] = avgLoss === 0 ? 100 : 100 - 100 / (1 + avgGain / avgLoss);
}
}
return out;
}
function calcMACD(closes, fast, slow, sigPeriod) {
fast = fast || 12;
slow = slow || 26;
sigPeriod = sigPeriod || 9;
const emaFast = calcEMA(closes, fast);
const emaSlow = calcEMA(closes, slow);
const macdLine = new Array(closes.length).fill(null);
for (let i = 0; i < closes.length; i++) {
if (emaFast[i] !== null && emaSlow[i] !== null) {
macdLine[i] = emaFast[i] - emaSlow[i];
}
}
const signalLine = new Array(closes.length).fill(null);
let prev = null, count = 0, sum = 0;
const k = 2 / (sigPeriod + 1);
for (let i = 0; i < closes.length; i++) {
if (macdLine[i] === null) continue;
count++;
if (count < sigPeriod) {
sum += macdLine[i];
} else if (count === sigPeriod) {
sum += macdLine[i];
prev = sum / sigPeriod;
signalLine[i] = prev;
} else {
prev = macdLine[i] * k + prev * (1 - k);
signalLine[i] = prev;
}
}
const hist = new Array(closes.length).fill(null);
for (let i = 0; i < closes.length; i++) {
if (macdLine[i] !== null && signalLine[i] !== null) {
hist[i] = macdLine[i] - signalLine[i];
}
}
return { macd: macdLine, signal: signalLine, hist };
}
// Menghasilkan seri indikator sesuai pilihan dropdown
function getIndicatorSeries(sel, closes, data) {
// === Dukung MA/EMA/WMA/Wilders dengan periode 5,10,20,50,100,200 ===
const m = /^(ma|ema|wma|wilders)(\d+)$/.exec(sel);
if (m) {
const type = m[1];
const period = parseInt(m[2], 10);
let values;
if (type === 'ma') values = calcSMA(closes, period);
else if (type === 'ema') values = calcEMA(closes, period);
else if (type === 'wma') values = calcWMA(closes, period);
else values = calcWilders(closes, period);
return { type: 'line', lines: [{ values: values }] };
}
switch (sel) {
case 'bollinger': {
const bb = calcBollinger(closes, 20, 2);
return {
type: 'line',
lines: [
{ values: bb.upper },
{ values: bb.middle },
{ values: bb.lower }
]
};
}
case 'squeeze':
return { type: 'squeeze', values: calcSqueeze(data) };
default:
return null;
}
}
/* ==================== UKURAN CANVAS ==================== */
function resizeCanvas() {
const parent = canvas.parentElement;
if (!parent) return;
const rect = parent.getBoundingClientRect();
const w = Math.round(rect.width);
const h = Math.round(rect.height);
if (w <= 0 || h <= 0) return;
dpr = window.devicePixelRatio || 1;
const pw = Math.round(w * dpr);
const ph = Math.round(h * dpr);
if (canvas.width !== pw || canvas.height !== ph) {
canvas.width = pw;
canvas.height = ph;
}
viewW = w;
viewH = h;
drawChart();
}
function resizeSubCanvas() {
const parent = subCanvas.parentElement;
if (!parent) return;
const rect = parent.getBoundingClientRect();
const w = Math.round(rect.width);
const h = Math.round(rect.height);
if (w <= 0 || h <= 0) return;
const _dpr = window.devicePixelRatio || 1;
const pw = Math.round(w * _dpr);
const ph = Math.round(h * _dpr);
if (subCanvas.width !== pw || subCanvas.height !== ph) {
subCanvas.width = pw;
subCanvas.height = ph;
}
subViewW = w;
subViewH = h;
drawSubChart();
}
/* ==================== RENDER GRAFIK UTAMA ==================== */
function drawChart() {
if (!viewW || !viewH) return;
const w = viewW;
const h = viewH;
ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
ctx.clearRect(0, 0, w, h);
const start = Math.max(0, currentIndex - VISIBLE_BARS + 1);
const displayData = fullData.slice(start, currentIndex + 1);
if (displayData.length === 0) return;
// --- Hitung indikator terpilih ---
const closes = fullData.map(d => d.close);
const indicators = [];
const selVals = [ind1El.value, ind2El.value, ind3El.value];
for (let s = 0; s < 3; s++) {
if (!selVals[s]) continue;
const series = getIndicatorSeries(selVals[s], closes, fullData);
if (series) indicators.push({ sel: selVals[s], color: SLOT_COLORS[s], series });
}
// --- Rentang Y (termasuk indikator) ---
let highest = -Infinity;
let lowest = Infinity;
for (let i = 0; i < displayData.length; i++) {
if (displayData[i].high > highest) highest = displayData[i].high;
if (displayData[i].low < lowest) lowest = displayData[i].low;
}
for (let k = 0; k < indicators.length; k++) {
const ind = indicators[k];
if (!ind.series || ind.series.type !== 'line') continue;
for (let li = 0; li < ind.series.lines.length; li++) {
const values = ind.series.lines[li].values;
for (let i = start; i <= currentIndex; i++) {
const v = values[i];
if (v === null || v === undefined) continue;
if (v > highest) highest = v;
if (v < lowest) lowest = v;
}
}
}
if (!isFinite(highest) || !isFinite(lowest)) return;
const padding = (highest - lowest) * 0.15 || 10;
highest += padding;
lowest -= padding;
const range = (highest - lowest) || 1;
const candleWidth = w / VISIBLE_BARS;
/* ---------- Grid horizontal + label harga ---------- */
ctx.lineWidth = 1;
ctx.font = '10px Arial';
ctx.textAlign = 'right';
ctx.textBaseline = 'middle';
for (let g = 1; g < 4; g++) {
const yGrid = (h / 4) * g;
ctx.strokeStyle = '#23282d';
ctx.beginPath();
ctx.moveTo(0, yGrid);
ctx.lineTo(w, yGrid);
ctx.stroke();
ctx.fillStyle = '#848e9c';
const priceLabel = highest - (range / 4) * g;
ctx.fillText(formatUnit(priceLabel), w - 6, yGrid - 9);
}
/* ---------- Candlestick ---------- */
const bodyW = Math.max(candleWidth * 0.7, 1);
const wickW = Math.max(1, Math.min(2, candleWidth * 0.12));
for (let i = 0; i < displayData.length; i++) {
const candle = displayData[i];
const x = i * candleWidth + (candleWidth - bodyW) / 2;
const xc = x + bodyW / 2;
const yOpen = h - ((candle.open - lowest) / range) * h;
const yClose = h - ((candle.close - lowest) / range) * h;
const yHigh = h - ((candle.high - lowest) / range) * h;
const yLow = h - ((candle.low - lowest) / range) * h;
const isBullish = candle.close >= candle.open;
const color = isBullish ? '#0ecb81' : '#f6465d';
ctx.strokeStyle = color;
ctx.fillStyle = color;
ctx.lineWidth = wickW;
ctx.beginPath();
ctx.moveTo(xc, yHigh);
ctx.lineTo(xc, yLow);
ctx.stroke();
const bodyTop = Math.min(yOpen, yClose);
const bodyH = Math.max(Math.abs(yClose - yOpen), 1.5);
ctx.fillRect(x, bodyTop, bodyW, bodyH);
}
/* ---------- Garis indikator ---------- */
for (let k = 0; k < indicators.length; k++) {
const ind = indicators[k];
if (!ind.series || ind.series.type !== 'line') continue;
const lines = ind.series.lines;
for (let li = 0; li < lines.length; li++) {
const values = lines[li].values;
const isMid = (lines.length === 3 && li === 1);
ctx.strokeStyle = ind.color;
ctx.lineWidth = isMid ? 1.6 : 1.1;
ctx.setLineDash(!isMid && lines.length === 3 ? [4, 3] : []);
ctx.beginPath();
let started = false;
for (let i = 0; i < displayData.length; i++) {
const gi = start + i;
const v = values[gi];
if (v === null || v === undefined) { started = false; continue; }
const x = i * candleWidth + candleWidth / 2;
const y = h - ((v - lowest) / range) * h;
if (!started) { ctx.moveTo(x, y); started = true; }
else ctx.lineTo(x, y);
}
ctx.stroke();
ctx.setLineDash([]);
}
}
/* ---------- Squeeze dots (di bagian bawah) ---------- */
for (let k = 0; k < indicators.length; k++) {
const ind = indicators[k];
if (!ind.series || ind.series.type !== 'squeeze') continue;
const values = ind.series.values;
const dotY = h - 8;
const dotR = Math.max(2, candleWidth * 0.14);
ctx.fillStyle = ind.color;
for (let i = 0; i < displayData.length; i++) {
const gi = start + i;
if (values[gi] !== 1) continue;
const x = i * candleWidth + candleWidth / 2;
ctx.beginPath();
ctx.arc(x, dotY, dotR, 0, Math.PI * 2);
ctx.fill();
}
}
/* ---------- Garis harga terakhir ---------- */
const lastCandle = displayData[displayData.length - 1];
const yLast = h - ((lastCandle.close - lowest) / range) * h;
ctx.save();
ctx.setLineDash([4, 4]);
ctx.strokeStyle = 'rgba(240, 185, 11, 0.55)';
ctx.lineWidth = 1;
ctx.beginPath();
ctx.moveTo(0, yLast);
ctx.lineTo(w, yLast);
ctx.stroke();
ctx.restore();
}
/* ==================== RENDER GRAFIK BAWAH (RSI / MACD) ==================== */
function drawSubChart() {
if (!subViewW || !subViewH) return;
const w = subViewW;
const h = subViewH;
sctx.setTransform(dpr, 0, 0, dpr, 0, 0);
sctx.clearRect(0, 0, w, h);
sctx.fillStyle = '#0b0e11';
sctx.fillRect(0, 0, w, h);
const type = subSelectEl.value;
const start = Math.max(0, currentIndex - VISIBLE_BARS + 1);
const count = currentIndex - start + 1;
if (count <= 0) return;
const closes = fullData.map(d => d.close);
const candleWidth = w / VISIBLE_BARS;
// Grid horizontal
sctx.strokeStyle = '#23282d';
sctx.lineWidth = 1;
for (let g = 1; g < 3; g++) {
const yGrid = (h / 3) * g;
sctx.beginPath();
sctx.moveTo(0, yGrid);
sctx.lineTo(w, yGrid);
sctx.stroke();
}
if (type === 'rsi') {
/* ---------- RSI(14) ---------- */
const rsiVals = calcRSI(closes, 14);
const toY = (v) => h - (v / 100) * h;
// Garis referensi 30 & 70
sctx.strokeStyle = 'rgba(132,142,156,0.35)';
sctx.setLineDash([4, 4]);
[30, 70].forEach(lvl => {
const y = toY(lvl);
sctx.beginPath();
sctx.moveTo(0, y);
sctx.lineTo(w, y);
sctx.stroke();
});
sctx.setLineDash([]);
// Label
sctx.fillStyle = '#848e9c';
sctx.font = '9px Arial';
sctx.textAlign = 'left';
sctx.textBaseline = 'middle';
sctx.fillText('70', 4, toY(70));
sctx.fillText('30', 4, toY(30));
sctx.textBaseline = 'top';
sctx.fillText('RSI(14)', 4, 4);
// Garis RSI
sctx.strokeStyle = '#f0b90b';
sctx.lineWidth = 1.5;
sctx.beginPath();
let started = false;
for (let i = 0; i < count; i++) {
const gi = start + i;
const v = rsiVals[gi];
if (v === null || v === undefined) { started = false; continue; }
const x = i * candleWidth + candleWidth / 2;
const y = toY(v);
if (!started) { sctx.moveTo(x, y); started = true; }
else sctx.lineTo(x, y);
}
sctx.stroke();
} else if (type === 'macd') {
/* ---------- MACD(12,26,9) + Signal ---------- */
const m = calcMACD(closes, 12, 26, 9);
// Rentang Y
let hi = 0, lo = 0;
for (let i = 0; i < count; i++) {
const gi = start + i;
const vals = [m.macd[gi], m.signal[gi], m.hist[gi]];
for (let k = 0; k < vals.length; k++) {
const v = vals[k];
if (v === null || v === undefined) continue;
if (v > hi) hi = v;
if (v < lo) lo = v;
}
}
if (hi === lo) { hi = 1; lo = -1; }
const pad = (hi - lo) * 0.1;
hi += pad; lo -= pad;
const rng = (hi - lo) || 1;
const toY = (v) => h - ((v - lo) / rng) * h;
// Garis nol
sctx.strokeStyle = 'rgba(132,142,156,0.4)';
sctx.setLineDash([4, 4]);
sctx.beginPath();
sctx.moveTo(0, toY(0));
sctx.lineTo(w, toY(0));
sctx.stroke();
sctx.setLineDash([]);
// Label
sctx.fillStyle = '#848e9c';
sctx.font = '9px Arial';
sctx.textAlign = 'left';
sctx.textBaseline = 'top';
sctx.fillText('MACD(12,26,9)', 4, 4);
// Histogram
for (let i = 0; i < count; i++) {
const gi = start + i;
const v = m.hist[gi];
if (v === null || v === undefined) continue;
const x = i * candleWidth + candleWidth * 0.15;
const bw = Math.max(candleWidth * 0.7, 1);
const y0 = toY(0);
const yv = toY(v);
sctx.fillStyle = v >= 0 ? 'rgba(14,203,129,0.55)' : 'rgba(246,70,93,0.55)';
sctx.fillRect(x, Math.min(y0, yv), bw, Math.max(Math.abs(yv - y0), 1));
}
// Garis MACD
sctx.strokeStyle = '#4fc3f7';
sctx.lineWidth = 1.5;
sctx.beginPath();
let started = false;
for (let i = 0; i < count; i++) {
const gi = start + i;
const v = m.macd[gi];
if (v === null || v === undefined) { started = false; continue; }
const x = i * candleWidth + candleWidth / 2;
const y = toY(v);
if (!started) { sctx.moveTo(x, y); started = true; }
else sctx.lineTo(x, y);
}
sctx.stroke();
// Garis Signal
sctx.strokeStyle = '#e91e63';
sctx.lineWidth = 1.5;
sctx.beginPath();
started = false;
for (let i = 0; i < count; i++) {
const gi = start + i;
const v = m.signal[gi];
if (v === null || v === undefined) { started = false; continue; }
const x = i * candleWidth + candleWidth / 2;
const y = toY(v);
if (!started) { sctx.moveTo(x, y); started = true; }
else sctx.lineTo(x, y);
}
sctx.stroke();
}
}
/* ==================== UPDATE UI ==================== */
function updateUI() {
const bar = fullData[currentIndex];
const currentPrice = bar ? bar.close : 0;
const assetValue = positionVolume * currentPrice;
const totalEquity = cash + assetValue;
const totalPnL = ((totalEquity - INITIAL_CASH) / INITIAL_CASH) * 100;
equityValEl.textContent = formatUnit(totalEquity);
cashValEl.textContent = formatUnit(cash);
assetValEl.textContent = formatUnit(assetValue);
tickerPriceEl.textContent = formatUnit(currentPrice);
const progress = Math.min(Math.max(currentIndex - WARMUP_BARS, 0), TOTAL_BARS);
barProgressEl.textContent = progress + '/' + TOTAL_BARS;
pnlPctEl.textContent = (totalPnL >= 0 ? '+' : '') + totalPnL.toFixed(2) + '%';
if (totalPnL > 0) {
pnlPctEl.style.backgroundColor = 'rgba(14, 203, 129, 0.2)';
pnlPctEl.style.color = '#0ecb81';
} else if (totalPnL < 0) {
pnlPctEl.style.backgroundColor = 'rgba(246, 70, 93, 0.2)';
pnlPctEl.style.color = '#f6465d';
} else {
pnlPctEl.style.backgroundColor = 'rgba(255,255,255,0.1)';
pnlPctEl.style.color = '#eaecef';
}
posInfoEl.textContent =
'Posisi saat ini: ' + formatUnit(positionVolume) +
' Unit (Rata-rata: ' + formatUnit(avgBuyPrice) + ')';
}
/* ==================== AKSI TRADING ==================== */
function doBuy() {
const bar = fullData[currentIndex];
if (!bar || finished || isPaused) return;
const currentPrice = bar.close;
const maxBuyable = cash / (currentPrice * (1 + feeBeli));
const buyVolume = Math.floor(maxBuyable);
if (buyVolume <= 0) return;
const cost = buyVolume * currentPrice;
const fee = cost * feeBeli;
cash -= (cost + fee);
const totalCostOld = positionVolume * avgBuyPrice;
const totalCostNew = buyVolume * currentPrice;
positionVolume += buyVolume;
avgBuyPrice = (totalCostOld + totalCostNew) / positionVolume;
updateUI();
}
function doSell() {
const bar = fullData[currentIndex];
if (!bar || finished || isPaused) return;
if (positionVolume <= 0) return;
const currentPrice = bar.close;
const revenue = positionVolume * currentPrice;
const fee = revenue * feeJual;
cash += (revenue - fee);
positionVolume = 0;
avgBuyPrice = 0;
updateUI();
}
/* ==================== LOOP SIMULASI ==================== */
function step() {
if (isPaused || finished) return;
currentIndex++;
if (currentIndex >= END_INDEX) {
currentIndex = END_INDEX;
finished = true;
clearInterval(timer);
timer = null;
updateUI();
drawChart();
drawSubChart();
btnBuy.disabled = true;
btnSell.disabled = true;
posInfoEl.textContent = '✅ Simulasi selesai! Tekan Restart untuk mencoba lagi.';
return;
}
updateUI();
drawChart();
drawSubChart();
}
function startSimulation() {
clearInterval(timer);
timer = null;
fullData = generateSyntheticData(END_INDEX + 10);
cash = INITIAL_CASH;
positionVolume = 0;
avgBuyPrice = 0;
currentIndex = WARMUP_BARS;
isPaused = false;
finished = false;
btnPause.textContent = '⏸ Pause';
btnBuy.disabled = false;
btnSell.disabled = false;
resizeCanvas();
resizeSubCanvas();
updateUI();
drawChart();
drawSubChart();
timer = setInterval(step, INTERVAL_TIME);
}
/* ==================== EVENT LISTENER ==================== */
btnPause.addEventListener('click', function () {
if (finished) return;
isPaused = !isPaused;
btnPause.textContent = isPaused ? '▶️ Resume' : '⏸ Pause';
});
btnRestart.addEventListener('click', startSimulation);
btnBuy.addEventListener('click', doBuy);
btnSell.addEventListener('click', doSell);
// Dropdown indikator → redraw grafik utama
ind1El.addEventListener('change', drawChart);
ind2El.addEventListener('change', drawChart);
ind3El.addEventListener('change', drawChart);
// Dropdown sub-chart → redraw grafik bawah
subSelectEl.addEventListener('change', drawSubChart);
// === input fee ===
function updateFees() {
let buyVal = parseFloat(feeBuyInput.value);
let sellVal = parseFloat(feeSellInput.value);
if (isNaN(buyVal) || buyVal < 0) buyVal = 0;
if (isNaN(sellVal) || sellVal < 0) sellVal = 0;
if (buyVal > 10) buyVal = 10;
if (sellVal > 10) sellVal = 10;
feeBeli = buyVal / 100;
feeJual = sellVal / 100;
}
feeBuyInput.addEventListener('input', updateFees);
feeSellInput.addEventListener('input', updateFees);
// Resize
window.addEventListener('resize', function () {
resizeCanvas();
resizeSubCanvas();
});
window.addEventListener('orientationchange', function () {
setTimeout(function () {
resizeCanvas();
resizeSubCanvas();
}, 150);
});
if (typeof ResizeObserver !== 'undefined') {
new ResizeObserver(resizeCanvas).observe(canvas.parentElement);
new ResizeObserver(resizeSubCanvas).observe(subCanvas.parentElement);
}
/* ==================== INISIALISASI ==================== */
function init() {
updateFees(); // sinkronkan fee dari input default
startSimulation();
requestAnimationFrame(function () {
resizeCanvas();
resizeSubCanvas();
});
setTimeout(function () {
resizeCanvas();
resizeSubCanvas();
}, 150);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
</script>
</body>
</html> |