-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
219 lines (190 loc) · 7.13 KB
/
main.py
File metadata and controls
219 lines (190 loc) · 7.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
from telethon import TelegramClient, events
import time
import threading
import os
import asyncio
import re
import requests
#logging
import csv
import datetime
# Variabili d'ambiente
api_id = int(os.getenv('API_ID'))
api_hash = os.getenv('API_HASH')
source_chat = -1002141199775 # ID gruppo privato
###source_chat = -1002355915425 # ID gruppo debug purpose
destination_chat = 690164647 # ID Bot
WEBHOOK_URL = os.getenv('WEBHOOK_URL')
WEBHOOK_SECRET = os.getenv('WEBHOOK_SECRET')
# IG Markets credentials
USERNAME = os.getenv('IG_USERNAME')
PASSWORD = os.getenv('IG_PASSWORD')
API_KEY = os.getenv('IG_API_KEY')
BASE_URL = 'https://demo-api.ig.com/gateway/deal'
# Crea client Telethon
client = TelegramClient('session_copytrading', api_id, api_hash)
def login_ig():
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
"X-IG-API-KEY": API_KEY,
"Version": "2"
}
payload = {
"identifier": USERNAME,
"password": PASSWORD
}
res = requests.post(f"{BASE_URL}/session", headers=headers, json=payload)
if res.status_code != 200:
print("Errore autenticazione IG:", res.text)
return None, None, None
return res.headers["CST"], res.headers["X-SECURITY-TOKEN"], res.json()["currentAccountId"]
def parse_signal(msg):
lines = msg.strip().splitlines()
data = {}
for line in lines:
if match := re.match(r'(Buy|Sell):\s*(\d+(\.\d+)?)', line, re.IGNORECASE):
data['direction'] = match.group(1).capitalize()
elif line.startswith('SL:'):
data['sl'] = float(line.split(':')[1].strip())
elif line.startswith('TP2:'):
data['tp2'] = float(line.split(':')[1].strip())
elif line.startswith('TP4:'):
data['tp4'] = float(line.split(':')[1].strip())
if not all(k in data for k in ['direction', 'sl', 'tp2', 'tp4']):
raise Warning("Messaggio non è un ordine o malformattato")
return data
def confirm_order(deal_ref, cst, x_sec):
headers = {
"X-IG-API-KEY": API_KEY,
"CST": cst,
"X-SECURITY-TOKEN": x_sec,
"Accept": "application/json",
"Version": "1"
}
res = requests.get(f"{BASE_URL}/confirms/{deal_ref}", headers=headers)
if res.status_code != 200:
return None, None, None
data = res.json()
return data.get("dealStatus"), data.get("reason"), data.get("level"), data.get("stopLevel")
def place_order(tp, direction, sl, cst, x_sec):
headers = {
"X-IG-API-KEY": API_KEY,
"CST": cst,
"X-SECURITY-TOKEN": x_sec,
"Content-Type": "application/json",
"Version": "2"
}
payload = {
"epic": "CS.D.CFDGOLD.CFDGC.IP",
"expiry": "-",
"direction": direction.upper(),
"size": 0.2,
"orderType": "MARKET",
"guaranteedStop": False,
"forceOpen": True,
"limitLevel": tp,
"stopLevel": sl,
"currencyCode": "USD",
"timeInForce": "FILL_OR_KILL"
}
res = requests.post(f"{BASE_URL}/positions/otc", headers=headers, json=payload)
if res.status_code != 200:
return None, None, None, None
deal_ref = res.json().get("dealReference")
status, reason, level, stop_level = confirm_order(deal_ref, cst, x_sec)
return status, reason, level, stop_level, deal_ref
# Handle message signal and call trade
async def handle_signal_and_trade(msg):
try:
signal = parse_signal(msg)
cst, x_sec, acc_id = login_ig()
if not cst:
await client.send_message(destination_chat, "❌ Login fallito su IG.")
return
# Ordine 1 con TP2
status1, reason1, price1, sl1, deal1 = place_order(signal['tp2'], signal['direction'], signal['sl'], cst, x_sec)
if status1 == "ACCEPTED":
log_order_to_csv({
'direction': signal['direction'],
'tp': signal['tp2'],
'sl': sl1,
'level': price1,
'dealReference': deal1,
'openLevel': price1
})
# Ordine 2 con TP4
status2, reason2, price2, sl2, deal2 = place_order(signal['tp4'], signal['direction'], signal['sl'], cst, x_sec)
if status2 == "ACCEPTED":
log_order_to_csv({
'direction': signal['direction'],
'tp': signal['tp4'],
'sl': sl2,
'level': price2,
'dealReference': deal2,
'openLevel': price2
})
if status1 == "ACCEPTED" and status2 == "ACCEPTED":
text = (
f"✅ **2 ordini su XAUUSD aperti**:\n\n"
f"📌 Direzione: **{signal['direction']}**\n"
f"🔸 **Ordine 1**: Entry = `{price1}` | TP = `{signal['tp2']}` | SL = `{sl1}` | DealRef = `{deal1}`\n"
f"🔸 **Ordine 2**: Entry = `{price2}` | TP = `{signal['tp4']}` | SL = `{sl2}` | DealRef = `{deal2}`"
)
else:
text = (
f"❌ Problemi nell'aprire gli ordini:\n"
f"🔹 **Ordine 1**: {status1} — **{reason1}**\n"
f"🔹 **Ordine 2**: {status2} — **{reason2}**"
)
print(text)
await client.send_message(destination_chat, text, parse_mode='markdown')
except Exception as e:
print(f"[⚠️] Problema nel gestire segnale: {e}")
# await client.send_message(destination_chat, f"⚠️ Errore nel gestire segnale: `{e}`", parse_mode="markdown")
# Log into csv function
def log_order_to_csv(data):
timestamp = datetime.datetime.now(datetime.timezone.utc).isoformat()
filename = 'order_log.csv'
row = {
'timestamp': timestamp,
'direction': data.get('direction'),
'tp': data.get('tp'),
'sl': data.get('sl'),
'level': data.get('level'),
'dealReference': data.get('dealReference'),
'openLevel': data.get('openLevel')
}
file_exists = os.path.isfile(filename)
with open(filename, 'a', newline='') as csvfile:
fieldnames = row.keys()
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
if not file_exists:
writer.writeheader()
writer.writerow(row)
print(f"[📁] Ordine salvato su {filename}")
# Handler dei messaggi in arrivo sul Gruppo privato
@client.on(events.NewMessage(chats=source_chat))
async def handler(event):
print(f"[📩] Nuovo messaggio ricevuto: {event.raw_text}")
await forward_last_message(event)
await handle_signal_and_trade(event.raw_text)
async def forward_last_message(event):
try:
await event.forward_to(destination_chat)
print("[➡️] Messaggio inoltrato al bot")
except Exception as e:
print(f"[❌] Errore inoltro: {e}")
def heartbeat():
while True:
print("[🟢] App attiva e in ascolto...")
time.sleep(3600*4) # bit ogni 4 ore
async def main():
print("[🚀] Avvio listener Telethon...")
await client.start()
await client.run_until_disconnected()
if __name__ == "__main__":
# ✅ Avvio thread heartbeat
threading.Thread(target=heartbeat, daemon=True).start()
# ✅ Avvio main
asyncio.run(main())