Spaces:
Running
Running
Download sim_free_V05.html from IndividualGamer/simV1: direct link, hf CLI and curl.
- Browser
- Download file 68.2 kB
-
https://huggingface.co/spaces/IndividualGamer/simV1/resolve/main/sim_free_V05.html
- Command line
-
hf download hf://spaces/IndividualGamer/simV1/sim_free_V05.html
-
curl -L -o sim_free_V05.html https://huggingface.co/spaces/IndividualGamer/simV1/resolve/main/sim_free_V05.html
68.2 kB
<!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;
}
.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;
}
.indicator-bar {
display: flex;
gap: 6px;
padding: 6px 8px;
background: #12161a;
border-bottom: 1px solid #2b3139;
position: relative;
z-index: 50;
}
.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);
}
.ind-wrap {
flex: 1 1 0;
min-width: 0;
display: flex;
}
.ind-select.ind-native-hidden {
display: none !important;
}
.ind-trigger {
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;
text-align: left;
cursor: pointer;
outline: none;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
-webkit-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;
user-select: none;
-webkit-user-select: none;
}
.ind-trigger:focus {
border-color: var(--accent);
}
.ind-panel {
position: absolute;
top: 100%;
left: 8px;
width: 220px;
z-index: 200;
background: #1e2329;
border: 1px solid #3a4048;
border-radius: 6px;
box-shadow: 0 10px 24px rgba(0, 0, 0, 0.65);
padding: 8px;
display: flex;
flex-direction: column;
gap: 6px;
max-height: 340px;
overflow: hidden;
}
.ind-panel[hidden] {
display: none;
}
.ind-search {
flex: 0 0 auto;
width: 100%;
background-color: #2b3139;
color: var(--text-main);
border: 1px solid #3a4048;
border-radius: 4px;
padding: 8px 10px;
font-size: 13px;
font-family: inherit;
outline: none;
}
.ind-search:focus {
border-color: var(--accent);
}
.ind-list {
flex: 1 1 auto;
min-height: 0;
overflow-y: auto;
display: flex;
flex-direction: column;
gap: 2px;
-webkit-overflow-scrolling: touch;
}
.ind-opt {
flex: 0 0 auto;
padding: 8px 10px;
font-size: 13px;
line-height: 1.45;
border-radius: 4px;
cursor: pointer;
color: var(--text-main);
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.ind-opt:hover,
.ind-opt.highlight {
background-color: #2b3139;
}
.ind-opt.selected {
color: var(--accent);
font-weight: 700;
}
.ind-opt.disabled {
color: #5b636e;
font-style: italic;
cursor: default;
pointer-events: none;
}
.ind-empty {
flex: 0 0 auto;
padding: 10px;
font-size: 13px;
color: var(--text-muted);
text-align: center;
}
.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);
}
.brand-bar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 6px 12px;
background: rgba(18, 22, 26, 0.92);
border-bottom: 1px solid #2b3139;
border-top: 1px solid #2b3139;
backdrop-filter: blur(4px);
-webkit-backdrop-filter: blur(4px);
gap: 8px;
}
.brand-link {
display: inline-flex;
align-items: center;
gap: 6px;
font-size: 12px;
font-weight: 700;
letter-spacing: 0.3px;
color: var(--accent);
text-decoration: none;
padding: 3px 8px;
border-radius: 4px;
transition: background-color 0.2s, color 0.2s;
flex-shrink: 0;
}
.brand-link:hover,
.brand-link:active {
background-color: var(--accent);
color: #000;
}
.brand-link .x-logo {
display: inline-block;
width: 13px;
height: 13px;
flex-shrink: 0;
}
.datasource-group {
display: flex;
gap: 0;
background: #2b3139;
border-radius: 5px;
padding: 2px;
flex-shrink: 0;
}
.ds-btn {
background: transparent;
color: var(--text-muted);
border: none;
padding: 4px 9px;
font-size: 11px;
font-weight: 700;
border-radius: 4px;
cursor: pointer;
font-family: inherit;
letter-spacing: 0.3px;
transition: background-color 0.15s, color 0.15s;
user-select: none;
-webkit-user-select: none;
}
.ds-btn:hover:not(.active) {
color: var(--text-main);
background: rgba(255, 255, 255, 0.06);
}
.ds-btn.active {
background: var(--accent);
color: #000;
}
.chart-container {
flex: 1.8 1 0;
position: relative;
background-color: var(--bg-main);
width: 100%;
min-height: 100px;
overflow: hidden;
}
.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>
<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>
<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="brand-bar">
<a class="brand-link" href="https://x.com/sahamharian" target="_blank" rel="noopener noreferrer">
<svg class="x-logo" viewBox="0 0 24 24" fill="currentColor" xmlns="http://www.w3.org/2000/svg">
<path d="M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z"/>
</svg>
<span>@sahamharian</span>
</a>
<div class="datasource-group" role="group" aria-label="Sumber data">
<button type="button" class="ds-btn active" data-source="synthetic" title="Data sintetis (dibuat acak)">Sintetis</button>
<button type="button" class="ds-btn" data-source="upload" title="Upload file CSV berisi OHLC">Upload</button>
</div>
<input type="file" id="csv-input" accept=".csv,.txt,.tsv" hidden>
</div>
<div class="chart-container" id="chart-parent">
<canvas id="tradingChart"></canvas>
</div>
<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;
const VISIBLE_BARS = 30;
const INTERVAL_TIME = 1000;
const START_PRICE_MIN = 100;
const START_PRICE_MAX = 5000;
const DEFAULT_TOTAL_BARS = 250;
let TOTAL_BARS = DEFAULT_TOTAL_BARS;
let END_INDEX = WARMUP_BARS + TOTAL_BARS;
let feeBeli = 0.003;
let feeJual = 0.003;
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;
let dataSource = 'synthetic';
let uploadedData = null;
/* ==================== 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');
const dsBtns = document.querySelectorAll('.ds-btn');
const csvInput = document.getElementById('csv-input');
/* ==================== 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');
}
/* ==================== PARSER CSV ==================== */
function toNum(str) {
if (str === null || str === undefined) return NaN;
let s = String(str).trim();
if (!s || s === '-' || s === 'null' || s === 'N/A' || s === 'n/a') return NaN;
s = s.replace(/[^\d.\-]/g, '');
if (!s || s === '-' || s === '.') return NaN;
return parseFloat(s);
}
function parseCSV(text) {
text = text.replace(/^\uFEFF/, '');
const lines = text.split(/\r?\n/).map(l => l.trim()).filter(l => l.length > 0);
if (lines.length < 2) throw new Error('File kosong atau terlalu pendek.');
const candidates = [',', ';', '\t'];
let sep = ',';
let maxCols = 0;
for (let i = 0; i < candidates.length; i++) {
const n = lines[0].split(candidates[i]).length;
if (n > maxCols) { maxCols = n; sep = candidates[i]; }
}
const firstCells = lines[0].split(sep).map(c => c.trim().toLowerCase().replace(/["']/g, ''));
const hasHeader = firstCells.some(c =>
/open|high|low|close|date|time|volume|adj/.test(c)
);
let colMap = null;
if (hasHeader) {
const findCol = (patterns) => {
for (let i = 0; i < firstCells.length; i++) {
for (let p = 0; p < patterns.length; p++) {
if (firstCells[i].indexOf(patterns[p]) !== -1) return i;
}
}
return -1;
};
const o = findCol(['open']);
const h = findCol(['high']);
const l = findCol(['low']);
const c = findCol(['close', 'last', 'price']);
if (o !== -1 && h !== -1 && l !== -1 && c !== -1) {
colMap = { open: o, high: h, low: l, close: c };
}
}
const startRow = hasHeader ? 1 : 0;
const data = [];
for (let r = startRow; r < lines.length; r++) {
const cells = lines[r].split(sep).map(c => c.trim().replace(/["']/g, ''));
if (cells.length < 4) continue;
let o, h, l, c;
if (colMap) {
o = toNum(cells[colMap.open]);
h = toNum(cells[colMap.high]);
l = toNum(cells[colMap.low]);
c = toNum(cells[colMap.close]);
} else {
const nums = [];
for (let k = 0; k < cells.length; k++) {
const v = toNum(cells[k]);
if (isFinite(v)) nums.push(v);
if (nums.length >= 4) break;
}
if (nums.length < 4) continue;
o = nums[0]; h = nums[1]; l = nums[2]; c = nums[3];
}
if (!isFinite(o) || !isFinite(h) || !isFinite(l) || !isFinite(c)) continue;
if (o <= 0 || h <= 0 || l <= 0 || c <= 0) continue;
const realHigh = Math.max(o, h, l, c);
const realLow = Math.min(o, h, l, c);
data.push({
open: bulatkanFraksi(o, false),
high: bulatkanFraksi(realHigh, false),
low: bulatkanFraksi(realLow, true),
close: bulatkanFraksi(c, false)
});
}
return data;
}
/* ==================== SUMBER DATA ==================== */
function setDataSource(src) {
dataSource = src;
for (let i = 0; i < dsBtns.length; i++) {
const b = dsBtns[i];
b.classList.toggle('active', b.getAttribute('data-source') === src);
}
}
dsBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
const src = btn.getAttribute('data-source');
if (src === 'upload') {
csvInput.click();
} else {
if (dataSource !== 'synthetic') {
setDataSource('synthetic');
startSimulation();
}
}
});
});
csvInput.addEventListener('change', function (e) {
const file = e.target.files && e.target.files[0];
csvInput.value = '';
if (!file) return;
const reader = new FileReader();
reader.onload = function (ev) {
try {
const parsed = parseCSV(ev.target.result);
const minBars = WARMUP_BARS + 20;
if (parsed.length < minBars) {
alert(
'File harus berisi minimal ' + minBars + ' baris data OHLC yang valid.\n' +
'Ditemukan: ' + parsed.length + ' baris.\n\n' +
'Format yang didukung:\n' +
'• open,high,low,close\n' +
'• date,open,high,low,close\n' +
'• Date,Open,High,Low,Close,Volume (dengan header)'
);
return;
}
uploadedData = parsed;
setDataSource('upload');
startSimulation();
} catch (err) {
alert('Gagal memproses file: ' + err.message);
}
};
reader.onerror = function () {
alert('Gagal membaca file.');
};
reader.readAsText(file);
});
/* ==================== DROPDOWN BISA DICARI ==================== */
const dropdownRegistry = [];
function normalizeSearch(str) {
return String(str).toLowerCase().replace(/[^a-z0-9]/g, '');
}
function closeAllDropdowns(except) {
for (let i = 0; i < dropdownRegistry.length; i++) {
const d = dropdownRegistry[i];
if (d !== except && d.isOpen()) d.close();
}
}
function createSearchableSelect(selectEl, barEl) {
const wrap = document.createElement('div');
wrap.className = 'ind-wrap';
selectEl.parentNode.insertBefore(wrap, selectEl);
wrap.appendChild(selectEl);
selectEl.classList.add('ind-native-hidden');
selectEl.setAttribute('aria-hidden', 'true');
selectEl.setAttribute('tabindex', '-1');
const trigger = document.createElement('button');
trigger.type = 'button';
trigger.className = 'ind-trigger';
trigger.setAttribute('aria-haspopup', 'listbox');
trigger.setAttribute('aria-expanded', 'false');
wrap.appendChild(trigger);
const panel = document.createElement('div');
panel.className = 'ind-panel';
panel.hidden = true;
const searchEl = document.createElement('input');
searchEl.type = 'text';
searchEl.className = 'ind-search';
searchEl.placeholder = 'Ketik untuk mencari...';
searchEl.autocomplete = 'off';
searchEl.spellcheck = false;
searchEl.setAttribute('aria-label', 'Cari indikator');
const listEl = document.createElement('div');
listEl.className = 'ind-list';
listEl.setAttribute('role', 'listbox');
panel.appendChild(searchEl);
panel.appendChild(listEl);
barEl.appendChild(panel);
let visibleOpts = [];
let highlightIdx = -1;
let isOpen = false;
let lastToggleTime = 0;
const instance = {
trigger: trigger,
panel: panel,
isOpen: function () { return isOpen; },
close: closePanel,
contains: function (node) {
if (!node) return false;
return wrap.contains(node) || panel.contains(node);
}
};
dropdownRegistry.push(instance);
function updateTriggerLabel() {
const opt = selectEl.options[selectEl.selectedIndex];
const label = opt ? opt.textContent : '';
trigger.textContent = label;
trigger.title = label;
}
function setHighlight(idx) {
if (highlightIdx >= 0 && visibleOpts[highlightIdx]) {
visibleOpts[highlightIdx].el.classList.remove('highlight');
}
highlightIdx = idx;
if (idx >= 0 && visibleOpts[idx]) {
const el = visibleOpts[idx].el;
el.classList.add('highlight');
if (el.scrollIntoView) {
el.scrollIntoView({ block: 'nearest' });
}
}
}
function moveHighlight(dir) {
if (visibleOpts.length === 0) return;
let i = highlightIdx;
for (let step = 0; step < visibleOpts.length; step++) {
i += dir;
if (i < 0) i = visibleOpts.length - 1;
if (i >= visibleOpts.length) i = 0;
if (!visibleOpts[i].disabled) {
setHighlight(i);
return;
}
}
}
function choose(value) {
selectEl.value = value;
updateTriggerLabel();
closePanel();
try { trigger.focus({ preventScroll: true }); } catch (err) {}
selectEl.dispatchEvent(new Event('change', { bubbles: true }));
}
function buildList(filter) {
const nf = normalizeSearch(filter);
listEl.innerHTML = '';
visibleOpts = [];
highlightIdx = -1;
const opts = selectEl.options;
for (let i = 0; i < opts.length; i++) {
const opt = opts[i];
const label = opt.textContent;
if (nf && normalizeSearch(label).indexOf(nf) === -1) continue;
const item = document.createElement('div');
item.className = 'ind-opt';
item.textContent = label;
item.setAttribute('role', 'option');
const entry = {
value: opt.value,
label: label,
disabled: !!opt.disabled,
el: item
};
visibleOpts.push(entry);
listEl.appendChild(item);
if (opt.disabled) {
item.classList.add('disabled');
item.setAttribute('aria-disabled', 'true');
} else {
if (opt.value === selectEl.value) item.classList.add('selected');
item.addEventListener('click', function () {
choose(entry.value);
});
item.addEventListener('mouseenter', function () {
setHighlight(visibleOpts.indexOf(entry));
});
}
}
if (visibleOpts.length === 0) {
const empty = document.createElement('div');
empty.className = 'ind-empty';
empty.textContent = 'Tidak ditemukan';
listEl.appendChild(empty);
return;
}
let idx = -1;
for (let i = 0; i < visibleOpts.length; i++) {
if (!visibleOpts[i].disabled && visibleOpts[i].value === selectEl.value) {
idx = i;
break;
}
}
if (idx === -1) {
for (let i = 0; i < visibleOpts.length; i++) {
if (!visibleOpts[i].disabled) { idx = i; break; }
}
}
setHighlight(idx);
}
function positionPanel() {
const PANEL_W = 220;
const barRect = barEl.getBoundingClientRect();
const wrapRect = wrap.getBoundingClientRect();
const barW = barEl.clientWidth || barRect.width;
let left = wrapRect.left - barRect.left;
const maxLeft = Math.max(8, barW - PANEL_W - 8);
if (left > maxLeft) left = maxLeft;
if (left < 8) left = 8;
panel.style.left = left + 'px';
panel.style.width = PANEL_W + 'px';
}
function openPanel(initialChar) {
closeAllDropdowns(instance);
panel.hidden = false;
isOpen = true;
trigger.setAttribute('aria-expanded', 'true');
searchEl.value = initialChar || '';
buildList(searchEl.value);
positionPanel();
// Fokus tanpa memicu scroll halaman (mencegah layout shift di mobile)
try { searchEl.focus({ preventScroll: true }); } catch (err) {
try { searchEl.focus(); } catch (err2) {}
}
if (searchEl.setSelectionRange) {
const len = searchEl.value.length;
try { searchEl.setSelectionRange(len, len); } catch (err) {}
}
}
function closePanel() {
if (!isOpen) return;
panel.hidden = true;
isOpen = false;
trigger.setAttribute('aria-expanded', 'false');
}
/* --- Tombol pemicu: debounce untuk mencegah double-fire di mobile --- */
function togglePanel() {
const now = Date.now();
if (now - lastToggleTime < 300) return;
lastToggleTime = now;
if (isOpen) closePanel();
else openPanel('');
}
trigger.addEventListener('click', function (e) {
e.stopPropagation();
e.preventDefault();
togglePanel();
});
// Untuk browser mobile yang mungkin tidak mengirim 'click' dengan andal
trigger.addEventListener('touchend', function (e) {
e.stopPropagation();
e.preventDefault();
togglePanel();
}, { passive: false });
trigger.addEventListener('keydown', function (e) {
if (e.key === 'ArrowDown' || e.key === 'ArrowUp' ||
e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
if (!isOpen) openPanel('');
return;
}
if (e.key === 'Escape') {
if (isOpen) { e.preventDefault(); closePanel(); }
return;
}
if (e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey) {
e.preventDefault();
openPanel(e.key);
}
});
searchEl.addEventListener('input', function () {
buildList(searchEl.value);
});
searchEl.addEventListener('keydown', function (e) {
if (e.key === 'ArrowDown') {
e.preventDefault();
moveHighlight(1);
} else if (e.key === 'ArrowUp') {
e.preventDefault();
moveHighlight(-1);
} else if (e.key === 'Enter') {
e.preventDefault();
if (highlightIdx >= 0 && visibleOpts[highlightIdx] &&
!visibleOpts[highlightIdx].disabled) {
choose(visibleOpts[highlightIdx].value);
}
} else if (e.key === 'Escape') {
e.preventDefault();
closePanel();
try { trigger.focus({ preventScroll: true }); } catch (err) {}
} else if (e.key === 'Tab') {
closePanel();
}
});
updateTriggerLabel();
return instance;
}
function setupSearchableSelects() {
const barEl = document.querySelector('.indicator-bar');
if (!barEl) return;
const selects = barEl.querySelectorAll('select.ind-select');
for (let i = 0; i < selects.length; i++) {
createSearchableSelect(selects[i], barEl);
}
}
document.addEventListener('click', function (e) {
for (let i = 0; i < dropdownRegistry.length; i++) {
const d = dropdownRegistry[i];
if (d.isOpen() && !d.contains(e.target)) d.close();
}
});
/* ==========================================================
PENTING: Hanya tutup dropdown saat terjadi perubahan lebar
viewport yang signifikan (indikasi rotasi layar).
Jangan tutup saat keyboard virtual membuka, karena keyboard
hanya mengubah TINGGI viewport.
========================================================== */
let lastViewportWidth = window.innerWidth;
window.addEventListener('resize', function () {
const newWidth = window.innerWidth;
if (Math.abs(newWidth - lastViewportWidth) > 100) {
closeAllDropdowns(null);
lastViewportWidth = newWidth;
}
resizeCanvas();
resizeSubCanvas();
});
window.addEventListener('orientationchange', function () {
setTimeout(function () {
closeAllDropdowns(null);
lastViewportWidth = window.innerWidth;
resizeCanvas();
resizeSubCanvas();
}, 200);
});
/* ==================== GENERATOR DATA SINTETIS ==================== */
function generateSyntheticData(totalBars) {
const data = [];
const rawStart = START_PRICE_MIN + Math.random() * (START_PRICE_MAX - START_PRICE_MIN);
let currentPrice = bulatkanFraksi(rawStart, false);
if (currentPrice < START_PRICE_MIN) currentPrice = START_PRICE_MIN;
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 };
}
function getIndicatorSeries(sel, closes, data) {
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;
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 });
}
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;
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);
}
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);
}
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([]);
}
}
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();
}
}
/* ====== WATERMARK TENGAH GRAFIK (@sahamharian) ====== */
ctx.save();
const wmText = '@sahamharian';
const wmSize = Math.max(20, Math.min(h * 0.08, w * 0.09));
ctx.font = '900 ' + wmSize + 'px -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif';
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
const wmX = w / 2;
const wmY = h / 2;
ctx.globalAlpha = 0.10;
ctx.fillStyle = '#000000';
ctx.fillText(wmText, wmX + 1.5, wmY + 1.5);
ctx.globalAlpha = 0.16;
ctx.fillStyle = '#eaecef';
ctx.fillText(wmText, wmX, wmY);
ctx.globalAlpha = 0.06;
ctx.fillStyle = '#f0b90b';
ctx.fillText(wmText, wmX, wmY - 0.5);
ctx.restore();
/* ====== AKHIR WATERMARK ====== */
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 ==================== */
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;
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') {
const rsiVals = calcRSI(closes, 14);
const toY = (v) => h - (v / 100) * h;
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([]);
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);
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') {
const m = calcMACD(closes, 12, 26, 9);
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;
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([]);
sctx.fillStyle = '#848e9c';
sctx.font = '9px Arial';
sctx.textAlign = 'left';
sctx.textBaseline = 'top';
sctx.fillText('MACD(12,26,9)', 4, 4);
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));
}
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();
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;
if (dataSource === 'upload' && uploadedData && uploadedData.length > 0) {
fullData = uploadedData.slice();
END_INDEX = fullData.length - 1;
TOTAL_BARS = Math.max(1, END_INDEX - WARMUP_BARS);
} else {
dataSource = 'synthetic';
setDataSource('synthetic');
TOTAL_BARS = DEFAULT_TOTAL_BARS;
END_INDEX = WARMUP_BARS + TOTAL_BARS;
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);
ind1El.addEventListener('change', drawChart);
ind2El.addEventListener('change', drawChart);
ind3El.addEventListener('change', drawChart);
subSelectEl.addEventListener('change', drawSubChart);
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);
if (typeof ResizeObserver !== 'undefined') {
new ResizeObserver(resizeCanvas).observe(canvas.parentElement);
new ResizeObserver(resizeSubCanvas).observe(subCanvas.parentElement);
}
/* ==================== INISIALISASI ==================== */
function init() {
setupSearchableSelects();
updateFees();
setDataSource('synthetic');
startSimulation();
requestAnimationFrame(function () {
resizeCanvas();
resizeSubCanvas();
});
setTimeout(function () {
resizeCanvas();
resizeSubCanvas();
}, 150);
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', init);
} else {
init();
}
})();
</script>
</body>
</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;
}
.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);
}