⏰ Time:
🌡️ Temp:
Loading...
📌 Code
โดย puk
•2025-09-01 20:46
import ccxt
import pandas as pd
import ta
from colorama import init, Fore, Style
import time
import logging
import numpy as np
# ตั้งค่า logging
logging.basicConfig(filename='trading_bot.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# ตั้งค่า colorama สำหรับคอนโซล
init(autoreset=True)
# การตั้งค่า API สำหรับ Binance, LBank, Gate.io
exchanges = {
'binance': ccxt.binance({
'apiKey': 'YOUR_BINANCE_API_KEY',
'secret': 'YOUR_BINANCE_SECRET',
'enableRateLimit': True,
}),
'lbank': ccxt.lbank({
'apiKey': 'YOUR_LBANK_API_KEY',
'secret': 'YOUR_LBANK_SECRET',
'enableRateLimit': True,
}),
'gateio': ccxt.gateio({
'apiKey': 'YOUR_GATEIO_API_KEY',
'secret': 'YOUR_GATEIO_SECRET',
'enableRateLimit': True,
})
}
# สัญลักษณ์การซื้อขาย (เช่น BTC/USDT)
symbol = 'BTC/USDT'
timeframe = '4h' # ไทม์เฟรม 4 ชั่วโมง
investment_percentage = 0.25 # ใช้ 25% ของยอดเงินในบัญชี
sl_percentage = 0.30 # Stop Loss 30%
tp_percentage = 0.10 # Take Profit 10%
# ฟังก์ชันคำนวณ Fibonacci Levels
def calculate_fibonacci_levels(high, low):
diff = high - low
fib_levels = {
'0.0%': low,
'23.6%': low + diff * 0.236,
'38.2%': low + diff * 0.382,
'50.0%': low + diff * 0.50,
'61.8%': low + diff * 0.618,
'78.6%': low + diff * 0.786,
'100.0%': high,
'127.2%': high + diff * 0.272,
'161.8%': high + diff * 0.618
}
return fib_levels
# ฟังก์ชันดึงข้อมูล OHLCV และคำนวณตัวชี้วัด
def get_ohlcv(exchange, symbol, timeframe):
ohlcv = exchange.fetch_ohlcv(symbol, timeframe, limit=100)
df = pd.DataFrame(ohlcv, columns=['timestamp', 'open', 'high', 'low', 'close', 'volume'])
df['timestamp'] = pd.to_datetime(df['timestamp'], unit='ms')
# คำนวณ SMA และ EMA
df['sma_fast'] = ta.trend.sma_indicator(df['close'], window=10)
df['sma_slow'] = ta.trend.sma_indicator(df['close'], window=20)
return df
# ฟังก์ชันตรวจสอบสัญญาณซื้อ/ขาย
def check_signal(df):
last_row = df.iloc[-1]
prev_row = df.iloc[-2]
# สัญญาณซื้อ (Long) เมื่อ SMA Fast ตัดขึ้น SMA Slow
if prev_row['sma_fast'] < prev_row['sma_slow'] and last_row['sma_fast'] > last_row['sma_slow']:
return 'BUY'
# สัญญาณขาย (Short) เมื่อ SMA Fast ตัดลง SMA Slow
elif prev_row['sma_fast'] > prev_row['sma_slow'] and last_row['sma_fast'] < last_row['sma_slow']:
return 'SELL'
return None
# ฟังก์ชันแสดงสถานะกระพริบ
def blink_status(message, color=Fore.YELLOW):
for _ in range(3):
print(f"{color}{message}{Style.RESET_ALL}")
time.sleep(0.5)
print("\033[1A\033[K", end="") # ลบข้อความก่อนหน้า
time.sleep(0.5)
# ฟังก์ชันหลักของบอต
def trading_bot():
position_open = False
position_type = None
entry_price = 0
sl_price = 0
tp_price = 0
while True:
try:
for exchange_name, exchange in exchanges.items():
print(f"\n{Fore.CYAN}=== Checking {exchange_name} ===")
# ดึงข้อมูล OHLCV
df = get_ohlcv(exchange, symbol, timeframe)
signal = check_signal(df)
current_price = df['close'].iloc[-1]
# ตรวจสอบสัญญาณ
if signal:
blink_status(f"Signal Detected: {signal} on {exchange_name}!", Fore.RED)
logging.info(f"Signal Detected: {signal} on {exchange_name} at price {current_price}")
# คำนวณ Fibonacci Levels
high = df['high'].iloc[-20:].max()
low = df['low'].iloc[-20:].min()
fib_levels = calculate_fibonacci_levels(high, low)
# ดึงยอดเงินในบัญชี
balance = exchange.fetch_balance()['total']['USDT']
investment = balance * investment_percentage
amount = investment / current_price # คำนวณจำนวนที่ซื้อ
if signal == 'BUY':
# เข้า Long
entry_price = current_price
sl_price = entry_price * (1 - sl_percentage) # SL 30% ต่ำกว่าราคาเข้า
tp_price = entry_price * (1 + tp_percentage) # TP 10% สูงกว่าราคาเข้า
# ใช้ Fibonacci 61.8% หรือ 78.6% เป็น TP ถ้าต้องการ
tp_price = fib_levels['61.8%'] if fib_levels['61.8%'] > entry_price else tp_price
order = exchange.create_market_buy_order(symbol, amount)
position_open = True
position_type = 'Long'
logging.info(f"Opened Long Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}, Amount={amount}")
print(f"{Fore.GREEN}Opened Long Position: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
elif signal == 'SELL':
# เข้า Short
entry_price = current_price
sl_price = entry_price * (1 + sl_percentage) # SL 30% สูงกว่าราคาเข้า
tp_price = entry_price * (1 - tp_percentage) # TP 10% ต่ำกว่าราคาเข้า
# ใช้ Fibonacci 38.2% หรือ 23.6% เป็น TP ถ้าต้องการ
tp_price = fib_levels['38.2%'] if fib_levels['38.2%'] < entry_price else tp_price
order = exchange.create_market_sell_order(symbol, amount)
position_open = True
position_type = 'Short'
logging.info(f"Opened Short Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}, Amount={amount}")
print(f"{Fore.RED}Opened Short Position: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
# แสดงสถานะ Position
if position_open:
print(f"{Fore.MAGENTA}Position Status: {position_type} | Entry: {entry_price} | Current: {current_price} | SL: {sl_price} | TP: {tp_price}")
# ตรวจสอบ SL/TP
if position_type == 'Long' and (current_price <= sl_price or current_price >= tp_price):
exchange.create_market_sell_order(symbol, amount)
position_open = False
logging.info(f"Closed Long Position on {exchange_name}: Price={current_price}")
print(f"{Fore.YELLOW}Closed Long Position: Price={current_price}")
elif position_type == 'Short' and (current_price >= sl_price or current_price <= tp_price):
exchange.create_market_buy_order(symbol, amount)
position_open = False
logging.info(f"Closed Short Position on {exchange_name}: Price={current_price}")
print(f"{Fore.YELLOW}Closed Short Position: Price={current_price}")
# รอ 5 นาทีก่อนตรวจสอบครั้งต่อไป
time.sleep(300)
except Exception as e:
logging.error(f"Error: {str(e)}")
print(f"{Fore.RED}Error: {str(e)}")
time.sleep(60)
# รันบอต
if __name__ == "__main__":
print(f"{Fore.CYAN}=== Starting Trading Bot ===")
trading_bot()