File size: 5,896 Bytes
8b7b267
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/**
 * Telegram Notification Service
 * Handles sending trading signals to Telegram with error handling
 */

export class TelegramService {
  constructor() {
    this.botToken = null;
    this.chatId = null;
    this.enabled = false;
    this.errorCount = 0;
    this.maxErrors = 3;
  }

  /**
   * Initializes Telegram service from settings
   */
  async init() {
    try {
      const settings = await this.loadSettings();
      this.botToken = settings.telegram?.botToken || null;
      this.chatId = settings.telegram?.chatId || null;
      this.enabled = settings.notifications?.telegramEnabled || false;
      
      if (this.botToken && this.chatId) {
        console.log('[TelegramService] Initialized');
      } else {
        console.log('[TelegramService] Not configured');
      }
    } catch (error) {
      console.warn('[TelegramService] Init error (non-critical):', error);
      this.enabled = false;
    }
  }

  /**
   * Loads settings from localStorage or API
   */
  async loadSettings() {
    try {
      const stored = localStorage.getItem('app_settings');
      if (stored) {
        return JSON.parse(stored);
      }
      
      const response = await fetch('/api/settings');
      if (response.ok) {
        return await response.json();
      }
    } catch (error) {
      console.warn('[TelegramService] Could not load settings:', error);
    }
    
    return {};
  }

  /**
   * Sends trading signal to Telegram
   * @param {Object} signalData - Signal data to send
   * @returns {Promise<boolean>} Success status
   */
  async sendSignal(signalData) {
    if (!this.enabled || !this.botToken || !this.chatId) {
      return false;
    }

    try {
      const message = this.formatSignalMessage(signalData);
      
      const response = await fetch(`https://api.telegram.org/bot${this.botToken}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: this.chatId,
          text: message,
          parse_mode: 'Markdown',
          disable_web_page_preview: true,
        }),
        signal: AbortSignal.timeout(10000),
      });

      const data = await response.json();
      
      if (data.ok) {
        this.errorCount = 0;
        console.log('[TelegramService] Signal sent successfully');
        return true;
      } else {
        throw new Error(data.description || 'Telegram API error');
      }
    } catch (error) {
      this.errorCount++;
      console.error('[TelegramService] Send error:', error.message);
      
      if (this.errorCount >= this.maxErrors) {
        console.warn('[TelegramService] Too many errors, disabling temporarily');
        this.enabled = false;
      }
      
      return false;
    }
  }

  /**
   * Formats signal data into Telegram message
   */
  formatSignalMessage(signalData) {
    const { symbol, signal, strategy, confidence, price, takeProfitLevels, stopLoss, levels, riskReward } = signalData;
    
    const signalEmoji = signal === 'buy' ? '🟒' : signal === 'sell' ? 'πŸ”΄' : '🟑';
    const signalText = signal.toUpperCase();
    
    let message = `${signalEmoji} *${symbol} Trading Signal*\n\n`;
    message += `πŸ“Š *Strategy:* ${strategy}\n`;
    message += `🎯 *Signal:* ${signalText}\n`;
    message += `πŸ’ͺ *Confidence:* ${confidence}%\n`;
    message += `πŸ’° *Price:* $${price.toLocaleString()}\n\n`;
    
    if (takeProfitLevels && takeProfitLevels.length > 0) {
      message += `*Take Profit Levels:*\n`;
      takeProfitLevels.forEach((tp, idx) => {
        const profit = ((tp.level / price - 1) * 100).toFixed(2);
        message += `  ${tp.type}: $${tp.level.toLocaleString()} (+${profit}%)\n`;
      });
      message += `\n`;
    }
    
    if (stopLoss) {
      const risk = Math.abs(((stopLoss / price - 1) * 100)).toFixed(2);
      message += `πŸ›‘ *Stop Loss:* $${stopLoss.toLocaleString()} (-${risk}%)\n`;
    }
    
    if (riskReward) {
      message += `βš–οΈ *Risk/Reward:* ${riskReward.riskRewardRatio}\n`;
    }
    
    if (levels) {
      if (levels.resistance && levels.resistance.length > 0) {
        message += `\n*Resistance Levels:*\n`;
        levels.resistance.slice(0, 2).forEach(r => {
          message += `  $${r.level.toLocaleString()} (${r.strength})\n`;
        });
      }
      
      if (levels.support && levels.support.length > 0) {
        message += `\n*Support Levels:*\n`;
        levels.support.slice(0, 2).forEach(s => {
          message += `  $${s.level.toLocaleString()} (${s.strength})\n`;
        });
      }
    }
    
    message += `\n_Time: ${new Date().toLocaleString()}_`;
    
    return message;
  }

  /**
   * Tests Telegram connection
   */
  async testConnection(botToken, chatId) {
    try {
      const response = await fetch(`https://api.telegram.org/bot${botToken}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: chatId,
          text: 'πŸ§ͺ *Test Message*\n\nTelegram integration is working correctly!',
          parse_mode: 'Markdown',
        }),
        signal: AbortSignal.timeout(10000),
      });

      const data = await response.json();
      return data.ok;
    } catch (error) {
      console.error('[TelegramService] Test error:', error);
      return false;
    }
  }

  /**
   * Updates Telegram configuration
   */
  updateConfig(botToken, chatId, enabled) {
    this.botToken = botToken;
    this.chatId = chatId;
    this.enabled = enabled && botToken && chatId;
    this.errorCount = 0;
  }

  /**
   * Checks if Telegram is properly configured
   */
  isConfigured() {
    return !!(this.botToken && this.chatId);
  }

  /**
   * Gets service status
   */
  getStatus() {
    return {
      enabled: this.enabled,
      configured: this.isConfigured(),
      errorCount: this.errorCount,
    };
  }
}