Spaces:
Running
Running
Download index.html from IndividualGamer/simV1: direct link, hf CLI and curl.
- Browser
- Download file 45.8 kB
-
https://huggingface.co/spaces/IndividualGamer/simV1/resolve/main/index.html
- Command line
-
hf download hf://spaces/IndividualGamer/simV1/index.html
-
curl -L -o index.html https://huggingface.co/spaces/IndividualGamer/simV1/resolve/main/index.html
45.8 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;
}
/* ====== 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>
<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);