⏰ Time:
🌡️ Temp:
Loading...
📌 Source Code AllybotPor
โดย puk
•2025-09-01 22:23
import ccxt
import pandas as pd
import ta
from colorama import init, Fore, Style
import time
import logging
import sqlite3
import subprocess
import json
import requests
import numpy as np
from datetime import datetime
# ตั้งค่า logging
logging.basicConfig(filename='trading_bot.log', level=logging.INFO,
format='%(asctime)s - %(levelname)s - %(message)s')
# ตั้งค่า colorama สำหรับคอนโซล
init(autoreset=True)
# ตั้งค่า SQLite สำหรับบันทึกการซื้อขาย
conn = sqlite3.connect('trades.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS trades
(timestamp TEXT, exchange TEXT, type TEXT, entry_price REAL, exit_price REAL, amount REAL, profit REAL)''')
conn.commit()
# ตั้งค่า 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,
})
}
# ตั้งค่า Telegram สำหรับการแจ้งเตือน
TELEGRAM_BOT_TOKEN = 'YOUR_TELEGRAM_BOT_TOKEN'
TELEGRAM_CHAT_ID = 'YOUR_TELEGRAM_CHAT_ID'
# การตั้งค่าการเทรด
symbol = 'BTC/USDT'
timeframe = '4h'
investment_percentage = 0.25 # ใช้ 25% ของยอดเงิน
sl_percentage = 0.30 # Stop Loss 30%
tp_percentage = 0.10 # Take Profit 10%
# ฟังก์ชันส่งการแจ้งเตือน Telegram
def send_telegram_alert(message):
url = f"https://api.telegram.org/bot{TELEGRAM_BOT_TOKEN}/sendMessage"
payload = {'chat_id': TELEGRAM_CHAT_ID, 'text': message}
try:
requests.post(url, json=payload)
except Exception as e:
logging.error(f"Telegram Alert Error: {str(e)}")
print(f"{Fore.RED}Telegram Alert Error: {str(e)}")
# ฟังก์ชันเรียก Codex CLI
def run_codex_exec(task, reasoning_level='medium'):
try:
result = subprocess.run([
'codex', 'exec',
'-s', 'restricted-access',
'-c', f'model_reasoning_effort={reasoning_level}',
task
], capture_output=True, text=True)
if result.returncode == 0:
return json.loads(result.stdout)
else:
logging.error(f"Codex Error: {result.stderr}")
return None
except Exception as e:
logging.error(f"Codex Execution Error: {str(e)}")
return None
# ฟังก์ชันคำนวณ 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 และ RSI
df['sma_fast'] = ta.trend.sma_indicator(df['close'], window=10)
df['sma_slow'] = ta.trend.sma_indicator(df['close'], window=20)
df['rsi'] = ta.momentum.rsi_indicator(df['close'], window=14)
return df
# ฟังก์ชันตรวจสอบสัญญาณซื้อ/ขาย
def check_signal(df, exchange_name):
last_row = df.iloc[-1]
prev_row = df.iloc[-2]
# ใช้ Codex CLI เพื่อวิเคราะห์สัญญาณเพิ่มเติม
codex_task = f"Analyze 4H OHLCV data for BTC/USDT on {exchange_name} and confirm if SMA crossover is valid with RSI"
codex_result = run_codex_exec(codex_task, reasoning_level='medium')
signal = None
if (prev_row['sma_fast'] < prev_row['sma_slow'] and
last_row['sma_fast'] > last_row['sma_slow'] and
last_row['rsi'] < 70): # Long: SMA Fast ตัดขึ้น SMA Slow และ RSI ไม่ Overbought
signal = 'BUY'
elif (prev_row['sma_fast'] > prev_row['sma_slow'] and
last_row['sma_fast'] < last_row['sma_slow'] and
last_row['rsi'] > 30): # Short: SMA Fast ตัดลง SMA Slow และ RSI ไม่ Oversold
signal = 'SELL'
if signal and codex_result and codex_result.get('is_valid', False):
return signal
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)
# ฟังก์ชันแสดง Progress Bar
def display_progress_bar():
print(f"{Fore.CYAN}Analyzing...{Style.RESET_ALL}", end="")
for _ in range(10):
print("█", end="", flush=True)
time.sleep(0.2)
print(f"{Fore.GREEN} Done!{Style.RESET_ALL}")
# ฟังก์ชันหลักของบอต
def trading_bot():
positions = {} # เก็บสถานะ Position สำหรับแต่ละกระดาน
while True:
try:
# รัน Parallel Tasks สำหรับแต่ละกระดาน
for exchange_name, exchange in exchanges.items():
print(f"\n{Fore.CYAN}=== Checking {exchange_name} ===")
display_progress_bar()
# ดึงข้อมูล OHLCV
df = get_ohlcv(exchange, symbol, timeframe)
current_price = df['close'].iloc[-1]
# ตรวจสอบสัญญาณ
signal = check_signal(df, exchange_name)
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}")
send_telegram_alert(f"🚨 Signal Detected: {signal} on {exchange_name} at {current_price}")
# คำนวณ Fibonacci Levels ด้วย Codex CLI
high = df['high'].iloc[-20:].max()
low = df['low'].iloc[-20:].min()
codex_task = f"Calculate Fibonacci retracement levels for BTC/USDT with high={high} and low={low}"
fib_levels = run_codex_exec(codex_task, reasoning_level='low') or calculate_fibonacci_levels(high, low)
# ดึงยอดเงินในบัญชี
balance = exchange.fetch_balance()['total']['USDT']
investment = balance * investment_percentage
amount = investment / current_price
if signal == 'BUY' and exchange_name not in positions:
# เข้า Long
entry_price = current_price
sl_price = entry_price * (1 - sl_percentage)
tp_price = fib_levels['61.8%'] if fib_levels['61.8%'] > entry_price else entry_price * (1 + tp_percentage)
order = exchange.create_market_buy_order(symbol, amount)
positions[exchange_name] = {
'type': 'Long',
'entry_price': entry_price,
'sl_price': sl_price,
'tp_price': tp_price,
'amount': amount
}
logging.info(f"Opened Long Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}, Amount={amount}")
send_telegram_alert(f"🟢 Opened Long Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
print(f"{Fore.GREEN}🟢 Opened Long Position: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
elif signal == 'SELL' and exchange_name not in positions:
# เข้า Short
entry_price = current_price
sl_price = entry_price * (1 + sl_percentage)
tp_price = fib_levels['38.2%'] if fib_levels['38.2%'] < entry_price else entry_price * (1 - tp_percentage)
order = exchange.create_market_sell_order(symbol, amount)
positions[exchange_name] = {
'type': 'Short',
'entry_price': entry_price,
'sl_price': sl_price,
'tp_price': tp_price,
'amount': amount
}
logging.info(f"Opened Short Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}, Amount={amount}")
send_telegram_alert(f"🔴 Opened Short Position on {exchange_name}: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
print(f"{Fore.RED}🔴 Opened Short Position: Entry={entry_price}, SL={sl_price}, TP={tp_price}")
# ตรวจสอบ Position ที่เปิดอยู่
if exchange_name in positions:
pos = positions[exchange_name]
print(f"{Fore.MAGENTA}Position Status: {pos['type']} | Entry: {pos['entry_price']} | Current: {current_price} | SL: {pos['sl_price']} | TP: {pos['tp_price']}")
# ตรวจสอบ SL/TP
if pos['type'] == 'Long' and (current_price <= pos['sl_price'] or current_price >= pos['tp_price']):
exchange.create_market_sell_order(symbol, pos['amount'])
profit = (current_price - pos['entry_price']) * pos['amount']
c.execute("INSERT INTO trades VALUES (?, ?, ?, ?, ?, ?, ?)",
(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), exchange_name, 'Long',
pos['entry_price'], current_price, pos['amount'], profit))
conn.commit()
logging.info(f"Closed Long Position on {exchange_name}: Price={current_price}, Profit={profit}")
send_telegram_alert(f"🟡 Closed Long Position on {exchange_name}: Price={current_price}, Profit={profit}")
print(f"{Fore.YELLOW}🟡 Closed Long Position: Price={current_price}, Profit={profit}")
del positions[exchange_name]
elif pos['type'] == 'Short' and (current_price >= pos['sl_price'] or current_price <= pos['tp_price']):
exchange.create_market_buy_order(symbol, pos['amount'])
profit = (pos['entry_price'] - current_price) * pos['amount']
c.execute("INSERT INTO trades VALUES (?, ?, ?, ?, ?, ?, ?)",
(datetime.now().strftime('%Y-%m-%d %H:%M:%S'), exchange_name, 'Short',
pos['entry_price'], current_price, pos['amount'], profit))
conn.commit()
logging.info(f"Closed Short Position on {exchange_name}: Price={current_price}, Profit={profit}")
send_telegram_alert(f"🟡 Closed Short Position on {exchange_name}: Price={current_price}, Profit={profit}")
print(f"{Fore.YELLOW}🟡 Closed Short Position: Price={current_price}, Profit={profit}")
del positions[exchange_name]
# รอ 5 นาทีก่อนตรวจสอบครั้งต่อไป
time.sleep(300)
except Exception as e:
logging.error(f"Error: {str(e)}")
print(f"{Fore.RED}Error: {str(e)}")
time.sleep(60)
finally:
conn.commit()
# รันบอต
if __name__ == "__main__":
print(f"{Fore.CYAN}=== Starting Trading Bot ===")
trading_bot()
conn.close()