19
import time
from datetime import datetime
import pandas as pd
import numpy as np
import ta
from iqoptionapi.stable_api import IQ_Option
from telegram import Bot

# ====== CONFIG ======
IQ_EMAIL = "you@example.com"
IQ_PASSWORD = "yourpassword"
BOT_TOKEN = "123456:ABC-DEF..." # Telegram bot token
CHAT_ID = "987654321" # your chat id
SYMBOL = "EURUSD" # ตัวอย่าง
TIMEFRAME = 60 # 60s candles => 1 minute
CANDLES = 100

MIN_CONFIRMS = 3

# Connect Telegram
bot = Bot(token=BOT_TOKEN)

# ===== indicator functions =====
def hl2(high, low):
return (high + low) / 2.0

def get_signals_from_df(df):
# df must have columns: 'from', 'open', 'close', 'min','max','volume'
price = (df['max'] + df['min'])/2.0 # hl2
close = df['close']
high = df['max']
low = df['min']

# EMA
emaF = ta.trend.ema_indicator(close, window=5)
emaS = ta.trend.ema_indicator(close, window=20)

# MACD
macd = ta.trend.MACD(close, window_slow=26, window_fast=12, window_sign=9)
macd_line = macd.macd()
macd_sig = macd.macd_signal()

# RSI
rsi = ta.momentum.rsi(close, window=14)

# Bollinger
bb = ta.volatility.BollingerBands(close, window=20, window_dev=2)
bb_high = bb.bollinger_hband()
bb_low = bb.bollinger_lband()

# S/R simple
sr_len = 20
sr_high = close.rolling(sr_len).max().iloc[-1]
sr_low = close.rolling(sr_len).min().iloc[-1]

# last bar
i = -1
bull = 0
bear = 0

# EMA trend
if emaF.iloc > emaS.iloc:
bull += 1
else:
bear += 1

# MACD cross
if macd_line.iloc > macd_sig.iloc and macd_line.iloc[i-1] <= macd_sig.iloc[i-1]:
bull += 1
if macd_line.iloc < macd_sig.iloc and macd_line.iloc[i-1] >= macd_sig.iloc[i-1]:
bear += 1

# RSI
if rsi.iloc > 50:
bull += 1
elif rsi.iloc < 50:
bear += 1

# Bollinger breakout
if close.iloc > bb_high.iloc:
bull += 1
if close.iloc < bb_low.iloc:
bear += 1

# re-test (previous close near EMA or SR then bounce)
prev_close = close.iloc[i-1]
tol = 0.0015
try:
if (prev_close <= emaF.iloc[i-1] and close.iloc > emaF.iloc) or (abs(prev_close - sr_low) <= sr_low*tol and close.iloc > sr_low):
bull += 1
except:
pass
try:
if (prev_close >= emaF.iloc[i-1] and close.iloc < emaF.iloc) or (abs(prev_close - sr_high) <= sr_high*tol and close.iloc < sr_high):
bear += 1
except:
pass

# candle strength
body = close.iloc - df['open'].iloc
if body > (df['max'].iloc - df['min'].iloc) * 0.25:
bull += 1
if body < -(df['max'].iloc - df['min'].iloc) * 0.25:
bear += 1

# decide
show_buy = (bull >= MIN_CONFIRMS) and (bull > bear)
show_sell = (bear >= MIN_CONFIRMS) and (bear > bull)

# risk text
def risk_text(c):
if c >= 5:
return "เสี่ยง: ต่ำ (Low)"
if c >= 3:
return "เสี่ยง: กลาง (Med)"
return "เสี่ยง: สูง (High)"

return {
"buy": show_buy,
"sell": show_sell,
"bull_count": bull,
"bear_count": bear,
"risk": risk_text(bull if show_buy else bear)
}

# ===== main loop =====
def main():
Iq = IQ_Option(IQ_EMAIL, IQ_PASSWORD)
Iq.connect()
if not Iq.check_connect():
print("Login failed")
return
print("Connected")
while True:
try:
candles = Iq.get_candles(SYMBOL, TIMEFRAME, CANDLES, time.time())
df = pd.DataFrame(candles)
# columns: 'from','at','open','close','min','max','volume' depending on API version
# ensure columns present:
if 'close' not in df.columns:
time.sleep(5)
continue
df['from'] = pd.to_datetime(df['from'], unit='s')
df.set_index('from', inplace=True)

res = get_signals_from_df(df)
t = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
if res['buy']:
text = f"🔺 CALL 1m | {SYMBOL} | {t}\n{res['risk']} | confirmations: {res['bull_count']}"
bot.send_message(chat_id=CHAT_ID, text=text)
print(text)
elif res['sell']:
text = f"🔻 PUT 1m | {SYMBOL} | {t}\n{res['risk']} | confirmations: {res['bear_count']}"
bot.send_message(chat_id=CHAT_ID, text=text)
print(text)
else:
print(f"{t} - No strong signal ({res['bull_count']}/{res['bear_count']})")
# wait until next candle close (align approx)
sleep_sec = 60 - datetime.utcnow().second
time.sleep(sleep_sec + 0.5)
except Exception as ex:
print("Error:", ex)
time.sleep(5)

if __name__ == "__main__":
main()

คำจำกัดสิทธิ์ความรับผิดชอบ

ข้อมูลและบทความไม่ได้มีวัตถุประสงค์เพื่อก่อให้เกิดกิจกรรมทางการเงิน, การลงทุน, การซื้อขาย, ข้อเสนอแนะ หรือคำแนะนำประเภทอื่น ๆ ที่ให้หรือรับรองโดย TradingView อ่านเพิ่มเติมใน ข้อกำหนดการใช้งาน