mirror of
https://github.com/chrisnov-it/quantumbotx.git
synced 2026-07-27 18:57:47 +00:00
Refactor and update bot management and routing
- Update `.gitignore` to include `lab/` for backtesting and raw data. - Refactor `app.py` to improve error handling and logging. - Remove deprecated files: `core/bot_logic.py`, `core/bots/base_bot.py`, `core/bots/manager.py`, `core/db/database.py`, `core/routes/api_analysis.py`, `core/routes/api_bots_analysis.py`, `core/strategies/logic_ma.py`, `core/strategies/logic_rsi.py`. - Modify multiple files to enhance bot management, routing, and strategy handling. - Update JavaScript and HTML templates for better UI and functionality.
This commit is contained in:
+2
-2
@@ -48,7 +48,7 @@ node_modules/ # Untuk dependensi frontend di masa depan
|
||||
.idea/
|
||||
.DS_Store # Untuk macOS
|
||||
Thumbs.db # Untuk Windows
|
||||
|
||||
lab/ # Folder backtesting dan data mentahan
|
||||
# ==============================================================================
|
||||
# File Sementara & Backup
|
||||
# ==============================================================================
|
||||
@@ -66,4 +66,4 @@ Thumbs.db # Untuk Windows
|
||||
# Simpan mereka di dalam folder 'data/'. Jika ada file CSV lain
|
||||
# (seperti laporan hasil) yang ingin diabaikan, sebutkan secara spesifik.
|
||||
# Contoh:
|
||||
# reports/*.csv
|
||||
# reports/*.csv
|
||||
|
||||
@@ -1,57 +1,60 @@
|
||||
# app.py - FIXED VERSION
|
||||
# app.py - FINAL VERSION
|
||||
import os
|
||||
from flask import Flask, render_template
|
||||
from flask import send_from_directory
|
||||
from dotenv import load_dotenv
|
||||
from core.bots.trading_bot import TradingBot
|
||||
from core.db.queries import get_db_connection, load_bots_from_db
|
||||
from core.utils.mt5 import initialize_mt5
|
||||
from core.bots.controller import load_all_bots
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
from flask import Flask, render_template, send_from_directory
|
||||
from dotenv import load_dotenv
|
||||
|
||||
# Load environment variables
|
||||
# Import modul inti yang diperlukan saat startup
|
||||
from core.utils.mt5 import initialize_mt5
|
||||
from core.bots.controller import ambil_semua_bot
|
||||
|
||||
# --- Konfigurasi Awal ---
|
||||
# Muat environment variables dari file .env
|
||||
load_dotenv()
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
||||
)
|
||||
logger = logging.getLogger(__name__)
|
||||
# Siapkan sistem logging
|
||||
log_dir = os.path.join(os.path.dirname(__file__), 'logs')
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_file = os.path.join(log_dir, 'app.log')
|
||||
|
||||
# === INIT APP ===
|
||||
file_handler = RotatingFileHandler(log_file, maxBytes=1024 * 1024 * 5, backupCount=5)
|
||||
file_handler.setLevel(logging.INFO)
|
||||
file_handler.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
# --- Inisialisasi Aplikasi Flask ---
|
||||
app = Flask(__name__)
|
||||
app.config['SECRET_KEY'] = os.getenv('SECRET_KEY', 'your-secret-key-here')
|
||||
|
||||
# === REGISTER BLUEPRINTS ===
|
||||
from core.routes.api_dashboard import api_dashboard
|
||||
from core.routes.api_chart import api_chart
|
||||
from core.routes.api_bots import api_bots
|
||||
from core.routes.api_profile import api_profile
|
||||
from core.routes.api_indicators import api_indicators
|
||||
from core.routes.api_bots_analysis import api_bots_analysis
|
||||
from core.routes.api_bots_fundamentals import api_bots_fundamentals
|
||||
from core.routes.api_portfolio import api_portfolio
|
||||
from core.routes.api_history import api_history
|
||||
from core.routes.api_notifications import api_notifications
|
||||
from core.routes.api_stocks import api_stocks
|
||||
from core.routes.api_forex import api_forex
|
||||
from core.routes.api_crypto import api_crypto
|
||||
from core.routes.api_analysis import api_analysis
|
||||
from core.routes.api_fundamentals import api_fundamentals
|
||||
# --- Registrasi Blueprints ---
|
||||
# Impor blueprints setelah 'app' dibuat untuk menghindari circular import
|
||||
from core.routes.api_dashboard import api_dashboard # noqa: E402
|
||||
from core.routes.api_chart import api_chart # noqa: E402
|
||||
from core.routes.api_bots import api_bots # noqa: E402
|
||||
from core.routes.api_profile import api_profile # noqa: E402
|
||||
from core.routes.api_portfolio import api_portfolio # noqa: E402
|
||||
from core.routes.api_history import api_history # noqa: E402
|
||||
from core.routes.api_notifications import api_notifications # noqa: E402
|
||||
from core.routes.api_stocks import api_stocks # noqa: E402
|
||||
from core.routes.api_forex import api_forex # noqa: E402
|
||||
from core.routes.api_crypto import api_crypto # noqa: E402
|
||||
from core.routes.api_fundamentals import api_fundamentals # noqa: E402
|
||||
|
||||
# Register blueprints
|
||||
# Buat daftar semua blueprints untuk registrasi yang lebih rapi
|
||||
blueprints = [
|
||||
api_dashboard, api_chart, api_bots, api_profile, api_indicators,
|
||||
api_bots_analysis, api_bots_fundamentals, api_portfolio, api_history,
|
||||
api_notifications, api_stocks, api_forex, api_crypto, api_analysis,
|
||||
api_fundamentals
|
||||
api_dashboard, api_chart, api_bots, api_profile, api_portfolio, api_history,
|
||||
api_notifications, api_stocks, api_forex, api_crypto, api_fundamentals
|
||||
]
|
||||
|
||||
# Daftarkan setiap blueprint ke aplikasi
|
||||
for blueprint in blueprints:
|
||||
app.register_blueprint(blueprint)
|
||||
|
||||
# === ROUTES ===
|
||||
# --- Rute Halaman (Views) ---
|
||||
@app.route('/')
|
||||
def dashboard():
|
||||
return render_template('index.html')
|
||||
@@ -64,6 +67,7 @@ def bots_page():
|
||||
def bot_detail_page(bot_id):
|
||||
return render_template('bot_detail.html')
|
||||
|
||||
# ... (rute-rute halaman lainnya tetap sama) ...
|
||||
@app.route('/portfolio')
|
||||
def portfolio_page():
|
||||
return render_template('portfolio.html')
|
||||
@@ -84,55 +88,68 @@ def profile_page():
|
||||
def notifications_page():
|
||||
return render_template('notifications.html')
|
||||
|
||||
# === ERROR HANDLERS ===
|
||||
@app.route('/cryptocurrency')
|
||||
def crypto_page():
|
||||
return render_template('cryptocurrency.html')
|
||||
|
||||
@app.route('/stocks')
|
||||
def stocks_page():
|
||||
return render_template('stocks.html')
|
||||
|
||||
@app.route('/forex')
|
||||
def forex_page():
|
||||
return render_template('forex.html')
|
||||
|
||||
# --- Error Handlers & Rute Lain-lain ---
|
||||
@app.errorhandler(404)
|
||||
def not_found_error(error):
|
||||
return render_template('404.html'), 404
|
||||
|
||||
@app.errorhandler(500)
|
||||
def internal_error(error):
|
||||
logger.error(f"Internal error: {error}")
|
||||
# Mencatat error ke log untuk debugging
|
||||
logger.error(f"Internal Server Error: {error}", exc_info=True)
|
||||
return render_template('500.html'), 500
|
||||
|
||||
@app.route('/favicon.ico')
|
||||
def favicon():
|
||||
return send_from_directory(os.path.join(app.root_path, 'static'),
|
||||
'favicon.ico', mimetype='image/vnd.microsoft.icon')
|
||||
|
||||
# === MAIN ===
|
||||
|
||||
# --- Titik Eksekusi Utama ---
|
||||
if __name__ == '__main__':
|
||||
# ✅ SECURE: Load from environment variables
|
||||
# Memuat kredensial MT5 dari .env dengan aman
|
||||
try:
|
||||
ACCOUNT = int(os.getenv('MT5_LOGIN'))
|
||||
PASSWORD = os.getenv('MT5_PASSWORD')
|
||||
SERVER = os.getenv('MT5_SERVER', 'MetaQuotes-Demo')
|
||||
|
||||
if not ACCOUNT or not PASSWORD:
|
||||
logger.error("MT5 credentials not found in .env file")
|
||||
|
||||
if not all([ACCOUNT, PASSWORD, SERVER]):
|
||||
logger.critical("Kredensial MT5 (LOGIN/PASSWORD/SERVER) tidak lengkap di file .env.")
|
||||
exit(1)
|
||||
|
||||
except (ValueError, TypeError) as e:
|
||||
logger.error(f"Invalid MT5 credentials in .env: {e}")
|
||||
|
||||
except (ValueError, TypeError):
|
||||
logger.critical("Kredensial MT5_LOGIN harus berupa angka di file .env.")
|
||||
exit(1)
|
||||
|
||||
# Initialize MT5
|
||||
# Inisialisasi koneksi ke MetaTrader 5
|
||||
if not initialize_mt5(ACCOUNT, PASSWORD, SERVER):
|
||||
logger.error("❌ Failed to connect to MT5")
|
||||
logger.critical("GAGAL terhubung ke MetaTrader 5. Pastikan kredensial benar dan terminal berjalan.")
|
||||
exit(1)
|
||||
else:
|
||||
logger.info("✅ MT5 connected successfully")
|
||||
|
||||
# Load all bots
|
||||
logger.info("Berhasil terhubung ke MetaTrader 5.")
|
||||
|
||||
# Muat semua bot yang ada di database
|
||||
try:
|
||||
load_all_bots()
|
||||
logger.info("✅ All bots loaded successfully")
|
||||
ambil_semua_bot()
|
||||
logger.info("Semua bot dari database berhasil dimuat.")
|
||||
except Exception as e:
|
||||
logger.error(f"Error loading bots: {e}")
|
||||
|
||||
# Start Flask app
|
||||
logger.error(f"Terjadi kesalahan saat memuat bot: {e}", exc_info=True)
|
||||
|
||||
# Jalankan aplikasi Flask
|
||||
app.run(
|
||||
debug=os.getenv('FLASK_DEBUG', 'False').lower() == 'true',
|
||||
host=os.getenv('FLASK_HOST', '127.0.0.1'),
|
||||
port=int(os.getenv('FLASK_PORT', 5000)),
|
||||
use_reloader=False
|
||||
)
|
||||
use_reloader=False # Penting: False untuk mencegah eksekusi ganda pada background thread
|
||||
)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
import ollama
|
||||
|
||||
def ask_ollama(prompt, model="llama3"):
|
||||
def ask_ollama(prompt, model="qwen2.5-coder:1.5b"):
|
||||
try:
|
||||
response = ollama.chat(
|
||||
model=model,
|
||||
|
||||
@@ -1,154 +0,0 @@
|
||||
#bot_logic.py
|
||||
|
||||
import time
|
||||
import threading
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from api import data_fetcher
|
||||
|
||||
from .helpers import parse_decimal, initialize_mt5, place_trade, close_trade
|
||||
|
||||
|
||||
class TradingBot:
|
||||
def __init__(self, bot_id, name, market, status='Dijeda', lot_size=0.01, sl_pips=100, tp_pips=200, timeframe='H1', strategy='MA_CROSSOVER', check_interval_seconds=60):
|
||||
self.bot_id = bot_id
|
||||
self.name = name
|
||||
self.market = market
|
||||
self.status = status
|
||||
self.lot_size = lot_size
|
||||
self.sl_pips = sl_pips
|
||||
self.tp_pips = tp_pips
|
||||
self.timeframe = timeframe
|
||||
self.strategy = strategy
|
||||
self.check_interval = check_interval_seconds
|
||||
self.mt5_timeframe_map = {
|
||||
"M1": mt5.TIMEFRAME_M1, "M5": mt5.TIMEFRAME_M5,
|
||||
"M15": mt5.TIMEFRAME_M15, "M30": mt5.TIMEFRAME_M30,
|
||||
"H1": mt5.TIMEFRAME_H1, "H4": mt5.TIMEFRAME_H4,
|
||||
"D1": mt5.TIMEFRAME_D1, "W1": mt5.TIMEFRAME_W1,
|
||||
"MN1": mt5.TIMEFRAME_MN1
|
||||
}
|
||||
self.mt5_timeframe = self.mt5_timeframe_map.get(self.timeframe, mt5.TIMEFRAME_H1)
|
||||
self._thread = None
|
||||
self._stop_event = threading.Event()
|
||||
|
||||
def _log_action(self, action, details):
|
||||
print(f"LOGGING: Bot {self.bot_id} - {action} - {details}")
|
||||
try:
|
||||
with sqlite3.connect('bots.db') as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)', (self.bot_id, action, details))
|
||||
if action.startswith("POSISI") or action.startswith("GAGAL") or action.startswith("AUTO"):
|
||||
notif_message = f"Bot '{self.name}' - {details}"
|
||||
cursor.execute('INSERT INTO notifications (bot_id, message) VALUES (?, ?)', (self.bot_id, notif_message))
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
print(f"Gagal mencatat aksi ke DB: {e}")
|
||||
|
||||
def _get_open_position(self, symbol: str):
|
||||
positions = mt5.positions_get(symbol=symbol)
|
||||
if positions:
|
||||
for p in positions:
|
||||
if p.magic == self.bot_id:
|
||||
return p
|
||||
return None
|
||||
|
||||
def _check_position_auto_close(self, symbol):
|
||||
pos = self._get_open_position(symbol)
|
||||
if not pos:
|
||||
return
|
||||
duration = datetime.now() - datetime.fromtimestamp(pos.time)
|
||||
if duration.total_seconds() > 7200:
|
||||
if close_trade(pos):
|
||||
self._log_action("AUTO-CUT BY TIME", f"Posisi ditutup setelah {duration}")
|
||||
elif pos.profit >= 100:
|
||||
if close_trade(pos):
|
||||
self._log_action("AUTO-CLOSE PROFIT", f"Profit = {pos.profit:.2f}")
|
||||
elif pos.profit <= -50:
|
||||
if close_trade(pos):
|
||||
self._log_action("AUTO-CLOSE LOSS", f"Loss = {pos.profit:.2f}")
|
||||
|
||||
def _analyze(self):
|
||||
print("Menjalankan MA Crossover...")
|
||||
symbol = self.market.replace('/', '')
|
||||
df = data_fetcher.get_rates_from_mt5(symbol, self.mt5_timeframe, 100)
|
||||
if df is None or len(df) < 50:
|
||||
return
|
||||
|
||||
df['SMA_fast'] = ta.sma(df['close'], length=20)
|
||||
df['SMA_slow'] = ta.sma(df['close'], length=50)
|
||||
last, prev = df.iloc[-1], df.iloc[-2]
|
||||
|
||||
if pd.isna(last['SMA_fast']) or pd.isna(last['SMA_slow']):
|
||||
return
|
||||
|
||||
pos = self._get_open_position(symbol)
|
||||
if prev['SMA_fast'] <= prev['SMA_slow'] and last['SMA_fast'] > last['SMA_slow']:
|
||||
if pos and pos.type == mt5.ORDER_TYPE_SELL:
|
||||
close_trade(pos)
|
||||
self._log_action("CLOSE SELL", "Tutup posisi jual karena sinyal BELI (MA)")
|
||||
if not pos or pos.type == mt5.ORDER_TYPE_SELL:
|
||||
self._log_action("SINYAL BELI (MA)", "Cross up terdeteksi")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_BUY, self.lot_size, self.sl_pips, self.tp_pips, self.bot_id)
|
||||
elif prev['SMA_fast'] >= prev['SMA_slow'] and last['SMA_fast'] < last['SMA_slow']:
|
||||
if pos and pos.type == mt5.ORDER_TYPE_BUY:
|
||||
close_trade(pos)
|
||||
self._log_action("CLOSE BUY", "Tutup posisi beli karena sinyal JUAL (MA)")
|
||||
if not pos or pos.type == mt5.ORDER_TYPE_BUY:
|
||||
self._log_action("SINYAL JUAL (MA)", "Cross down terdeteksi")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_SELL, self.lot_size, self.sl_pips, self.tp_pips, self.bot_id)
|
||||
|
||||
def _analyze(self):
|
||||
print("Menjalankan RSI Breakout...")
|
||||
symbol = self.market.replace('/', '')
|
||||
df = data_fetcher.get_rates_from_mt5(symbol, self.mt5_timeframe, 100)
|
||||
if df is None or len(df) < 20:
|
||||
return
|
||||
df['RSI'] = ta.rsi(df['close'], length=14)
|
||||
last, prev = df.iloc[-1], df.iloc[-2]
|
||||
|
||||
if pd.isna(last['RSI']) or pd.isna(prev['RSI']):
|
||||
return
|
||||
|
||||
pos = self._get_open_position(symbol)
|
||||
if not pos:
|
||||
if prev['RSI'] < 30 and last['RSI'] > 30:
|
||||
self._log_action("SINYAL BELI (RSI)", f"Breakout RSI naik: {last['RSI']:.2f}")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_BUY, self.lot_size, self.sl_pips, self.tp_pips, self.bot_id)
|
||||
elif prev['RSI'] > 70 and last['RSI'] < 70:
|
||||
self._log_action("SINYAL JUAL (RSI)", f"Breakout RSI turun: {last['RSI']:.2f}")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_SELL, self.lot_size, self.sl_pips, self.tp_pips, self.bot_id)
|
||||
|
||||
def _run_logic(self):
|
||||
symbol = self.market.replace('/', '')
|
||||
self._log_action("INFO", f"Bot memulai untuk {self.market} dengan strategi {self.strategy}")
|
||||
try:
|
||||
while self.status == 'Aktif' and not self._stop_event.is_set():
|
||||
if self.strategy == 'MA_CROSSOVER':
|
||||
self._analyze()
|
||||
elif self.strategy == 'RSI_BREAKOUT':
|
||||
self._analyze()
|
||||
self._check_position_auto_close(symbol)
|
||||
time.sleep(self.check_interval)
|
||||
except Exception as e:
|
||||
self._log_action("ERROR", str(e))
|
||||
finally:
|
||||
self._log_action("INFO", "Bot dihentikan.")
|
||||
|
||||
def start(self):
|
||||
if self.status != 'Aktif' and (self._thread is None or not self._thread.is_alive()):
|
||||
self.status = 'Aktif'
|
||||
self._stop_event.clear()
|
||||
self._thread = threading.Thread(target=self._run_logic, daemon=True)
|
||||
self._thread.start()
|
||||
|
||||
def stop(self):
|
||||
if self.status == 'Aktif':
|
||||
self.status = 'Dijeda'
|
||||
self._stop_event.set()
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=2)
|
||||
self._thread = None
|
||||
@@ -1,2 +1 @@
|
||||
# Init untuk modul bot trading
|
||||
from .manager import start_bot, stop_bot, get_bot_status
|
||||
# Init untuk modul bot trading
|
||||
@@ -1,7 +0,0 @@
|
||||
class BaseStrategy:
|
||||
def __init__(self, bot):
|
||||
self.bot = bot # bot instance yang punya atribut: market, lot_size, dst.
|
||||
|
||||
def analyze(self):
|
||||
"""Override this method in your custom strategy"""
|
||||
raise NotImplementedError("analyze() harus diimplementasikan di strategi turunan.")
|
||||
+104
-44
@@ -1,51 +1,111 @@
|
||||
# core/bots/controller.py
|
||||
from core.bots.trading_bot import TradingBot
|
||||
from core.db.queries import ambil_semua_bot
|
||||
import threading
|
||||
|
||||
# Dictionary untuk menyimpan semua bot aktif
|
||||
import logging
|
||||
from core.db import queries
|
||||
from .trading_bot import TradingBot
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Dictionary untuk menyimpan instance thread bot yang aktif
|
||||
# Key: bot_id (int), Value: TradingBot instance
|
||||
active_bots = {}
|
||||
|
||||
def load_all_bots():
|
||||
bots = ambil_semua_bot()
|
||||
for bot_data in bots:
|
||||
bot_data['bot_id'] = bot_data.pop('id') # GANTI id → bot_id
|
||||
bot = TradingBot(**bot_data)
|
||||
active_bots[bot.bot_id] = bot
|
||||
if bot.status == 'Aktif':
|
||||
bot.start()
|
||||
def ambil_semua_bot():
|
||||
"""
|
||||
Mengambil semua bot dari database saat aplikasi pertama kali dimulai.
|
||||
Tidak memulai thread, hanya memuat konfigurasi.
|
||||
"""
|
||||
try:
|
||||
all_bots_data = queries.get_all_bots()
|
||||
logger.info(f"Memuat {len(all_bots_data)} bot dari database.")
|
||||
# Anda bisa menambahkan logika untuk memulai bot yang statusnya 'Aktif' di sini jika perlu
|
||||
except Exception as e:
|
||||
logger.error(f"Gagal memuat bot dari database saat startup: {e}", exc_info=True)
|
||||
|
||||
def get_active_bot(bot_id):
|
||||
return active_bots.get(int(bot_id))
|
||||
def mulai_bot(bot_id: int):
|
||||
"""Memulai thread untuk bot yang dipilih."""
|
||||
if bot_id in active_bots and active_bots[bot_id].is_alive():
|
||||
return True, f"Bot {bot_id} sudah berjalan."
|
||||
|
||||
bot_data = queries.get_bot_by_id(bot_id)
|
||||
if not bot_data:
|
||||
return False, f"Bot dengan ID {bot_id} tidak ditemukan."
|
||||
|
||||
try:
|
||||
bot_thread = TradingBot(
|
||||
id=bot_data['id'], name=bot_data['name'], market=bot_data['market'],
|
||||
lot_size=bot_data['lot_size'], sl_pips=bot_data['sl_pips'],
|
||||
tp_pips=bot_data['tp_pips'], timeframe=bot_data['timeframe'],
|
||||
check_interval=bot_data['check_interval_seconds'], strategy=bot_data['strategy']
|
||||
)
|
||||
bot_thread.start()
|
||||
active_bots[bot_id] = bot_thread
|
||||
queries.update_bot_status(bot_id, 'Aktif')
|
||||
logger.info(f"Bot {bot_id} ({bot_data['name']}) berhasil dimulai.")
|
||||
return True, f"Bot {bot_data['name']} berhasil dimulai."
|
||||
except Exception as e:
|
||||
logger.error(f"Gagal memulai bot {bot_id}: {e}", exc_info=True)
|
||||
queries.update_bot_status(bot_id, 'Error')
|
||||
return False, f"Gagal memulai bot: {e}"
|
||||
|
||||
def stop_bot(bot_id: int):
|
||||
"""Menghentikan thread bot yang sedang berjalan."""
|
||||
if bot_id in active_bots and active_bots[bot_id].is_alive():
|
||||
bot_thread = active_bots[bot_id]
|
||||
bot_thread.stop()
|
||||
bot_thread.join(timeout=10) # Tunggu thread berhenti
|
||||
del active_bots[bot_id]
|
||||
queries.update_bot_status(bot_id, 'Dijeda')
|
||||
logger.info(f"Bot {bot_id} berhasil dihentikan.")
|
||||
return True, f"Bot {bot_thread.name} berhasil dihentikan."
|
||||
|
||||
def start_bot(bot_id):
|
||||
# Jika bot tidak ada di memori tapi statusnya 'Aktif' di DB (state tidak konsisten)
|
||||
queries.update_bot_status(bot_id, 'Dijeda')
|
||||
return True, f"Bot {bot_id} dihentikan (state tidak konsisten telah diperbaiki)."
|
||||
|
||||
def perbarui_bot(bot_id: int, data: dict):
|
||||
"""Memperbarui konfigurasi bot di database."""
|
||||
bot_instance = active_bots.get(bot_id)
|
||||
if bot_instance and bot_instance.is_alive():
|
||||
logger.info(f"Menghentikan bot {bot_id} sementara untuk pembaruan.")
|
||||
stop_bot(bot_id)
|
||||
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
# Ganti nama kunci 'check_interval_seconds' dari frontend
|
||||
# menjadi 'interval' yang sesuai dengan kolom database.
|
||||
if 'check_interval_seconds' in data:
|
||||
data['interval'] = data.pop('check_interval_seconds')
|
||||
# --- AKHIR PERBAIKAN ---
|
||||
|
||||
try:
|
||||
success = queries.update_bot(bot_id=bot_id, **data)
|
||||
if success:
|
||||
logger.info(f"Konfigurasi bot {bot_id} berhasil diperbarui di database.")
|
||||
return True, "Bot berhasil diperbarui."
|
||||
else:
|
||||
return False, "Gagal memperbarui bot di database."
|
||||
except Exception as e:
|
||||
logger.error(f"Error saat memperbarui bot {bot_id} di DB: {e}", exc_info=True)
|
||||
return False, str(e)
|
||||
|
||||
def hapus_bot(bot_id: int):
|
||||
"""Menghentikan dan menghapus bot."""
|
||||
stop_bot(bot_id) # Pastikan thread berhenti sebelum dihapus
|
||||
return queries.delete_bot(bot_id)
|
||||
|
||||
def add_new_bot_to_controller(bot_id: int):
|
||||
"""Menambahkan bot baru dan langsung memulainya jika statusnya 'Aktif'."""
|
||||
bot_data = queries.get_bot_by_id(bot_id)
|
||||
if bot_data and bot_data.get('status') == 'Aktif':
|
||||
mulai_bot(bot_id)
|
||||
|
||||
def get_bot_instance_by_id(bot_id: int):
|
||||
"""Mengembalikan instance thread bot yang aktif."""
|
||||
return active_bots.get(bot_id)
|
||||
|
||||
def get_bot_analysis_data(bot_id: int):
|
||||
"""Mengambil data analisis terakhir dari instance bot."""
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot and bot.status != 'Aktif':
|
||||
bot.start()
|
||||
|
||||
def stop_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot and bot.status == 'Aktif':
|
||||
bot.stop()
|
||||
|
||||
def get_bot_status(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot:
|
||||
return bot.status
|
||||
return "Tidak ditemukan"
|
||||
|
||||
def restart_all_bots():
|
||||
for bot in active_bots.values():
|
||||
if bot.status == 'Aktif':
|
||||
bot.stop()
|
||||
bot.start()
|
||||
|
||||
def reload_all_bots():
|
||||
"""
|
||||
Hentikan semua bot, hapus dictionary,
|
||||
lalu load ulang dari database.
|
||||
"""
|
||||
for bot in active_bots.values():
|
||||
bot.stop()
|
||||
active_bots.clear()
|
||||
load_all_bots()
|
||||
if bot and hasattr(bot, 'last_analysis'):
|
||||
return bot.last_analysis
|
||||
return None
|
||||
@@ -1,6 +1,5 @@
|
||||
import pandas_ta as ta
|
||||
from core.bots.base_bot import BaseStrategy
|
||||
import MetaTrader5 as mt5
|
||||
|
||||
class MACrossoverStrategy(BaseStrategy):
|
||||
def analyze(self):
|
||||
|
||||
@@ -1,34 +0,0 @@
|
||||
# core/bots/manager.py
|
||||
|
||||
from core.bots.trading_bot import TradingBot
|
||||
from core.db.queries import load_bots_from_db
|
||||
|
||||
active_bots = {}
|
||||
|
||||
def start_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot and bot.status != "Aktif":
|
||||
bot.start()
|
||||
print(f"[MANAGER] Bot #{bot_id} dimulai.")
|
||||
|
||||
def stop_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot and bot.status == "Aktif":
|
||||
bot.stop()
|
||||
print(f"[MANAGER] Bot #{bot_id} dihentikan.")
|
||||
|
||||
def get_bot_status(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
return bot.status if bot else "Tidak Ditemukan"
|
||||
|
||||
def get_active_bot(bot_id):
|
||||
return active_bots.get(bot_id)
|
||||
|
||||
def load_all_bots():
|
||||
bots_data = load_bots_from_db()
|
||||
for bot_data in bots_data:
|
||||
bot = TradingBot(**bot_data)
|
||||
active_bots[bot.bot_id] = bot
|
||||
if bot.status == "Aktif":
|
||||
bot.start()
|
||||
print(f"[MANAGER] Total bot dimuat: {len(active_bots)}")
|
||||
@@ -5,7 +5,7 @@ import MetaTrader5 as mt5
|
||||
|
||||
class PulseSyncStrategy(BaseStrategy):
|
||||
def analyze(self):
|
||||
symbol = self.bot.market.replace('/', '')
|
||||
self.bot.market.replace('/', '')
|
||||
df_d1 = self.bot.fetch_data(mt5.TIMEFRAME_D1, 200)
|
||||
df_h1 = self.bot.fetch_data(mt5.TIMEFRAME_H1, 100)
|
||||
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
import pandas_ta as ta
|
||||
from core.bots.base_bot import BaseStrategy
|
||||
import MetaTrader5 as mt5
|
||||
|
||||
class RSIBreakoutStrategy(BaseStrategy):
|
||||
def analyze(self):
|
||||
|
||||
+122
-175
@@ -1,197 +1,144 @@
|
||||
# core/bots/trading_bot.py - FIXED VERSION
|
||||
import time
|
||||
import threading
|
||||
import sqlite3
|
||||
import logging
|
||||
from datetime import datetime
|
||||
import MetaTrader5 as mt5
|
||||
from core.db.models import log_trade_action
|
||||
from core.mt5.trade import place_trade, close_trade
|
||||
from core.strategies.ma_crossover import analyze as analyze_ma
|
||||
from core.strategies.rsi_breakout import analyze as analyze_rsi
|
||||
from core.strategies.pulse_sync import analyze as analyze_pulse
|
||||
from core.strategies.mercy_edge import analyze as analyze_mercy
|
||||
from core.data.fetch import get_rates
|
||||
# core/bots/trading_bot.py - VERSI GABUNGAN FINAL
|
||||
|
||||
import threading
|
||||
import time
|
||||
import logging
|
||||
import MetaTrader5 as mt5
|
||||
from core.strategies.strategy_map import STRATEGY_MAP
|
||||
from core.mt5.trade import place_trade, close_trade
|
||||
from core.utils.mt5 import TIMEFRAME_MAP # <-- Impor dari lokasi terpusat
|
||||
|
||||
# Setup logging
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
class TradingBot:
|
||||
def __init__(self, bot_id, name, market, status='Dijeda', lot_size=0.01,
|
||||
sl_pips=100, tp_pips=200, timeframe='H1', strategy='MA_CROSSOVER',
|
||||
check_interval_seconds=60):
|
||||
self.bot_id = bot_id
|
||||
|
||||
class TradingBot(threading.Thread):
|
||||
def __init__(self, id, name, market, lot_size, sl_pips, tp_pips, timeframe, check_interval, strategy, status='Dijeda'):
|
||||
super().__init__()
|
||||
self.id = id
|
||||
self.name = name
|
||||
self.market = market
|
||||
self.status = status
|
||||
self.lot_size = lot_size
|
||||
self.sl_pips = sl_pips
|
||||
self.tp_pips = tp_pips
|
||||
self.timeframe = timeframe
|
||||
self.strategy = strategy
|
||||
self.check_interval = check_interval_seconds
|
||||
self._thread = None
|
||||
self.check_interval = check_interval
|
||||
self.strategy_name = strategy
|
||||
self.market_for_mt5 = self.market.replace('/', '') # Versi simbol yang bersih untuk MT5
|
||||
self.status = status
|
||||
|
||||
self.last_analysis = {}
|
||||
self._stop_event = threading.Event()
|
||||
self.tf_map = {
|
||||
"M1": mt5.TIMEFRAME_M1, "M5": mt5.TIMEFRAME_M5,
|
||||
"M15": mt5.TIMEFRAME_M15, "H1": mt5.TIMEFRAME_H1,
|
||||
"H4": mt5.TIMEFRAME_H4, "D1": mt5.TIMEFRAME_D1,
|
||||
"W1": mt5.TIMEFRAME_W1, "MN1": mt5.TIMEFRAME_MN1
|
||||
}
|
||||
self.strategy_instance = None
|
||||
# Gunakan map yang diimpor untuk menjaga konsistensi
|
||||
self.tf_map = TIMEFRAME_MAP
|
||||
|
||||
def run(self):
|
||||
"""Metode utama yang dijalankan oleh thread, kini dengan eksekusi trade."""
|
||||
self.status = 'Aktif'
|
||||
self.log_activity('START', f"Bot '{self.name}' dimulai dengan strategi {self.strategy_name}.") # <-- Menggunakan log_activity
|
||||
|
||||
def _get_open_position(self, symbol):
|
||||
"""Get open position for this bot's magic number"""
|
||||
try:
|
||||
positions = mt5.positions_get(symbol=symbol)
|
||||
if positions:
|
||||
for p in positions:
|
||||
if p.magic == self.bot_id:
|
||||
return p
|
||||
return None
|
||||
strategy_class = STRATEGY_MAP.get(self.strategy_name)
|
||||
if not strategy_class:
|
||||
raise ValueError(f"Strategi '{self.strategy_name}' tidak ditemukan.")
|
||||
|
||||
# --- PERBAIKAN: Inisialisasi kelas strategi dengan benar ---
|
||||
self.strategy_instance = strategy_class(bot_instance=self)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error getting positions: {e}")
|
||||
return None
|
||||
self.log_activity('ERROR', f"Inisialisasi Gagal: {e}")
|
||||
self.status = 'Error'
|
||||
return
|
||||
|
||||
def _auto_close(self, pos):
|
||||
"""Auto close position based on rules"""
|
||||
try:
|
||||
duration = datetime.now() - datetime.fromtimestamp(pos.time)
|
||||
|
||||
# Rule 1: Close after 2 hours
|
||||
if duration.total_seconds() > 7200:
|
||||
if close_trade(pos):
|
||||
log_trade_action(self.bot_id, "AUTO-CUT", f"Duration > 2h: {duration}")
|
||||
return True
|
||||
|
||||
# Rule 2: Take profit at +$100
|
||||
elif pos.profit >= 100:
|
||||
if close_trade(pos):
|
||||
log_trade_action(self.bot_id, "AUTO-TP", f"Profit: {pos.profit:.2f}")
|
||||
return True
|
||||
|
||||
# Rule 3: Stop loss at -$50
|
||||
elif pos.profit <= -50:
|
||||
if close_trade(pos):
|
||||
log_trade_action(self.bot_id, "AUTO-SL", f"Loss: {pos.profit:.2f}")
|
||||
return True
|
||||
|
||||
return False
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in auto_close: {e}")
|
||||
return False
|
||||
|
||||
def _execute_strategy(self):
|
||||
"""Execute trading strategy - FIXED VERSION"""
|
||||
try:
|
||||
symbol = self.market.replace('/', '')
|
||||
tf = self.tf_map.get(self.timeframe, mt5.TIMEFRAME_H1)
|
||||
pos = self._get_open_position(symbol)
|
||||
|
||||
# Get market data
|
||||
df = get_rates(symbol, tf, 100)
|
||||
if df is None or df.empty:
|
||||
logger.warning(f"No data available for {symbol}")
|
||||
return
|
||||
|
||||
# ✅ FIXED: Call correct strategy functions
|
||||
signal = 'HOLD'
|
||||
|
||||
while not self._stop_event.is_set():
|
||||
try:
|
||||
if self.strategy == 'MA_CROSSOVER':
|
||||
signal = analyze_ma(df)
|
||||
elif self.strategy == 'RSI_BREAKOUT':
|
||||
signal = analyze_rsi(df)
|
||||
elif self.strategy == 'PULSE_SYNC':
|
||||
signal = analyze_pulse(df)
|
||||
elif self.strategy == 'MERCY_EDGE':
|
||||
signal = analyze_mercy(self)
|
||||
else:
|
||||
logger.warning(f"Unknown strategy: {self.strategy}")
|
||||
return
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Strategy analysis error: {e}")
|
||||
return
|
||||
if not mt5.symbol_select(self.market_for_mt5, True):
|
||||
self.log_activity('WARNING', f"Gagal mengaktifkan simbol {self.market} (di MT5: {self.market_for_mt5}). Pastikan simbol ada di Market Watch.")
|
||||
time.sleep(self.check_interval)
|
||||
continue
|
||||
|
||||
# Execute trades based on signal
|
||||
self._handle_trade_signal(signal, symbol, pos)
|
||||
|
||||
# Auto close check
|
||||
if pos:
|
||||
self._auto_close(pos)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error in execute_strategy: {e}")
|
||||
log_trade_action(self.bot_id, "ERROR", str(e))
|
||||
symbol_info = mt5.symbol_info(self.market_for_mt5)
|
||||
if not symbol_info:
|
||||
self.log_activity('WARNING', f"Tidak dapat mengambil info untuk simbol {self.market} (di MT5: {self.market_for_mt5}).")
|
||||
time.sleep(self.check_interval)
|
||||
continue
|
||||
|
||||
def _handle_trade_signal(self, signal, symbol, pos):
|
||||
"""Handle trade signals"""
|
||||
try:
|
||||
if signal == 'BUY':
|
||||
# Close opposite position first
|
||||
if pos and pos.type == mt5.ORDER_TYPE_SELL:
|
||||
if close_trade(pos):
|
||||
log_trade_action(self.bot_id, "CLOSE SELL", "Switch to BUY")
|
||||
pos = None
|
||||
|
||||
# Open new BUY if no position
|
||||
if not pos:
|
||||
if place_trade(symbol, mt5.ORDER_TYPE_BUY, self.lot_size,
|
||||
self.sl_pips, self.tp_pips, self.bot_id):
|
||||
log_trade_action(self.bot_id, "OPEN BUY", f"Strategy: {self.strategy}")
|
||||
|
||||
elif signal == 'SELL':
|
||||
# Close opposite position first
|
||||
if pos and pos.type == mt5.ORDER_TYPE_BUY:
|
||||
if close_trade(pos):
|
||||
log_trade_action(self.bot_id, "CLOSE BUY", "Switch to SELL")
|
||||
pos = None
|
||||
|
||||
# Open new SELL if no position
|
||||
if not pos:
|
||||
if place_trade(symbol, mt5.ORDER_TYPE_SELL, self.lot_size,
|
||||
self.sl_pips, self.tp_pips, self.bot_id):
|
||||
log_trade_action(self.bot_id, "OPEN SELL", f"Strategy: {self.strategy}")
|
||||
else:
|
||||
logger.info(f"[{self.name}] No signal. HOLD...")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error handling trade signal: {e}")
|
||||
# --- PERBAIKAN: Panggil metode analyze dari objek strategi ---
|
||||
# Metode analyze tidak lagi memerlukan argumen
|
||||
self.last_analysis = self.strategy_instance.analyze()
|
||||
logger.info(f"Bot {self.id} [{self.strategy_name}] - Last Analysis: {self.last_analysis}")
|
||||
signal = self.last_analysis.get("signal", "HOLD")
|
||||
|
||||
current_position = self._get_open_position()
|
||||
|
||||
self._handle_trade_signal(signal, current_position)
|
||||
|
||||
def _run_logic(self):
|
||||
"""Main bot loop"""
|
||||
log_trade_action(self.bot_id, "START", f"Bot {self.name} started with {self.strategy}")
|
||||
logger.info(f"Bot {self.name} started with strategy {self.strategy}")
|
||||
|
||||
try:
|
||||
while self.status == 'Aktif' and not self._stop_event.is_set():
|
||||
self._execute_strategy()
|
||||
time.sleep(self.check_interval)
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Bot {self.name} error: {e}")
|
||||
log_trade_action(self.bot_id, "ERROR", str(e))
|
||||
finally:
|
||||
log_trade_action(self.bot_id, "STOP", "Bot stopped")
|
||||
logger.info(f"Bot {self.name} stopped")
|
||||
except Exception as e:
|
||||
self.log_activity('ERROR', f"Error pada loop utama: {e}", exc_info=True)
|
||||
time.sleep(self.check_interval * 2)
|
||||
|
||||
def start(self):
|
||||
"""Start the trading bot"""
|
||||
if self.status != 'Aktif' and (self._thread is None or not self._thread.is_alive()):
|
||||
self.status = 'Aktif'
|
||||
self._stop_event.clear()
|
||||
self._thread = threading.Thread(target=self._run_logic, daemon=True)
|
||||
self._thread.start()
|
||||
logger.info(f"Bot {self.name} started successfully")
|
||||
self.status = 'Dijeda'
|
||||
self.log_activity('STOP', f"Bot '{self.name}' dihentikan.")
|
||||
|
||||
def stop(self):
|
||||
"""Stop the trading bot"""
|
||||
if self.status == 'Aktif':
|
||||
self.status = 'Dijeda'
|
||||
self._stop_event.set()
|
||||
if self._thread and self._thread.is_alive():
|
||||
self._thread.join(timeout=5) # Increased timeout
|
||||
self._thread = None
|
||||
logger.info(f"Bot {self.name} stopped successfully")
|
||||
"""Mengirim sinyal berhenti ke thread."""
|
||||
self._stop_event.set()
|
||||
|
||||
def is_stopped(self):
|
||||
"""Memeriksa apakah thread sudah diberi sinyal berhenti."""
|
||||
return self._stop_event.is_set()
|
||||
|
||||
def log_activity(self, action, details, exc_info=False):
|
||||
"""Mencatat aktivitas bot ke database dan file log."""
|
||||
try:
|
||||
from core.db.queries import add_history_log
|
||||
add_history_log(self.id, action, details)
|
||||
log_message = f"Bot {self.id} [{action}]: {details}"
|
||||
if exc_info:
|
||||
logger.error(log_message, exc_info=True)
|
||||
else:
|
||||
logger.info(log_message)
|
||||
except Exception as e:
|
||||
logger.error(f"Gagal mencatat riwayat untuk bot {self.id}: {e}")
|
||||
|
||||
def _get_open_position(self):
|
||||
"""Mendapatkan posisi terbuka untuk bot ini berdasarkan magic number (ID bot)."""
|
||||
try:
|
||||
positions = mt5.positions_get(symbol=self.market_for_mt5)
|
||||
if positions:
|
||||
for pos in positions:
|
||||
if pos.magic == self.id:
|
||||
return pos
|
||||
return None
|
||||
except Exception as e:
|
||||
self.log_activity('ERROR', f"Gagal mendapatkan posisi terbuka: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def _handle_trade_signal(self, signal, position):
|
||||
"""Menangani sinyal trading: membuka, menutup, atau tidak melakukan apa-apa."""
|
||||
# Logika untuk sinyal BUY
|
||||
if signal == 'BUY':
|
||||
# Jika ada posisi SELL, tutup dulu
|
||||
if position and position.type == mt5.ORDER_TYPE_SELL:
|
||||
self.log_activity('CLOSE SELL', "Menutup posisi JUAL untuk membuka posisi BELI.")
|
||||
close_trade(position)
|
||||
position = None # Reset posisi setelah ditutup
|
||||
|
||||
# Jika tidak ada posisi, buka posisi BUY baru
|
||||
if not position:
|
||||
self.log_activity('OPEN BUY', "Membuka posisi BELI berdasarkan sinyal.")
|
||||
place_trade(self.market_for_mt5, mt5.ORDER_TYPE_BUY, self.lot_size, self.sl_pips, self.tp_pips, self.id)
|
||||
|
||||
# Logika untuk sinyal SELL
|
||||
elif signal == 'SELL':
|
||||
# Jika ada posisi BUY, tutup dulu
|
||||
if position and position.type == mt5.ORDER_TYPE_BUY:
|
||||
self.log_activity('CLOSE BUY', "Menutup posisi BELI untuk membuka posisi JUAL.")
|
||||
close_trade(position)
|
||||
position = None # Reset posisi setelah ditutup
|
||||
|
||||
# Jika tidak ada posisi, buka posisi SELL baru
|
||||
if not position:
|
||||
self.log_activity('OPEN SELL', "Membuka posisi JUAL berdasarkan sinyal.")
|
||||
place_trade(self.market_for_mt5, mt5.ORDER_TYPE_SELL, self.lot_size, self.sl_pips, self.tp_pips, self.id)
|
||||
|
||||
+12
-8
@@ -1,8 +1,12 @@
|
||||
# /core/data/fetch.py
|
||||
import MetaTrader5 as mt5
|
||||
import pandas as pd
|
||||
import logging
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
# Gunakan logger yang konsisten dengan seluruh aplikasi
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# =================================================
|
||||
# FUNGSI-FUNGSI PENGAMBILAN DATA DARI METATRADER 5
|
||||
# =================================================
|
||||
@@ -17,7 +21,7 @@ def get_rates(symbol: str, timeframe: int, count: int = 100):
|
||||
|
||||
# Periksa apakah data berhasil diambil
|
||||
if rates is None or len(rates) == 0:
|
||||
print(f"[FETCH ERROR] Gagal mengambil data harga untuk {symbol} (Timeframe: {timeframe}). MT5 mengembalikan None atau data kosong.")
|
||||
logger.warning(f"Gagal mengambil data harga untuk {symbol} (Timeframe: {timeframe}). MT5 mengembalikan None atau data kosong.")
|
||||
return None
|
||||
|
||||
# Konversi ke DataFrame
|
||||
@@ -27,7 +31,7 @@ def get_rates(symbol: str, timeframe: int, count: int = 100):
|
||||
|
||||
return df
|
||||
except Exception as e:
|
||||
print(f"[FETCH CRITICAL] Terjadi error tak terduga saat get_rates untuk {symbol}: {e}")
|
||||
logger.error(f"Error tak terduga saat get_rates untuk {symbol}: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def get_mt5_account_info():
|
||||
@@ -38,10 +42,10 @@ def get_mt5_account_info():
|
||||
if info:
|
||||
return info._asdict()
|
||||
else:
|
||||
print(f"[FETCH ERROR] Gagal mengambil info akun. MT5 mengembalikan None. Error: {mt5.last_error()}")
|
||||
logger.error(f"Gagal mengambil info akun. MT5 mengembalikan None. Error: {mt5.last_error()}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"[FETCH CRITICAL] Terjadi error tak terduga saat get_mt5_account_info: {e}")
|
||||
logger.error(f"Error tak terduga saat get_mt5_account_info: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def get_todays_profit():
|
||||
@@ -58,7 +62,7 @@ def get_todays_profit():
|
||||
# Gunakan generator expression untuk efisiensi
|
||||
return sum(d.profit for d in deals if d.entry == 1)
|
||||
except Exception as e:
|
||||
print(f"[FETCH CRITICAL] Terjadi error tak terduga saat get_todays_profit: {e}")
|
||||
logger.error(f"Error tak terduga saat get_todays_profit: {e}", exc_info=True)
|
||||
return 0.0
|
||||
|
||||
def get_trade_history_from_mt5(days_history: int = 30):
|
||||
@@ -70,7 +74,7 @@ def get_trade_history_from_mt5(days_history: int = 30):
|
||||
deals = mt5.history_deals_get(from_date, to_date)
|
||||
|
||||
if deals is None:
|
||||
print("[FETCH ERROR] Gagal mengambil histori deals dari MT5.")
|
||||
logger.warning("Gagal mengambil histori deals dari MT5. MT5 mengembalikan None.")
|
||||
return []
|
||||
|
||||
# Proses data hanya jika ada deals yang ditemukan
|
||||
@@ -83,7 +87,7 @@ def get_trade_history_from_mt5(days_history: int = 30):
|
||||
return []
|
||||
|
||||
except Exception as e:
|
||||
print(f"[FETCH CRITICAL] Terjadi error tak terduga saat get_trade_history: {e}")
|
||||
logger.error(f"Error tak terduga saat get_trade_history: {e}", exc_info=True)
|
||||
return []
|
||||
|
||||
def get_open_positions_from_mt5():
|
||||
@@ -106,5 +110,5 @@ def get_open_positions_from_mt5():
|
||||
for pos in positions
|
||||
]
|
||||
except Exception as e:
|
||||
print(f"[FETCH CRITICAL] Terjadi error tak terduga saat get_open_positions: {e}")
|
||||
logger.error(f"Error tak terduga saat get_open_positions: {e}", exc_info=True)
|
||||
return []
|
||||
+1
-2
@@ -1,2 +1 @@
|
||||
# Handler DB SQLite
|
||||
from .database import get_connection
|
||||
# Handler DB SQLite
|
||||
+15
-36
@@ -1,45 +1,24 @@
|
||||
# core/db/connection.py
|
||||
# core/db/connection.py - VERSI FINAL
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
DB_PATH = os.getenv("DB_PATH", "bots.db")
|
||||
# Menentukan path absolut ke file database
|
||||
# Ini memastikan DB ditemukan dari mana pun skrip dijalankan
|
||||
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
|
||||
DB_PATH = os.path.join(BASE_DIR, '..', '..', 'bots.db')
|
||||
|
||||
def get_connection():
|
||||
def get_db_connection():
|
||||
"""
|
||||
Membuat dan mengembalikan koneksi ke database SQLite.
|
||||
Fungsi ini adalah satu-satunya sumber koneksi database untuk seluruh aplikasi.
|
||||
"""
|
||||
try:
|
||||
conn = sqlite3.connect(DB_PATH)
|
||||
conn.row_factory = sqlite3.Row # biar hasilnya bisa dipanggil pakai nama kolom
|
||||
# check_same_thread=False diperlukan untuk aplikasi multi-threaded seperti Flask
|
||||
conn = sqlite3.connect(DB_PATH, check_same_thread=False)
|
||||
# 'row_factory' membuat hasil query bisa diakses seperti dictionary
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DB] Gagal koneksi ke database: {e}")
|
||||
print(f"FATAL: Gagal koneksi ke database di {DB_PATH}: {e}")
|
||||
return None
|
||||
|
||||
def fetch_all(query, params=()):
|
||||
conn = get_connection()
|
||||
if not conn:
|
||||
return []
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(query, params)
|
||||
results = cur.fetchall()
|
||||
return [dict(row) for row in results]
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DB] Error saat fetch_all: {e}")
|
||||
return []
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
def execute_query(query, params=()):
|
||||
conn = get_connection()
|
||||
if not conn:
|
||||
return False
|
||||
try:
|
||||
cur = conn.cursor()
|
||||
cur.execute(query, params)
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.Error as e:
|
||||
print(f"[DB] Error saat execute_query: {e}")
|
||||
return False
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
@@ -1,68 +0,0 @@
|
||||
# core/db/database.py
|
||||
|
||||
import sqlite3
|
||||
from werkzeug.security import generate_password_hash
|
||||
|
||||
def get_connection():
|
||||
return sqlite3.connect('bots.db')
|
||||
|
||||
def init_db():
|
||||
conn = get_connection()
|
||||
cursor = conn.cursor()
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS bots (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
market TEXT NOT NULL,
|
||||
status TEXT NOT NULL,
|
||||
lot_size REAL DEFAULT 0.01,
|
||||
sl_pips INTEGER DEFAULT 100,
|
||||
tp_pips INTEGER DEFAULT 200,
|
||||
timeframe TEXT DEFAULT 'H1',
|
||||
check_interval_seconds INTEGER DEFAULT 60,
|
||||
strategy TEXT DEFAULT 'MA_CROSSOVER'
|
||||
)
|
||||
''')
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS trade_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
bot_id INTEGER, action TEXT, details TEXT,
|
||||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (bot_id) REFERENCES bots (id)
|
||||
)
|
||||
''')
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
bot_id INTEGER, message TEXT, is_read INTEGER DEFAULT 0,
|
||||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
FOREIGN KEY (bot_id) REFERENCES bots (id)
|
||||
)
|
||||
''')
|
||||
|
||||
cursor.execute('''
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL, email TEXT NOT NULL UNIQUE,
|
||||
password_hash TEXT NOT NULL, join_date DATE DEFAULT CURRENT_TIMESTAMP
|
||||
)
|
||||
''')
|
||||
|
||||
# Add default user
|
||||
cursor.execute("SELECT id FROM users WHERE id = 1")
|
||||
if cursor.fetchone() is None:
|
||||
cursor.execute(
|
||||
'INSERT INTO users (id, name, email, password_hash) VALUES (?, ?, ?, ?)',
|
||||
(1, 'Reynov Christian', 'contact@chrisnov.com', generate_password_hash('password123'))
|
||||
)
|
||||
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
# Untuk bisa dijalankan langsung
|
||||
if __name__ == '__main__':
|
||||
init_db()
|
||||
print("Database berhasil dibuat / diperbarui!")
|
||||
+92
-70
@@ -1,81 +1,103 @@
|
||||
# core/db/queries.py
|
||||
# core/db/queries.py - VERSI PERBAIKAN LENGKAP
|
||||
|
||||
import logging
|
||||
import sqlite3
|
||||
from .connection import get_db_connection
|
||||
|
||||
def get_db_connection():
|
||||
conn = sqlite3.connect('bots.db')
|
||||
conn.row_factory = sqlite3.Row
|
||||
return conn
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
def load_bots_from_db():
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT * FROM bots")
|
||||
rows = cursor.fetchall()
|
||||
conn.close()
|
||||
return [dict(row) for row in rows]
|
||||
|
||||
def tambah_bot(name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO bots (name, market, status, lot_size, sl_pips, tp_pips, timeframe, check_interval_seconds, strategy)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
|
||||
''', (name, market, 'Dijeda', lot_size, sl_pips, tp_pips, timeframe, interval, strategy))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
def ambil_semua_bot():
|
||||
conn = sqlite3.connect('bots.db')
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('SELECT * FROM bots')
|
||||
bots = cursor.fetchall()
|
||||
conn.close()
|
||||
return [dict(bot) for bot in bots]
|
||||
def get_all_bots():
|
||||
"""Mengambil semua data bot dari database."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
bots = conn.execute('SELECT * FROM bots ORDER BY id DESC').fetchall()
|
||||
return [dict(row) for row in bots]
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Database error saat mengambil semua bot: {e}")
|
||||
return []
|
||||
|
||||
def get_bot_by_id(bot_id):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
conn.row_factory = sqlite3.Row
|
||||
cursor = conn.cursor()
|
||||
cursor.execute("SELECT * FROM bots WHERE id = ?", (bot_id,))
|
||||
row = cursor.fetchone()
|
||||
conn.close()
|
||||
return dict(row) if row else None
|
||||
"""Mengambil satu data bot berdasarkan ID-nya."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
bot = conn.execute('SELECT * FROM bots WHERE id = ?', (bot_id,)).fetchone()
|
||||
return dict(bot) if bot else None
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Database error saat mengambil bot {bot_id}: {e}")
|
||||
return None
|
||||
|
||||
def add_bot(name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy):
|
||||
"""Menambahkan bot baru ke database."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO bots (name, market, lot_size, sl_pips, tp_pips, timeframe, check_interval_seconds, strategy, status)
|
||||
VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'Dijeda')
|
||||
''', (name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy))
|
||||
conn.commit()
|
||||
return cursor.lastrowid
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Gagal menambah bot ke DB: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def update_bot(bot_id, name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
UPDATE bots SET name=?, market=?, lot_size=?, sl_pips=?, tp_pips=?, timeframe=?, check_interval_seconds=?, strategy=?
|
||||
WHERE id=?
|
||||
''', (name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy, bot_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
"""Memperbarui data bot yang sudah ada di database."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
conn.execute('''
|
||||
UPDATE bots SET
|
||||
name = ?, market = ?, lot_size = ?, sl_pips = ?, tp_pips = ?,
|
||||
timeframe = ?, check_interval_seconds = ?, strategy = ?
|
||||
WHERE id = ?
|
||||
''', (name, market, lot_size, sl_pips, tp_pips, timeframe, interval, strategy, bot_id))
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Gagal memperbarui bot {bot_id} di DB: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
def hapus_bot(bot_id):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('DELETE FROM bots WHERE id=?', (bot_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
def delete_bot(bot_id):
|
||||
"""Menghapus bot dari database berdasarkan ID."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
conn.execute('DELETE FROM bots WHERE id = ?', (bot_id,))
|
||||
conn.commit()
|
||||
return True
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Gagal menghapus bot {bot_id} dari DB: {e}", exc_info=True)
|
||||
return False
|
||||
|
||||
def tambah_history(bot_id, action, details):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO trade_history (bot_id, action, details)
|
||||
VALUES (?, ?, ?)
|
||||
''', (bot_id, action, details))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
def update_bot_status(bot_id, status):
|
||||
"""Memperbarui status bot (Aktif/Dijeda) di database."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
conn.execute('UPDATE bots SET status = ? WHERE id = ?', (status, bot_id))
|
||||
conn.commit()
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Gagal update status bot {bot_id}: {e}")
|
||||
|
||||
def tambah_notifikasi(bot_id, message):
|
||||
conn = sqlite3.connect('bots.db')
|
||||
cursor = conn.cursor()
|
||||
cursor.execute('''
|
||||
INSERT INTO notifications (bot_id, message)
|
||||
VALUES (?, ?)
|
||||
''', (bot_id, message))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
def add_history_log(bot_id, action, details):
|
||||
"""Menambahkan log aktivitas/riwayat untuk bot tertentu."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
conn.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, action, details)
|
||||
)
|
||||
conn.commit()
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Gagal mencatat riwayat untuk bot {bot_id}: {e}")
|
||||
|
||||
def get_history_by_bot_id(bot_id):
|
||||
"""Mengambil semua riwayat dari satu bot berdasarkan ID."""
|
||||
try:
|
||||
with get_db_connection() as conn:
|
||||
history = conn.execute(
|
||||
'SELECT * FROM trade_history WHERE bot_id = ? ORDER BY timestamp DESC',
|
||||
(bot_id,)
|
||||
).fetchall()
|
||||
return [dict(row) for row in history]
|
||||
except sqlite3.Error as e:
|
||||
logger.error(f"Database error saat mengambil riwayat bot {bot_id}: {e}")
|
||||
return []
|
||||
@@ -3,14 +3,12 @@ import locale
|
||||
|
||||
locale.setlocale(locale.LC_NUMERIC, 'C')
|
||||
|
||||
|
||||
def parse_decimal(val):
|
||||
try:
|
||||
return float(str(val).replace(',', '.'))
|
||||
except Exception:
|
||||
return 0.0
|
||||
|
||||
|
||||
def initialize_mt5(account, password, server):
|
||||
if not mt5.initialize():
|
||||
print("Gagal inisialisasi MT5:", mt5.last_error())
|
||||
@@ -22,7 +20,6 @@ def initialize_mt5(account, password, server):
|
||||
print(f"Berhasil login ke akun MT5: {account} di server {server}")
|
||||
return True
|
||||
|
||||
|
||||
def place_trade(symbol, trade_type, lot, sl_pips, tp_pips, magic_number):
|
||||
info = mt5.symbol_info(symbol)
|
||||
if info is None:
|
||||
@@ -53,7 +50,6 @@ def place_trade(symbol, trade_type, lot, sl_pips, tp_pips, magic_number):
|
||||
print(f"Order dikirim! Ticket: {result.order}")
|
||||
return result
|
||||
|
||||
|
||||
def close_trade(position):
|
||||
price = mt5.symbol_info_tick(position.symbol).bid if position.type == mt5.ORDER_TYPE_BUY else mt5.symbol_info_tick(position.symbol).ask
|
||||
close_request = {
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
from .api_profile import api_profile
|
||||
from .api_dashboard import api_dashboard
|
||||
from .api_chart import api_chart
|
||||
from .api_bots import api_bots
|
||||
from .api_indicators import api_indicators
|
||||
from .api_bots_analysis import api_bots_analysis
|
||||
from .api_bots_fundamentals import api_bots_fundamentals
|
||||
from .api_portfolio import api_portfolio
|
||||
from .api_history import api_history
|
||||
from .api_notifications import api_notifications
|
||||
from .api_stocks import api_stocks
|
||||
from .api_forex import api_forex
|
||||
from .api_crypto import api_crypto
|
||||
from .api_analysis import api_analysis
|
||||
from .api_fundamentals import api_fundamentals
|
||||
|
||||
@@ -1,53 +0,0 @@
|
||||
# core/routes/api_analysis.py
|
||||
from flask import Blueprint, jsonify, request
|
||||
from core.bots.controller import get_active_bot
|
||||
from core.strategies.ma_crossover import analyze
|
||||
from core.strategies.rsi_breakout import analyze
|
||||
from core.strategies.pulse_sync import analyze
|
||||
from core.strategies.mercy_edge import analyze
|
||||
|
||||
api_analysis = Blueprint("api_analysis", __name__)
|
||||
|
||||
@api_analysis.route("/api/bots/<int:bot_id>/analysis")
|
||||
def get_bot_analysis(bot_id):
|
||||
bot = get_active_bot(bot_id)
|
||||
if not bot:
|
||||
return jsonify({'error': 'Bot tidak ditemukan di memori'}), 404
|
||||
|
||||
|
||||
tf = bot.tf_map.get(bot.timeframe)
|
||||
|
||||
result = {
|
||||
"price": None,
|
||||
"signal": "-",
|
||||
"strategy": bot.strategy,
|
||||
"explanation": "",
|
||||
"extra": {}
|
||||
}
|
||||
|
||||
try:
|
||||
# Ambil analisis berdasarkan strategi
|
||||
if bot.strategy == "MA_CROSSOVER":
|
||||
df = bot.fetch_data(tf, 100)
|
||||
analysis = analyze(df)
|
||||
elif bot.strategy == "RSI_BREAKOUT":
|
||||
df = bot.fetch_data(tf, 100)
|
||||
analysis = analyze(df)
|
||||
elif bot.strategy == "PULSE_SYNC":
|
||||
df = bot.fetch_data(tf, 100)
|
||||
analysis = analyze(df)
|
||||
elif bot.strategy == "MERCY_EDGE":
|
||||
analysis = analyze(bot)
|
||||
else:
|
||||
analysis = None
|
||||
|
||||
if analysis:
|
||||
result["price"] = float(analysis.get("price", 0))
|
||||
result["signal"] = analysis.get("signal", "-")
|
||||
result["explanation"] = analysis.get("explanation", "")
|
||||
result["extra"] = {k: v for k, v in analysis.items() if k not in ["price", "signal", "explanation"]}
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
except Exception as e:
|
||||
return jsonify({"error": str(e)})
|
||||
+117
-140
@@ -1,157 +1,134 @@
|
||||
# core/routes/api_bots.py
|
||||
# core/routes/api_bots.py - VERSI PERBAIKAN LENGKAP
|
||||
|
||||
from flask import Blueprint, request, jsonify
|
||||
from core.db.queries import get_db_connection
|
||||
from core.bots.trading_bot import TradingBot
|
||||
from core.bots.controller import active_bots
|
||||
from core.utils.validation import validate_bot_params
|
||||
import sqlite3
|
||||
import logging
|
||||
from flask import Blueprint, jsonify, request
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from core.bots import controller
|
||||
from core.db import queries
|
||||
from core.data.fetch import get_rates
|
||||
from core.utils.mt5 import TIMEFRAME_MAP
|
||||
from core.strategies.strategy_map import STRATEGY_MAP
|
||||
|
||||
api_bots = Blueprint('api_bots', __name__)
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
@api_bots.route('/api/strategies', methods=['GET'])
|
||||
def get_strategies_route():
|
||||
try:
|
||||
strategies = []
|
||||
for key, strategy_class in STRATEGY_MAP.items():
|
||||
strategies.append({
|
||||
'id': key,
|
||||
'name': getattr(strategy_class, 'name', key.replace('_', ' ').title()),
|
||||
'description': getattr(strategy_class, 'description', 'No description available.')
|
||||
})
|
||||
return jsonify(strategies)
|
||||
except Exception as e:
|
||||
logger.error(f"Gagal memuat daftar strategi: {e}", exc_info=True)
|
||||
return jsonify({"error": "Gagal memuat daftar strategi"}), 500
|
||||
|
||||
@api_bots.route('/api/bots', methods=['GET'])
|
||||
def get_bots():
|
||||
conn = get_db_connection()
|
||||
bots = conn.execute('SELECT * FROM bots').fetchall()
|
||||
conn.close()
|
||||
return jsonify([dict(bot) for bot in bots])
|
||||
def get_bots_route():
|
||||
"""Mengambil semua bot."""
|
||||
bots = queries.get_all_bots()
|
||||
# Perkaya data bot dengan nama strategi yang mudah dibaca
|
||||
for bot in bots:
|
||||
strategy_key = bot.get('strategy')
|
||||
strategy_class = STRATEGY_MAP.get(strategy_key)
|
||||
if strategy_class:
|
||||
bot['strategy_name'] = getattr(strategy_class, 'name', strategy_key)
|
||||
else:
|
||||
bot['strategy_name'] = strategy_key # Fallback jika tidak ditemukan
|
||||
return jsonify(bots)
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>', methods=['GET'])
|
||||
def get_bot(bot_id):
|
||||
conn = get_db_connection()
|
||||
bot = conn.execute('SELECT * FROM bots WHERE id = ?', (bot_id,)).fetchone()
|
||||
conn.close()
|
||||
if not bot:
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
return jsonify(dict(bot))
|
||||
def get_single_bot_route(bot_id):
|
||||
"""Mengambil detail satu bot."""
|
||||
bot = queries.get_bot_by_id(bot_id)
|
||||
return jsonify(bot) if bot else (jsonify({"error": "Bot tidak ditemukan"}), 404)
|
||||
|
||||
@api_bots.route('/api/bots', methods=['POST'])
|
||||
def create_bot():
|
||||
data = request.json
|
||||
errors = validate_bot_params(data)
|
||||
if errors:
|
||||
return jsonify({'error': errors}), 400
|
||||
|
||||
bot_name = data['name']
|
||||
bot_market = data['market']
|
||||
lot_size = data.get('lot_size', 0.01)
|
||||
sl_pips = data.get('sl_pips', 100)
|
||||
tp_pips = data.get('tp_pips', 200)
|
||||
timeframe = data.get('timeframe', 'H1')
|
||||
check_interval = data.get('check_interval_seconds', 60)
|
||||
strategy = data.get('strategy', 'MA_CROSSOVER')
|
||||
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
'INSERT INTO bots (name, market, status, lot_size, sl_pips, tp_pips, timeframe, check_interval_seconds, strategy) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
||||
(bot_name, bot_market, 'Dijeda', lot_size, sl_pips, tp_pips, timeframe, check_interval, strategy)
|
||||
)
|
||||
bot_id = cursor.lastrowid
|
||||
cursor.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, 'Dibuat', f"Bot '{bot_name}' ({strategy}) untuk pasar '{bot_market}' telah dibuat.")
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
|
||||
new_bot = TradingBot(bot_id=bot_id, name=bot_name, market=bot_market,
|
||||
status='Dijeda', lot_size=float(lot_size),
|
||||
sl_pips=int(sl_pips), tp_pips=int(tp_pips),
|
||||
timeframe=timeframe, check_interval_seconds=int(check_interval),
|
||||
strategy=strategy)
|
||||
active_bots[bot_id] = new_bot
|
||||
|
||||
return jsonify({'message': 'Bot berhasil dibuat', 'bot_id': bot_id}), 201
|
||||
except Exception as e:
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>/start', methods=['POST'])
|
||||
def start_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot:
|
||||
bot.start()
|
||||
conn = get_db_connection()
|
||||
conn.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, 'Mulai', 'Bot diaktifkan oleh pengguna.')
|
||||
)
|
||||
conn.execute('UPDATE bots SET status = ? WHERE id = ?', ('Aktif', bot_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'message': f'Bot {bot.name} dimulai.'})
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>/stop', methods=['POST'])
|
||||
def stop_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if bot:
|
||||
bot.stop()
|
||||
conn = get_db_connection()
|
||||
conn.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, 'Berhenti', 'Bot dijeda oleh pengguna.')
|
||||
)
|
||||
conn.execute('UPDATE bots SET status = ? WHERE id = ?', ('Dijeda', bot_id))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
return jsonify({'message': f'Bot {bot.name} dihentikan.'})
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
def add_bot_route():
|
||||
"""Membuat bot baru."""
|
||||
data = request.get_json()
|
||||
new_bot_id = queries.add_bot(
|
||||
name=data.get('name'), market=data.get('market'), lot_size=data.get('lot_size'),
|
||||
sl_pips=data.get('sl_pips'), tp_pips=data.get('tp_pips'), timeframe=data.get('timeframe'),
|
||||
interval=data.get('check_interval_seconds'), strategy=data.get('strategy')
|
||||
)
|
||||
if new_bot_id:
|
||||
controller.add_new_bot_to_controller(new_bot_id)
|
||||
return jsonify({"message": "Bot berhasil dibuat", "bot_id": new_bot_id}), 201
|
||||
return jsonify({"error": "Gagal menyimpan bot"}), 500
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>', methods=['PUT'])
|
||||
def update_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if not bot:
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
def update_bot_route(bot_id):
|
||||
"""Memperbarui pengaturan bot."""
|
||||
bot_data = request.get_json()
|
||||
|
||||
bot_instance = controller.get_bot_instance_by_id(bot_id)
|
||||
bot_was_running = bot_instance and bot_instance.status == 'Aktif'
|
||||
|
||||
data = request.json
|
||||
errors = validate_bot_params(data)
|
||||
if errors:
|
||||
return jsonify({'error': errors}), 400
|
||||
|
||||
try:
|
||||
conn = get_db_connection()
|
||||
details = f"Pengaturan diubah: Nama='{data['name']}', Strategi='{data['strategy']}', Pasar='{data['market']}', Lot={data['lot_size']}, SL={data['sl_pips']}, TP={data['tp_pips']}, TF='{data['timeframe']}'"
|
||||
conn.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, 'Edit', details)
|
||||
)
|
||||
conn.execute(
|
||||
'''UPDATE bots SET name = ?, market = ?, lot_size = ?, sl_pips = ?, tp_pips = ?, timeframe = ?, check_interval_seconds = ?, strategy = ?
|
||||
WHERE id = ?''',
|
||||
(data['name'], data['market'], data['lot_size'], data['sl_pips'], data['tp_pips'],
|
||||
data['timeframe'], data['check_interval_seconds'], data['strategy'], bot_id)
|
||||
)
|
||||
conn.commit()
|
||||
conn.close()
|
||||
except Exception as e:
|
||||
return jsonify({'error': f'Gagal memperbarui bot: {str(e)}'}), 500
|
||||
|
||||
bot.name = data['name']
|
||||
bot.market = data['market']
|
||||
bot.lot_size = float(data['lot_size'])
|
||||
bot.sl_pips = int(data['sl_pips'])
|
||||
bot.tp_pips = int(data['tp_pips'])
|
||||
bot.timeframe = data['timeframe']
|
||||
bot.check_interval = int(data['check_interval_seconds'])
|
||||
bot.strategy = data['strategy']
|
||||
|
||||
return jsonify({'message': f'Bot {bot.name} berhasil diperbarui.'})
|
||||
success, result = controller.perbarui_bot(bot_id, bot_data)
|
||||
|
||||
if success:
|
||||
if bot_was_running:
|
||||
controller.mulai_bot(bot_id)
|
||||
return jsonify({"message": "Bot berhasil diperbarui."}), 200
|
||||
|
||||
return jsonify({"error": result or "Gagal memperbarui bot"}), 500
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>', methods=['DELETE'])
|
||||
def delete_bot(bot_id):
|
||||
bot = active_bots.get(bot_id)
|
||||
if not bot:
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
def delete_bot_route(bot_id):
|
||||
"""Menghapus bot."""
|
||||
if controller.hapus_bot(bot_id):
|
||||
return jsonify({"message": "Bot berhasil dihapus."}), 200
|
||||
else:
|
||||
return jsonify({"error": "Gagal menghapus bot dari database"}), 500
|
||||
|
||||
bot.stop()
|
||||
del active_bots[bot_id]
|
||||
@api_bots.route('/api/bots/<int:bot_id>/start', methods=['POST'])
|
||||
def start_bot_route(bot_id):
|
||||
"""Memulai bot."""
|
||||
success, message = controller.mulai_bot(bot_id)
|
||||
return jsonify({'message': message}) if success else (jsonify({'error': message}), 500)
|
||||
|
||||
conn = get_db_connection()
|
||||
conn.execute('DELETE FROM trade_history WHERE bot_id = ?', (bot_id,))
|
||||
conn.execute('DELETE FROM bots WHERE id = ?', (bot_id,))
|
||||
conn.commit()
|
||||
conn.close()
|
||||
@api_bots.route('/api/bots/<int:bot_id>/stop', methods=['POST'])
|
||||
def stop_bot_route(bot_id):
|
||||
"""Menghentikan bot."""
|
||||
success, message = controller.stop_bot(bot_id)
|
||||
return jsonify({'message': message}) if success else (jsonify({'error': message}), 500)
|
||||
|
||||
return jsonify({'message': 'Bot dan riwayatnya berhasil dihapus.'})
|
||||
@api_bots.route('/api/bots/<int:bot_id>/analysis', methods=['GET'])
|
||||
def get_analysis_route(bot_id):
|
||||
"""Mendapatkan data analisis terakhir."""
|
||||
data = controller.get_bot_analysis_data(bot_id)
|
||||
return jsonify(data if data else {"signal": "Data belum tersedia"})
|
||||
|
||||
@api_bots.route('/api/bots/<int:bot_id>/history', methods=['GET'])
|
||||
def get_bot_history_route(bot_id):
|
||||
"""Mengembalikan riwayat aktivitas untuk bot."""
|
||||
history = queries.get_history_by_bot_id(bot_id)
|
||||
return jsonify(history)
|
||||
|
||||
@api_bots.route('/api/rsi_data', methods=['GET'])
|
||||
def get_rsi_data_route():
|
||||
"""Menyediakan data RSI untuk grafik di dashboard."""
|
||||
symbol = request.args.get('symbol', 'EURUSD', type=str)
|
||||
timeframe_str = request.args.get('timeframe', 'H1', type=str)
|
||||
|
||||
timeframe = TIMEFRAME_MAP.get(timeframe_str, mt5.TIMEFRAME_H1)
|
||||
|
||||
df = get_rates(symbol, timeframe, 100)
|
||||
|
||||
if df is None or df.empty:
|
||||
return jsonify({"error": f"Tidak dapat mengambil data untuk {symbol}"}), 404
|
||||
|
||||
df['rsi'] = ta.rsi(df['close'], length=14)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
chart_data = {
|
||||
'timestamps': [dt.strftime('%H:%M') for dt in df['time'].tail(50)],
|
||||
'rsi_values': list(df['rsi'].tail(50))
|
||||
}
|
||||
return jsonify(chart_data)
|
||||
@@ -1,109 +0,0 @@
|
||||
# core/routes/api_bots_analysis.py
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
from core.bots.manager import active_bots
|
||||
from core.data.fetch import get_rates as get_rates_from_mt5
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
import pandas as pd
|
||||
|
||||
api_bots_analysis = Blueprint('api_bots_analysis', __name__)
|
||||
|
||||
@api_bots_analysis.route('/api/bots/<int:bot_id>/analysis')
|
||||
def get_bot_analysis(bot_id):
|
||||
bot_obj = active_bots.get(bot_id)
|
||||
if not bot_obj:
|
||||
return jsonify({'error': 'Objek bot tidak ditemukan di memori'}), 404
|
||||
|
||||
strategy = bot_obj.strategy
|
||||
symbol = bot_obj.market.replace('/', '')
|
||||
response_data = {}
|
||||
|
||||
try:
|
||||
# --- LOGIKA DINAMIS BERDASARKAN STRATEGI ---
|
||||
|
||||
if strategy == 'MA_CROSSOVER':
|
||||
df = get_rates_from_mt5(symbol, bot_obj.mt5_timeframe, 52)
|
||||
if df is None or len(df) < 51: return jsonify({'error': 'Data tidak cukup'}), 400
|
||||
|
||||
df["ma_fast"] = ta.sma(df["close"], length=20)
|
||||
df["ma_slow"] = ta.sma(df["close"], length=50)
|
||||
df.dropna(inplace=True)
|
||||
if df.empty: return jsonify({'error': 'Indikator belum matang'}), 400
|
||||
|
||||
last = df.iloc[-1]
|
||||
signal = "BULLISH (Beli)" if last['ma_fast'] > last['ma_slow'] else "BEARISH (Jual)"
|
||||
|
||||
response_data = {
|
||||
"price": last['close'],
|
||||
"ma_fast": last['ma_fast'],
|
||||
"ma_slow": last['ma_slow'],
|
||||
"signal": signal
|
||||
}
|
||||
|
||||
elif strategy == 'RSI_BREAKOUT':
|
||||
df = get_rates_from_mt5(symbol, bot_obj.mt5_timeframe, 15)
|
||||
if df is None or len(df) < 15: return jsonify({'error': 'Data tidak cukup'}), 400
|
||||
|
||||
df["rsi"] = ta.rsi(df["close"], length=14)
|
||||
df.dropna(inplace=True)
|
||||
if df.empty: return jsonify({'error': 'Indikator belum matang'}), 400
|
||||
|
||||
last = df.iloc[-1]
|
||||
signal = "NETRAL"
|
||||
if last['rsi'] > 70: signal = "OVERBOUGHT (Jual)"
|
||||
elif last['rsi'] < 30: signal = "OVERSOLD (Beli)"
|
||||
|
||||
response_data = {
|
||||
"price": last['close'],
|
||||
"rsi": last['rsi'],
|
||||
"signal": signal
|
||||
}
|
||||
|
||||
elif strategy in ['MERCY_EDGE', 'FULL_MERCY']:
|
||||
df_d1 = get_rates_from_mt5(symbol, mt5.TIMEFRAME_D1, 200)
|
||||
df_h1 = get_rates_from_mt5(symbol, bot_obj.mt5_timeframe, 100)
|
||||
if df_d1 is None or df_h1 is None or len(df_d1) < 50 or len(df_h1) < 30:
|
||||
return jsonify({'error': 'Data tidak cukup'}), 400
|
||||
|
||||
df_d1.ta.macd(append=True)
|
||||
df_h1.ta.macd(append=True)
|
||||
df_h1.ta.stoch(append=True)
|
||||
df_d1.dropna(inplace=True)
|
||||
df_h1.dropna(inplace=True)
|
||||
if df_d1.empty or df_h1.empty: return jsonify({'error': 'Indikator belum matang'}), 400
|
||||
|
||||
last_d1 = df_d1.iloc[-1]
|
||||
last_h1 = df_h1.iloc[-1]
|
||||
|
||||
signal = "TAHAN"
|
||||
if last_d1['MACDh_12_26_9'] > 0 and last_h1['MACDh_12_26_9'] > 0: signal = "BULLISH (Beli)"
|
||||
elif last_d1['MACDh_12_26_9'] < 0 and last_h1['MACDh_12_26_9'] < 0: signal = "BEARISH (Jual)"
|
||||
|
||||
# ** PERBAIKAN KUNCI DI SINI: Samakan nama kunci dengan yang diharapkan JavaScript **
|
||||
response_data = {
|
||||
"price": last_h1['close'],
|
||||
"D1_MACDh": last_d1['MACDh_12_26_9'],
|
||||
"H1_MACDh": last_h1['MACDh_12_26_9'],
|
||||
"H1_STOCHk": last_h1['STOCHk_14_3_3'],
|
||||
"H1_STOCHd": last_h1['STOCHd_14_3_3'],
|
||||
"signal": signal
|
||||
}
|
||||
|
||||
else:
|
||||
last_price_df = get_rates_from_mt5(symbol, bot_obj.mt5_timeframe, 1)
|
||||
if last_price_df is not None and not last_price_df.empty:
|
||||
response_data = {
|
||||
"price": last_price_df.iloc[-1]['close'],
|
||||
"signal": "TAHAN",
|
||||
"info": f"UI Analisis untuk strategi '{strategy}' belum diimplementasikan."
|
||||
}
|
||||
else:
|
||||
return jsonify({'error': 'Gagal mengambil harga terakhir'}), 400
|
||||
|
||||
return jsonify(response_data)
|
||||
|
||||
except Exception as e:
|
||||
print(f"CRITICAL ERROR in get_bot_analysis for bot {bot_id} ({strategy}): {e}")
|
||||
# Kirim error 500 yang jelas jika terjadi crash
|
||||
return jsonify({'error': 'Terjadi kesalahan internal di server saat melakukan analisis.'}), 500
|
||||
@@ -1,25 +1,10 @@
|
||||
# core/routes/api_bots_fundamentals.py
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
from core.db.queries import get_bot_by_id
|
||||
from flask import Blueprint
|
||||
|
||||
# Initialize blueprint
|
||||
api_bots_fundamentals = Blueprint('api_bots_fundamentals', __name__)
|
||||
|
||||
@api_bots_fundamentals.route('/api/bots/<int:bot_id>/fundamentals')
|
||||
def get_bot_fundamentals(bot_id):
|
||||
bot = get_bot_by_id(bot_id)
|
||||
if not bot:
|
||||
return jsonify({'error': 'Bot tidak ditemukan'}), 404
|
||||
|
||||
# Hanya untuk saham
|
||||
if '/' in bot['market']:
|
||||
return jsonify({}) # Kosong untuk forex/crypto
|
||||
|
||||
symbol = bot['market']
|
||||
recommendations = get_recommendation_trends(symbol)
|
||||
profile = get_company_profile(symbol)
|
||||
|
||||
return jsonify({
|
||||
'recommendations': recommendations,
|
||||
'profile': profile
|
||||
})
|
||||
# Define routes here
|
||||
@api_bots_fundamentals.route('/fundamental-data')
|
||||
def get_fundamental_data():
|
||||
# Sample route - implement actual functionality as needed
|
||||
return {'status': 'success', 'data': 'Fundamental data placeholder'}
|
||||
|
||||
@@ -11,11 +11,11 @@ def api_chart_data():
|
||||
symbol = request.args.get('symbol', 'EURUSD')
|
||||
df = get_rates_from_mt5(symbol, mt5.TIMEFRAME_H1, 100)
|
||||
|
||||
if df is None:
|
||||
if df is None or df.empty:
|
||||
return jsonify({"error": "Gagal mengambil data grafik"}), 500
|
||||
|
||||
chart_data = {
|
||||
"labels": df['time'].dt.strftime('%H:%M').tolist(),
|
||||
"labels": df.index.strftime('%H:%M').tolist(),
|
||||
"data": df['close'].tolist()
|
||||
}
|
||||
return jsonify(chart_data)
|
||||
|
||||
@@ -1,11 +1,39 @@
|
||||
# core/routes/api_crypto.py
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
from core.utils.external import get_crypto_data_from_cmc
|
||||
|
||||
# Initialize blueprint
|
||||
api_crypto = Blueprint('api_crypto', __name__)
|
||||
|
||||
@api_crypto.route('/api/cryptos')
|
||||
def get_cryptos():
|
||||
cryptos = get_crypto_data_from_cmc()
|
||||
return jsonify(cryptos)
|
||||
# Sample data for initial load
|
||||
SAMPLE_CRYPTO_DATA = [
|
||||
{
|
||||
'name': 'Bitcoin',
|
||||
'symbol': 'BTC',
|
||||
'price': 'Rp 1.234,567,890.00',
|
||||
'change': '+2.34%',
|
||||
'market_cap': 'Rp 2.345,678,901,234.00'
|
||||
},
|
||||
{
|
||||
'name': 'Ethereum',
|
||||
'symbol': 'ETH',
|
||||
'price': 'Rp 123,456,789.00',
|
||||
'change': '-1.23%',
|
||||
'market_cap': 'Rp 1.234,567,890,123.00'
|
||||
}
|
||||
]
|
||||
|
||||
@api_crypto.route('/api/crypto')
|
||||
def get_crypto_data():
|
||||
"""Get cryptocurrency market data"""
|
||||
try:
|
||||
# Try to get real data from CMC
|
||||
from core.utils.external import get_crypto_data_from_cmc
|
||||
real_data = get_crypto_data_from_cmc()
|
||||
|
||||
if real_data and len(real_data) > 0:
|
||||
return jsonify(real_data)
|
||||
|
||||
# Fallback to sample data if API fails
|
||||
return jsonify(SAMPLE_CRYPTO_DATA)
|
||||
except Exception as e:
|
||||
# Return error response
|
||||
return jsonify({'error': str(e)}), 500
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
from core.utils.symbols import get_forex_symbols
|
||||
from core.utils.external import get_mt5_symbol_profile
|
||||
|
||||
api_forex = Blueprint('api_forex', __name__)
|
||||
|
||||
@@ -11,3 +12,15 @@ def get_forex_data():
|
||||
if forex_symbols:
|
||||
return jsonify({s['name']: s for s in forex_symbols})
|
||||
return jsonify({})
|
||||
|
||||
@api_forex.route('/api/forex/<symbol>/profile')
|
||||
def get_forex_profile(symbol):
|
||||
profile = get_mt5_symbol_profile(symbol)
|
||||
if profile:
|
||||
return jsonify(profile)
|
||||
return jsonify({"error": "Could not fetch symbol profile from MT5"}), 404
|
||||
def get_forex_data():
|
||||
forex_symbols = get_forex_symbols()
|
||||
if forex_symbols:
|
||||
return jsonify({s['name']: s for s in forex_symbols})
|
||||
return jsonify({})
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
from flask import Blueprint, jsonify
|
||||
import sqlite3
|
||||
from core.utils.external import get_recommendation_trends, get_company_profile
|
||||
|
||||
|
||||
api_fundamentals = Blueprint('api_fundamentals', __name__)
|
||||
|
||||
@@ -23,7 +23,4 @@ def get_bot_fundamentals(bot_id):
|
||||
return jsonify({}) # Skip if not stock
|
||||
|
||||
symbol = bot['market']
|
||||
return jsonify({
|
||||
'recommendations': get_recommendation_trends(symbol),
|
||||
'profile': get_company_profile(symbol)
|
||||
})
|
||||
return jsonify({})
|
||||
|
||||
+35
-37
@@ -1,59 +1,57 @@
|
||||
# core/routes/api_stocks.py
|
||||
|
||||
from flask import Blueprint, jsonify, request
|
||||
from flask import Blueprint, jsonify
|
||||
import MetaTrader5 as mt5 # Dipertahankan untuk mt5.terminal_info() jika diperlukan
|
||||
from core.utils.symbols import get_stock_symbols
|
||||
import MetaTrader5 as mt5
|
||||
import pandas as pd
|
||||
from core.utils.external import get_mt5_symbol_profile
|
||||
from core.data.fetch import get_rates # <-- Impor fungsi terpusat
|
||||
|
||||
api_stocks = Blueprint('api_stocks', __name__)
|
||||
|
||||
@api_stocks.route('/api/stocks/<symbol>/profile')
|
||||
def get_stock_profile(symbol):
|
||||
profile = get_mt5_symbol_profile(symbol)
|
||||
if profile:
|
||||
return jsonify(profile)
|
||||
return jsonify({"error": "Could not fetch symbol profile from MT5"}), 404
|
||||
|
||||
@api_stocks.route('/api/stocks')
|
||||
def get_stocks():
|
||||
if not mt5.terminal_info():
|
||||
if not mt5.initialize():
|
||||
return jsonify({"error": "MT5 connection failed"}), 500
|
||||
|
||||
stock_symbols = get_stock_symbols()
|
||||
result = []
|
||||
|
||||
for stock in stock_symbols[:20]: # Max 20 untuk UI
|
||||
symbol = stock['name']
|
||||
rates = mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_M1, 0, 1)
|
||||
# Gunakan fungsi dari fetch.py
|
||||
df = get_rates(symbol, mt5.TIMEFRAME_M1, 2) # Ambil 2 bar untuk hitung change
|
||||
|
||||
if rates is not None and len(rates) > 0:
|
||||
last = rates[0]
|
||||
try:
|
||||
result.append({
|
||||
'symbol': symbol,
|
||||
'last_price': last['close'],
|
||||
'change': round(last['close'] - last['open'], 2),
|
||||
'time': pd.to_datetime(last['time'], unit='s').strftime('%H:%M')
|
||||
})
|
||||
except Exception:
|
||||
pass
|
||||
if df is not None and not df.empty and len(df) > 1:
|
||||
last_row = df.iloc[-1]
|
||||
prev_row = df.iloc[-2]
|
||||
result.append({
|
||||
'symbol': symbol,
|
||||
'last_price': last_row['close'],
|
||||
'change': round(last_row['close'] - prev_row['close'], 2), # Perubahan dari close sebelumnya
|
||||
'time': last_row['time'].strftime('%H:%M')
|
||||
})
|
||||
|
||||
return jsonify(result)
|
||||
|
||||
@api_stocks.route('/api/stocks/<symbol>')
|
||||
def get_stock_detail(symbol):
|
||||
if not mt5.terminal_info():
|
||||
if not mt5.initialize():
|
||||
return jsonify({"error": "MT5 connection failed"}), 500
|
||||
# Gunakan fungsi dari fetch.py
|
||||
df = get_rates(symbol, mt5.TIMEFRAME_M1, 1)
|
||||
|
||||
rates = mt5.copy_rates_from_pos(symbol, mt5.TIMEFRAME_M1, 0, 1)
|
||||
if not rates:
|
||||
if df is None or df.empty:
|
||||
return jsonify({"error": f"Tidak bisa mengambil data untuk {symbol}"}), 404
|
||||
|
||||
last = rates[0]
|
||||
try:
|
||||
return jsonify({
|
||||
"symbol": symbol,
|
||||
"time": pd.to_datetime(last['time'], unit='s').strftime('%Y-%m-%d %H:%M:%S'),
|
||||
"open": last['open'],
|
||||
"high": last['high'],
|
||||
"low": last['low'],
|
||||
"close": last['close'],
|
||||
"volume": last['tick_volume']
|
||||
})
|
||||
except Exception:
|
||||
return jsonify({"error": "Format data tidak valid"}), 500
|
||||
last = df.iloc[-1]
|
||||
return jsonify({
|
||||
"symbol": symbol,
|
||||
"time": last['time'].strftime('%Y-%m-%d %H:%M:%S'),
|
||||
"open": last['open'],
|
||||
"high": last['high'],
|
||||
"low": last['low'],
|
||||
"close": last['close'],
|
||||
"volume": last['tick_volume']
|
||||
})
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
# core/strategies/base_strategy.py
|
||||
|
||||
class BaseStrategy:
|
||||
"""
|
||||
Kelas dasar abstrak untuk semua strategi trading.
|
||||
Setiap strategi harus mewarisi kelas ini dan mengimplementasikan metode `analyze`.
|
||||
"""
|
||||
def __init__(self, bot_instance):
|
||||
"""
|
||||
Inisialisasi strategi dengan instance dari bot yang menjalankannya.
|
||||
|
||||
Args:
|
||||
bot_instance (TradingBot): Instance dari bot yang aktif.
|
||||
"""
|
||||
self.bot = bot_instance
|
||||
|
||||
def analyze(self):
|
||||
"""
|
||||
Metode inti yang harus di-override oleh setiap strategi turunan.
|
||||
Metode ini harus mengembalikan sebuah dictionary yang berisi hasil analisis.
|
||||
"""
|
||||
raise NotImplementedError("Setiap strategi harus mengimplementasikan metode `analyze()`.")
|
||||
@@ -0,0 +1,53 @@
|
||||
# /core/strategies/bollinger_bands.py
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.data.fetch import get_rates
|
||||
|
||||
class BollingerBandsStrategy(BaseStrategy):
|
||||
name = 'Bollinger Bands Reversion'
|
||||
description = 'Sinyal berdasarkan harga yang menyentuh atau melintasi batas atas atau bawah Bollinger Bands (Mean Reversion).'
|
||||
|
||||
def analyze(self):
|
||||
"""
|
||||
Menganalisis pasar menggunakan strategi Bollinger Bands® Mean Reversion.
|
||||
Ideal untuk pasar ranging yang volatil seperti EURUSD.
|
||||
"""
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
|
||||
# Butuh data yang cukup untuk BBands(20)
|
||||
df = get_rates(self.bot.market_for_mt5, tf_const, 21)
|
||||
|
||||
if df is None or df.empty or len(df) < 21:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup untuk Bollinger Bands."}
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
if len(df) < 1:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
last = df.iloc[-1]
|
||||
price = last["close"]
|
||||
signal = "HOLD"
|
||||
explanation = f"Harga [{price:.4f}] di dalam Bands. Tidak ada sinyal."
|
||||
|
||||
# --- Logika Sinyal ---
|
||||
# Sinyal Beli: Harga menyentuh atau menembus Band Bawah
|
||||
if last['low'] <= last['BBL_20_2.0']:
|
||||
signal = "BUY"
|
||||
explanation = f"Oversold: Harga [{last['low']:.4f}] menyentuh Band Bawah [{last['BBL_20_2.0']:.4f}]"
|
||||
# Sinyal Jual: Harga menyentuh atau menembus Band Atas
|
||||
elif last['high'] >= last['BBU_20_2.0']:
|
||||
signal = "SELL"
|
||||
explanation = f"Overbought: Harga [{last['high']:.4f}] menyentuh Band Atas [{last['BBU_20_2.0']:.4f}]"
|
||||
|
||||
analysis_data = {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation,
|
||||
"BB_Upper": last.get('BBU_20_2.0'),
|
||||
"BB_Middle": last.get('BBM_20_2.0'),
|
||||
"BB_Lower": last.get('BBL_20_2.0'),
|
||||
}
|
||||
return analysis_data
|
||||
@@ -0,0 +1,99 @@
|
||||
# /core/strategies/bollinger_squeeze.py
|
||||
import pandas_ta as ta
|
||||
import numpy as np
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.data.fetch import get_rates # <-- PERBAIKAN: Impor dari lokasi yang benar
|
||||
|
||||
class BollingerSqueezeStrategy(BaseStrategy):
|
||||
name = 'Bollinger Squeeze Breakout'
|
||||
description = 'Mencari periode volatilitas rendah (squeeze) sebagai sinyal potensi breakout harga yang kuat.'
|
||||
|
||||
def analyze(self):
|
||||
"""
|
||||
Menganalisis pasar menggunakan strategi Bollinger Band Squeeze.
|
||||
Strategi ini menunggu periode volatilitas rendah ("squeeze") lalu
|
||||
masuk saat harga breakout.
|
||||
"""
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
|
||||
# Butuh data yang cukup untuk rolling window squeeze (120) + BBands (20)
|
||||
df = get_rates(self.bot.market_for_mt5, tf_const, 150) # <-- PERBAIKAN: Gunakan fungsi yang benar
|
||||
|
||||
if df is None or df.empty or len(df) < 121:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup untuk Bollinger Squeeze."}
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df['BB_WIDTH'] = df['BBU_20_2.0'] - df['BBL_20_2.0']
|
||||
|
||||
# FIX 1: Mencegah ZeroDivisionError dengan pembagian yang aman
|
||||
df['BB_BANDWIDTH'] = np.where(
|
||||
df['BBM_20_2.0'] != 0,
|
||||
(df['BBU_20_2.0'] - df['BBL_20_2.0']) / df['BBM_20_2.0'] * 100,
|
||||
0 # Jika middle band 0, anggap bandwidth 0
|
||||
)
|
||||
|
||||
df['AVG_BANDWIDTH'] = df['BB_BANDWIDTH'].rolling(window=10).mean()
|
||||
df['SQUEEZE_LEVEL'] = df['AVG_BANDWIDTH'] * 0.7
|
||||
df['SQUEEZE'] = df['BB_BANDWIDTH'] < df['SQUEEZE_LEVEL']
|
||||
df['RSI'] = ta.rsi(df['close'], length=14)
|
||||
|
||||
# FIX 2: Menggunakan nama kolom volume yang benar ('tick_volume')
|
||||
if 'tick_volume' in df.columns:
|
||||
df['AVG_VOLUME'] = df['tick_volume'].rolling(window=10).mean()
|
||||
df['VOLUME_SURGE'] = df['tick_volume'] > df['AVG_VOLUME'] * 1.5
|
||||
df['VOLUME_SURGE'] = df['VOLUME_SURGE'].astype(int)
|
||||
else:
|
||||
df['VOLUME_SURGE'] = 0
|
||||
|
||||
df.dropna(inplace=True)
|
||||
|
||||
if len(df) < 2:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
last = df.iloc[-1]
|
||||
prev = df.iloc[-2]
|
||||
|
||||
price = last["close"]
|
||||
signal = "HOLD"
|
||||
explanation = "Tidak ada kondisi Squeeze & Breakout yang terdeteksi."
|
||||
|
||||
# --- Logika Sinyal ---
|
||||
|
||||
# Kondisi 1: Apakah candle SEBELUMNYA berada dalam kondisi "Squeeze"?
|
||||
is_in_squeeze = prev['SQUEEZE']
|
||||
|
||||
if is_in_squeeze:
|
||||
explanation = f"Squeeze terdeteksi (Lebar: {prev['BB_WIDTH']:.4f}). Menunggu breakout."
|
||||
|
||||
# Kondisi 2: Jika ya, apakah candle SEKARANG breakout dari Bands SEBELUMNYA?
|
||||
if last['close'] > prev['BBU_20_2.0'] and last['RSI'] < 70:
|
||||
signal = "BUY"
|
||||
explanation = f"Squeeze & Breakout NAIK! Harga [{last['close']:.2f}] > Band Atas [{prev['BBU_20_2.0']:.2f}]"
|
||||
elif last['close'] < prev['BBL_20_2.0'] and last['RSI'] > 30:
|
||||
signal = "SELL"
|
||||
explanation = f"Squeeze & Breakout TURUN! Harga [{last['close']:.2f}] < Band Bawah [{prev['BBL_20_2.0']:.2f}]"
|
||||
else:
|
||||
# Kondisi 3: Post-Squeeze Momentum
|
||||
if prev['BB_BANDWIDTH'] > prev['AVG_BANDWIDTH'] * 1.2: # Bands expanding
|
||||
if last['close'] > prev['BBU_20_2.0'] and last['VOLUME_SURGE']:
|
||||
signal = 'BUY'
|
||||
explanation = f"Momentum NAIK! Harga [{last['close']:.2f}] > Band Atas [{prev['BBU_20_2.0']:.2f}] dengan volume"
|
||||
elif last['close'] < prev['BBL_20_2.0'] and last['VOLUME_SURGE']:
|
||||
signal = 'SELL'
|
||||
explanation = f"Momentum TURUN! Harga [{last['close']:.2f}] < Band Bawah [{prev['BBL_20_2.0']:.2f}] dengan volume"
|
||||
|
||||
# --- PERBAIKAN: Kembalikan semua data analisis yang relevan ---
|
||||
analysis_data = {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation,
|
||||
"RSI": last.get('RSI'),
|
||||
"BB_Width": last.get('BB_WIDTH'),
|
||||
"BB_Bandwidth": last.get('BB_BANDWIDTH'),
|
||||
"Is_Squeeze": bool(last.get('SQUEEZE', False)), # FIX: Konversi numpy.bool_ ke bool standar
|
||||
"Volume_Surge": bool(last.get('VOLUME_SURGE', 0))
|
||||
}
|
||||
|
||||
return analysis_data
|
||||
@@ -0,0 +1,169 @@
|
||||
# core/strategies/bollinger_squeeze.py
|
||||
import pandas_ta as ta
|
||||
|
||||
def analyze(df):
|
||||
"""
|
||||
Bollinger Squeeze Strategy Analysis
|
||||
|
||||
Squeeze occurs when:
|
||||
1. Bollinger Bands width is narrow (low volatility)
|
||||
2. Price is consolidating
|
||||
|
||||
Breakout occurs when:
|
||||
1. Price breaks above/below Bollinger Bands
|
||||
2. After a squeeze period
|
||||
"""
|
||||
|
||||
if df is None or len(df) < 21:
|
||||
return 'HOLD'
|
||||
|
||||
try:
|
||||
# Calculate Bollinger Bands
|
||||
bb = ta.bbands(df['close'], length=20, std=2)
|
||||
|
||||
if bb is None or bb.empty:
|
||||
return 'HOLD'
|
||||
|
||||
# Get latest values
|
||||
latest = df.iloc[-1]
|
||||
current_price = latest['close']
|
||||
|
||||
# Bollinger Band values
|
||||
bb_upper = bb['BBU_20_2.0'].iloc[-1]
|
||||
bb_middle = bb['BBM_20_2.0'].iloc[-1] # SMA
|
||||
bb_lower = bb['BBL_20_2.0'].iloc[-1]
|
||||
|
||||
# Calculate bandwidth (volatility measure)
|
||||
bandwidth = (bb_upper - bb_lower) / bb_middle * 100
|
||||
|
||||
# Get historical bandwidth for comparison
|
||||
bb_bandwidth = (bb['BBU_20_2.0'] - bb['BBL_20_2.0']) / bb['BBM_20_2.0'] * 100
|
||||
avg_bandwidth = bb_bandwidth.rolling(window=10).mean().iloc[-1]
|
||||
|
||||
# Squeeze Detection
|
||||
# Squeeze occurs when current bandwidth is significantly lower than average
|
||||
squeeze_threshold = avg_bandwidth * 0.7 # 30% below average
|
||||
is_squeezing = bandwidth < squeeze_threshold
|
||||
|
||||
# Price position relative to bands
|
||||
price_position = (current_price - bb_lower) / (bb_upper - bb_lower)
|
||||
|
||||
# Momentum indicator (simple)
|
||||
rsi = ta.rsi(df['close'], length=14).iloc[-1]
|
||||
|
||||
# Volume analysis (if available)
|
||||
volume_surge = False
|
||||
if 'volume' in df.columns:
|
||||
avg_volume = df['volume'].rolling(window=10).mean().iloc[-1]
|
||||
current_volume = df['volume'].iloc[-1]
|
||||
volume_surge = current_volume > avg_volume * 1.5
|
||||
|
||||
# === SIGNAL LOGIC ===
|
||||
|
||||
# 1. Breakout from Squeeze (HIGH PRIORITY)
|
||||
if is_squeezing:
|
||||
# During squeeze, wait for breakout
|
||||
if current_price > bb_upper and rsi < 70:
|
||||
return 'BUY' # Bullish breakout
|
||||
elif current_price < bb_lower and rsi > 30:
|
||||
return 'SELL' # Bearish breakout
|
||||
else:
|
||||
return 'HOLD' # Still squeezing
|
||||
|
||||
# 2. Post-Squeeze Momentum
|
||||
elif bandwidth > avg_bandwidth * 1.2: # Bands expanding
|
||||
if price_position > 0.8 and volume_surge: # Near upper band with volume
|
||||
return 'BUY'
|
||||
elif price_position < 0.2 and volume_surge: # Near lower band with volume
|
||||
return 'SELL'
|
||||
|
||||
# 3. Mean Reversion (when not squeezing)
|
||||
else:
|
||||
if current_price > bb_upper and rsi > 70:
|
||||
return 'SELL' # Overbought
|
||||
elif current_price < bb_lower and rsi < 30:
|
||||
return 'BUY' # Oversold
|
||||
|
||||
return 'HOLD'
|
||||
|
||||
except Exception as e:
|
||||
print(f"Bollinger Squeeze Analysis Error: {e}")
|
||||
return 'HOLD'
|
||||
|
||||
def get_analysis_data(df):
|
||||
"""
|
||||
Return detailed analysis data for dashboard
|
||||
"""
|
||||
if df is None or len(df) < 21:
|
||||
return {
|
||||
'signal': 'HOLD',
|
||||
'explanation': 'Insufficient data for Bollinger analysis',
|
||||
'indicators': {}
|
||||
}
|
||||
|
||||
try:
|
||||
bb = ta.bbands(df['close'], length=20, std=2)
|
||||
|
||||
if bb is None or bb.empty:
|
||||
return {
|
||||
'signal': 'HOLD',
|
||||
'explanation': 'Unable to calculate Bollinger Bands',
|
||||
'indicators': {}
|
||||
}
|
||||
|
||||
# Get latest values
|
||||
latest = df.iloc[-1]
|
||||
current_price = latest['close']
|
||||
|
||||
bb_upper = bb['BBU_20_2.0'].iloc[-1]
|
||||
bb_middle = bb['BBM_20_2.0'].iloc[-1]
|
||||
bb_lower = bb['BBL_20_2.0'].iloc[-1]
|
||||
|
||||
bandwidth = (bb_upper - bb_lower) / bb_middle * 100
|
||||
bb_bandwidth = (bb['BBU_20_2.0'] - bb['BBL_20_2.0']) / bb['BBM_20_2.0'] * 100
|
||||
avg_bandwidth = bb_bandwidth.rolling(window=10).mean().iloc[-1]
|
||||
|
||||
is_squeezing = bandwidth < avg_bandwidth * 0.7
|
||||
price_position = (current_price - bb_lower) / (bb_upper - bb_lower)
|
||||
|
||||
signal = analyze(df)
|
||||
|
||||
# Generate explanation
|
||||
explanation = ""
|
||||
if is_squeezing:
|
||||
explanation = f"🔄 SQUEEZE detected! Bandwidth: {bandwidth:.2f}% (Avg: {avg_bandwidth:.2f}%). "
|
||||
if signal == 'BUY':
|
||||
explanation += "Bullish breakout above upper band!"
|
||||
elif signal == 'SELL':
|
||||
explanation += "Bearish breakout below lower band!"
|
||||
else:
|
||||
explanation += "Waiting for breakout..."
|
||||
else:
|
||||
explanation = f"📊 Normal volatility. Bandwidth: {bandwidth:.2f}%. "
|
||||
if signal == 'BUY':
|
||||
explanation += "Bullish momentum or oversold bounce."
|
||||
elif signal == 'SELL':
|
||||
explanation += "Bearish momentum or overbought correction."
|
||||
else:
|
||||
explanation += "No clear signal."
|
||||
|
||||
return {
|
||||
'signal': signal,
|
||||
'explanation': explanation,
|
||||
'indicators': {
|
||||
'bb_upper': round(bb_upper, 4),
|
||||
'bb_middle': round(bb_middle, 4),
|
||||
'bb_lower': round(bb_lower, 4),
|
||||
'bandwidth': round(bandwidth, 2),
|
||||
'avg_bandwidth': round(avg_bandwidth, 2),
|
||||
'is_squeezing': is_squeezing,
|
||||
'price_position': round(price_position * 100, 1)
|
||||
}
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
'signal': 'HOLD',
|
||||
'explanation': f'Analysis error: {str(e)}',
|
||||
'indicators': {}
|
||||
}
|
||||
@@ -1,43 +0,0 @@
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from core.data.fetch import get_rates as get_rates_from_mt5
|
||||
from core.bots.trade import place_trade, close_trade
|
||||
|
||||
|
||||
def run_ma_crossover(bot):
|
||||
print(f"[{bot.name}] Analisis MA_CROSSOVER aktif...")
|
||||
|
||||
symbol = bot.market.replace('/', '')
|
||||
df = get_rates_from_mt5(symbol, bot.mt5_timeframe, 100)
|
||||
|
||||
if df is None or len(df) < 50:
|
||||
print(f"[{bot.name}] Data tidak cukup.")
|
||||
return
|
||||
|
||||
df['SMA_fast'] = ta.sma(df['close'], length=20)
|
||||
df['SMA_slow'] = ta.sma(df['close'], length=50)
|
||||
last, prev = df.iloc[-1], df.iloc[-2]
|
||||
|
||||
if pd.isna(last['SMA_fast']) or pd.isna(last['SMA_slow']):
|
||||
return
|
||||
|
||||
pos = bot._get_open_position(symbol)
|
||||
|
||||
# --- SINYAL BELI ---
|
||||
if prev['SMA_fast'] <= prev['SMA_slow'] and last['SMA_fast'] > last['SMA_slow']:
|
||||
if pos and pos.type == mt5.ORDER_TYPE_SELL:
|
||||
close_trade(pos)
|
||||
bot._log_action("CLOSE SELL", "Tutup posisi jual karena sinyal BELI (MA)")
|
||||
if not pos or pos.type == mt5.ORDER_TYPE_SELL:
|
||||
bot._log_action("SINYAL BELI (MA)", "Cross up terdeteksi")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_BUY, bot.lot_size, bot.sl_pips, bot.tp_pips, bot.bot_id)
|
||||
|
||||
# --- SINYAL JUAL ---
|
||||
elif prev['SMA_fast'] >= prev['SMA_slow'] and last['SMA_fast'] < last['SMA_slow']:
|
||||
if pos and pos.type == mt5.ORDER_TYPE_BUY:
|
||||
close_trade(pos)
|
||||
bot._log_action("CLOSE BUY", "Tutup posisi beli karena sinyal JUAL (MA)")
|
||||
if not pos or pos.type == mt5.ORDER_TYPE_BUY:
|
||||
bot._log_action("SINYAL JUAL (MA)", "Cross down terdeteksi")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_SELL, bot.lot_size, bot.sl_pips, bot.tp_pips, bot.bot_id)
|
||||
@@ -1,31 +0,0 @@
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from core.data.fetch import get_rates as get_rates_from_mt5
|
||||
from core.bots.trade import place_trade
|
||||
|
||||
|
||||
def run_rsi_breakout(bot):
|
||||
print(f"[{bot.name}] Analisis RSI_BREAKOUT aktif...")
|
||||
|
||||
symbol = bot.market.replace('/', '')
|
||||
df = get_rates_from_mt5(symbol, bot.mt5_timeframe, 100)
|
||||
|
||||
if df is None or len(df) < 20:
|
||||
print(f"[{bot.name}] Data tidak cukup untuk analisis RSI.")
|
||||
return
|
||||
|
||||
df['RSI'] = ta.rsi(df['close'], length=14)
|
||||
last, prev = df.iloc[-1], df.iloc[-2]
|
||||
|
||||
if pd.isna(last['RSI']) or pd.isna(prev['RSI']):
|
||||
return
|
||||
|
||||
pos = bot._get_open_position(symbol)
|
||||
if not pos:
|
||||
if prev['RSI'] < 30 and last['RSI'] > 30:
|
||||
bot._log_action("SINYAL BELI (RSI)", f"Breakout RSI naik: {last['RSI']:.2f}")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_BUY, bot.lot_size, bot.sl_pips, bot.tp_pips, bot.bot_id)
|
||||
elif prev['RSI'] > 70 and last['RSI'] < 70:
|
||||
bot._log_action("SINYAL JUAL (RSI)", f"Breakout RSI turun: {last['RSI']:.2f}")
|
||||
place_trade(symbol, mt5.ORDER_TYPE_SELL, bot.lot_size, bot.sl_pips, bot.tp_pips, bot.bot_id)
|
||||
@@ -1,36 +1,53 @@
|
||||
# core/strategies/ma_crossover.py
|
||||
# /core/strategies/ma_crossover.py
|
||||
import pandas_ta as ta
|
||||
from core.data.fetch import get_rates
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.data.fetch import get_rates
|
||||
|
||||
def analyze(bot):
|
||||
symbol = bot.market.replace('/', '')
|
||||
tf = bot.tf_map.get(bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
df = get_rates(symbol, tf, 100)
|
||||
class MACrossoverStrategy(BaseStrategy):
|
||||
name = 'Moving Average Crossover'
|
||||
description = 'Sinyal berdasarkan persilangan antara dua Moving Averages (misal, 20 & 50). Cocok untuk pasar trending.'
|
||||
|
||||
if df is None or df.empty or len(df) < 30:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
def analyze(self):
|
||||
"""
|
||||
Menganalisis pasar menggunakan strategi Moving Average Crossover (20/50).
|
||||
Ideal untuk pasar dengan tren kuat seperti XAUUSD.
|
||||
"""
|
||||
# Mengakses properti dari instance bot yang tersimpan
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
|
||||
# Butuh data yang cukup untuk MA 50
|
||||
df = get_rates(self.bot.market_for_mt5, tf_const, 52)
|
||||
|
||||
df["ma7"] = ta.sma(df["close"], length=7)
|
||||
df["ma25"] = ta.sma(df["close"], length=25)
|
||||
df = df.dropna()
|
||||
last = df.iloc[-1]
|
||||
prev = df.iloc[-2]
|
||||
if df is None or df.empty or len(df) < 51:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup untuk MA Crossover."}
|
||||
|
||||
price = last["close"]
|
||||
# --- Hitung Indikator ---
|
||||
df["ma_fast"] = ta.sma(df["close"], length=20)
|
||||
df["ma_slow"] = ta.sma(df["close"], length=50)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
if len(df) < 2:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
signal = "HOLD"
|
||||
explanation = "Tidak ada crossover yang jelas"
|
||||
last = df.iloc[-1]
|
||||
prev = df.iloc[-2]
|
||||
|
||||
if prev["ma7"] < prev["ma25"] and last["ma7"] > last["ma25"]:
|
||||
signal = "BUY"
|
||||
explanation = "MA7 cross up MA25"
|
||||
elif prev["ma7"] > prev["ma25"] and last["ma7"] < last["ma25"]:
|
||||
signal = "SELL"
|
||||
explanation = "MA7 cross down MA25"
|
||||
price = last["close"]
|
||||
signal = "HOLD"
|
||||
explanation = f"MA(20): {last['ma_fast']:.2f}, MA(50): {last['ma_slow']:.2f}. Tidak ada sinyal."
|
||||
|
||||
return {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation
|
||||
}
|
||||
# --- Logika Sinyal ---
|
||||
# Golden Cross (Sinyal Beli)
|
||||
if prev["ma_fast"] <= prev["ma_slow"] and last["ma_fast"] > last["ma_slow"]:
|
||||
signal = "BUY"
|
||||
explanation = f"Golden Cross: MA(20) [{last['ma_fast']:.2f}] memotong ke atas MA(50) [{last['ma_slow']:.2f}]"
|
||||
# Death Cross (Sinyal Jual)
|
||||
elif prev["ma_fast"] >= prev["ma_slow"] and last["ma_fast"] < last["ma_slow"]:
|
||||
signal = "SELL"
|
||||
explanation = f"Death Cross: MA(20) [{last['ma_fast']:.2f}] memotong ke bawah MA(50) [{last['ma_slow']:.2f}]"
|
||||
|
||||
return {
|
||||
"signal": signal, "price": price, "explanation": explanation,
|
||||
"ma_fast": last['ma_fast'], "ma_slow": last['ma_slow']
|
||||
}
|
||||
@@ -1,68 +1,57 @@
|
||||
# core/strategies/mercy_edge.py
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from core.data.fetch import get_rates
|
||||
from core.utils.ollama import ask_ollama
|
||||
from core.utils.trade import place_trade
|
||||
import pandas_ta as ta
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.utils.mt5 import get_rates_from_mt5
|
||||
|
||||
def analyze(bot):
|
||||
symbol = bot.market.replace('/', '')
|
||||
df_d1 = get_rates(symbol, mt5.TIMEFRAME_D1, 200)
|
||||
df_h1 = get_rates(symbol, mt5.TIMEFRAME_H1, 100)
|
||||
class MercyEdgeStrategy(BaseStrategy):
|
||||
name = 'Mercy Edge (AI)'
|
||||
description = 'Strategi hybrid yang menggabungkan MACD, Stochastic, dan validasi AI untuk sinyal presisi tinggi.'
|
||||
|
||||
if df_d1 is None or df_h1 is None or len(df_d1) < 50 or len(df_h1) < 30:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
def analyze(self):
|
||||
df_d1 = get_rates_from_mt5(self.bot.market_for_mt5, mt5.TIMEFRAME_D1, 200)
|
||||
df_h1 = get_rates_from_mt5(self.bot.market_for_mt5, mt5.TIMEFRAME_H1, 100)
|
||||
|
||||
macd_d1 = ta.macd(df_d1['close']).rename(columns={'MACDh_12_26_9': 'hist_d1'})
|
||||
macd_h1 = ta.macd(df_h1['close']).rename(columns={'MACDh_12_26_9': 'hist_h1'})
|
||||
stoch = ta.stoch(df_h1['high'], df_h1['low'], df_h1['close'])
|
||||
if df_d1 is None or df_h1 is None or len(df_d1) < 50 or len(df_h1) < 30:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
|
||||
df_d1 = df_d1.join(macd_d1)
|
||||
df_h1 = df_h1.join(macd_h1)
|
||||
df_h1['stoch_k'] = stoch.iloc[:, 0]
|
||||
df_h1['stoch_d'] = stoch.iloc[:, 1]
|
||||
macd_d1 = ta.macd(df_d1['close']).rename(columns={'MACDh_12_26_9': 'hist_d1'})
|
||||
macd_h1 = ta.macd(df_h1['close']).rename(columns={'MACDh_12_26_9': 'hist_h1'})
|
||||
stoch = ta.stoch(df_h1['high'], df_h1['low'], df_h1['close'])
|
||||
|
||||
last_d1 = df_d1.iloc[-1]
|
||||
last_h1 = df_h1.iloc[-1]
|
||||
prev_h1 = df_h1.iloc[-2]
|
||||
df_d1 = df_d1.join(macd_d1).dropna()
|
||||
df_h1 = df_h1.join(macd_h1)
|
||||
df_h1['stoch_k'] = stoch.iloc[:, 0]
|
||||
df_h1['stoch_d'] = stoch.iloc[:, 1]
|
||||
df_h1 = df_h1.dropna()
|
||||
|
||||
ta_suggestion = "HOLD"
|
||||
if (
|
||||
last_d1['hist_d1'] > 0 and last_h1['hist_h1'] > 0 and
|
||||
last_h1['stoch_k'] > last_h1['stoch_d'] and
|
||||
prev_h1['stoch_k'] <= prev_h1['stoch_d']
|
||||
):
|
||||
ta_suggestion = "BUY"
|
||||
elif (
|
||||
last_d1['hist_d1'] < 0 and last_h1['hist_h1'] < 0 and
|
||||
last_h1['stoch_k'] < last_h1['stoch_d'] and
|
||||
prev_h1['stoch_k'] >= prev_h1['stoch_d']
|
||||
):
|
||||
ta_suggestion = "SELL"
|
||||
if len(df_d1) < 1 or len(df_h1) < 2:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data indikator belum matang."}
|
||||
|
||||
prompt = f"""
|
||||
I'm building a trading bot. Based on my technical indicators:
|
||||
- Daily MACD Histogram: {last_d1['hist_d1']:.5f}
|
||||
- H1 MACD Histogram: {last_h1['hist_h1']:.5f}
|
||||
- Stochastic K: {last_h1['stoch_k']:.2f}, D: {last_h1['stoch_d']:.2f}
|
||||
|
||||
My initial suggestion is: {ta_suggestion}
|
||||
last_d1 = df_d1.iloc[-1]
|
||||
last_h1 = df_h1.iloc[-1]
|
||||
prev_h1 = df_h1.iloc[-2]
|
||||
|
||||
Do you agree? Respond with BUY, SELL, or HOLD.
|
||||
"""
|
||||
ta_suggestion = "HOLD"
|
||||
if (
|
||||
last_d1['hist_d1'] > 0 and last_h1['hist_h1'] > 0 and
|
||||
last_h1['stoch_k'] > last_h1['stoch_d'] and
|
||||
prev_h1['stoch_k'] <= prev_h1['stoch_d']
|
||||
):
|
||||
ta_suggestion = "BUY"
|
||||
elif (
|
||||
last_d1['hist_d1'] < 0 and last_h1['hist_h1'] < 0 and
|
||||
last_h1['stoch_k'] < last_h1['stoch_d'] and
|
||||
prev_h1['stoch_k'] >= prev_h1['stoch_d']
|
||||
):
|
||||
ta_suggestion = "SELL"
|
||||
|
||||
ai_decision = ask_ollama(prompt)
|
||||
ai_decision = ai_decision.upper() if ai_decision else "HOLD"
|
||||
# AI functionality is temporarily disabled.
|
||||
final_signal = ta_suggestion
|
||||
|
||||
print(f"[AI Feedback] {symbol}: {ai_decision} (TA suggestion: {ta_suggestion})")
|
||||
|
||||
final_signal = "HOLD"
|
||||
if ai_decision == ta_suggestion and ai_decision in ["BUY", "SELL"]:
|
||||
final_signal = ai_decision
|
||||
place_trade(symbol, mt5.ORDER_TYPE_BUY if ai_decision == "BUY" else mt5.ORDER_TYPE_SELL, bot)
|
||||
|
||||
return {
|
||||
"signal": final_signal,
|
||||
"price": last_h1["close"],
|
||||
"explanation": f"TA: {ta_suggestion}, AI: {ai_decision}"
|
||||
}
|
||||
return {
|
||||
"signal": final_signal, "price": last_h1["close"],
|
||||
"explanation": f"TA: {ta_suggestion} (AI disabled)",
|
||||
"D1_MACDh": last_d1['hist_d1'], "H1_MACDh": last_h1['hist_h1'],
|
||||
"H1_STOCHk": last_h1['stoch_k'], "H1_STOCHd": last_h1['stoch_d']
|
||||
}
|
||||
|
||||
@@ -1,38 +1,37 @@
|
||||
# core/strategies/pulse_sync.py
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.data.fetch import get_rates
|
||||
from core.utils.ollama import ask_ollama
|
||||
|
||||
def analyze(bot):
|
||||
symbol = bot.market.replace('/', '')
|
||||
tf = bot.tf_map.get(bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
df = get_rates(symbol, tf, 100)
|
||||
class PulseSyncStrategy(BaseStrategy):
|
||||
name = 'Pulse Sync (AI)'
|
||||
description = 'Menggunakan AI untuk menganalisis momentum harga berdasarkan Simple Moving Average (SMA).'
|
||||
|
||||
if df is None or df.empty or len(df) < 30:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
def analyze(self):
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
df = get_rates(self.bot.market_for_mt5, tf_const, 100)
|
||||
|
||||
df['SMA21'] = ta.sma(df['close'], length=21)
|
||||
last = df.iloc[-1]
|
||||
if df is None or df.empty or len(df) < 30:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
|
||||
prompt = f"""
|
||||
I'm building an AI trading bot. The current price of {symbol} is {last['close']:.5f}.
|
||||
The 21-period moving average is {last['SMA21']:.5f}.
|
||||
Based on this info, what would you recommend: BUY or SELL?
|
||||
Respond only with 'BUY' or 'SELL'.
|
||||
"""
|
||||
df['SMA21'] = ta.sma(df['close'], length=21)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
ai_decision = ask_ollama(prompt)
|
||||
ai_decision = ai_decision.upper() if ai_decision else "HOLD"
|
||||
if len(df) < 1:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
signal = "HOLD"
|
||||
if "BUY" in ai_decision:
|
||||
signal = "BUY"
|
||||
elif "SELL" in ai_decision:
|
||||
signal = "SELL"
|
||||
last = df.iloc[-1]
|
||||
price = last["close"]
|
||||
|
||||
return {
|
||||
"signal": signal,
|
||||
"price": last["close"],
|
||||
"explanation": f"Ollama AI recommends: {ai_decision}"
|
||||
}
|
||||
# AI functionality is temporarily disabled.
|
||||
signal = "HOLD"
|
||||
explanation = "AI functionality is currently disabled for performance reasons."
|
||||
|
||||
analysis_data = {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation,
|
||||
"SMA_21": last.get('SMA21'),
|
||||
}
|
||||
return analysis_data
|
||||
|
||||
@@ -0,0 +1,76 @@
|
||||
# /core/strategies/quantumbotx_hybrid.py
|
||||
import pandas_ta as ta
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.data.fetch import get_rates
|
||||
|
||||
class QuantumBotXHybridStrategy(BaseStrategy):
|
||||
name = 'QuantumBotX Hybrid'
|
||||
description = 'Strategi eksklusif yang menggabungkan beberapa indikator untuk performa optimal di berbagai kondisi pasar.'
|
||||
|
||||
def analyze(self):
|
||||
"""
|
||||
Menganalisis pasar menggunakan strategi Hybrid yang adaptif.
|
||||
Menggunakan MA Crossover saat trending (ADX > 25) dan
|
||||
Bollinger Bands saat ranging (ADX < 25).
|
||||
"""
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
|
||||
# Butuh data yang cukup untuk indikator terpanjang (SMA 50)
|
||||
df = get_rates(self.bot.market_for_mt5, tf_const, 52)
|
||||
|
||||
if df is None or df.empty or len(df) < 51:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup untuk Hybrid."}
|
||||
|
||||
# --- Hitung SEMUA Indikator yang Dibutuhkan ---
|
||||
df.ta.adx(length=14, append=True)
|
||||
df['SMA_20'] = ta.sma(df['close'], length=20)
|
||||
df['SMA_50'] = ta.sma(df['close'], length=50)
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
if len(df) < 2:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
last = df.iloc[-1]
|
||||
prev = df.iloc[-2]
|
||||
price = last["close"]
|
||||
signal = "HOLD"
|
||||
explanation = "Kondisi pasar tidak memenuhi syarat."
|
||||
market_mode = "N/A"
|
||||
|
||||
# --- Logika "Wasit Pasar" (ADX) ---
|
||||
adx_value = last['ADX_14']
|
||||
|
||||
# KONDISI 1: PASAR TRENDING
|
||||
if adx_value > 25:
|
||||
market_mode = "Trending"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Menunggu Crossover."
|
||||
if prev['SMA_20'] <= prev['SMA_50'] and last['SMA_20'] > last['SMA_50']:
|
||||
signal = "BUY"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Sinyal: Golden Cross."
|
||||
elif prev['SMA_20'] >= prev['SMA_50'] and last['SMA_20'] < last['SMA_50']:
|
||||
signal = "SELL"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Sinyal: Death Cross."
|
||||
|
||||
# KONDISI 2: PASAR SIDEWAYS
|
||||
elif adx_value < 25:
|
||||
market_mode = "Ranging"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Menunggu pantulan Bands."
|
||||
if last['low'] <= last['BBL_20_2.0']:
|
||||
signal = "BUY"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Sinyal: Oversold di Band Bawah."
|
||||
elif last['high'] >= last['BBU_20_2.0']:
|
||||
signal = "SELL"
|
||||
explanation = f"Mode: {market_mode} (ADX {adx_value:.1f}). Sinyal: Overbought di Band Atas."
|
||||
|
||||
analysis_data = {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation,
|
||||
"Market_Mode": market_mode,
|
||||
"ADX_14": adx_value,
|
||||
"SMA_20": last.get('SMA_20'),
|
||||
"SMA_50": last.get('SMA_50'),
|
||||
}
|
||||
return analysis_data
|
||||
@@ -1,34 +1,41 @@
|
||||
# core/strategies/rsi_breakout.py
|
||||
import pandas_ta as ta
|
||||
from core.data.fetch import get_rates
|
||||
import MetaTrader5 as mt5
|
||||
from .base_strategy import BaseStrategy
|
||||
from core.utils.mt5 import get_rates_from_mt5
|
||||
|
||||
def analyze(bot):
|
||||
symbol = bot.market.replace('/', '')
|
||||
tf = bot.tf_map.get(bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
df = get_rates(symbol, tf, 100)
|
||||
class RSIBreakoutStrategy(BaseStrategy):
|
||||
name = 'RSI Breakout'
|
||||
description = 'Sinyal berdasarkan level jenuh beli (overbought) dan jenuh jual (oversold) dari Relative Strength Index (RSI).'
|
||||
|
||||
if df is None or df.empty or len(df) < 20:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
def analyze(self):
|
||||
tf_const = self.bot.tf_map.get(self.bot.timeframe, mt5.TIMEFRAME_H1)
|
||||
df = get_rates_from_mt5(self.bot.market_for_mt5, tf_const, 100)
|
||||
|
||||
df["RSI"] = ta.rsi(df["close"], length=14)
|
||||
df = df.dropna()
|
||||
last = df.iloc[-1]
|
||||
price = last["close"]
|
||||
rsi = last["RSI"]
|
||||
if df is None or df.empty or len(df) < 20:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Data tidak cukup"}
|
||||
|
||||
signal = "HOLD"
|
||||
explanation = f"RSI saat ini {rsi:.2f}, dalam zona netral"
|
||||
df["RSI"] = ta.rsi(df["close"], length=14)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
if rsi > 70:
|
||||
signal = "SELL"
|
||||
explanation = f"RSI {rsi:.2f} > 70 (overbought)"
|
||||
elif rsi < 30:
|
||||
signal = "BUY"
|
||||
explanation = f"RSI {rsi:.2f} < 30 (oversold)"
|
||||
if len(df) < 1:
|
||||
return {"signal": "HOLD", "price": None, "explanation": "Indikator belum matang."}
|
||||
|
||||
return {
|
||||
"signal": signal,
|
||||
"price": price,
|
||||
"explanation": explanation
|
||||
}
|
||||
last = df.iloc[-1]
|
||||
price = last["close"]
|
||||
rsi = last["RSI"]
|
||||
|
||||
signal = "HOLD"
|
||||
explanation = f"RSI saat ini {rsi:.2f}, dalam zona netral"
|
||||
|
||||
if rsi > 70:
|
||||
signal = "SELL"
|
||||
explanation = f"RSI {rsi:.2f} > 70 (overbought)"
|
||||
elif rsi < 30:
|
||||
signal = "BUY"
|
||||
explanation = f"RSI {rsi:.2f} < 30 (oversold)"
|
||||
|
||||
return {
|
||||
"signal": signal, "price": price, "explanation": explanation,
|
||||
"rsi": rsi
|
||||
}
|
||||
|
||||
@@ -1,9 +1,23 @@
|
||||
from core.strategies.logic_ma import run_ma_crossover
|
||||
from core.strategies.logic_rsi import run_rsi_breakout
|
||||
from core.strategies.logic_mercy import run_full_mercy
|
||||
# core/strategies/strategy_map.py
|
||||
|
||||
STRATEGY_FUNCTIONS = {
|
||||
'MA_CROSSOVER': run_ma_crossover,
|
||||
'RSI_BREAKOUT': run_rsi_breakout,
|
||||
'FULL_MERCY': run_full_mercy
|
||||
# Import the STRATEGY CLASSES, not the old analyze functions.
|
||||
from .ma_crossover import MACrossoverStrategy
|
||||
from .quantumbotx_hybrid import QuantumBotXHybridStrategy
|
||||
from .rsi_breakout import RSIBreakoutStrategy
|
||||
from .bollinger_bands import BollingerBandsStrategy
|
||||
from .bollinger_squeeze import BollingerSqueezeStrategy
|
||||
from .mercy_edge import MercyEdgeStrategy
|
||||
from .pulse_sync import PulseSyncStrategy
|
||||
|
||||
STRATEGY_MAP = {
|
||||
# The map is now a simple key-to-class mapping.
|
||||
'MA_CROSSOVER': MACrossoverStrategy,
|
||||
'QUANTUMBOTX_HYBRID': QuantumBotXHybridStrategy,
|
||||
'RSI_BREAKOUT': RSIBreakoutStrategy,
|
||||
'BOLLINGER_BANDS': BollingerBandsStrategy,
|
||||
'BOLLINGER_SQUEEZE': BollingerSqueezeStrategy,
|
||||
'MERCY_EDGE': MercyEdgeStrategy,
|
||||
'PULSE_SYNC': PulseSyncStrategy,
|
||||
}
|
||||
|
||||
# NOTE: You will need to refactor your other strategy files
|
||||
|
||||
+52
-16
@@ -1,23 +1,59 @@
|
||||
# core/utils/ai.py
|
||||
# core/utils/ai.py - VERSI PERBAIKAN
|
||||
|
||||
import subprocess
|
||||
import ollama
|
||||
import logging
|
||||
# Hapus impor ini dari bagian atas file untuk memutus lingkaran
|
||||
# from core.bots.controller import get_bot_analysis_data, get_bot_instance_by_id
|
||||
|
||||
def get_ollama_prediction(prompt, model="llama3"):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# Fungsi lain di file ini... (jika ada)
|
||||
|
||||
def get_ai_analysis(bot_id, market_data):
|
||||
"""
|
||||
Kirim prompt ke Ollama model lokal dan ambil prediksi (BUY/SELL)
|
||||
Menganalisis data pasar menggunakan model AI dari Ollama dan memberikan keputusan.
|
||||
"""
|
||||
# Lakukan impor di dalam fungsi (impor lokal)
|
||||
from core.bots.controller import get_bot_instance_by_id
|
||||
|
||||
try:
|
||||
result = subprocess.run(
|
||||
["ollama", "run", model, prompt],
|
||||
capture_output=True, text=True, timeout=30
|
||||
bot = get_bot_instance_by_id(bot_id)
|
||||
if not bot:
|
||||
return {
|
||||
"ai_decision": "ERROR",
|
||||
"ai_explanation": "Bot instance not found in controller.",
|
||||
"ai_suggested_strategy": "N/A"
|
||||
}
|
||||
|
||||
# ... (sisa kode fungsi Anda tetap sama) ...
|
||||
|
||||
# Contoh sisa kode:
|
||||
prompt = f"Analyze the following market data for {bot.market} and decide whether to BUY, SELL, or HOLD..."
|
||||
|
||||
response = ollama.chat(
|
||||
model='llama3',
|
||||
messages=[{'role': 'user', 'content': prompt}]
|
||||
)
|
||||
response = result.stdout.strip().lower()
|
||||
if "buy" in response:
|
||||
return "BUY"
|
||||
elif "sell" in response:
|
||||
return "SELL"
|
||||
else:
|
||||
return None
|
||||
|
||||
# Logika untuk mem-parsing response AI
|
||||
decision = "HOLD" # Default
|
||||
explanation = response['message']['content']
|
||||
|
||||
if "BUY" in explanation.upper():
|
||||
decision = "BUY"
|
||||
elif "SELL" in explanation.upper():
|
||||
decision = "SELL"
|
||||
|
||||
return {
|
||||
"ai_decision": decision,
|
||||
"ai_explanation": explanation,
|
||||
"ai_suggested_strategy": "Based on analysis"
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
print(f"[AI Error] {e}")
|
||||
return None
|
||||
logger.error(f"Error during AI analysis for bot {bot_id}: {e}", exc_info=True)
|
||||
return {
|
||||
"ai_decision": "ERROR",
|
||||
"ai_explanation": str(e),
|
||||
"ai_suggested_strategy": "N/A"
|
||||
}
|
||||
+40
-19
@@ -2,21 +2,30 @@
|
||||
|
||||
import os
|
||||
import requests
|
||||
import MetaTrader5 as mt5
|
||||
from dotenv import load_dotenv
|
||||
import logging
|
||||
|
||||
load_dotenv()
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
CMC_API_KEY = os.getenv("CMC_API_KEY")
|
||||
FINNHUB_API_KEY = os.getenv("FINNHUB_API_KEY")
|
||||
CMC_API_BASE_URL = os.getenv("CMC_API_BASE_URL", "https://pro-api.coinmarketcap.com")
|
||||
if not CMC_API_KEY:
|
||||
logger.warning("CMC_API_KEY not found in .env file.")
|
||||
|
||||
def get_crypto_data_from_cmc():
|
||||
url = "https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest"
|
||||
headers = {'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': CMC_API_KEY}
|
||||
params = {'start': '1', 'limit': '5', 'convert': 'IDR'}
|
||||
url = f"{CMC_API_BASE_URL}/v1/cryptocurrency/listings/latest"
|
||||
headers = {'Accepts': 'application/json', 'X-CMC-PRO-API-KEY': CMC_API_KEY}
|
||||
params = {'start': '1', 'limit': '5', 'convert': 'IDR', 'sort': 'market_cap', 'sort_dir': 'desc'}
|
||||
|
||||
logger.info(f"Fetching crypto data from CMC. API Key present: {bool(CMC_API_KEY)}")
|
||||
try:
|
||||
res = requests.get(url, headers=headers, params=params)
|
||||
res.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
|
||||
data = res.json().get('data', [])
|
||||
logger.info(f"Received {len(data)} crypto entries from CMC.")
|
||||
crypto_list = []
|
||||
for c in data:
|
||||
quote = c.get('quote', {}).get('IDR', {})
|
||||
@@ -28,22 +37,34 @@ def get_crypto_data_from_cmc():
|
||||
'market_cap': f"Rp {quote.get('market_cap', 0):,.0f}".replace(',', '.')
|
||||
})
|
||||
return crypto_list
|
||||
except Exception:
|
||||
except requests.exceptions.RequestException as e:
|
||||
logger.error(f"Request error fetching crypto data from CMC: {e}")
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"An unexpected error occurred fetching crypto data from CMC: {e}")
|
||||
return []
|
||||
|
||||
def get_recommendation_trends(symbol):
|
||||
try:
|
||||
res = requests.get("https://finnhub.io/api/v1/stock/recommendation", params={"symbol": symbol, "token": FINNHUB_API_KEY})
|
||||
res.raise_for_status()
|
||||
data = res.json()
|
||||
return data[0] if data else None
|
||||
except:
|
||||
def get_mt5_symbol_profile(symbol):
|
||||
if not mt5.initialize():
|
||||
print("MT5 initialization failed in external.py")
|
||||
return None
|
||||
|
||||
def get_company_profile(symbol):
|
||||
try:
|
||||
res = requests.get("https://finnhub.io/api/v1/stock/profile2", params={"symbol": symbol, "token": FINNHUB_API_KEY})
|
||||
res.raise_for_status()
|
||||
return res.json()
|
||||
except:
|
||||
return None
|
||||
symbol_info = mt5.symbol_info(symbol)
|
||||
mt5.shutdown()
|
||||
|
||||
if symbol_info:
|
||||
return {
|
||||
"name": symbol_info.description,
|
||||
"symbol": symbol_info.name,
|
||||
"currency_base": symbol_info.currency_base,
|
||||
"currency_profit": symbol_info.currency_profit,
|
||||
"digits": symbol_info.digits,
|
||||
"spread": symbol_info.spread,
|
||||
"trade_contract_size": symbol_info.trade_contract_size,
|
||||
"volume_min": symbol_info.volume_min,
|
||||
"volume_max": symbol_info.volume_max,
|
||||
"volume_step": symbol_info.volume_step,
|
||||
"margin_initial": symbol_info.margin_initial,
|
||||
"margin_maintenance": symbol_info.margin_maintenance,
|
||||
}
|
||||
return None
|
||||
|
||||
+23
-67
@@ -1,21 +1,26 @@
|
||||
# core/utils/mt5.py
|
||||
import MetaTrader5 as mt5
|
||||
import sqlite3
|
||||
from datetime import datetime
|
||||
from core.utils.trade import close_trade
|
||||
import pandas as pd
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# --- PERBAIKAN: Definisikan TIMEFRAME_MAP di sini ---
|
||||
TIMEFRAME_MAP = {
|
||||
"M1": mt5.TIMEFRAME_M1, "M5": mt5.TIMEFRAME_M5,
|
||||
"M15": mt5.TIMEFRAME_M15, "H1": mt5.TIMEFRAME_H1,
|
||||
"H4": mt5.TIMEFRAME_H4, "D1": mt5.TIMEFRAME_D1,
|
||||
"W1": mt5.TIMEFRAME_W1, "MN1": mt5.TIMEFRAME_MN1
|
||||
}
|
||||
|
||||
def initialize_mt5(account, password, server):
|
||||
"""Login ke MetaTrader 5."""
|
||||
if not mt5.initialize():
|
||||
print("Gagal inisialisasi MT5:", mt5.last_error())
|
||||
if not mt5.initialize(login=account, password=password, server=server):
|
||||
logger.error(f"Inisialisasi atau Login MT5 gagal: {mt5.last_error()}")
|
||||
return False
|
||||
authorized = mt5.login(account, password=password, server=server)
|
||||
if not authorized:
|
||||
print("Login gagal:", mt5.last_error())
|
||||
mt5.shutdown()
|
||||
return False
|
||||
print(f"Berhasil login ke MT5 ({account}) di server {server}")
|
||||
|
||||
logger.info(f"Berhasil login ke MT5 ({account}) di server {server}")
|
||||
return True
|
||||
|
||||
def get_mt5_account_info():
|
||||
@@ -25,10 +30,10 @@ def get_mt5_account_info():
|
||||
if info is not None:
|
||||
return info._asdict()
|
||||
else:
|
||||
print("Gagal mengambil account_info():", mt5.last_error())
|
||||
logger.error(f"Gagal mengambil account_info(): {mt5.last_error()}")
|
||||
return None
|
||||
except Exception as e:
|
||||
print(f"Error saat mengambil info akun MT5: {e}")
|
||||
logger.error(f"Error saat mengambil info akun MT5: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
def get_todays_profit():
|
||||
@@ -51,71 +56,22 @@ def get_todays_profit():
|
||||
total_profit += deal.profit
|
||||
return total_profit
|
||||
except Exception as e:
|
||||
print(f"Gagal menghitung profit hari ini: {e}")
|
||||
logger.error(f"Gagal menghitung profit hari ini: {e}", exc_info=True)
|
||||
return 0.0
|
||||
|
||||
def get_open_position(symbol, bot_id):
|
||||
"""Ambil posisi terbuka berdasarkan magic number bot."""
|
||||
positions = mt5.positions_get(symbol=symbol)
|
||||
if not positions:
|
||||
return None
|
||||
for p in positions:
|
||||
if p.magic == bot_id:
|
||||
return p
|
||||
return None
|
||||
|
||||
def log_bot_action(bot_id, action, details, bot_name=None):
|
||||
"""Catat aktivitas bot ke DB + notifikasi."""
|
||||
print(f"[LOG] Bot #{bot_id} - {action} - {details}")
|
||||
try:
|
||||
with sqlite3.connect("bots.db") as conn:
|
||||
cursor = conn.cursor()
|
||||
cursor.execute(
|
||||
'INSERT INTO trade_history (bot_id, action, details) VALUES (?, ?, ?)',
|
||||
(bot_id, action, details)
|
||||
)
|
||||
if action.startswith("POSISI") or action.startswith("GAGAL") or action.startswith("AUTO"):
|
||||
notif = f"Bot '{bot_name}' - {details}" if bot_name else details
|
||||
cursor.execute(
|
||||
'INSERT INTO notifications (bot_id, message) VALUES (?, ?)',
|
||||
(bot_id, notif)
|
||||
)
|
||||
conn.commit()
|
||||
except Exception as e:
|
||||
print("Gagal mencatat aksi ke DB:", e)
|
||||
|
||||
def auto_close_position(bot, symbol):
|
||||
"""Cek apakah posisi perlu ditutup otomatis berdasarkan durasi/profit/loss."""
|
||||
pos = get_open_position(symbol, bot.bot_id)
|
||||
if not pos:
|
||||
return
|
||||
|
||||
duration = datetime.now() - datetime.fromtimestamp(pos.time)
|
||||
if duration.total_seconds() > 7200:
|
||||
if close_trade(pos):
|
||||
log_bot_action(bot.bot_id, "AUTO-CUT BY TIME", f"Ditutup setelah {duration}", bot.name)
|
||||
elif pos.profit >= 100:
|
||||
if close_trade(pos):
|
||||
log_bot_action(bot.bot_id, "AUTO-CLOSE PROFIT", f"Profit = {pos.profit:.2f}", bot.name)
|
||||
elif pos.profit <= -50:
|
||||
if close_trade(pos):
|
||||
log_bot_action(bot.bot_id, "AUTO-CLOSE LOSS", f"Loss = {pos.profit:.2f}", bot.name)
|
||||
|
||||
def get_rates_from_mt5(symbol, timeframe, count):
|
||||
"""Fungsi utama untuk mengambil data harga historis langsung dari MT5."""
|
||||
try:
|
||||
rates = mt5.copy_rates_from_pos(symbol, timeframe, 0, count)
|
||||
if rates is None or len(rates) == 0:
|
||||
print(f"Gagal mengambil data dari MT5 untuk {symbol}")
|
||||
return None
|
||||
logger.warning(f"Tidak ada data yang diterima dari MT5 untuk {symbol}")
|
||||
return pd.DataFrame() # Kembalikan DataFrame kosong agar tidak error
|
||||
|
||||
df = pd.DataFrame(rates)
|
||||
df['time'] = pd.to_datetime(df['time'], unit='s')
|
||||
df.set_index('time', inplace=True)
|
||||
return df
|
||||
|
||||
except Exception as e:
|
||||
print(f"Error saat mengambil data dari MT5: {e}")
|
||||
return None
|
||||
|
||||
# 🔁 Alias supaya bisa di-import sebagai get_rates_df
|
||||
get_rates_df = get_rates_from_mt5
|
||||
logger.error(f"Error saat mengambil data dari MT5 untuk {symbol}: {e}", exc_info=True)
|
||||
return pd.DataFrame()
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import requests
|
||||
|
||||
def ask_ollama(prompt, model="llama3"):
|
||||
def ask_ollama(prompt, model="qwen2.5-coder:1.5b"):
|
||||
try:
|
||||
response = requests.post(
|
||||
"http://localhost:11434/api/generate",
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
import js from "@eslint/js";
|
||||
import globals from "globals";
|
||||
import json from "@eslint/json";
|
||||
import markdown from "@eslint/markdown";
|
||||
import css from "@eslint/css";
|
||||
import { defineConfig } from "eslint/config";
|
||||
|
||||
export default defineConfig([
|
||||
{ files: ["**/*.{js,mjs,cjs}"], plugins: { js }, extends: ["js/recommended"], languageOptions: { globals: globals.browser } },
|
||||
{ files: ["**/*.js"], languageOptions: { sourceType: "commonjs" } },
|
||||
{ files: ["**/*.json"], plugins: { json }, language: "json/json", extends: ["json/recommended"] },
|
||||
{ files: ["**/*.jsonc"], plugins: { json }, language: "json/jsonc", extends: ["json/recommended"] },
|
||||
{ files: ["**/*.json5"], plugins: { json }, language: "json/json5", extends: ["json/recommended"] },
|
||||
{ files: ["**/*.md"], plugins: { markdown }, language: "markdown/gfm", extends: ["markdown/recommended"] },
|
||||
{ files: ["**/*.css"], plugins: { css }, language: "css/css", extends: ["css/recommended"] },
|
||||
]);
|
||||
+93
@@ -0,0 +1,93 @@
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
# Nama file database
|
||||
DB_FILE = "bots.db"
|
||||
|
||||
def create_connection(db_file):
|
||||
""" Membuat koneksi ke database SQLite """
|
||||
conn = None
|
||||
try:
|
||||
conn = sqlite3.connect(db_file)
|
||||
print(f"Berhasil terhubung ke SQLite versi {sqlite3.version}")
|
||||
return conn
|
||||
except sqlite3.Error as e:
|
||||
print(e)
|
||||
return conn
|
||||
|
||||
def create_table(conn, create_table_sql):
|
||||
""" Membuat tabel dari statement SQL """
|
||||
try:
|
||||
c = conn.cursor()
|
||||
c.execute(create_table_sql)
|
||||
print("Tabel berhasil dibuat.")
|
||||
except sqlite3.Error as e:
|
||||
print(e)
|
||||
|
||||
def main():
|
||||
# Hapus database lama jika ada, untuk memastikan mulai dari awal
|
||||
if os.path.exists(DB_FILE):
|
||||
os.remove(DB_FILE)
|
||||
print(f"File database lama '{DB_FILE}' telah dihapus.")
|
||||
|
||||
# SQL statement untuk membuat tabel 'bots'
|
||||
sql_create_bots_table = """
|
||||
CREATE TABLE IF NOT EXISTS bots (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
name TEXT NOT NULL,
|
||||
market TEXT NOT NULL,
|
||||
status TEXT NOT NULL DEFAULT 'Dijeda',
|
||||
lot_size REAL NOT NULL DEFAULT 0.01,
|
||||
sl_pips INTEGER NOT NULL DEFAULT 100,
|
||||
tp_pips INTEGER NOT NULL DEFAULT 200,
|
||||
timeframe TEXT NOT NULL DEFAULT 'H1',
|
||||
check_interval_seconds INTEGER NOT NULL DEFAULT 60,
|
||||
strategy TEXT NOT NULL
|
||||
);
|
||||
"""
|
||||
|
||||
# SQL statement untuk membuat tabel 'trade_history'
|
||||
sql_create_history_table = """
|
||||
CREATE TABLE IF NOT EXISTS trade_history (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
bot_id INTEGER NOT NULL,
|
||||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
action TEXT NOT NULL,
|
||||
details TEXT,
|
||||
FOREIGN KEY (bot_id) REFERENCES bots (id) ON DELETE CASCADE
|
||||
);
|
||||
"""
|
||||
|
||||
# SQL statement untuk membuat tabel 'notifications'
|
||||
sql_create_notifications_table = """
|
||||
CREATE TABLE IF NOT EXISTS notifications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
bot_id INTEGER,
|
||||
message TEXT NOT NULL,
|
||||
timestamp DATETIME DEFAULT CURRENT_TIMESTAMP,
|
||||
is_read INTEGER NOT NULL DEFAULT 0,
|
||||
FOREIGN KEY (bot_id) REFERENCES bots (id) ON DELETE CASCADE
|
||||
);
|
||||
"""
|
||||
|
||||
# Buat koneksi database
|
||||
conn = create_connection(DB_FILE)
|
||||
|
||||
# Buat tabel-tabel
|
||||
if conn is not None:
|
||||
print("\nMembuat tabel 'bots'...")
|
||||
create_table(conn, sql_create_bots_table)
|
||||
|
||||
print("\nMembuat tabel 'trade_history'...")
|
||||
create_table(conn, sql_create_history_table)
|
||||
|
||||
print("\nMembuat tabel 'notifications'...")
|
||||
create_table(conn, sql_create_notifications_table)
|
||||
|
||||
conn.close()
|
||||
print(f"\nDatabase '{DB_FILE}' berhasil dibuat dengan semua tabel yang diperlukan.")
|
||||
else:
|
||||
print("Error! Tidak dapat membuat koneksi database.")
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,119 @@
|
||||
# backtester.py (VERSI DIPERBAIKI)
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit berdasarkan
|
||||
simbol, kelas aset, dan ukuran lot.
|
||||
"""
|
||||
# 1. Untuk Indeks Saham (seperti US500, NAS100, SPX500m, dll.)
|
||||
# Pergerakan 1 poin = profit $0.01 untuk 0.01 lot.
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
|
||||
# 2. Untuk Emas (XAUUSD)
|
||||
# Pergerakan $1 = profit $1 untuk 0.01 lot.
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
|
||||
# 3. Untuk Pasangan Mata Uang Forex (seperti EURUSD, USDJPY)
|
||||
# Pergerakan 1 pip = profit ~$0.10 untuk 0.01 lot.
|
||||
# Nilai 100000 adalah standar industri untuk 1 lot.
|
||||
else:
|
||||
# Periksa apakah ini pasangan JPY, karena nilainya berbeda
|
||||
if "JPY" in symbol:
|
||||
return 1000 * lot_size # Untuk pasangan JPY, 1 pip adalah 0.01
|
||||
else:
|
||||
return 100000 * lot_size # Untuk pasangan non-JPY, 1 pip adalah 0.0001
|
||||
|
||||
def run_backtest(data_path, symbol, initial_balance=10000):
|
||||
"""Fungsi utama untuk menjalankan simulasi backtesting."""
|
||||
|
||||
print(f"Memulai backtest MA_CROSSOVER untuk simbol: {symbol}")
|
||||
# Kode baru yang disarankan
|
||||
LOT_SIZE = 0.01 # Definisikan ukuran lot di satu tempat
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
# 1. Muat dan siapkan data historis
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Parameter Strategi ---
|
||||
FAST_MA = 20
|
||||
SLOW_MA = 50
|
||||
|
||||
# Hitung indikator
|
||||
df.ta.sma(length=FAST_MA, append=True)
|
||||
df.ta.sma(length=SLOW_MA, append=True)
|
||||
|
||||
fast_ma_col = f'SMA_{FAST_MA}'
|
||||
slow_ma_col = f'SMA_{SLOW_MA}'
|
||||
|
||||
# 2. Siapkan variabel untuk simulasi
|
||||
balance = initial_balance
|
||||
position = None
|
||||
trades = []
|
||||
equity_curve = []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
# 3. Loop utama
|
||||
for i in range(1, len(df)):
|
||||
current_row = df.iloc[i]
|
||||
prev_row = df.iloc[i - 1]
|
||||
|
||||
# --- Simulasi Logika Exit ---
|
||||
if position:
|
||||
# Sinyal keluar untuk BUY adalah Death Cross
|
||||
if position['type'] == 'BUY' and prev_row[fast_ma_col] > prev_row[slow_ma_col] and current_row[fast_ma_col] < current_row[slow_ma_col]:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (current_row['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
# Sinyal keluar untuk SELL adalah Golden Cross
|
||||
elif position['type'] == 'SELL' and prev_row[fast_ma_col] < prev_row[slow_ma_col] and current_row[fast_ma_col] > current_row[slow_ma_col]:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (position['entry_price'] - current_row['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
# --- Simulasi Logika Entry ---
|
||||
if not position:
|
||||
# Golden Cross (Sinyal BELI)
|
||||
if prev_row[fast_ma_col] <= prev_row[slow_ma_col] and current_row[fast_ma_col] > current_row[slow_ma_col]:
|
||||
position = {'type': 'BUY', 'entry_price': current_row['close']}
|
||||
# Death Cross (Sinyal JUAL)
|
||||
elif prev_row[fast_ma_col] >= prev_row[slow_ma_col] and current_row[fast_ma_col] < current_row[slow_ma_col]:
|
||||
position = {'type': 'SELL', 'entry_price': current_row['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# 4. Analisis Hasil
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
# Tampilkan Grafik Equity
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi MA_CROSSOVER on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
# --- Jalankan Backtest ---
|
||||
if __name__ == '__main__':
|
||||
# --- KONFIGURASI PENGUJIAN ---
|
||||
symbol_to_test = "XAUUSD" # Ubah ini ke "EURUSD" jika ingin menguji EURUSD
|
||||
# Gunakan nama file yang sesuai dengan data yang Anda download
|
||||
file_name = "lab/XAUUSD_16385_data.csv"
|
||||
|
||||
run_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,94 @@
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
elif "JPY" in symbol:
|
||||
return 1000 * lot_size
|
||||
else:
|
||||
return 100000 * lot_size
|
||||
|
||||
def run_bb_rsi_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest BBANDS + RSI untuk simbol: {symbol}")
|
||||
LOT_SIZE = 0.01
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df["rsi"] = ta.rsi(df["close"], length=14)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
cooldown = 0
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
if cooldown > 0:
|
||||
cooldown -= 1
|
||||
equity_curve.append(balance)
|
||||
continue
|
||||
|
||||
# Exit logic
|
||||
if position:
|
||||
if position['type'] == 'BUY' and current['close'] >= current['BBM_20_2.0']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'BUY', 'profit': profit})
|
||||
position = None
|
||||
cooldown = 3
|
||||
elif position['type'] == 'SELL' and current['close'] <= current['BBM_20_2.0']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'SELL', 'profit': profit})
|
||||
position = None
|
||||
cooldown = 3
|
||||
|
||||
# Entry logic
|
||||
if not position:
|
||||
if current['low'] <= current['BBL_20_2.0'] and current['rsi'] < 30:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif current['high'] >= current['BBU_20_2.0'] and current['rsi'] > 70:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# Output Summary
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal : ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir : ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades : {len(trades)}")
|
||||
|
||||
wins = [t['profit'] for t in trades if t['profit'] > 0]
|
||||
losses = [t['profit'] for t in trades if t['profit'] <= 0]
|
||||
winrate = len(wins) / len(trades) * 100 if trades else 0
|
||||
profit_factor = sum(wins) / abs(sum(losses)) if losses else float('inf')
|
||||
avg_win = pd.Series(wins).mean() if wins else 0
|
||||
avg_loss = pd.Series(losses).mean() if losses else 0
|
||||
|
||||
print(f"Win Rate : {winrate:.2f}%")
|
||||
print(f"Profit Factor : {profit_factor:.2f}")
|
||||
print(f"Avg Win / Loss : ${avg_win:.2f} / ${avg_loss:.2f}")
|
||||
|
||||
# Equity Curve
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[-len(equity_curve):], equity_curve, label='Equity Curve')
|
||||
plt.title(f'Equity Curve - BBANDS + RSI on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "USDJPY" # Ganti dengan EURUSD, USDJPY, dll
|
||||
file_name = "lab/USDJPY_16385_data.csv"
|
||||
run_bb_rsi_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,81 @@
|
||||
# backtester_bb_squeeze.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_bb_squeeze_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest BOLLINGER BAND SQUEEZE untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
# Gunakan parameter standar Bollinger Bands
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
|
||||
# Hitung Lebar Bollinger Band (Band Atas - Band Bawah)
|
||||
df['BB_WIDTH'] = df['BBU_20_2.0'] - df['BBL_20_2.0']
|
||||
|
||||
# Cari titik terendah dari Lebar Band dalam 120 candle terakhir (sekitar 5 hari di H1)
|
||||
df['SQUEEZE_LEVEL'] = df['BB_WIDTH'].rolling(window=120).min()
|
||||
|
||||
df.dropna(inplace=True)
|
||||
df = df.reset_index(drop=True)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)): # Mulai dari 1 agar bisa akses `prev`
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i-1]
|
||||
|
||||
# --- Logika Exit (Keluar jika harga kembali cross ke MA tengah) ---
|
||||
if position:
|
||||
if position['type'] == 'BUY' and current['close'] < current['BBM_20_2.0']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and current['close'] > current['BBM_20_2.0']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
|
||||
# --- Logika Entry (Hanya jika tidak ada posisi) ---
|
||||
if not position:
|
||||
# Kondisi 1: Apakah pasar sedang dalam kondisi "Squeeze"?
|
||||
# Kita lihat di candle SEBELUMNYA untuk menghindari melihat masa depan.
|
||||
is_in_squeeze = prev['BB_WIDTH'] <= prev['SQUEEZE_LEVEL']
|
||||
|
||||
if is_in_squeeze:
|
||||
# Kondisi 2: Jika ya, apakah harga SEKARANG breakout?
|
||||
# Breakout ke atas (sinyal Beli)
|
||||
if current['close'] > prev['BBU_20_2.0']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
# Breakout ke bawah (sinyal Jual)
|
||||
elif current['close'] < prev['BBL_20_2.0']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi BOLLINGER SQUEEZE on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "US500" # Ganti dengan simbol yang ingin diuji
|
||||
file_name = "lab/US500_16385_data.csv"
|
||||
run_bb_squeeze_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,87 @@
|
||||
# backtester_bollinger.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit berdasarkan
|
||||
simbol, kelas aset, dan ukuran lot.
|
||||
"""
|
||||
# 1. Untuk Indeks Saham (seperti US500, NAS100, SPX500m, dll.)
|
||||
# Pergerakan 1 poin = profit $0.01 untuk 0.01 lot.
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
|
||||
# 2. Untuk Emas (XAUUSD)
|
||||
# Pergerakan $1 = profit $1 untuk 0.01 lot.
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
|
||||
# 3. Untuk Pasangan Mata Uang Forex (seperti EURUSD, USDJPY)
|
||||
# Pergerakan 1 pip = profit ~$0.10 untuk 0.01 lot.
|
||||
# Nilai 100000 adalah standar industri untuk 1 lot.
|
||||
else:
|
||||
# Periksa apakah ini pasangan JPY, karena nilainya berbeda
|
||||
if "JPY" in symbol:
|
||||
return 1000 * lot_size # Untuk pasangan JPY, 1 pip adalah 0.01
|
||||
else:
|
||||
return 100000 * lot_size # Untuk pasangan non-JPY, 1 pip adalah 0.0001
|
||||
|
||||
def run_bollinger_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest BOLLINGER BANDS untuk simbol: {symbol}")
|
||||
# Kode baru yang disarankan
|
||||
LOT_SIZE = 0.01 # Definisikan ukuran lot di satu tempat
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
|
||||
# --- Logika Exit (Keluar jika menyentuh MA tengah) ---
|
||||
if position:
|
||||
if position['type'] == 'BUY' and current['close'] >= current['BBM_20_2.0']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and current['close'] <= current['BBM_20_2.0']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
|
||||
# --- Logika Entry (Hanya jika tidak ada posisi) ---
|
||||
if not position:
|
||||
# Sinyal BELI: Harga menyentuh atau menembus band bawah
|
||||
if current['low'] <= current['BBL_20_2.0']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
# Sinyal JUAL: Harga menyentuh atau menembus band atas
|
||||
elif current['high'] >= current['BBU_20_2.0']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi BOLLINGER BANDS on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "XAUUSD" # Ganti dengan simbol yang ingin diuji
|
||||
file_name = "lab/XAUUSD_16385_data.csv"
|
||||
run_bollinger_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,98 @@
|
||||
# backtester_bollinger_v2.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
elif "JPY" in symbol:
|
||||
return 1000 * lot_size
|
||||
else:
|
||||
return 100000 * lot_size
|
||||
|
||||
def run_bollinger_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest BOLLINGER BANDS (v2) untuk simbol: {symbol}")
|
||||
LOT_SIZE = 0.01
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# Hitung Bollinger Bands dan MA filter
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
df["ma_filter"] = ta.sma(df["close"], length=50)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
cooldown = 0 # Delay antar posisi
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
|
||||
# Cooldown aktif, skip entry
|
||||
if cooldown > 0:
|
||||
cooldown -= 1
|
||||
equity_curve.append(balance)
|
||||
continue
|
||||
|
||||
# Exit logic
|
||||
if position:
|
||||
if position['type'] == 'BUY' and current['close'] >= current['BBM_20_2.0']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'BUY', 'profit': profit})
|
||||
position = None
|
||||
cooldown = 3
|
||||
elif position['type'] == 'SELL' and current['close'] <= current['BBM_20_2.0']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'SELL', 'profit': profit})
|
||||
position = None
|
||||
cooldown = 3
|
||||
|
||||
# Entry logic (dengan trend filter)
|
||||
if not position:
|
||||
if current['low'] <= current['BBL_20_2.0'] and current['close'] > current['ma_filter']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif current['high'] >= current['BBU_20_2.0'] and current['close'] < current['ma_filter']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# Summary
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal : ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir : ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total P/L : ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades : {len(trades)}")
|
||||
|
||||
# Metrik performa
|
||||
wins = [t['profit'] for t in trades if t['profit'] > 0]
|
||||
losses = [t['profit'] for t in trades if t['profit'] <= 0]
|
||||
winrate = len(wins) / len(trades) * 100 if trades else 0
|
||||
profit_factor = sum(wins) / abs(sum(losses)) if losses else float('inf')
|
||||
avg_win = pd.Series(wins).mean() if wins else 0
|
||||
avg_loss = pd.Series(losses).mean() if losses else 0
|
||||
|
||||
print(f"Win Rate : {winrate:.2f}%")
|
||||
print(f"Profit Factor : {profit_factor:.2f}")
|
||||
print(f"Avg Win / Loss : ${avg_win:.2f} / ${avg_loss:.2f}")
|
||||
|
||||
# Plot
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[-len(equity_curve):], equity_curve, label='Equity Curve')
|
||||
plt.title(f'Equity Curve - BOLLINGER BANDS v2 on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "EURUSD" # Ganti dengan simbol yang ingin diuji
|
||||
file_name = "lab/EURUSD_16385_data.csv"
|
||||
run_bollinger_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,120 @@
|
||||
# backtester_full_mercy.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit berdasarkan
|
||||
simbol, kelas aset, dan ukuran lot.
|
||||
"""
|
||||
# 1. Untuk Indeks Saham (seperti US500, NAS100, SPX500m, dll.)
|
||||
# Pergerakan 1 poin = profit $0.01 untuk 0.01 lot.
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
|
||||
# 2. Untuk Emas (XAUUSD)
|
||||
# Pergerakan $1 = profit $1 untuk 0.01 lot.
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
|
||||
# 3. Untuk Pasangan Mata Uang Forex (seperti EURUSD, USDJPY)
|
||||
# Pergerakan 1 pip = profit ~$0.10 untuk 0.01 lot.
|
||||
# Nilai 100000 adalah standar industri untuk 1 lot.
|
||||
else:
|
||||
# Periksa apakah ini pasangan JPY, karena nilainya berbeda
|
||||
if "JPY" in symbol:
|
||||
return 1000 * lot_size # Untuk pasangan JPY, 1 pip adalah 0.01
|
||||
else:
|
||||
return 100000 * lot_size # Untuk pasangan non-JPY, 1 pip adalah 0.0001
|
||||
|
||||
def run_full_mercy_backtest(h1_data_path, symbol, initial_balance=10000):
|
||||
"""
|
||||
Fungsi utama untuk menjalankan simulasi backtesting
|
||||
untuk strategi multi-timeframe "Full Mercy".
|
||||
"""
|
||||
print(f"Memulai backtest FULL MERCY untuk simbol: {symbol}")
|
||||
# Kode baru yang disarankan
|
||||
LOT_SIZE = 0.01 # Definisikan ukuran lot di satu tempat
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
# ... (kode dari Tahap 1 sampai 4 tetap sama persis) ...
|
||||
print("1. Memuat data H1...")
|
||||
df_h1 = pd.read_csv(h1_data_path, parse_dates=['time'])
|
||||
if df_h1.empty:
|
||||
print("Gagal memuat data H1. Keluar.")
|
||||
return
|
||||
|
||||
print("2. Membuat data D1 dari data H1 (Resampling)...")
|
||||
df_d1 = df_h1.resample('D', on='time').agg({
|
||||
'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'
|
||||
}).dropna().reset_index()
|
||||
|
||||
print("3. Menghitung indikator MACD di D1 dan H1...")
|
||||
df_d1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.stoch(high='high', low='low', close='close', k=14, d=3, smooth_k=3, append=True)
|
||||
|
||||
print("4. Menggabungkan data D1 dan H1...")
|
||||
df_d1_indicator = df_d1[['time', 'MACDh_12_26_9']].rename(columns={'MACDh_12_26_9': 'D1_MACDh'})
|
||||
df_d1_indicator['date_key'] = df_d1_indicator['time'].dt.date
|
||||
df_h1['date_key'] = df_h1['time'].dt.date
|
||||
df_merged = pd.merge(df_h1, df_d1_indicator[['date_key', 'D1_MACDh']], on='date_key', how='left')
|
||||
df_merged['D1_MACDh'] = df_merged['D1_MACDh'].ffill()
|
||||
df_merged.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("5. Memulai loop backtest...")
|
||||
for i in range(1, len(df_merged)):
|
||||
current, prev = df_merged.iloc[i], df_merged.iloc[i - 1]
|
||||
|
||||
if position:
|
||||
is_buy_pos = position['type'] == 'BUY'
|
||||
|
||||
if is_buy_pos and prev['STOCHk_14_3_3'] > prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3']:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
elif not is_buy_pos and prev['STOCHk_14_3_3'] < prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3']:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
if not position:
|
||||
is_buy_signal = (current['D1_MACDh'] > 0 and current['MACDh_12_26_9'] > 0 and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] <= prev['STOCHd_14_3_3'])
|
||||
is_sell_signal = (current['D1_MACDh'] < 0 and current['MACDh_12_26_9'] < 0 and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] >= prev['STOCHd_14_3_3'])
|
||||
if is_buy_signal:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif is_sell_signal:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df_merged['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi "Full Mercy" on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
# --- Jalankan Backtest ---
|
||||
if __name__ == '__main__':
|
||||
# Sekarang kita perlu memberi tahu backtester simbol apa yang sedang diuji
|
||||
symbol_to_test = "US500" # Ubah ini ke "EURUSD" jika ingin menguji EURUSD
|
||||
file_name = "lab/US500_16385_data.csv" # Pastikan nama file cocok
|
||||
|
||||
run_full_mercy_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,95 @@
|
||||
# backtester_hybrid.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_hybrid_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest QUANTUMBOTX HYBRID untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung SEMUA Indikator yang Dibutuhkan ---
|
||||
# Indikator untuk "Wasit Pasar"
|
||||
df.ta.adx(length=14, append=True)
|
||||
|
||||
# Indikator untuk Pemain #1: MA Crossover
|
||||
df['SMA_20'] = ta.sma(df['close'], length=20)
|
||||
df['SMA_50'] = ta.sma(df['close'], length=50)
|
||||
|
||||
# Indikator untuk Pemain #2: Bollinger Bands
|
||||
df.ta.bbands(length=20, std=2.0, append=True)
|
||||
|
||||
df.dropna(inplace=True)
|
||||
df = df.reset_index(drop=True)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i-1]
|
||||
|
||||
# --- Tahap 1: "Wasit" Menganalisis Pasar ---
|
||||
adx_value = current['ADX_14']
|
||||
|
||||
# --- Tahap 2: Pilih Pemain Berdasarkan Kondisi Pasar ---
|
||||
|
||||
# KONDISI 1: PASAR SEDANG TRENDING (ADX > 25)
|
||||
if adx_value > 25:
|
||||
# Gunakan Logika MA_CROSSOVER
|
||||
if position: # Logika Exit
|
||||
if position['type'] == 'BUY' and prev['SMA_20'] > prev['SMA_50'] and current['SMA_20'] < current['SMA_50']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and prev['SMA_20'] < prev['SMA_50'] and current['SMA_20'] > current['SMA_50']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
if not position: # Logika Entry
|
||||
if prev['SMA_20'] <= prev['SMA_50'] and current['SMA_20'] > current['SMA_50']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif prev['SMA_20'] >= prev['SMA_50'] and current['SMA_20'] < current['SMA_50']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
# KONDISI 2: PASAR SEDANG SIDEWAYS (ADX < 25)
|
||||
elif adx_value < 25:
|
||||
# Gunakan Logika BOLLINGER BANDS
|
||||
if position: # Logika Exit
|
||||
if position['type'] == 'BUY' and current['close'] >= current['BBM_20_2.0']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and current['close'] <= current['BBM_20_2.0']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
if not position: # Logika Entry
|
||||
if current['low'] <= current['BBL_20_2.0']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif current['high'] >= current['BBU_20_2.0']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi QUANTUMBOTX HYBRID on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "EURUSD"
|
||||
file_name = "EURUSD_16385_data.csv"
|
||||
run_hybrid_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,88 @@
|
||||
# backtester_ichimoku.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_ichimoku_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest ICHIMOKU CLOUD untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Indikator Ichimoku ---
|
||||
# Pengaturan standar 9, 26, 52
|
||||
df.ta.ichimoku(append=True)
|
||||
df.dropna(inplace=True)
|
||||
df = df.reset_index(drop=True) # Reset index setelah dropna
|
||||
|
||||
# Nama kolom dari pandas_ta:
|
||||
tenkan_col = 'ITS_9' # Conversion Line
|
||||
kijun_col = 'IKS_26' # Base Line
|
||||
span_a_col = 'ISA_9' # Leading Span A (membentuk Awan)
|
||||
span_b_col = 'ISB_26' # Leading Span B (membentuk Awan)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i-1]
|
||||
|
||||
# --- Kondisi Awan (Filter Utama) ---
|
||||
is_above_cloud = current['close'] > current[span_a_col] and current['close'] > current[span_b_col]
|
||||
is_below_cloud = current['close'] < current[span_a_col] and current['close'] < current[span_b_col]
|
||||
|
||||
# --- Kondisi Persilangan Tenkan/Kijun (Pemicu) ---
|
||||
tk_cross_up = prev[tenkan_col] <= prev[kijun_col] and current[tenkan_col] > current[kijun_col]
|
||||
tk_cross_down = prev[tenkan_col] >= prev[kijun_col] and current[tenkan_col] < current[kijun_col]
|
||||
|
||||
# --- Logika Exit (Keluar jika ada sinyal berlawanan) ---
|
||||
if position:
|
||||
if position['type'] == 'BUY' and tk_cross_down:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and tk_cross_up:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
|
||||
# --- Logika Entry (Hanya jika tidak ada posisi) ---
|
||||
if not position:
|
||||
# Sinyal BELI: Harga di atas Awan DAN terjadi Golden Cross Tenkan/Kijun
|
||||
if is_above_cloud and tk_cross_up:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
# Sinyal JUAL: Harga di bawah Awan DAN terjadi Death Cross Tenkan/Kijun
|
||||
elif is_below_cloud and tk_cross_down:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve) # Mulai dari 1 karena kita butuh `prev`
|
||||
plt.title(f'Equity Curve - Strategi ICHIMOKU CLOUD on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# UJI COBA #1: Di pasar tren (XAUUSD)
|
||||
# symbol_to_test = "XAUUSD"
|
||||
# file_name = "XAUUSD_16385_data.csv"
|
||||
|
||||
# UJI COBA #2: Di pasar sideways (EURUSD)
|
||||
symbol_to_test = "EURUSD"
|
||||
file_name = "EURUSD_16385_data.csv"
|
||||
|
||||
run_ichimoku_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,63 @@
|
||||
# backtester.py
|
||||
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
import os
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit berdasarkan
|
||||
simbol, kelas aset, dan ukuran lot.
|
||||
"""
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
else:
|
||||
if "JPY" in symbol:
|
||||
return 1000 * lot_size
|
||||
else:
|
||||
return 100000 * lot_size
|
||||
|
||||
def run_backtest(data_path, symbol, initial_balance=10000, lot_size=0.01):
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# Tambahkan indikator teknikal (contoh: SMA 20 & SMA 50)
|
||||
df['sma_20'] = ta.sma(df['close'], length=20)
|
||||
df['sma_50'] = ta.sma(df['close'], length=50)
|
||||
|
||||
# Logika strategi sederhana (golden cross)
|
||||
df['signal'] = 0
|
||||
df.loc[df['sma_20'] > df['sma_50'], 'signal'] = 1
|
||||
df.loc[df['sma_20'] < df['sma_50'], 'signal'] = -1
|
||||
|
||||
# Hitung perubahan harga dan profit
|
||||
df['price_change'] = df['close'].diff()
|
||||
multiplier = get_profit_multiplier(symbol, lot_size)
|
||||
df['profit'] = df['price_change'] * df['signal'].shift(1) * multiplier
|
||||
df['balance'] = initial_balance + df['profit'].cumsum()
|
||||
|
||||
# Plot hasil backtest
|
||||
plt.figure(figsize=(14, 6))
|
||||
plt.plot(df['time'], df['balance'], label='Equity Curve')
|
||||
plt.title(f'Backtest Result - {symbol}')
|
||||
plt.xlabel('Time')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
if __name__ == "__main__":
|
||||
# Ganti nama file sesuai file CSV yang kamu download
|
||||
file_name = "XAUUSD_16385_data.csv"
|
||||
symbol = "XAUUSD" # Ganti dengan simbol yang sesuai
|
||||
|
||||
# Pastikan path benar
|
||||
data_path = os.path.join(os.path.dirname(__file__), file_name)
|
||||
|
||||
if os.path.exists(data_path):
|
||||
run_backtest(data_path, symbol)
|
||||
else:
|
||||
print(f"File {file_name} tidak ditemukan!")
|
||||
@@ -0,0 +1,88 @@
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
elif "JPY" in symbol:
|
||||
return 1000 * lot_size
|
||||
else:
|
||||
return 100000 * lot_size
|
||||
|
||||
def run_macd_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest MACD CROSSOVER untuk simbol: {symbol}")
|
||||
LOT_SIZE = 0.01
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
macd = ta.macd(df['close'])
|
||||
df = pd.concat([df, macd], axis=1)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
print("Memulai Loop Backtest...")
|
||||
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i - 1]
|
||||
|
||||
# EXIT
|
||||
if position:
|
||||
if position['type'] == 'BUY' and prev['MACD_12_26_9'] > prev['MACDs_12_26_9'] and current['MACD_12_26_9'] < current['MACDs_12_26_9']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'BUY', 'profit': profit})
|
||||
position = None
|
||||
elif position['type'] == 'SELL' and prev['MACD_12_26_9'] < prev['MACDs_12_26_9'] and current['MACD_12_26_9'] > current['MACDs_12_26_9']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': 'SELL', 'profit': profit})
|
||||
position = None
|
||||
|
||||
# ENTRY
|
||||
if not position:
|
||||
if prev['MACD_12_26_9'] <= prev['MACDs_12_26_9'] and current['MACD_12_26_9'] > current['MACDs_12_26_9']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif prev['MACD_12_26_9'] >= prev['MACDs_12_26_9'] and current['MACD_12_26_9'] < current['MACDs_12_26_9']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# Summary
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal : ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir : ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades : {len(trades)}")
|
||||
|
||||
wins = [t['profit'] for t in trades if t['profit'] > 0]
|
||||
losses = [t['profit'] for t in trades if t['profit'] <= 0]
|
||||
winrate = len(wins) / len(trades) * 100 if trades else 0
|
||||
profit_factor = sum(wins) / abs(sum(losses)) if losses else float('inf')
|
||||
avg_win = pd.Series(wins).mean() if wins else 0
|
||||
avg_loss = pd.Series(losses).mean() if losses else 0
|
||||
|
||||
print(f"Win Rate : {winrate:.2f}%")
|
||||
print(f"Profit Factor : {profit_factor:.2f}")
|
||||
print(f"Avg Win / Loss : ${avg_win:.2f} / ${avg_loss:.2f}")
|
||||
|
||||
# Equity Curve
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[-len(equity_curve):], equity_curve, label='Equity Curve')
|
||||
plt.title(f'Equity Curve - MACD CROSSOVER on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "USDJPY" # Ganti dengan simbol yang ingin diuji
|
||||
file_name = "lab/USDJPY_16385_data.csv"
|
||||
run_macd_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,107 @@
|
||||
# backtester_mercy_reversal.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit
|
||||
berdasarkan simbol dan ukuran lot.
|
||||
"""
|
||||
if "USD" in symbol and symbol != "XAUUSD": # Untuk pasangan Forex seperti EURUSD, GBPUSD
|
||||
# 0.01 lot (micro lot) = 1,000 unit.
|
||||
return 1000 * (lot_size / 0.01)
|
||||
elif symbol == "XAUUSD": # Untuk Emas
|
||||
# 0.01 lot = 1 ons (umumnya). Pergerakan $1 = profit $1.
|
||||
return 1 * (lot_size / 0.01)
|
||||
else: # Default jika tidak dikenali
|
||||
return 1
|
||||
|
||||
def run_mercy_reversal_backtest(h1_data_path, symbol, initial_balance=10000):
|
||||
"""
|
||||
Fungsi utama untuk menjalankan simulasi backtesting
|
||||
untuk strategi multi-timeframe "Full Mercy".
|
||||
"""
|
||||
print(f"Memulai backtest untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
# ... (kode dari Tahap 1 sampai 4 tetap sama persis) ...
|
||||
print("1. Memuat data H1...")
|
||||
df_h1 = pd.read_csv(h1_data_path, parse_dates=['time'])
|
||||
if df_h1.empty:
|
||||
print("Gagal memuat data H1. Keluar.")
|
||||
return
|
||||
|
||||
print("2. Membuat data D1 dari data H1 (Resampling)...")
|
||||
df_d1 = df_h1.resample('D', on='time').agg({
|
||||
'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'
|
||||
}).dropna().reset_index()
|
||||
|
||||
print("3. Menghitung indikator MACD di D1 dan H1...")
|
||||
df_d1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.stoch(high='high', low='low', close='close', k=14, d=3, smooth_k=3, append=True)
|
||||
|
||||
print("4. Menggabungkan data D1 dan H1...")
|
||||
df_d1_indicator = df_d1[['time', 'MACDh_12_26_9']].rename(columns={'MACDh_12_26_9': 'D1_MACDh'})
|
||||
df_d1_indicator['date_key'] = df_d1_indicator['time'].dt.date
|
||||
df_h1['date_key'] = df_h1['time'].dt.date
|
||||
df_merged = pd.merge(df_h1, df_d1_indicator[['date_key', 'D1_MACDh']], on='date_key', how='left')
|
||||
df_merged['D1_MACDh'] = df_merged['D1_MACDh'].ffill()
|
||||
df_merged.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("5. Memulai loop backtest...")
|
||||
for i in range(1, len(df_merged)):
|
||||
current, prev = df_merged.iloc[i], df_merged.iloc[i - 1]
|
||||
|
||||
if position:
|
||||
is_buy_pos = position['type'] == 'BUY'
|
||||
|
||||
if is_buy_pos and prev['STOCHk_14_3_3'] > prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3']:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
elif not is_buy_pos and prev['STOCHk_14_3_3'] < prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3']:
|
||||
# --- PERBAIKAN DI SINI ---
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
if not position:
|
||||
is_buy_signal = (current['D1_MACDh'] < -0.02 and current['MACDh_12_26_9'] < -0.02 and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] <= prev['STOCHd_14_3_3'])
|
||||
is_sell_signal = (current['D1_MACDh'] < 0 and current['MACDh_12_26_9'] < 0 and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] >= prev['STOCHd_14_3_3'])
|
||||
if is_buy_signal:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif is_sell_signal:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df_merged['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi "MERCY_REVERSAL" on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
# --- Jalankan Backtest ---
|
||||
if __name__ == '__main__':
|
||||
# Sekarang kita perlu memberi tahu backtester simbol apa yang sedang diuji
|
||||
symbol_to_test = "EURUSD" # Ubah ini ke "EURUSD" jika ingin menguji EURUSD
|
||||
file_name = "EURUSD_16385_data.csv" # Pastikan nama file cocok
|
||||
|
||||
run_mercy_reversal_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,76 @@
|
||||
# backtester_mercy_trend.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_mercy_trend_backtest(h1_data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest MERCY_TREND (Technical Base) untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
|
||||
# Tahap 1 & 2: Load dan siapkan data (sama seperti Full Mercy)
|
||||
df_h1 = pd.read_csv(h1_data_path, parse_dates=['time'])
|
||||
df_d1 = df_h1.resample('D', on='time').agg({'open': 'first', 'high': 'max', 'low': 'min', 'close': 'last'}).dropna().reset_index()
|
||||
df_d1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.macd(close='close', fast=12, slow=26, signal=9, append=True)
|
||||
df_h1.ta.stoch(high='high', low='low', close='close', k=14, d=3, smooth_k=3, append=True)
|
||||
|
||||
# Tahap 3: Gabungkan data
|
||||
df_d1_indicator = df_d1[['time', 'MACDh_12_26_9']].rename(columns={'MACDh_12_26_9': 'D1_MACDh'})
|
||||
df_d1_indicator['date_key'] = df_d1_indicator['time'].dt.date
|
||||
df_h1['date_key'] = df_h1['time'].dt.date
|
||||
df_merged = pd.merge(df_h1, df_d1_indicator[['date_key', 'D1_MACDh']], on='date_key', how='left')
|
||||
df_merged['D1_MACDh'] = df_merged['D1_MACDh'].ffill()
|
||||
df_merged.dropna(inplace=True)
|
||||
|
||||
# Tahap 4: Simulasi
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df_merged)):
|
||||
current, prev = df_merged.iloc[i], df_merged.iloc[i - 1]
|
||||
|
||||
# Logika Exit
|
||||
if position:
|
||||
is_buy_pos = position['type'] == 'BUY'
|
||||
if is_buy_pos and prev['STOCHk_14_3_3'] > prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif not is_buy_pos and prev['STOCHk_14_3_3'] < prev['STOCHd_14_3_3'] and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
|
||||
# Logika Entry (Sesuai sinyal TA dari Mercy Edge)
|
||||
if not position:
|
||||
is_buy_signal = (current['D1_MACDh'] > 0 and current['MACDh_12_26_9'] > 0 and current['STOCHk_14_3_3'] > current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] <= prev['STOCHd_14_3_3'])
|
||||
is_sell_signal = (current['D1_MACDh'] < 0 and current['MACDh_12_26_9'] < 0 and current['STOCHk_14_3_3'] < current['STOCHd_14_3_3'] and prev['STOCHk_14_3_3'] >= prev['STOCHd_14_3_3'])
|
||||
if is_buy_signal:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif is_sell_signal:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# Tahap 5: Analisis
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df_merged['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi MERCY_TREND (TA Base) on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "EURUSD"
|
||||
file_name = "lab/EURUSD_16385_data.csv"
|
||||
run_mercy_trend_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,73 @@
|
||||
# backtester_rsi_breakout.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
# Kita pinjam fungsi helper dari backtester sebelumnya
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_rsi_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest RSI_BREAKOUT untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
df.ta.rsi(length=14, append=True)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i-1] # Kita butuh baris sebelumnya untuk deteksi cross
|
||||
|
||||
# --- Logika Exit (Sangat Penting untuk RSI) ---
|
||||
# Keluar posisi jika RSI kembali ke zona netral (misal: cross 50)
|
||||
if position:
|
||||
if position['type'] == 'BUY' and prev['RSI_14'] < 50 and current['RSI_14'] >= 50:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
elif position['type'] == 'SELL' and prev['RSI_14'] > 50 and current['RSI_14'] <= 50:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
# --- Logika Entry (Hanya jika tidak ada posisi) ---
|
||||
if not position:
|
||||
# Sinyal BELI: RSI cross ke bawah 30
|
||||
if prev['RSI_14'] >= 30 and current['RSI_14'] < 30:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
# Sinyal JUAL: RSI cross ke atas 70
|
||||
elif prev['RSI_14'] <= 70 and current['RSI_14'] > 70:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi RSI_BREAKOUT on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
# --- Jalankan Backtest ---
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "EURUSD"
|
||||
file_name = "lab/EURUSD_16385_data.csv"
|
||||
run_rsi_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,90 @@
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
elif "JPY" in symbol:
|
||||
return 1000 * lot_size
|
||||
else:
|
||||
return 100000 * lot_size
|
||||
|
||||
def run_rsi_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest RSI ONLY untuk simbol: {symbol}")
|
||||
LOT_SIZE = 0.01
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
print(f"Multiplier profit yang digunakan: {multiplier}")
|
||||
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
df['rsi'] = ta.rsi(df['close'], length=14)
|
||||
df.dropna(inplace=True)
|
||||
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
cooldown = 0
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)):
|
||||
current = df.iloc[i]
|
||||
if cooldown > 0:
|
||||
cooldown -= 1
|
||||
equity_curve.append(balance)
|
||||
continue
|
||||
|
||||
# EXIT
|
||||
if position:
|
||||
if 40 <= current['rsi'] <= 60:
|
||||
if position['type'] == 'BUY':
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
else:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'type': position['type'], 'profit': profit})
|
||||
position = None
|
||||
cooldown = 3
|
||||
|
||||
# ENTRY
|
||||
if not position:
|
||||
if current['rsi'] < 30:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
elif current['rsi'] > 70:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# Summary
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal : ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir : ${balance:.2f}")
|
||||
total_profit = balance - initial_balance
|
||||
print(f"Total Profit/Loss: ${total_profit:.2f} ({total_profit/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades : {len(trades)}")
|
||||
|
||||
wins = [t['profit'] for t in trades if t['profit'] > 0]
|
||||
losses = [t['profit'] for t in trades if t['profit'] <= 0]
|
||||
winrate = len(wins) / len(trades) * 100 if trades else 0
|
||||
profit_factor = sum(wins) / abs(sum(losses)) if losses else float('inf')
|
||||
avg_win = pd.Series(wins).mean() if wins else 0
|
||||
avg_loss = pd.Series(losses).mean() if losses else 0
|
||||
|
||||
print(f"Win Rate : {winrate:.2f}%")
|
||||
print(f"Profit Factor : {profit_factor:.2f}")
|
||||
print(f"Avg Win / Loss : ${avg_win:.2f} / ${avg_loss:.2f}")
|
||||
|
||||
# Plot
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[-len(equity_curve):], equity_curve, label='Equity Curve')
|
||||
plt.title(f'Equity Curve - RSI ONLY on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.legend()
|
||||
plt.tight_layout()
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
symbol_to_test = "USDJPY" # Ganti dengan simbol yang ingin diuji
|
||||
file_name = "lab/USDJPY_16385_data.csv"
|
||||
run_rsi_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,106 @@
|
||||
# backtester_trend_dip.py
|
||||
import pandas as pd
|
||||
import pandas_ta as ta
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
"""
|
||||
Mengembalikan multiplier yang benar untuk perhitungan profit berdasarkan
|
||||
simbol, kelas aset, dan ukuran lot.
|
||||
"""
|
||||
# 1. Untuk Indeks Saham (seperti US500, NAS100, SPX500m, dll.)
|
||||
# Pergerakan 1 poin = profit $0.01 untuk 0.01 lot.
|
||||
if "500" in symbol or "100" in symbol or "30" in symbol:
|
||||
return 1 * lot_size
|
||||
|
||||
# 2. Untuk Emas (XAUUSD)
|
||||
# Pergerakan $1 = profit $1 untuk 0.01 lot.
|
||||
elif "XAU" in symbol:
|
||||
return 100 * lot_size
|
||||
|
||||
# 3. Untuk Pasangan Mata Uang Forex (seperti EURUSD, USDJPY)
|
||||
# Pergerakan 1 pip = profit ~$0.10 untuk 0.01 lot.
|
||||
# Nilai 100000 adalah standar industri untuk 1 lot.
|
||||
else:
|
||||
# Periksa apakah ini pasangan JPY, karena nilainya berbeda
|
||||
if "JPY" in symbol:
|
||||
return 1000 * lot_size # Untuk pasangan JPY, 1 pip adalah 0.01
|
||||
else:
|
||||
return 100000 * lot_size # Untuk pasangan non-JPY, 1 pip adalah 0.0001
|
||||
|
||||
def run_trend_dip_backtest(data_path, symbol, initial_balance=10000):
|
||||
"""
|
||||
Menjalankan backtest untuk strategi "Trend & Dip", yang dirancang khusus
|
||||
untuk pasar saham/indeks dengan bias bullish jangka panjang.
|
||||
"""
|
||||
print(f"Memulai backtest TREND & DIP untuk simbol: {symbol}")
|
||||
# Kode baru yang disarankan
|
||||
LOT_SIZE = 0.01 # Definisikan ukuran lot di satu tempat
|
||||
multiplier = get_profit_multiplier(symbol, LOT_SIZE)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Indikator ---
|
||||
# 1. "Wasit" Tren Jangka Panjang: SMA 200
|
||||
df['SMA_200'] = ta.sma(df['close'], length=200)
|
||||
|
||||
# 2. "Pemicu" Entry/Exit Jangka Pendek: RSI 14
|
||||
df['RSI_14'] = ta.rsi(df['close'], length=14)
|
||||
|
||||
df.dropna(inplace=True)
|
||||
df = df.reset_index(drop=True)
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(1, len(df)): # Mulai dari 1 agar bisa akses `prev`
|
||||
current = df.iloc[i]
|
||||
prev = df.iloc[i-1]
|
||||
|
||||
# --- Logika Exit (Keluar jika pasar sudah "panas" kembali) ---
|
||||
if position:
|
||||
# Keluar dari posisi Beli jika RSI cross ke atas 70
|
||||
if position['type'] == 'BUY' and prev['RSI_14'] <= 70 and current['RSI_14'] > 70:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit
|
||||
trades.append({'profit': profit})
|
||||
position = None
|
||||
|
||||
# --- Logika Entry (SANGAT SELEKTIF) ---
|
||||
if not position:
|
||||
# Kondisi 1: Apakah kita di "Musim Bullish"? (Harga di atas SMA 200)
|
||||
is_bull_market = current['close'] > current['SMA_200']
|
||||
|
||||
# Kondisi 2: Apakah ada "Diskon"? (RSI baru saja turun di bawah 40)
|
||||
is_dip_signal = prev['RSI_14'] >= 40 and current['RSI_14'] < 40
|
||||
|
||||
# Hanya buka posisi Beli jika KEDUA kondisi terpenuhi
|
||||
if is_bull_market and is_dip_signal:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
|
||||
# Strategi ini TIDAK membuka posisi JUAL (short).
|
||||
# Ini adalah fitur desain untuk menghormati bias bullish pasar saham.
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'].iloc[1:], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi TREND & DIP on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# Ganti ini untuk menguji Indeks yang berbeda
|
||||
symbol_to_test = "US500" # atau "SP500m", "ND100m", dll.
|
||||
file_name = "lab/US500_16385_data.csv" # Pastikan nama file cocok
|
||||
|
||||
run_trend_dip_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,79 @@
|
||||
# backtester_turtle.py
|
||||
import pandas as pd
|
||||
import matplotlib.pyplot as plt
|
||||
|
||||
def get_profit_multiplier(symbol, lot_size=0.01):
|
||||
if "USD" in symbol and "XAU" not in symbol: return 100000 * lot_size
|
||||
elif "XAU" in symbol: return 100 * lot_size
|
||||
else: return 1
|
||||
|
||||
def run_turtle_backtest(data_path, symbol, initial_balance=10000):
|
||||
print(f"Memulai backtest TURTLE BREAKOUT untuk simbol: {symbol}")
|
||||
multiplier = get_profit_multiplier(symbol)
|
||||
df = pd.read_csv(data_path, parse_dates=['time'])
|
||||
|
||||
# --- Hitung Channel untuk Entry dan Exit ---
|
||||
# Channel untuk sinyal masuk (periode 20)
|
||||
# .shift(1) SANGAT PENTING untuk mencegah "melihat ke masa depan"
|
||||
df['entry_upper'] = df['high'].rolling(window=20).max().shift(1)
|
||||
df['entry_lower'] = df['low'].rolling(window=20).min().shift(1)
|
||||
|
||||
# Channel untuk sinyal keluar (periode 10)
|
||||
df['exit_upper'] = df['high'].rolling(window=10).max().shift(1)
|
||||
df['exit_lower'] = df['low'].rolling(window=10).min().shift(1)
|
||||
|
||||
df.dropna(inplace=True)
|
||||
df = df.reset_index(drop=True) # Reset index setelah dropna
|
||||
|
||||
# --- Siapkan Variabel Simulasi ---
|
||||
balance, position, trades, equity_curve = initial_balance, None, [], []
|
||||
|
||||
print("Memulai Loop Backtest...")
|
||||
for i in range(len(df)):
|
||||
current = df.iloc[i]
|
||||
|
||||
# --- Logika Exit ---
|
||||
if position:
|
||||
if position['type'] == 'BUY' and current['close'] < current['exit_lower']:
|
||||
profit = (current['close'] - position['entry_price']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
elif position['type'] == 'SELL' and current['close'] > current['exit_upper']:
|
||||
profit = (position['entry_price'] - current['close']) * multiplier
|
||||
balance += profit; trades.append({'profit': profit}); position = None
|
||||
|
||||
# --- Logika Entry (Hanya jika tidak ada posisi) ---
|
||||
if not position:
|
||||
# Sinyal BELI: Harga menembus ke atas channel 20 periode
|
||||
if current['close'] > current['entry_upper']:
|
||||
position = {'type': 'BUY', 'entry_price': current['close']}
|
||||
# Sinyal JUAL: Harga menembus ke bawah channel 20 periode
|
||||
elif current['close'] < current['entry_lower']:
|
||||
position = {'type': 'SELL', 'entry_price': current['close']}
|
||||
|
||||
equity_curve.append(balance)
|
||||
|
||||
# --- Analisis Hasil ---
|
||||
print("\n--- Backtest Selesai ---")
|
||||
print(f"Balance Awal: ${initial_balance:.2f}")
|
||||
print(f"Balance Akhir: ${balance:.2f}")
|
||||
print(f"Total Profit/Loss: ${balance - initial_balance:.2f} ({(balance - initial_balance)/initial_balance*100:.2f}%)")
|
||||
print(f"Total Trades: {len(trades)}")
|
||||
|
||||
plt.figure(figsize=(12, 6))
|
||||
plt.plot(df['time'], equity_curve)
|
||||
plt.title(f'Equity Curve - Strategi TURTLE BREAKOUT on {symbol}')
|
||||
plt.xlabel('Tanggal')
|
||||
plt.ylabel('Balance ($)')
|
||||
plt.grid(True)
|
||||
plt.show()
|
||||
|
||||
if __name__ == '__main__':
|
||||
# UJI COBA #1: Di pasar tren (XAUUSD)
|
||||
symbol_to_test = "XAUUSD"
|
||||
file_name = "XAUUSD_16385_data.csv"
|
||||
|
||||
# UJI COBA #2: Di pasar sideways (EURUSD)
|
||||
#symbol_to_test = "EURUSD"
|
||||
#file_name = "EURUSD_16385_data.csv"
|
||||
|
||||
run_turtle_backtest(file_name, symbol=symbol_to_test)
|
||||
@@ -0,0 +1,38 @@
|
||||
# download_data.py
|
||||
import MetaTrader5 as mt5
|
||||
import pandas as pd
|
||||
from datetime import datetime
|
||||
|
||||
# --- Kredensial Anda ---
|
||||
ACCOUNT = 94464091
|
||||
PASSWORD = "3rX@GcMm"
|
||||
SERVER = "MetaQuotes-Demo"
|
||||
|
||||
# --- Inisialisasi MT5 ---
|
||||
if not mt5.initialize(login=ACCOUNT, password=PASSWORD, server=SERVER):
|
||||
print("Gagal menginisialisasi MT5!", mt5.last_error())
|
||||
mt5.shutdown()
|
||||
else:
|
||||
print("Berhasil terhubung ke MT5")
|
||||
|
||||
# --- Parameter Download ---
|
||||
symbol = "SP500m" # Ganti dengan simbol yang Anda inginkan
|
||||
timeframe = mt5.TIMEFRAME_H1 # Timeframe 1 Jam
|
||||
start_date = datetime(2020, 1, 1) # Mulai dari 1 Januari 2020
|
||||
end_date = datetime.now() # Sampai sekarang
|
||||
|
||||
# --- Ambil Data ---
|
||||
rates = mt5.copy_rates_range(symbol, timeframe, start_date, end_date)
|
||||
mt5.shutdown()
|
||||
|
||||
# --- Simpan ke File CSV ---
|
||||
if rates is not None and len(rates) > 0:
|
||||
df = pd.DataFrame(rates)
|
||||
df['time'] = pd.to_datetime(df['time'], unit='s')
|
||||
|
||||
# Simpan ke file agar tidak perlu download lagi
|
||||
file_path = f'{symbol}_{timeframe}_data.csv'
|
||||
df.to_csv(file_path, index=False)
|
||||
print(f"Data berhasil disimpan ke {file_path}. Total {len(df)} baris.")
|
||||
else:
|
||||
print("Tidak ada data yang diunduh.")
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../acorn/bin/acorn" "$@"
|
||||
else
|
||||
exec node "$basedir/../acorn/bin/acorn" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\acorn\bin\acorn" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../acorn/bin/acorn" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../eslint/bin/eslint.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../eslint/bin/eslint.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\eslint\bin\eslint.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../eslint/bin/eslint.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||
else
|
||||
exec node "$basedir/../js-yaml/bin/js-yaml.js" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\js-yaml\bin\js-yaml.js" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../js-yaml/bin/js-yaml.js" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
#!/bin/sh
|
||||
basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')")
|
||||
|
||||
case `uname` in
|
||||
*CYGWIN*|*MINGW*|*MSYS*)
|
||||
if command -v cygpath > /dev/null 2>&1; then
|
||||
basedir=`cygpath -w "$basedir"`
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
|
||||
if [ -x "$basedir/node" ]; then
|
||||
exec "$basedir/node" "$basedir/../which/bin/node-which" "$@"
|
||||
else
|
||||
exec node "$basedir/../which/bin/node-which" "$@"
|
||||
fi
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
@ECHO off
|
||||
GOTO start
|
||||
:find_dp0
|
||||
SET dp0=%~dp0
|
||||
EXIT /b
|
||||
:start
|
||||
SETLOCAL
|
||||
CALL :find_dp0
|
||||
|
||||
IF EXIST "%dp0%\node.exe" (
|
||||
SET "_prog=%dp0%\node.exe"
|
||||
) ELSE (
|
||||
SET "_prog=node"
|
||||
SET PATHEXT=%PATHEXT:;.JS;=;%
|
||||
)
|
||||
|
||||
endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & "%_prog%" "%dp0%\..\which\bin\node-which" %*
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env pwsh
|
||||
$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent
|
||||
|
||||
$exe=""
|
||||
if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) {
|
||||
# Fix case when both the Windows and Linux builds of Node
|
||||
# are installed in the same directory
|
||||
$exe=".exe"
|
||||
}
|
||||
$ret=0
|
||||
if (Test-Path "$basedir/node$exe") {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||
} else {
|
||||
& "$basedir/node$exe" "$basedir/../which/bin/node-which" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
} else {
|
||||
# Support pipeline input
|
||||
if ($MyInvocation.ExpectingInput) {
|
||||
$input | & "node$exe" "$basedir/../which/bin/node-which" $args
|
||||
} else {
|
||||
& "node$exe" "$basedir/../which/bin/node-which" $args
|
||||
}
|
||||
$ret=$LASTEXITCODE
|
||||
}
|
||||
exit $ret
|
||||
+2268
File diff suppressed because it is too large
Load Diff
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
# @eslint-community/eslint-utils
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/eslint-utils)
|
||||
[](http://www.npmtrends.com/@eslint-community/eslint-utils)
|
||||
[](https://github.com/eslint-community/eslint-utils/actions)
|
||||
[](https://codecov.io/gh/eslint-community/eslint-utils)
|
||||
|
||||
## 🏁 Goal
|
||||
|
||||
This package provides utility functions and classes for make ESLint custom rules.
|
||||
|
||||
For examples:
|
||||
|
||||
- [`getStaticValue`](https://eslint-community.github.io/eslint-utils/api/ast-utils.html#getstaticvalue) evaluates static value on AST.
|
||||
- [`ReferenceTracker`](https://eslint-community.github.io/eslint-utils/api/scope-utils.html#referencetracker-class) checks the members of modules/globals as handling assignments and destructuring.
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
See [documentation](https://eslint-community.github.io/eslint-utils).
|
||||
|
||||
## 📰 Changelog
|
||||
|
||||
See [releases](https://github.com/eslint-community/eslint-utils/releases).
|
||||
|
||||
## ❤️ Contributing
|
||||
|
||||
Welcome contributing!
|
||||
|
||||
Please use GitHub's Issues/PRs.
|
||||
|
||||
### Development Tools
|
||||
|
||||
- `npm run test-coverage` runs tests and measures coverage.
|
||||
- `npm run clean` removes the coverage result of `npm run test-coverage` command.
|
||||
- `npm run coverage` shows the coverage result of the last `npm run test-coverage` command.
|
||||
- `npm run lint` runs ESLint.
|
||||
- `npm run watch` runs tests on each file change.
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
import * as eslint from 'eslint';
|
||||
import { Rule, AST } from 'eslint';
|
||||
import * as estree from 'estree';
|
||||
|
||||
declare const READ: unique symbol;
|
||||
declare const CALL: unique symbol;
|
||||
declare const CONSTRUCT: unique symbol;
|
||||
declare const ESM: unique symbol;
|
||||
declare class ReferenceTracker {
|
||||
constructor(globalScope: Scope$2, options?: {
|
||||
mode?: "legacy" | "strict" | undefined;
|
||||
globalObjectNames?: string[] | undefined;
|
||||
} | undefined);
|
||||
private variableStack;
|
||||
private globalScope;
|
||||
private mode;
|
||||
private globalObjectNames;
|
||||
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
|
||||
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
|
||||
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
|
||||
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
|
||||
private _iterateVariableReferences;
|
||||
private _iteratePropertyReferences;
|
||||
private _iterateLhsReferences;
|
||||
private _iterateImportReferences;
|
||||
}
|
||||
declare namespace ReferenceTracker {
|
||||
export { READ };
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
}
|
||||
type Scope$2 = eslint.Scope.Scope;
|
||||
type Expression = estree.Expression;
|
||||
type TraceMap$2<T> = TraceMap$1<T>;
|
||||
type TrackedReferences$2<T> = TrackedReferences$1<T>;
|
||||
|
||||
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
|
||||
type StaticValueProvided$1 = {
|
||||
optional?: undefined;
|
||||
value: unknown;
|
||||
};
|
||||
type StaticValueOptional$1 = {
|
||||
optional?: true;
|
||||
value: undefined;
|
||||
};
|
||||
type ReferenceTrackerOptions$1 = {
|
||||
globalObjectNames?: string[];
|
||||
mode?: "legacy" | "strict";
|
||||
};
|
||||
type TraceMap$1<T = unknown> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
};
|
||||
type TraceMapObject<T> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
[CALL]?: T;
|
||||
[CONSTRUCT]?: T;
|
||||
[READ]?: T;
|
||||
[ESM]?: boolean;
|
||||
};
|
||||
type TrackedReferences$1<T> = {
|
||||
info: T;
|
||||
node: Rule.Node;
|
||||
path: string[];
|
||||
type: typeof CALL | typeof CONSTRUCT | typeof READ;
|
||||
};
|
||||
type HasSideEffectOptions$1 = {
|
||||
considerGetters?: boolean;
|
||||
considerImplicitTypeConversion?: boolean;
|
||||
};
|
||||
type PunctuatorToken<Value extends string> = AST.Token & {
|
||||
type: "Punctuator";
|
||||
value: Value;
|
||||
};
|
||||
type ArrowToken$1 = PunctuatorToken<"=>">;
|
||||
type CommaToken$1 = PunctuatorToken<",">;
|
||||
type SemicolonToken$1 = PunctuatorToken<";">;
|
||||
type ColonToken$1 = PunctuatorToken<":">;
|
||||
type OpeningParenToken$1 = PunctuatorToken<"(">;
|
||||
type ClosingParenToken$1 = PunctuatorToken<")">;
|
||||
type OpeningBracketToken$1 = PunctuatorToken<"[">;
|
||||
type ClosingBracketToken$1 = PunctuatorToken<"]">;
|
||||
type OpeningBraceToken$1 = PunctuatorToken<"{">;
|
||||
type ClosingBraceToken$1 = PunctuatorToken<"}">;
|
||||
|
||||
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
|
||||
type Scope$1 = eslint.Scope.Scope;
|
||||
type Variable = eslint.Scope.Variable;
|
||||
type Identifier = estree.Identifier;
|
||||
|
||||
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
|
||||
type SourceCode$2 = eslint.SourceCode;
|
||||
type FunctionNode$1 = estree.Function;
|
||||
type SourceLocation = estree.SourceLocation;
|
||||
|
||||
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
|
||||
type FunctionNode = estree.Function;
|
||||
|
||||
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
|
||||
type Scope = eslint.Scope.Scope;
|
||||
type Node$4 = estree.Node;
|
||||
|
||||
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
|
||||
type MemberExpression = estree.MemberExpression;
|
||||
type MethodDefinition = estree.MethodDefinition;
|
||||
type Property = estree.Property;
|
||||
type PropertyDefinition = estree.PropertyDefinition;
|
||||
|
||||
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
|
||||
type StaticValue$1 = StaticValue$2;
|
||||
type Node$3 = estree.Node;
|
||||
|
||||
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
|
||||
type Node$2 = estree.Node;
|
||||
|
||||
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
|
||||
type Node$1 = estree.Node;
|
||||
type SourceCode$1 = eslint.SourceCode;
|
||||
|
||||
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
|
||||
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
|
||||
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
|
||||
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
|
||||
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
|
||||
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
|
||||
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
|
||||
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
|
||||
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
|
||||
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
|
||||
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
|
||||
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotColonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
|
||||
type Token = eslint.AST.Token;
|
||||
type Comment = estree.Comment;
|
||||
type CommentOrToken = Comment | Token;
|
||||
|
||||
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
|
||||
type Node = estree.Node;
|
||||
type SourceCode = eslint.SourceCode;
|
||||
|
||||
declare class PatternMatcher {
|
||||
constructor(pattern: RegExp, options?: {
|
||||
escaped?: boolean | undefined;
|
||||
} | undefined);
|
||||
execAll(str: string): IterableIterator<RegExpExecArray>;
|
||||
test(str: string): boolean;
|
||||
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
|
||||
}
|
||||
|
||||
declare namespace _default {
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
export { findVariable };
|
||||
export { getFunctionHeadLocation };
|
||||
export { getFunctionNameWithKind };
|
||||
export { getInnermostScope };
|
||||
export { getPropertyName };
|
||||
export { getStaticValue };
|
||||
export { getStringIfConstant };
|
||||
export { hasSideEffect };
|
||||
export { isArrowToken };
|
||||
export { isClosingBraceToken };
|
||||
export { isClosingBracketToken };
|
||||
export { isClosingParenToken };
|
||||
export { isColonToken };
|
||||
export { isCommaToken };
|
||||
export { isCommentToken };
|
||||
export { isNotArrowToken };
|
||||
export { isNotClosingBraceToken };
|
||||
export { isNotClosingBracketToken };
|
||||
export { isNotClosingParenToken };
|
||||
export { isNotColonToken };
|
||||
export { isNotCommaToken };
|
||||
export { isNotCommentToken };
|
||||
export { isNotOpeningBraceToken };
|
||||
export { isNotOpeningBracketToken };
|
||||
export { isNotOpeningParenToken };
|
||||
export { isNotSemicolonToken };
|
||||
export { isOpeningBraceToken };
|
||||
export { isOpeningBracketToken };
|
||||
export { isOpeningParenToken };
|
||||
export { isParenthesized };
|
||||
export { isSemicolonToken };
|
||||
export { PatternMatcher };
|
||||
export { READ };
|
||||
export { ReferenceTracker };
|
||||
}
|
||||
|
||||
type StaticValue = StaticValue$2;
|
||||
type StaticValueOptional = StaticValueOptional$1;
|
||||
type StaticValueProvided = StaticValueProvided$1;
|
||||
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
|
||||
type TraceMap<T> = TraceMap$1<T>;
|
||||
type TrackedReferences<T> = TrackedReferences$1<T>;
|
||||
type HasSideEffectOptions = HasSideEffectOptions$1;
|
||||
type ArrowToken = ArrowToken$1;
|
||||
type CommaToken = CommaToken$1;
|
||||
type SemicolonToken = SemicolonToken$1;
|
||||
type ColonToken = ColonToken$1;
|
||||
type OpeningParenToken = OpeningParenToken$1;
|
||||
type ClosingParenToken = ClosingParenToken$1;
|
||||
type OpeningBracketToken = OpeningBracketToken$1;
|
||||
type ClosingBracketToken = ClosingBracketToken$1;
|
||||
type OpeningBraceToken = OpeningBraceToken$1;
|
||||
type ClosingBraceToken = ClosingBraceToken$1;
|
||||
|
||||
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
+217
@@ -0,0 +1,217 @@
|
||||
import * as eslint from 'eslint';
|
||||
import { Rule, AST } from 'eslint';
|
||||
import * as estree from 'estree';
|
||||
|
||||
declare const READ: unique symbol;
|
||||
declare const CALL: unique symbol;
|
||||
declare const CONSTRUCT: unique symbol;
|
||||
declare const ESM: unique symbol;
|
||||
declare class ReferenceTracker {
|
||||
constructor(globalScope: Scope$2, options?: {
|
||||
mode?: "legacy" | "strict" | undefined;
|
||||
globalObjectNames?: string[] | undefined;
|
||||
} | undefined);
|
||||
private variableStack;
|
||||
private globalScope;
|
||||
private mode;
|
||||
private globalObjectNames;
|
||||
iterateGlobalReferences<T>(traceMap: TraceMap$2<T>): IterableIterator<TrackedReferences$2<T>>;
|
||||
iterateCjsReferences<T_1>(traceMap: TraceMap$2<T_1>): IterableIterator<TrackedReferences$2<T_1>>;
|
||||
iterateEsmReferences<T_2>(traceMap: TraceMap$2<T_2>): IterableIterator<TrackedReferences$2<T_2>>;
|
||||
iteratePropertyReferences<T_3>(node: Expression, traceMap: TraceMap$2<T_3>): IterableIterator<TrackedReferences$2<T_3>>;
|
||||
private _iterateVariableReferences;
|
||||
private _iteratePropertyReferences;
|
||||
private _iterateLhsReferences;
|
||||
private _iterateImportReferences;
|
||||
}
|
||||
declare namespace ReferenceTracker {
|
||||
export { READ };
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
}
|
||||
type Scope$2 = eslint.Scope.Scope;
|
||||
type Expression = estree.Expression;
|
||||
type TraceMap$2<T> = TraceMap$1<T>;
|
||||
type TrackedReferences$2<T> = TrackedReferences$1<T>;
|
||||
|
||||
type StaticValue$2 = StaticValueProvided$1 | StaticValueOptional$1;
|
||||
type StaticValueProvided$1 = {
|
||||
optional?: undefined;
|
||||
value: unknown;
|
||||
};
|
||||
type StaticValueOptional$1 = {
|
||||
optional?: true;
|
||||
value: undefined;
|
||||
};
|
||||
type ReferenceTrackerOptions$1 = {
|
||||
globalObjectNames?: string[];
|
||||
mode?: "legacy" | "strict";
|
||||
};
|
||||
type TraceMap$1<T = unknown> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
};
|
||||
type TraceMapObject<T> = {
|
||||
[i: string]: TraceMapObject<T>;
|
||||
[CALL]?: T;
|
||||
[CONSTRUCT]?: T;
|
||||
[READ]?: T;
|
||||
[ESM]?: boolean;
|
||||
};
|
||||
type TrackedReferences$1<T> = {
|
||||
info: T;
|
||||
node: Rule.Node;
|
||||
path: string[];
|
||||
type: typeof CALL | typeof CONSTRUCT | typeof READ;
|
||||
};
|
||||
type HasSideEffectOptions$1 = {
|
||||
considerGetters?: boolean;
|
||||
considerImplicitTypeConversion?: boolean;
|
||||
};
|
||||
type PunctuatorToken<Value extends string> = AST.Token & {
|
||||
type: "Punctuator";
|
||||
value: Value;
|
||||
};
|
||||
type ArrowToken$1 = PunctuatorToken<"=>">;
|
||||
type CommaToken$1 = PunctuatorToken<",">;
|
||||
type SemicolonToken$1 = PunctuatorToken<";">;
|
||||
type ColonToken$1 = PunctuatorToken<":">;
|
||||
type OpeningParenToken$1 = PunctuatorToken<"(">;
|
||||
type ClosingParenToken$1 = PunctuatorToken<")">;
|
||||
type OpeningBracketToken$1 = PunctuatorToken<"[">;
|
||||
type ClosingBracketToken$1 = PunctuatorToken<"]">;
|
||||
type OpeningBraceToken$1 = PunctuatorToken<"{">;
|
||||
type ClosingBraceToken$1 = PunctuatorToken<"}">;
|
||||
|
||||
declare function findVariable(initialScope: Scope$1, nameOrNode: string | Identifier): Variable | null;
|
||||
type Scope$1 = eslint.Scope.Scope;
|
||||
type Variable = eslint.Scope.Variable;
|
||||
type Identifier = estree.Identifier;
|
||||
|
||||
declare function getFunctionHeadLocation(node: FunctionNode$1, sourceCode: SourceCode$2): SourceLocation | null;
|
||||
type SourceCode$2 = eslint.SourceCode;
|
||||
type FunctionNode$1 = estree.Function;
|
||||
type SourceLocation = estree.SourceLocation;
|
||||
|
||||
declare function getFunctionNameWithKind(node: FunctionNode, sourceCode?: eslint.SourceCode | undefined): string;
|
||||
type FunctionNode = estree.Function;
|
||||
|
||||
declare function getInnermostScope(initialScope: Scope, node: Node$4): Scope;
|
||||
type Scope = eslint.Scope.Scope;
|
||||
type Node$4 = estree.Node;
|
||||
|
||||
declare function getPropertyName(node: MemberExpression | MethodDefinition | Property | PropertyDefinition, initialScope?: eslint.Scope.Scope | undefined): string | null | undefined;
|
||||
type MemberExpression = estree.MemberExpression;
|
||||
type MethodDefinition = estree.MethodDefinition;
|
||||
type Property = estree.Property;
|
||||
type PropertyDefinition = estree.PropertyDefinition;
|
||||
|
||||
declare function getStaticValue(node: Node$3, initialScope?: eslint.Scope.Scope | null | undefined): StaticValue$1 | null;
|
||||
type StaticValue$1 = StaticValue$2;
|
||||
type Node$3 = estree.Node;
|
||||
|
||||
declare function getStringIfConstant(node: Node$2, initialScope?: eslint.Scope.Scope | null | undefined): string | null;
|
||||
type Node$2 = estree.Node;
|
||||
|
||||
declare function hasSideEffect(node: Node$1, sourceCode: SourceCode$1, options?: HasSideEffectOptions$1 | undefined): boolean;
|
||||
type Node$1 = estree.Node;
|
||||
type SourceCode$1 = eslint.SourceCode;
|
||||
|
||||
declare function isArrowToken(token: CommentOrToken): token is ArrowToken$1;
|
||||
declare function isCommaToken(token: CommentOrToken): token is CommaToken$1;
|
||||
declare function isSemicolonToken(token: CommentOrToken): token is SemicolonToken$1;
|
||||
declare function isColonToken(token: CommentOrToken): token is ColonToken$1;
|
||||
declare function isOpeningParenToken(token: CommentOrToken): token is OpeningParenToken$1;
|
||||
declare function isClosingParenToken(token: CommentOrToken): token is ClosingParenToken$1;
|
||||
declare function isOpeningBracketToken(token: CommentOrToken): token is OpeningBracketToken$1;
|
||||
declare function isClosingBracketToken(token: CommentOrToken): token is ClosingBracketToken$1;
|
||||
declare function isOpeningBraceToken(token: CommentOrToken): token is OpeningBraceToken$1;
|
||||
declare function isClosingBraceToken(token: CommentOrToken): token is ClosingBraceToken$1;
|
||||
declare function isCommentToken(token: CommentOrToken): token is estree.Comment;
|
||||
declare function isNotArrowToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommaToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotSemicolonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotColonToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingParenToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBracketToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotOpeningBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotClosingBraceToken(arg0: CommentOrToken): boolean;
|
||||
declare function isNotCommentToken(arg0: CommentOrToken): boolean;
|
||||
type Token = eslint.AST.Token;
|
||||
type Comment = estree.Comment;
|
||||
type CommentOrToken = Comment | Token;
|
||||
|
||||
declare function isParenthesized(timesOrNode: Node | number, nodeOrSourceCode: Node | SourceCode, optionalSourceCode?: eslint.SourceCode | undefined): boolean;
|
||||
type Node = estree.Node;
|
||||
type SourceCode = eslint.SourceCode;
|
||||
|
||||
declare class PatternMatcher {
|
||||
constructor(pattern: RegExp, options?: {
|
||||
escaped?: boolean | undefined;
|
||||
} | undefined);
|
||||
execAll(str: string): IterableIterator<RegExpExecArray>;
|
||||
test(str: string): boolean;
|
||||
[Symbol.replace](str: string, replacer: string | ((...strs: string[]) => string)): string;
|
||||
}
|
||||
|
||||
declare namespace _default {
|
||||
export { CALL };
|
||||
export { CONSTRUCT };
|
||||
export { ESM };
|
||||
export { findVariable };
|
||||
export { getFunctionHeadLocation };
|
||||
export { getFunctionNameWithKind };
|
||||
export { getInnermostScope };
|
||||
export { getPropertyName };
|
||||
export { getStaticValue };
|
||||
export { getStringIfConstant };
|
||||
export { hasSideEffect };
|
||||
export { isArrowToken };
|
||||
export { isClosingBraceToken };
|
||||
export { isClosingBracketToken };
|
||||
export { isClosingParenToken };
|
||||
export { isColonToken };
|
||||
export { isCommaToken };
|
||||
export { isCommentToken };
|
||||
export { isNotArrowToken };
|
||||
export { isNotClosingBraceToken };
|
||||
export { isNotClosingBracketToken };
|
||||
export { isNotClosingParenToken };
|
||||
export { isNotColonToken };
|
||||
export { isNotCommaToken };
|
||||
export { isNotCommentToken };
|
||||
export { isNotOpeningBraceToken };
|
||||
export { isNotOpeningBracketToken };
|
||||
export { isNotOpeningParenToken };
|
||||
export { isNotSemicolonToken };
|
||||
export { isOpeningBraceToken };
|
||||
export { isOpeningBracketToken };
|
||||
export { isOpeningParenToken };
|
||||
export { isParenthesized };
|
||||
export { isSemicolonToken };
|
||||
export { PatternMatcher };
|
||||
export { READ };
|
||||
export { ReferenceTracker };
|
||||
}
|
||||
|
||||
type StaticValue = StaticValue$2;
|
||||
type StaticValueOptional = StaticValueOptional$1;
|
||||
type StaticValueProvided = StaticValueProvided$1;
|
||||
type ReferenceTrackerOptions = ReferenceTrackerOptions$1;
|
||||
type TraceMap<T> = TraceMap$1<T>;
|
||||
type TrackedReferences<T> = TrackedReferences$1<T>;
|
||||
type HasSideEffectOptions = HasSideEffectOptions$1;
|
||||
type ArrowToken = ArrowToken$1;
|
||||
type CommaToken = CommaToken$1;
|
||||
type SemicolonToken = SemicolonToken$1;
|
||||
type ColonToken = ColonToken$1;
|
||||
type OpeningParenToken = OpeningParenToken$1;
|
||||
type ClosingParenToken = ClosingParenToken$1;
|
||||
type OpeningBracketToken = OpeningBracketToken$1;
|
||||
type ClosingBracketToken = ClosingBracketToken$1;
|
||||
type OpeningBraceToken = OpeningBraceToken$1;
|
||||
type ClosingBraceToken = ClosingBraceToken$1;
|
||||
|
||||
export { ArrowToken, CALL, CONSTRUCT, ClosingBraceToken, ClosingBracketToken, ClosingParenToken, ColonToken, CommaToken, ESM, HasSideEffectOptions, OpeningBraceToken, OpeningBracketToken, OpeningParenToken, PatternMatcher, READ, ReferenceTracker, ReferenceTrackerOptions, SemicolonToken, StaticValue, StaticValueOptional, StaticValueProvided, TraceMap, TrackedReferences, _default as default, findVariable, getFunctionHeadLocation, getFunctionNameWithKind, getInnermostScope, getPropertyName, getStaticValue, getStringIfConstant, hasSideEffect, isArrowToken, isClosingBraceToken, isClosingBracketToken, isClosingParenToken, isColonToken, isCommaToken, isCommentToken, isNotArrowToken, isNotClosingBraceToken, isNotClosingBracketToken, isNotClosingParenToken, isNotColonToken, isNotCommaToken, isNotCommentToken, isNotOpeningBraceToken, isNotOpeningBracketToken, isNotOpeningParenToken, isNotSemicolonToken, isOpeningBraceToken, isOpeningBracketToken, isOpeningParenToken, isParenthesized, isSemicolonToken };
|
||||
+2494
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+2453
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
Generated
Vendored
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright contributors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
Generated
Vendored
+105
@@ -0,0 +1,105 @@
|
||||
# eslint-visitor-keys
|
||||
|
||||
[](https://www.npmjs.com/package/eslint-visitor-keys)
|
||||
[](http://www.npmtrends.com/eslint-visitor-keys)
|
||||
[](https://github.com/eslint/eslint-visitor-keys/actions)
|
||||
|
||||
Constants and utilities about visitor keys to traverse AST.
|
||||
|
||||
## 💿 Installation
|
||||
|
||||
Use [npm] to install.
|
||||
|
||||
```bash
|
||||
$ npm install eslint-visitor-keys
|
||||
```
|
||||
|
||||
### Requirements
|
||||
|
||||
- [Node.js] `^12.22.0`, `^14.17.0`, or `>=16.0.0`
|
||||
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
To use in an ESM file:
|
||||
|
||||
```js
|
||||
import * as evk from "eslint-visitor-keys"
|
||||
```
|
||||
|
||||
To use in a CommonJS file:
|
||||
|
||||
```js
|
||||
const evk = require("eslint-visitor-keys")
|
||||
```
|
||||
|
||||
### evk.KEYS
|
||||
|
||||
> type: `{ [type: string]: string[] | undefined }`
|
||||
|
||||
Visitor keys. This keys are frozen.
|
||||
|
||||
This is an object. Keys are the type of [ESTree] nodes. Their values are an array of property names which have child nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```
|
||||
console.log(evk.KEYS.AssignmentExpression) // → ["left", "right"]
|
||||
```
|
||||
|
||||
### evk.getKeys(node)
|
||||
|
||||
> type: `(node: object) => string[]`
|
||||
|
||||
Get the visitor keys of a given AST node.
|
||||
|
||||
This is similar to `Object.keys(node)` of ES Standard, but some keys are excluded: `parent`, `leadingComments`, `trailingComments`, and names which start with `_`.
|
||||
|
||||
This will be used to traverse unknown nodes.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
const node = {
|
||||
type: "AssignmentExpression",
|
||||
left: { type: "Identifier", name: "foo" },
|
||||
right: { type: "Literal", value: 0 }
|
||||
}
|
||||
console.log(evk.getKeys(node)) // → ["type", "left", "right"]
|
||||
```
|
||||
|
||||
### evk.unionWith(additionalKeys)
|
||||
|
||||
> type: `(additionalKeys: object) => { [type: string]: string[] | undefined }`
|
||||
|
||||
Make the union set with `evk.KEYS` and the given keys.
|
||||
|
||||
- The order of keys is, `additionalKeys` is at first, then `evk.KEYS` is concatenated after that.
|
||||
- It removes duplicated keys as keeping the first one.
|
||||
|
||||
For example:
|
||||
|
||||
```js
|
||||
console.log(evk.unionWith({
|
||||
MethodDefinition: ["decorators"]
|
||||
})) // → { ..., MethodDefinition: ["decorators", "key", "value"], ... }
|
||||
```
|
||||
|
||||
## 📰 Change log
|
||||
|
||||
See [GitHub releases](https://github.com/eslint/eslint-visitor-keys/releases).
|
||||
|
||||
## 🍻 Contributing
|
||||
|
||||
Welcome. See [ESLint contribution guidelines](https://eslint.org/docs/developer-guide/contributing/).
|
||||
|
||||
### Development commands
|
||||
|
||||
- `npm test` runs tests and measures code coverage.
|
||||
- `npm run lint` checks source codes with ESLint.
|
||||
- `npm run test:open-coverage` opens the code coverage report of the previous test with your default browser.
|
||||
|
||||
|
||||
[npm]: https://www.npmjs.com/
|
||||
[Node.js]: https://nodejs.org/
|
||||
[ESTree]: https://github.com/estree/estree
|
||||
Generated
Vendored
+65
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* @author Toru Nagashima <https://github.com/mysticatea>
|
||||
* See LICENSE file in root directory for full license.
|
||||
*/
|
||||
import KEYS from "./visitor-keys.js";
|
||||
|
||||
/**
|
||||
* @typedef {import('./visitor-keys.js').VisitorKeys} VisitorKeys
|
||||
*/
|
||||
|
||||
// List to ignore keys.
|
||||
const KEY_BLACKLIST = new Set([
|
||||
"parent",
|
||||
"leadingComments",
|
||||
"trailingComments"
|
||||
]);
|
||||
|
||||
/**
|
||||
* Check whether a given key should be used or not.
|
||||
* @param {string} key The key to check.
|
||||
* @returns {boolean} `true` if the key should be used.
|
||||
*/
|
||||
function filterKey(key) {
|
||||
return !KEY_BLACKLIST.has(key) && key[0] !== "_";
|
||||
}
|
||||
|
||||
/**
|
||||
* Get visitor keys of a given node.
|
||||
* @param {object} node The AST node to get keys.
|
||||
* @returns {readonly string[]} Visitor keys of the node.
|
||||
*/
|
||||
export function getKeys(node) {
|
||||
return Object.keys(node).filter(filterKey);
|
||||
}
|
||||
|
||||
// Disable valid-jsdoc rule because it reports syntax error on the type of @returns.
|
||||
// eslint-disable-next-line valid-jsdoc
|
||||
/**
|
||||
* Make the union set with `KEYS` and given keys.
|
||||
* @param {VisitorKeys} additionalKeys The additional keys.
|
||||
* @returns {VisitorKeys} The union set.
|
||||
*/
|
||||
export function unionWith(additionalKeys) {
|
||||
const retv = /** @type {{
|
||||
[type: string]: ReadonlyArray<string>
|
||||
}} */ (Object.assign({}, KEYS));
|
||||
|
||||
for (const type of Object.keys(additionalKeys)) {
|
||||
if (Object.prototype.hasOwnProperty.call(retv, type)) {
|
||||
const keys = new Set(additionalKeys[type]);
|
||||
|
||||
for (const key of retv[type]) {
|
||||
keys.add(key);
|
||||
}
|
||||
|
||||
retv[type] = Object.freeze(Array.from(keys));
|
||||
} else {
|
||||
retv[type] = Object.freeze(Array.from(additionalKeys[type]));
|
||||
}
|
||||
}
|
||||
|
||||
return Object.freeze(retv);
|
||||
}
|
||||
|
||||
export { KEYS };
|
||||
Generated
Vendored
+315
@@ -0,0 +1,315 @@
|
||||
/**
|
||||
* @typedef {{ readonly [type: string]: ReadonlyArray<string> }} VisitorKeys
|
||||
*/
|
||||
|
||||
/**
|
||||
* @type {VisitorKeys}
|
||||
*/
|
||||
const KEYS = {
|
||||
ArrayExpression: [
|
||||
"elements"
|
||||
],
|
||||
ArrayPattern: [
|
||||
"elements"
|
||||
],
|
||||
ArrowFunctionExpression: [
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
AssignmentExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
AssignmentPattern: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
AwaitExpression: [
|
||||
"argument"
|
||||
],
|
||||
BinaryExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
BlockStatement: [
|
||||
"body"
|
||||
],
|
||||
BreakStatement: [
|
||||
"label"
|
||||
],
|
||||
CallExpression: [
|
||||
"callee",
|
||||
"arguments"
|
||||
],
|
||||
CatchClause: [
|
||||
"param",
|
||||
"body"
|
||||
],
|
||||
ChainExpression: [
|
||||
"expression"
|
||||
],
|
||||
ClassBody: [
|
||||
"body"
|
||||
],
|
||||
ClassDeclaration: [
|
||||
"id",
|
||||
"superClass",
|
||||
"body"
|
||||
],
|
||||
ClassExpression: [
|
||||
"id",
|
||||
"superClass",
|
||||
"body"
|
||||
],
|
||||
ConditionalExpression: [
|
||||
"test",
|
||||
"consequent",
|
||||
"alternate"
|
||||
],
|
||||
ContinueStatement: [
|
||||
"label"
|
||||
],
|
||||
DebuggerStatement: [],
|
||||
DoWhileStatement: [
|
||||
"body",
|
||||
"test"
|
||||
],
|
||||
EmptyStatement: [],
|
||||
ExperimentalRestProperty: [
|
||||
"argument"
|
||||
],
|
||||
ExperimentalSpreadProperty: [
|
||||
"argument"
|
||||
],
|
||||
ExportAllDeclaration: [
|
||||
"exported",
|
||||
"source"
|
||||
],
|
||||
ExportDefaultDeclaration: [
|
||||
"declaration"
|
||||
],
|
||||
ExportNamedDeclaration: [
|
||||
"declaration",
|
||||
"specifiers",
|
||||
"source"
|
||||
],
|
||||
ExportSpecifier: [
|
||||
"exported",
|
||||
"local"
|
||||
],
|
||||
ExpressionStatement: [
|
||||
"expression"
|
||||
],
|
||||
ForInStatement: [
|
||||
"left",
|
||||
"right",
|
||||
"body"
|
||||
],
|
||||
ForOfStatement: [
|
||||
"left",
|
||||
"right",
|
||||
"body"
|
||||
],
|
||||
ForStatement: [
|
||||
"init",
|
||||
"test",
|
||||
"update",
|
||||
"body"
|
||||
],
|
||||
FunctionDeclaration: [
|
||||
"id",
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
FunctionExpression: [
|
||||
"id",
|
||||
"params",
|
||||
"body"
|
||||
],
|
||||
Identifier: [],
|
||||
IfStatement: [
|
||||
"test",
|
||||
"consequent",
|
||||
"alternate"
|
||||
],
|
||||
ImportDeclaration: [
|
||||
"specifiers",
|
||||
"source"
|
||||
],
|
||||
ImportDefaultSpecifier: [
|
||||
"local"
|
||||
],
|
||||
ImportExpression: [
|
||||
"source"
|
||||
],
|
||||
ImportNamespaceSpecifier: [
|
||||
"local"
|
||||
],
|
||||
ImportSpecifier: [
|
||||
"imported",
|
||||
"local"
|
||||
],
|
||||
JSXAttribute: [
|
||||
"name",
|
||||
"value"
|
||||
],
|
||||
JSXClosingElement: [
|
||||
"name"
|
||||
],
|
||||
JSXClosingFragment: [],
|
||||
JSXElement: [
|
||||
"openingElement",
|
||||
"children",
|
||||
"closingElement"
|
||||
],
|
||||
JSXEmptyExpression: [],
|
||||
JSXExpressionContainer: [
|
||||
"expression"
|
||||
],
|
||||
JSXFragment: [
|
||||
"openingFragment",
|
||||
"children",
|
||||
"closingFragment"
|
||||
],
|
||||
JSXIdentifier: [],
|
||||
JSXMemberExpression: [
|
||||
"object",
|
||||
"property"
|
||||
],
|
||||
JSXNamespacedName: [
|
||||
"namespace",
|
||||
"name"
|
||||
],
|
||||
JSXOpeningElement: [
|
||||
"name",
|
||||
"attributes"
|
||||
],
|
||||
JSXOpeningFragment: [],
|
||||
JSXSpreadAttribute: [
|
||||
"argument"
|
||||
],
|
||||
JSXSpreadChild: [
|
||||
"expression"
|
||||
],
|
||||
JSXText: [],
|
||||
LabeledStatement: [
|
||||
"label",
|
||||
"body"
|
||||
],
|
||||
Literal: [],
|
||||
LogicalExpression: [
|
||||
"left",
|
||||
"right"
|
||||
],
|
||||
MemberExpression: [
|
||||
"object",
|
||||
"property"
|
||||
],
|
||||
MetaProperty: [
|
||||
"meta",
|
||||
"property"
|
||||
],
|
||||
MethodDefinition: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
NewExpression: [
|
||||
"callee",
|
||||
"arguments"
|
||||
],
|
||||
ObjectExpression: [
|
||||
"properties"
|
||||
],
|
||||
ObjectPattern: [
|
||||
"properties"
|
||||
],
|
||||
PrivateIdentifier: [],
|
||||
Program: [
|
||||
"body"
|
||||
],
|
||||
Property: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
PropertyDefinition: [
|
||||
"key",
|
||||
"value"
|
||||
],
|
||||
RestElement: [
|
||||
"argument"
|
||||
],
|
||||
ReturnStatement: [
|
||||
"argument"
|
||||
],
|
||||
SequenceExpression: [
|
||||
"expressions"
|
||||
],
|
||||
SpreadElement: [
|
||||
"argument"
|
||||
],
|
||||
StaticBlock: [
|
||||
"body"
|
||||
],
|
||||
Super: [],
|
||||
SwitchCase: [
|
||||
"test",
|
||||
"consequent"
|
||||
],
|
||||
SwitchStatement: [
|
||||
"discriminant",
|
||||
"cases"
|
||||
],
|
||||
TaggedTemplateExpression: [
|
||||
"tag",
|
||||
"quasi"
|
||||
],
|
||||
TemplateElement: [],
|
||||
TemplateLiteral: [
|
||||
"quasis",
|
||||
"expressions"
|
||||
],
|
||||
ThisExpression: [],
|
||||
ThrowStatement: [
|
||||
"argument"
|
||||
],
|
||||
TryStatement: [
|
||||
"block",
|
||||
"handler",
|
||||
"finalizer"
|
||||
],
|
||||
UnaryExpression: [
|
||||
"argument"
|
||||
],
|
||||
UpdateExpression: [
|
||||
"argument"
|
||||
],
|
||||
VariableDeclaration: [
|
||||
"declarations"
|
||||
],
|
||||
VariableDeclarator: [
|
||||
"id",
|
||||
"init"
|
||||
],
|
||||
WhileStatement: [
|
||||
"test",
|
||||
"body"
|
||||
],
|
||||
WithStatement: [
|
||||
"object",
|
||||
"body"
|
||||
],
|
||||
YieldExpression: [
|
||||
"argument"
|
||||
]
|
||||
};
|
||||
|
||||
// Types.
|
||||
const NODE_TYPES = Object.keys(KEYS);
|
||||
|
||||
// Freeze the keys.
|
||||
for (const type of NODE_TYPES) {
|
||||
Object.freeze(KEYS[type]);
|
||||
}
|
||||
Object.freeze(KEYS);
|
||||
|
||||
export default KEYS;
|
||||
Generated
Vendored
+74
@@ -0,0 +1,74 @@
|
||||
{
|
||||
"name": "eslint-visitor-keys",
|
||||
"version": "3.4.3",
|
||||
"description": "Constants and utilities about visitor keys to traverse AST.",
|
||||
"type": "module",
|
||||
"main": "dist/eslint-visitor-keys.cjs",
|
||||
"types": "./dist/index.d.ts",
|
||||
"exports": {
|
||||
".": [
|
||||
{
|
||||
"import": "./lib/index.js",
|
||||
"require": "./dist/eslint-visitor-keys.cjs"
|
||||
},
|
||||
"./dist/eslint-visitor-keys.cjs"
|
||||
],
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"files": [
|
||||
"dist/index.d.ts",
|
||||
"dist/visitor-keys.d.ts",
|
||||
"dist/eslint-visitor-keys.cjs",
|
||||
"dist/eslint-visitor-keys.d.cts",
|
||||
"lib"
|
||||
],
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/estree": "^0.0.51",
|
||||
"@types/estree-jsx": "^0.0.1",
|
||||
"@typescript-eslint/parser": "^5.14.0",
|
||||
"c8": "^7.11.0",
|
||||
"chai": "^4.3.6",
|
||||
"eslint": "^7.29.0",
|
||||
"eslint-config-eslint": "^7.0.0",
|
||||
"eslint-plugin-jsdoc": "^35.4.0",
|
||||
"eslint-plugin-node": "^11.1.0",
|
||||
"eslint-release": "^3.2.0",
|
||||
"esquery": "^1.4.0",
|
||||
"json-diff": "^0.7.3",
|
||||
"mocha": "^9.2.1",
|
||||
"opener": "^1.5.2",
|
||||
"rollup": "^2.70.0",
|
||||
"rollup-plugin-dts": "^4.2.3",
|
||||
"tsd": "^0.19.1",
|
||||
"typescript": "^4.6.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "npm run build:cjs && npm run build:types",
|
||||
"build:cjs": "rollup -c",
|
||||
"build:debug": "npm run build:cjs -- -m && npm run build:types",
|
||||
"build:keys": "node tools/build-keys-from-ts",
|
||||
"build:types": "tsc",
|
||||
"lint": "eslint .",
|
||||
"prepare": "npm run build",
|
||||
"release:generate:latest": "eslint-generate-release",
|
||||
"release:generate:alpha": "eslint-generate-prerelease alpha",
|
||||
"release:generate:beta": "eslint-generate-prerelease beta",
|
||||
"release:generate:rc": "eslint-generate-prerelease rc",
|
||||
"release:publish": "eslint-publish-release",
|
||||
"test": "mocha tests/lib/**/*.cjs && c8 mocha tests/lib/**/*.js && npm run test:types",
|
||||
"test:open-coverage": "c8 report --reporter lcov && opener coverage/lcov-report/index.html",
|
||||
"test:types": "tsd"
|
||||
},
|
||||
"repository": "eslint/eslint-visitor-keys",
|
||||
"funding": "https://opencollective.com/eslint",
|
||||
"keywords": [],
|
||||
"author": "Toru Nagashima (https://github.com/mysticatea)",
|
||||
"license": "Apache-2.0",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint/eslint-visitor-keys/issues"
|
||||
},
|
||||
"homepage": "https://github.com/eslint/eslint-visitor-keys#readme"
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"name": "@eslint-community/eslint-utils",
|
||||
"version": "4.7.0",
|
||||
"description": "Utilities for ESLint plugins.",
|
||||
"keywords": [
|
||||
"eslint"
|
||||
],
|
||||
"homepage": "https://github.com/eslint-community/eslint-utils#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint-community/eslint-utils/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint-community/eslint-utils"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Toru Nagashima",
|
||||
"sideEffects": false,
|
||||
"exports": {
|
||||
".": {
|
||||
"import": "./index.mjs",
|
||||
"require": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "index",
|
||||
"module": "index.mjs",
|
||||
"files": [
|
||||
"index.*"
|
||||
],
|
||||
"scripts": {
|
||||
"prebuild": "npm run -s clean",
|
||||
"build": "npm run build:dts && npm run build:rollup",
|
||||
"build:dts": "tsc -p tsconfig.build.json",
|
||||
"build:rollup": "rollup -c",
|
||||
"clean": "rimraf .nyc_output coverage index.* dist",
|
||||
"coverage": "opener ./coverage/lcov-report/index.html",
|
||||
"docs:build": "vitepress build docs",
|
||||
"docs:watch": "vitepress dev docs",
|
||||
"format": "npm run -s format:prettier -- --write",
|
||||
"format:prettier": "prettier .",
|
||||
"format:check": "npm run -s format:prettier -- --check",
|
||||
"lint:eslint": "eslint .",
|
||||
"lint:format": "npm run -s format:check",
|
||||
"lint:installed-check": "installed-check -v -i installed-check -i npm-run-all2 -i knip -i rollup-plugin-dts",
|
||||
"lint:knip": "knip",
|
||||
"lint": "run-p lint:*",
|
||||
"test-coverage": "c8 mocha --reporter dot \"test/*.mjs\"",
|
||||
"test": "mocha --reporter dot \"test/*.mjs\"",
|
||||
"preversion": "npm run test-coverage && npm run -s build",
|
||||
"postversion": "git push && git push --tags",
|
||||
"prewatch": "npm run -s clean",
|
||||
"watch": "warun \"{src,test}/**/*.mjs\" -- npm run -s test:mocha"
|
||||
},
|
||||
"dependencies": {
|
||||
"eslint-visitor-keys": "^3.4.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-mysticatea": "^15.6.1",
|
||||
"@types/eslint": "^9.6.1",
|
||||
"@types/estree": "^1.0.7",
|
||||
"@typescript-eslint/parser": "^5.62.0",
|
||||
"@typescript-eslint/types": "^5.62.0",
|
||||
"c8": "^8.0.1",
|
||||
"dot-prop": "^7.2.0",
|
||||
"eslint": "^8.57.1",
|
||||
"installed-check": "^8.0.1",
|
||||
"knip": "^5.33.3",
|
||||
"mocha": "^9.2.2",
|
||||
"npm-run-all2": "^6.2.3",
|
||||
"opener": "^1.5.2",
|
||||
"prettier": "2.8.8",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.79.2",
|
||||
"rollup-plugin-dts": "^4.2.3",
|
||||
"rollup-plugin-sourcemaps": "^0.6.3",
|
||||
"semver": "^7.6.3",
|
||||
"typescript": "^4.9.5",
|
||||
"vitepress": "^1.4.1",
|
||||
"warun": "^1.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"eslint": "^6.0.0 || ^7.0.0 || >=8.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.22.0 || ^14.17.0 || >=16.0.0"
|
||||
},
|
||||
"funding": "https://opencollective.com/eslint"
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Toru Nagashima
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# @eslint-community/regexpp
|
||||
|
||||
[](https://www.npmjs.com/package/@eslint-community/regexpp)
|
||||
[](http://www.npmtrends.com/@eslint-community/regexpp)
|
||||
[](https://github.com/eslint-community/regexpp/actions)
|
||||
[](https://codecov.io/gh/eslint-community/regexpp)
|
||||
|
||||
A regular expression parser for ECMAScript.
|
||||
|
||||
## 💿 Installation
|
||||
|
||||
```bash
|
||||
$ npm install @eslint-community/regexpp
|
||||
```
|
||||
|
||||
- require Node@^12.0.0 || ^14.0.0 || >=16.0.0.
|
||||
|
||||
## 📖 Usage
|
||||
|
||||
```ts
|
||||
import {
|
||||
AST,
|
||||
RegExpParser,
|
||||
RegExpValidator,
|
||||
RegExpVisitor,
|
||||
parseRegExpLiteral,
|
||||
validateRegExpLiteral,
|
||||
visitRegExpAST
|
||||
} from "@eslint-community/regexpp"
|
||||
```
|
||||
|
||||
### parseRegExpLiteral(source, options?)
|
||||
|
||||
Parse a given regular expression literal then make AST object.
|
||||
|
||||
This is equivalent to `new RegExpParser(options).parseLiteral(source)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string | RegExp`) The source code to parse.
|
||||
- `options?` ([`RegExpParser.Options`]) The options to parse.
|
||||
- **Return:**
|
||||
- The AST of the regular expression.
|
||||
|
||||
### validateRegExpLiteral(source, options?)
|
||||
|
||||
Validate a given regular expression literal.
|
||||
|
||||
This is equivalent to `new RegExpValidator(options).validateLiteral(source)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `options?` ([`RegExpValidator.Options`]) The options to validate.
|
||||
|
||||
### visitRegExpAST(ast, handlers)
|
||||
|
||||
Visit each node of a given AST.
|
||||
|
||||
This is equivalent to `new RegExpVisitor(handlers).visit(ast)`.
|
||||
|
||||
- **Parameters:**
|
||||
- `ast` ([`AST.Node`]) The AST to visit.
|
||||
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
|
||||
|
||||
### RegExpParser
|
||||
|
||||
#### new RegExpParser(options?)
|
||||
|
||||
- **Parameters:**
|
||||
- `options?` ([`RegExpParser.Options`]) The options to parse.
|
||||
|
||||
#### parser.parseLiteral(source, start?, end?)
|
||||
|
||||
Parse a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"/abc/g"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- **Return:**
|
||||
- The AST of the regular expression.
|
||||
|
||||
#### parser.parsePattern(source, start?, end?, flags?)
|
||||
|
||||
Parse a regular expression pattern.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"abc"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
|
||||
- **Return:**
|
||||
- The AST of the regular expression pattern.
|
||||
|
||||
#### parser.parseFlags(source, start?, end?)
|
||||
|
||||
Parse a regular expression flags.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to parse. E.g. `"gim"`.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- **Return:**
|
||||
- The AST of the regular expression flags.
|
||||
|
||||
### RegExpValidator
|
||||
|
||||
#### new RegExpValidator(options)
|
||||
|
||||
- **Parameters:**
|
||||
- `options` ([`RegExpValidator.Options`]) The options to validate.
|
||||
|
||||
#### validator.validateLiteral(source, start, end)
|
||||
|
||||
Validate a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
|
||||
#### validator.validatePattern(source, start, end, flags)
|
||||
|
||||
Validate a regular expression pattern.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
- `flags?` (`{ unicode?: boolean, unicodeSets?: boolean }`) The flags to enable Unicode mode, and Unicode Set mode.
|
||||
|
||||
#### validator.validateFlags(source, start, end)
|
||||
|
||||
Validate a regular expression flags.
|
||||
|
||||
- **Parameters:**
|
||||
- `source` (`string`) The source code to validate.
|
||||
- `start?` (`number`) The start index in the source code. Default is `0`.
|
||||
- `end?` (`number`) The end index in the source code. Default is `source.length`.
|
||||
|
||||
### RegExpVisitor
|
||||
|
||||
#### new RegExpVisitor(handlers)
|
||||
|
||||
- **Parameters:**
|
||||
- `handlers` ([`RegExpVisitor.Handlers`]) The callbacks.
|
||||
|
||||
#### visitor.visit(ast)
|
||||
|
||||
Validate a regular expression literal.
|
||||
|
||||
- **Parameters:**
|
||||
- `ast` ([`AST.Node`]) The AST to visit.
|
||||
|
||||
## 📰 Changelog
|
||||
|
||||
- [GitHub Releases](https://github.com/eslint-community/regexpp/releases)
|
||||
|
||||
## 🍻 Contributing
|
||||
|
||||
Welcome contributing!
|
||||
|
||||
Please use GitHub's Issues/PRs.
|
||||
|
||||
### Development Tools
|
||||
|
||||
- `npm test` runs tests and measures coverage.
|
||||
- `npm run build` compiles TypeScript source code to `index.js`, `index.js.map`, and `index.d.ts`.
|
||||
- `npm run clean` removes the temporary files which are created by `npm test` and `npm run build`.
|
||||
- `npm run lint` runs ESLint.
|
||||
- `npm run update:test` updates test fixtures.
|
||||
- `npm run update:ids` updates `src/unicode/ids.ts`.
|
||||
- `npm run watch` runs tests with `--watch` option.
|
||||
|
||||
[`AST.Node`]: src/ast.ts#L4
|
||||
[`RegExpParser.Options`]: src/parser.ts#L743
|
||||
[`RegExpValidator.Options`]: src/validator.ts#L220
|
||||
[`RegExpVisitor.Handlers`]: src/visitor.ts#L291
|
||||
+1163
File diff suppressed because it is too large
Load Diff
+3037
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+3027
File diff suppressed because it is too large
Load Diff
+1
File diff suppressed because one or more lines are too long
+91
@@ -0,0 +1,91 @@
|
||||
{
|
||||
"name": "@eslint-community/regexpp",
|
||||
"version": "4.12.1",
|
||||
"description": "Regular expression parser for ECMAScript.",
|
||||
"keywords": [
|
||||
"regexp",
|
||||
"regular",
|
||||
"expression",
|
||||
"parser",
|
||||
"validator",
|
||||
"ast",
|
||||
"abstract",
|
||||
"syntax",
|
||||
"tree",
|
||||
"ecmascript",
|
||||
"es2015",
|
||||
"es2016",
|
||||
"es2017",
|
||||
"es2018",
|
||||
"es2019",
|
||||
"es2020",
|
||||
"es2021",
|
||||
"annexB"
|
||||
],
|
||||
"homepage": "https://github.com/eslint-community/regexpp#readme",
|
||||
"bugs": {
|
||||
"url": "https://github.com/eslint-community/regexpp/issues"
|
||||
},
|
||||
"repository": {
|
||||
"type": "git",
|
||||
"url": "https://github.com/eslint-community/regexpp"
|
||||
},
|
||||
"license": "MIT",
|
||||
"author": "Toru Nagashima",
|
||||
"exports": {
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"import": "./index.mjs",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"./package.json": "./package.json"
|
||||
},
|
||||
"main": "index",
|
||||
"files": [
|
||||
"index.*"
|
||||
],
|
||||
"scripts": {
|
||||
"prebuild": "npm run -s clean",
|
||||
"build": "run-s build:*",
|
||||
"build:tsc": "tsc --module es2015",
|
||||
"build:rollup": "rollup -c",
|
||||
"build:dts": "npm run -s build:tsc -- --removeComments false && dts-bundle --name @eslint-community/regexpp --main .temp/index.d.ts --out ../index.d.ts && prettier --write index.d.ts",
|
||||
"clean": "rimraf .temp index.*",
|
||||
"lint": "eslint . --ext .ts",
|
||||
"test": "nyc _mocha \"test/*.ts\" --reporter dot --timeout 10000",
|
||||
"debug": "mocha --require ts-node/register/transpile-only \"test/*.ts\" --reporter dot --timeout 10000",
|
||||
"update:test": "ts-node scripts/update-fixtures.ts",
|
||||
"update:unicode": "run-s update:unicode:*",
|
||||
"update:unicode:ids": "ts-node scripts/update-unicode-ids.ts",
|
||||
"update:unicode:props": "ts-node scripts/update-unicode-properties.ts",
|
||||
"update:test262:extract": "ts-node -T scripts/extract-test262.ts",
|
||||
"preversion": "npm test && npm run -s build",
|
||||
"postversion": "git push && git push --tags",
|
||||
"prewatch": "npm run -s clean",
|
||||
"watch": "_mocha \"test/*.ts\" --require ts-node/register --reporter dot --timeout 10000 --watch-extensions ts --watch --growl"
|
||||
},
|
||||
"dependencies": {},
|
||||
"devDependencies": {
|
||||
"@eslint-community/eslint-plugin-mysticatea": "^15.5.1",
|
||||
"@rollup/plugin-node-resolve": "^14.1.0",
|
||||
"@types/eslint": "^8.44.3",
|
||||
"@types/jsdom": "^16.2.15",
|
||||
"@types/mocha": "^9.1.1",
|
||||
"@types/node": "^12.20.55",
|
||||
"dts-bundle": "^0.7.3",
|
||||
"eslint": "^8.50.0",
|
||||
"js-tokens": "^8.0.2",
|
||||
"jsdom": "^19.0.0",
|
||||
"mocha": "^9.2.2",
|
||||
"npm-run-all2": "^6.2.2",
|
||||
"nyc": "^14.1.1",
|
||||
"rimraf": "^3.0.2",
|
||||
"rollup": "^2.79.1",
|
||||
"rollup-plugin-sourcemaps": "^0.6.3",
|
||||
"ts-node": "^10.9.1",
|
||||
"typescript": "~5.0.2"
|
||||
},
|
||||
"engines": {
|
||||
"node": "^12.0.0 || ^14.0.0 || >=16.0.0"
|
||||
}
|
||||
}
|
||||
+201
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
+369
@@ -0,0 +1,369 @@
|
||||
# Config Array
|
||||
|
||||
## Description
|
||||
|
||||
A config array is a way of managing configurations that are based on glob pattern matching of filenames. Each config array contains the information needed to determine the correct configuration for any file based on the filename.
|
||||
|
||||
**Note:** This is a generic package that can be used outside of ESLint. It contains no ESLint-specific functionality.
|
||||
|
||||
## Installation
|
||||
|
||||
For Node.js and compatible runtimes:
|
||||
|
||||
```shell
|
||||
npm install @eslint/config-array
|
||||
# or
|
||||
yarn add @eslint/config-array
|
||||
# or
|
||||
pnpm install @eslint/config-array
|
||||
# or
|
||||
bun add @eslint/config-array
|
||||
```
|
||||
|
||||
For Deno:
|
||||
|
||||
```shell
|
||||
deno add @eslint/config-array
|
||||
```
|
||||
|
||||
## Background
|
||||
|
||||
The basic idea is that all configuration, including overrides, can be represented by a single array where each item in the array is a config object. Config objects appearing later in the array override config objects appearing earlier in the array. You can calculate a config for a given file by traversing all config objects in the array to find the ones that match the filename. Matching is done by specifying glob patterns in `files` and `ignores` properties on each config object. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
In this example, there are two config objects: the first matches all JSON files in all directories and the second matches just `package.json` in the base path directory (all the globs are evaluated as relative to a base path that can be specified). When you retrieve a configuration for `foo.json`, only the first config object matches so `handler` is equal to `jsonHandler`; when you retrieve a configuration for `package.json`, `handler` is equal to `packageJsonHandler` (because both config objects match, the second one wins).
|
||||
|
||||
## Usage
|
||||
|
||||
First, import the `ConfigArray` constructor:
|
||||
|
||||
```js
|
||||
import { ConfigArray } from "@eslint/config-array";
|
||||
|
||||
// or using CommonJS
|
||||
|
||||
const { ConfigArray } = require("@eslint/config-array");
|
||||
```
|
||||
|
||||
When you create a new instance of `ConfigArray`, you must pass in two arguments: an array of configs and an options object. The array of configs is most likely read in from a configuration file, so here's a typical example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional items in each config
|
||||
schema: mySchema,
|
||||
});
|
||||
```
|
||||
|
||||
This example reads in an object or array from `my.config.js` and passes it into the `ConfigArray` constructor as the first argument. The second argument is an object specifying the `basePath` (the directory in which `my.config.js` is found) and a `schema` to define the additional properties of a config object beyond `files`, `ignores`, `basePath`, and `name`.
|
||||
|
||||
### Specifying a Schema
|
||||
|
||||
The `schema` option is required for you to use additional properties in config objects. The schema is an object that follows the format of an [`ObjectSchema`](https://npmjs.com/package/@eslint/object-schema). The schema specifies both validation and merge rules that the `ConfigArray` instance needs to combine configs when there are multiple matches. Here's an example:
|
||||
|
||||
```js
|
||||
const configFilename = path.resolve(process.cwd(), "my.config.js");
|
||||
const { default: rawConfigs } = await import(configFilename);
|
||||
|
||||
const mySchema = {
|
||||
|
||||
// define the handler key in configs
|
||||
handler: {
|
||||
required: true,
|
||||
merge(a, b) {
|
||||
if (!b) return a;
|
||||
if (!a) return b;
|
||||
},
|
||||
validate(value) {
|
||||
if (typeof value !== "function") {
|
||||
throw new TypeError("Function expected.");
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const configs = new ConfigArray(rawConfigs, {
|
||||
|
||||
// the path to match filenames from
|
||||
basePath: process.cwd(),
|
||||
|
||||
// additional item schemas in each config
|
||||
schema: mySchema,
|
||||
|
||||
// additional config types supported (default: [])
|
||||
extraConfigTypes: ["array", "function"];
|
||||
});
|
||||
```
|
||||
|
||||
### Config Arrays
|
||||
|
||||
Config arrays can be multidimensional, so it's possible for a config array to contain another config array when `extraConfigTypes` contains `"array"`, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler,
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
[
|
||||
// match all JSON files
|
||||
{
|
||||
name: "JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: "package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
],
|
||||
|
||||
// filename must match function
|
||||
{
|
||||
files: [filePath => filePath.endsWith(".md")],
|
||||
handler: markdownHandler,
|
||||
},
|
||||
|
||||
// filename must match all patterns in subarray
|
||||
{
|
||||
files: [["*.test.*", "*.js"]],
|
||||
handler: jsTestHandler,
|
||||
},
|
||||
|
||||
// filename must not match patterns beginning with !
|
||||
{
|
||||
name: "Non-JS files",
|
||||
files: ["!*.js"],
|
||||
settings: {
|
||||
js: false,
|
||||
},
|
||||
},
|
||||
|
||||
// specific settings for files inside `src` directory
|
||||
{
|
||||
name: "Source files",
|
||||
basePath: "src",
|
||||
files: ["**/*"],
|
||||
settings: {
|
||||
source: true,
|
||||
},
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
In this example, the array contains both config objects and a config array. When a config array is normalized (see details below), it is flattened so only config objects remain. However, the order of evaluation remains the same.
|
||||
|
||||
If the `files` array contains a function, then that function is called with the path of the file as it was passed in. The function is expected to return `true` if there is a match and `false` if not. (The `ignores` array can also contain functions.)
|
||||
|
||||
If the `files` array contains an item that is an array of strings and functions, then all patterns must match in order for the config to match. In the preceding examples, both `*.test.*` and `*.js` must match in order for the config object to be used.
|
||||
|
||||
If a pattern in the files array begins with `!` then it excludes that pattern. In the preceding example, any filename that doesn't end with `.js` will automatically get a `settings.js` property set to `false`.
|
||||
|
||||
You can also specify an `ignores` key that will force files matching those patterns to not be included. If the `ignores` key is in a config object without any other keys, then those ignores will always be applied; otherwise those ignores act as exclusions. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
|
||||
// Always ignored
|
||||
{
|
||||
ignores: ["**/.git/**", "**/node_modules/**"]
|
||||
},
|
||||
|
||||
// .eslintrc.js file is ignored only when .js file matches
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
ignores: [".eslintrc.js"]
|
||||
handler: jsHandler
|
||||
}
|
||||
];
|
||||
```
|
||||
|
||||
You can use negated patterns in `ignores` to exclude a file that was already ignored, such as:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// Ignore all JSON files except tsconfig.json
|
||||
{
|
||||
files: ["**/*"],
|
||||
ignores: ["**/*.json", "!tsconfig.json"],
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
### Config Functions
|
||||
|
||||
Config arrays can also include config functions when `extraConfigTypes` contains `"function"`. A config function accepts a single parameter, `context` (defined by you), and must return either a config object or a config array (it cannot return another function). Config functions allow end users to execute code in the creation of appropriate config objects. Here's an example:
|
||||
|
||||
```js
|
||||
export default [
|
||||
// JS config
|
||||
{
|
||||
files: ["**/*.js"],
|
||||
handler: jsHandler,
|
||||
},
|
||||
|
||||
// JSON configs
|
||||
function (context) {
|
||||
return [
|
||||
// match all JSON files
|
||||
{
|
||||
name: context.name + " JSON Handler",
|
||||
files: ["**/*.json"],
|
||||
handler: jsonHandler,
|
||||
},
|
||||
|
||||
// match only package.json
|
||||
{
|
||||
name: context.name + " package.json Handler",
|
||||
files: ["package.json"],
|
||||
handler: packageJsonHandler,
|
||||
},
|
||||
];
|
||||
},
|
||||
];
|
||||
```
|
||||
|
||||
When a config array is normalized, each function is executed and replaced in the config array with the return value.
|
||||
|
||||
**Note:** Config functions can also be async.
|
||||
|
||||
### Normalizing Config Arrays
|
||||
|
||||
Once a config array has been created and loaded with all of the raw config data, it must be normalized before it can be used. The normalization process goes through and flattens the config array as well as executing all config functions to get their final values.
|
||||
|
||||
To normalize a config array, call the `normalize()` method and pass in a context object:
|
||||
|
||||
```js
|
||||
await configs.normalize({
|
||||
name: "MyApp",
|
||||
});
|
||||
```
|
||||
|
||||
The `normalize()` method returns a promise, so be sure to use the `await` operator. The config array instance is normalized in-place, so you don't need to create a new variable.
|
||||
|
||||
If you want to disallow async config functions, you can call `normalizeSync()` instead. This method is completely synchronous and does not require using the `await` operator as it does not return a promise:
|
||||
|
||||
```js
|
||||
await configs.normalizeSync({
|
||||
name: "MyApp",
|
||||
});
|
||||
```
|
||||
|
||||
**Important:** Once a `ConfigArray` is normalized, it cannot be changed further. You can, however, create a new `ConfigArray` and pass in the normalized instance to create an unnormalized copy.
|
||||
|
||||
### Getting Config for a File
|
||||
|
||||
To get the config for a file, use the `getConfig()` method on a normalized config array and pass in the filename to get a config for:
|
||||
|
||||
```js
|
||||
// pass in filename
|
||||
const fileConfig = configs.getConfig(
|
||||
path.resolve(process.cwd(), "package.json"),
|
||||
);
|
||||
```
|
||||
|
||||
The config array always returns an object, even if there are no configs matching the given filename. You can then inspect the returned config object to determine how to proceed.
|
||||
|
||||
A few things to keep in mind:
|
||||
|
||||
- If a filename is not an absolute path, it will be resolved relative to the base path directory.
|
||||
- The returned config object never has `files`, `ignores`, `basePath`, or `name` properties; the only properties on the object will be the other configuration options specified.
|
||||
- The config array caches configs, so subsequent calls to `getConfig()` with the same filename will return in a fast lookup rather than another calculation.
|
||||
- A config will only be generated if the filename matches an entry in a `files` key. A config will not be generated without matching a `files` key (configs without a `files` key are only applied when another config with a `files` key is applied; configs without `files` are never applied on their own). Any config with a `files` key entry that is `*` or ends with `/**` or `/*` will only be applied if another entry in the same `files` key matches or another config matches.
|
||||
|
||||
## Determining Ignored Paths
|
||||
|
||||
You can determine if a file is ignored by using the `isFileIgnored()` method and passing in the path of any file, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isFileIgnored("/foo/bar/baz.txt");
|
||||
```
|
||||
|
||||
A file is considered ignored if any of the following is true:
|
||||
|
||||
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/a.js` is considered ignored.
|
||||
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/baz/a.js` is considered ignored.
|
||||
- **It matches an ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
For directories, use the `isDirectoryIgnored()` method and pass in the path of any directory, as in this example:
|
||||
|
||||
```js
|
||||
const ignored = configs.isDirectoryIgnored("/foo/bar/");
|
||||
```
|
||||
|
||||
A directory is considered ignored if any of the following is true:
|
||||
|
||||
- **It's parent directory is ignored.** For example, if `foo` is in `ignores`, then `foo/baz` is considered ignored.
|
||||
- **It has an ancestor directory that is ignored.** For example, if `foo` is in `ignores`, then `foo/bar/baz/a.js` is considered ignored.
|
||||
- **It matches and ignored file pattern.** For example, if `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **If it matches an entry in `files` and also in `ignores`.** For example, if `**/*.js` is in `files` and `**/a.js` is in `ignores`, then `foo/a.js` and `foo/baz/a.js` are considered ignored.
|
||||
- **The file is outside the `basePath`.** If the `basePath` is `/usr/me`, then `/foo/a.js` is considered ignored.
|
||||
|
||||
**Important:** A pattern such as `foo/**` means that `foo` and `foo/` are _not_ ignored whereas `foo/bar` is ignored. If you want to ignore `foo` and all of its subdirectories, use the pattern `foo` or `foo/` in `ignores`.
|
||||
|
||||
## Caching Mechanisms
|
||||
|
||||
Each `ConfigArray` aggressively caches configuration objects to avoid unnecessary work. This caching occurs in two ways:
|
||||
|
||||
1. **File-based Caching.** For each filename that is passed into a method, the resulting config is cached against that filename so you're always guaranteed to get the same object returned from `getConfig()` whenever you pass the same filename in.
|
||||
2. **Index-based Caching.** Whenever a config is calculated, the config elements that were used to create the config are also cached. So if a given filename matches elements 1, 5, and 7, the resulting config is cached with a key of `1,5,7`. That way, if another file is passed that matches the same config elements, the result is already known and doesn't have to be recalculated. That means two files that match all the same elements will return the same config from `getConfig()`.
|
||||
|
||||
## Acknowledgements
|
||||
|
||||
The design of this project was influenced by feedback on the ESLint RFC, and incorporates ideas from:
|
||||
|
||||
- Teddy Katz (@not-an-aardvark)
|
||||
- Toru Nagashima (@mysticatea)
|
||||
- Kai Cataldo (@kaicataldo)
|
||||
|
||||
## License
|
||||
|
||||
Apache 2.0
|
||||
|
||||
<!-- NOTE: This section is autogenerated. Do not manually edit.-->
|
||||
<!--sponsorsstart-->
|
||||
|
||||
## Sponsors
|
||||
|
||||
The following companies, organizations, and individuals support ESLint's ongoing maintenance and development. [Become a Sponsor](https://eslint.org/donate)
|
||||
to get your logo on our READMEs and [website](https://eslint.org/sponsors).
|
||||
|
||||
<h3>Diamond Sponsors</h3>
|
||||
<p><a href="https://www.ag-grid.com/"><img src="https://images.opencollective.com/ag-grid/bec0580/logo.png" alt="AG Grid" height="128"></a></p><h3>Platinum Sponsors</h3>
|
||||
<p><a href="https://automattic.com"><img src="https://images.opencollective.com/automattic/d0ef3e1/logo.png" alt="Automattic" height="128"></a> <a href="https://www.airbnb.com/"><img src="https://images.opencollective.com/airbnb/d327d66/logo.png" alt="Airbnb" height="128"></a></p><h3>Gold Sponsors</h3>
|
||||
<p><a href="https://qlty.sh/"><img src="https://images.opencollective.com/qltysh/33d157d/logo.png" alt="Qlty Software" height="96"></a> <a href="https://trunk.io/"><img src="https://images.opencollective.com/trunkio/fb92d60/avatar.png" alt="trunk.io" height="96"></a> <a href="https://shopify.engineering/"><img src="https://avatars.githubusercontent.com/u/8085" alt="Shopify" height="96"></a></p><h3>Silver Sponsors</h3>
|
||||
<p><a href="https://vite.dev/"><img src="https://images.opencollective.com/vite/e6d15e1/logo.png" alt="Vite" height="64"></a> <a href="https://liftoff.io/"><img src="https://images.opencollective.com/liftoff/5c4fa84/logo.png" alt="Liftoff" height="64"></a> <a href="https://americanexpress.io"><img src="https://avatars.githubusercontent.com/u/3853301" alt="American Express" height="64"></a> <a href="https://stackblitz.com"><img src="https://avatars.githubusercontent.com/u/28635252" alt="StackBlitz" height="64"></a></p><h3>Bronze Sponsors</h3>
|
||||
<p><a href="https://sentry.io"><img src="https://github.com/getsentry.png" alt="Sentry" height="32"></a> <a href="https://syntax.fm"><img src="https://github.com/syntaxfm.png" alt="Syntax" height="32"></a> <a href="https://cybozu.co.jp/"><img src="https://images.opencollective.com/cybozu/933e46d/logo.png" alt="Cybozu" height="32"></a> <a href="https://www.crosswordsolver.org/anagram-solver/"><img src="https://images.opencollective.com/anagram-solver/2666271/logo.png" alt="Anagram Solver" height="32"></a> <a href="https://icons8.com/"><img src="https://images.opencollective.com/icons8/7fa1641/logo.png" alt="Icons8" height="32"></a> <a href="https://discord.com"><img src="https://images.opencollective.com/discordapp/f9645d9/logo.png" alt="Discord" height="32"></a> <a href="https://www.gitbook.com"><img src="https://avatars.githubusercontent.com/u/7111340" alt="GitBook" height="32"></a> <a href="https://nolebase.ayaka.io"><img src="https://avatars.githubusercontent.com/u/11081491" alt="Neko" height="32"></a> <a href="https://nx.dev"><img src="https://avatars.githubusercontent.com/u/23692104" alt="Nx" height="32"></a> <a href="https://opensource.mercedes-benz.com/"><img src="https://avatars.githubusercontent.com/u/34240465" alt="Mercedes-Benz Group" height="32"></a> <a href="https://herocoders.com"><img src="https://avatars.githubusercontent.com/u/37549774" alt="HeroCoders" height="32"></a> <a href="https://www.lambdatest.com"><img src="https://avatars.githubusercontent.com/u/171592363" alt="LambdaTest" height="32"></a></p>
|
||||
<h3>Technology Sponsors</h3>
|
||||
Technology sponsors allow us to use their products and services for free as part of a contribution to the open source ecosystem and our work.
|
||||
<p><a href="https://netlify.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/netlify-icon.svg" alt="Netlify" height="32"></a> <a href="https://algolia.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/algolia-icon.svg" alt="Algolia" height="32"></a> <a href="https://1password.com"><img src="https://raw.githubusercontent.com/eslint/eslint.org/main/src/assets/images/techsponsors/1password-icon.svg" alt="1Password" height="32"></a></p>
|
||||
<!--sponsorsend-->
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user