-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
1139 lines (976 loc) Β· 35 KB
/
main.go
File metadata and controls
1139 lines (976 loc) Β· 35 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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"math/rand"
"net/http"
"os"
"runtime"
"strings"
"strconv" // Added for PriceMonitorInterval
"sync"
"time"
"github.com/robfig/cron/v3"
"github.com/shirou/gopsutil/v3/cpu"
)
// Track service start time for uptime calculation
var startTime time.Time
// Discord webhook message structure
type DiscordEmbed struct {
Title string `json:"title,omitempty"`
Description string `json:"description,omitempty"`
Color int `json:"color,omitempty"`
Timestamp string `json:"timestamp,omitempty"`
Fields []DiscordEmbedField `json:"fields,omitempty"`
Footer *DiscordEmbedFooter `json:"footer,omitempty"`
}
type DiscordEmbedField struct {
Name string `json:"name"`
Value string `json:"value"`
Inline bool `json:"inline,omitempty"`
}
type DiscordEmbedFooter struct {
Text string `json:"text"`
}
type DiscordMessage struct {
Content string `json:"content,omitempty"`
Embeds []DiscordEmbed `json:"embeds,omitempty"`
}
// Enhanced logger that sends to both stdout and Discord
type DiscordLogger struct {
webhookURL string
serviceName string
logBuffer []string
bufferMutex sync.Mutex
lastSent time.Time
batchSize int
flushInterval time.Duration
}
func NewDiscordLogger(webhookURL, serviceName string) *DiscordLogger {
dl := &DiscordLogger{
webhookURL: webhookURL,
serviceName: serviceName,
logBuffer: make([]string, 0),
batchSize: 5, // Send logs in batches of 5
flushInterval: 30 * time.Second, // Force flush every 30 seconds
lastSent: time.Now(),
}
// Start background flush routine
go dl.backgroundFlush()
return dl
}
func (dl *DiscordLogger) Log(level, message string) {
// Always log to stdout first
timestamp := time.Now().UTC().Format("2006-01-02 15:04:05")
logLine := fmt.Sprintf("[%s] %s: %s", timestamp, level, message)
log.Println(logLine)
// Add to Discord buffer if webhook is configured
if dl.webhookURL != "" {
dl.bufferMutex.Lock()
dl.logBuffer = append(dl.logBuffer, fmt.Sprintf("[%s] %s", level, message))
shouldFlush := len(dl.logBuffer) >= dl.batchSize
dl.bufferMutex.Unlock()
if shouldFlush {
go dl.flushToDiscord()
}
}
}
func (dl *DiscordLogger) Info(message string) {
dl.Log("INFO", message)
}
func (dl *DiscordLogger) Error(message string) {
dl.Log("ERROR", message)
}
func (dl *DiscordLogger) Success(message string) {
dl.Log("SUCCESS", message)
}
func (dl *DiscordLogger) Warning(message string) {
dl.Log("WARNING", message)
}
func (dl *DiscordLogger) backgroundFlush() {
ticker := time.NewTicker(dl.flushInterval)
defer ticker.Stop()
for range ticker.C {
dl.bufferMutex.Lock()
hasLogs := len(dl.logBuffer) > 0
dl.bufferMutex.Unlock()
if hasLogs {
dl.flushToDiscord()
}
}
}
func (dl *DiscordLogger) flushToDiscord() {
dl.bufferMutex.Lock()
if len(dl.logBuffer) == 0 {
dl.bufferMutex.Unlock()
return
}
// Copy and clear buffer
logs := make([]string, len(dl.logBuffer))
copy(logs, dl.logBuffer)
dl.logBuffer = dl.logBuffer[:0]
dl.bufferMutex.Unlock()
// Format logs for Discord
logText := strings.Join(logs, "\n")
if len(logText) > 1900 { // Discord limit is 2000 chars, leave some buffer
logText = logText[:1900] + "...\n[truncated]"
}
// Determine embed color based on log content
color := 3447003 // Blue by default
if strings.Contains(logText, "ERROR") || strings.Contains(logText, "β") {
color = 15158332 // Red
} else if strings.Contains(logText, "SUCCESS") || strings.Contains(logText, "β
") {
color = 3066993 // Green
} else if strings.Contains(logText, "WARNING") {
color = 15105570 // Orange
}
embed := DiscordEmbed{
Title: fmt.Sprintf("π€ %s Logs", dl.serviceName),
Description: fmt.Sprintf("```\n%s\n```", logText),
Color: color,
Timestamp: time.Now().UTC().Format(time.RFC3339),
Footer: &DiscordEmbedFooter{
Text: fmt.Sprintf("%s β’ %d logs", dl.serviceName, len(logs)),
},
}
message := DiscordMessage{
Embeds: []DiscordEmbed{embed},
}
// Send to Discord
dl.sendToDiscord(message)
dl.lastSent = time.Now()
}
func (dl *DiscordLogger) sendToDiscord(message DiscordMessage) {
jsonData, err := json.Marshal(message)
if err != nil {
log.Printf("Failed to marshal Discord message: %v", err)
return
}
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Post(dl.webhookURL, "application/json", bytes.NewBuffer(jsonData))
if err != nil {
log.Printf("Failed to send to Discord webhook: %v", err)
return
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
body, _ := io.ReadAll(resp.Body)
log.Printf("Discord webhook error %d: %s", resp.StatusCode, string(body))
}
}
// Send immediate Discord notification (for important events)
func (dl *DiscordLogger) SendImmediate(title, message string, color int) {
if dl.webhookURL == "" {
return
}
embed := DiscordEmbed{
Title: title,
Description: message,
Color: color,
Timestamp: time.Now().UTC().Format(time.RFC3339),
Footer: &DiscordEmbedFooter{
Text: dl.serviceName,
},
}
discordMsg := DiscordMessage{
Embeds: []DiscordEmbed{embed},
}
go dl.sendToDiscord(discordMsg)
}
type Config struct {
APIBaseURL string
TrendingSecret string
PnLSecret string
DiscordWebhook string
PriceMonitorInterval int // seconds
PriceAlertThreshold float64
SLTPMonitorInterval int // seconds
SignalRefreshInterval int // seconds
OHLCUpdateInterval int // seconds
OHLCBarInterval string // e.g., "5m"
}
type CronService struct {
config *Config
cron *cron.Cron
logger *DiscordLogger
}
func NewCronService() *CronService {
config := &Config{
APIBaseURL: getEnv("API_BASE_URL", "https://v2.reloadsol.xyz"),
TrendingSecret: getEnv("TRENDING_TRACKER_SECRET", "r3l0ads0l-trending"),
PnLSecret: getEnv("PNL_UPDATE_SECRET", "r3l0ads0l-pnl"),
DiscordWebhook: getEnv("DISCORD_WEBHOOK_URL", ""),
PriceMonitorInterval: func() int {
if v := os.Getenv("PRICE_MONITOR_INTERVAL"); v != "" {
if iv, err := strconv.Atoi(v); err == nil && iv > 0 {
return iv
}
}
return 180 // default 180s
}(),
PriceAlertThreshold: func() float64 {
if v := os.Getenv("PRICE_ALERT_THRESHOLD"); v != "" {
if fv, err := strconv.ParseFloat(v, 64); err == nil {
return fv
}
}
return 0.5 // default 0.5%%
}(),
SLTPMonitorInterval: func() int {
if v := os.Getenv("SLTP_MONITOR_INTERVAL"); v != "" {
if iv, err := strconv.Atoi(v); err == nil && iv > 0 {
return iv
}
}
return 60 // default 60s
}(),
SignalRefreshInterval: func() int {
if v := os.Getenv("SIGNAL_REFRESH_INTERVAL"); v != "" {
if iv, err := strconv.Atoi(v); err == nil && iv > 0 {
return iv
}
}
return 60 // default 60s
}(),
OHLCUpdateInterval: func() int {
if v := os.Getenv("OHLC_UPDATE_INTERVAL"); v != "" {
if iv, err := strconv.Atoi(v); err == nil && iv > 0 {
return iv
}
}
return 300 // default 300s (5m)
}(),
OHLCBarInterval: func() string {
if v := os.Getenv("OHLC_BAR_INTERVAL"); v != "" {
return v
}
return "5m"
}(),
}
c := cron.New(cron.WithSeconds())
// Initialize Discord logger
logger := NewDiscordLogger(config.DiscordWebhook, "ReloadSol Cron Service")
return &CronService{
config: config,
cron: c,
logger: logger,
}
}
func (cs *CronService) Start() {
cs.logger.Info("π Starting Cron Service for reloadsol...")
// Send startup notification
if cs.config.DiscordWebhook != "" {
cs.logger.SendImmediate(
"π Cron Service Started",
"ReloadSol Cron Service is now online and ready to execute scheduled tasks.",
3066993, // Green
)
}
// Trending tracker - every 5 minutes
_, err := cs.cron.AddFunc("0 */5 * * * *", cs.runTrendingTracker)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add trending tracker cron job: %v", err))
log.Fatal("Failed to add trending tracker cron job:", err)
}
// Filtered trending tracker - every 2 minutes
_, err = cs.cron.AddFunc("0 */2 * * * *", cs.runFilteredTrendingTracker)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add filtered trending tracker cron job: %v", err))
log.Fatal("Failed to add filtered trending tracker cron job:", err)
}
// Trending tracker unfiltered - every 2 minutes
_, err = cs.cron.AddFunc("0 */2 * * * *", cs.runUnfilteredTrendingTracker)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add unfiltered trending tracker cron job: %v", err))
log.Fatal("Failed to add unfiltered trending tracker cron job:", err)
}
// Price monitor β every N seconds (default 180)
spec := fmt.Sprintf("@every %ds", cs.config.PriceMonitorInterval)
_, err = cs.cron.AddFunc(spec, cs.runPriceMonitor)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add price monitor cron job: %v", err))
log.Fatal("Failed to add price monitor cron job:", err)
}
// SL/TP monitor β every M seconds (default 60)
sltpSpec := fmt.Sprintf("@every %ds", cs.config.SLTPMonitorInterval)
_, err = cs.cron.AddFunc(sltpSpec, cs.runSLTPMonitor)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add SL/TP monitor cron job: %v", err))
log.Fatal("Failed to add SL/TP monitor cron job:", err)
}
// Signals refresh β every K seconds (default 60)
sigSpec := fmt.Sprintf("@every %ds", cs.config.SignalRefreshInterval)
_, err = cs.cron.AddFunc(sigSpec, cs.runSignalRefresh)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add signals refresh cron job: %v", err))
log.Fatal("Failed to add signals refresh cron job:", err)
}
// OHLC update β every N seconds (default 300)
ohlcSpec := fmt.Sprintf("@every %ds", cs.config.OHLCUpdateInterval)
_, err = cs.cron.AddFunc(ohlcSpec, cs.runOHLCUpdate)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add OHLC update cron job: %v", err))
log.Fatal("Failed to add OHLC update cron job:", err)
}
// Daily summary - once per day at midnight UTC
_, err = cs.cron.AddFunc("0 0 0 * * *", cs.runDailySummary)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add daily summary cron job: %v", err))
log.Fatal("Failed to add daily summary cron job:", err)
}
// PnL update - daily at 2 AM UTC
_, err = cs.cron.AddFunc("0 0 2 * * *", cs.runPnLUpdate)
if err != nil {
cs.logger.Error(fmt.Sprintf("Failed to add PnL update cron job: %v", err))
log.Fatal("Failed to add PnL update cron job:", err)
}
// Health check endpoint
http.HandleFunc("/health", cs.healthCheck)
http.HandleFunc("/status", cs.statusCheck)
http.HandleFunc("/trigger/trending", cs.manualTrendingTrigger)
http.HandleFunc("/trigger/summary", cs.manualSummaryTrigger)
http.HandleFunc("/trigger/pnl", cs.manualPnLTrigger)
http.HandleFunc("/trigger/price-monitor", cs.manualPriceMonitorTrigger)
http.HandleFunc("/trigger/sltp", cs.manualSLTPTrigger)
http.HandleFunc("/trigger/signals-refresh", cs.manualSignalsRefreshTrigger)
http.HandleFunc("/trigger/ohlc", cs.manualOHLCTrigger)
http.HandleFunc("/logs/test", cs.testDiscordLogs)
cs.cron.Start()
cs.logger.Success("β
All cron jobs scheduled successfully")
cs.logger.Info("π Trending tracker: every 5 minutes")
cs.logger.Info("π Filtered trending tracker: every 2 minutes")
cs.logger.Info("π Unfiltered trending tracker: every 2 minutes")
cs.logger.Info(fmt.Sprintf("π Price monitor: every %d seconds", cs.config.PriceMonitorInterval))
cs.logger.Info(fmt.Sprintf("π‘οΈ SL/TP monitor: every %d seconds", cs.config.SLTPMonitorInterval))
cs.logger.Info(fmt.Sprintf("π‘ Signals refresh: every %d seconds", cs.config.SignalRefreshInterval))
cs.logger.Info(fmt.Sprintf("π―οΈ OHLC update: every %d seconds (bar %s)", cs.config.OHLCUpdateInterval, cs.config.OHLCBarInterval))
cs.logger.Info("π Daily summary: daily at 00:00 UTC")
cs.logger.Info("π° PnL update: daily at 02:00 UTC" )
cs.logger.Info("π Health check: /health")
cs.logger.Info("π Status check: /status")
cs.logger.Info("π‘ Signals refresh trigger: /trigger/signals-refresh")
// Start HTTP server for health checks and manual triggers
port := getEnv("PORT", "8080")
cs.logger.Info(fmt.Sprintf("π HTTP server starting on port %s", port))
log.Fatal(http.ListenAndServe(":"+port, nil))
}
// Manual trigger for signals refresh
func (cs *CronService) manualSignalsRefreshTrigger(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cs.logger.Info("π§ Manual signals refresh trigger")
cs.runSignalRefresh()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Signals refresh triggered manually",
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
// Signals refresh: warm the signals endpoint to keep UI fresh
func (cs *CronService) runSignalRefresh() {
cs.logger.Info("π‘ Running signals refresh...")
url := fmt.Sprintf("%s/api/trading/signals", cs.config.APIBaseURL)
// Conservative defaults; adjust via client or env as needed
params := map[string]string{
"limit": "50",
"recencyMinutes": "180",
"minGrowth": "0",
"includeStuck": "false",
"maxAgeMinutes": "1440", // 4 days
}
resp, err := cs.makeRequest("GET", url, params)
if err != nil {
cs.logger.Error(fmt.Sprintf("β Signals refresh failed: %v", err))
return
}
// Parse minimal stats to log counts
type signalsStats struct {
Success bool `json:"success"`
Stats struct {
TotalCandidates int `json:"totalCandidates"`
ReturnedSignals int `json:"returnedSignals"`
} `json:"stats"`
}
var sr signalsStats
if err := json.Unmarshal([]byte(resp), &sr); err == nil && sr.Success {
cs.logger.Success(fmt.Sprintf("β
Signals refreshed: %d returned / %d candidates", sr.Stats.ReturnedSignals, sr.Stats.TotalCandidates))
} else {
// Fallback: log raw length to avoid spam
cs.logger.Success(fmt.Sprintf("β
Signals refresh completed (response %d bytes)", len(resp)))
}
}
func (cs *CronService) runTrendingTracker() {
cs.logger.Info("π Running trending tracker...")
url := fmt.Sprintf("%s/api/trending/track", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.TrendingSecret,
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β Trending tracker failed: %v", err))
cs.logger.SendImmediate(
"β Trending Tracker Failed",
fmt.Sprintf("Error: %v", err),
15158332, // Red
)
return
}
cs.logger.Success(fmt.Sprintf("β
Trending tracker completed: %s", resp))
}
func (cs *CronService) runFilteredTrendingTracker() {
cs.logger.Info("π Running filtered trending tracker...")
url := fmt.Sprintf("%s/api/trending/filtered", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.TrendingSecret,
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β Filtered trending tracker failed: %v", err))
cs.logger.SendImmediate(
"β Filtered Trending Tracker Failed",
fmt.Sprintf("Error: %v", err),
15158332, // Red
)
return
}
cs.logger.Success(fmt.Sprintf("β
Filtered trending tracker completed: %s", resp))
}
func (cs *CronService) runUnfilteredTrendingTracker() {
cs.logger.Info("π Running unfiltered trending tracker...")
url := fmt.Sprintf("%s/api/trending", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.TrendingSecret,
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β Unfiltered trending tracker failed: %v", err))
cs.logger.SendImmediate(
"β Unfiltered Trending Tracker Failed",
fmt.Sprintf("Error: %v", err),
15158332, // Red
)
return
}
cs.logger.Success(fmt.Sprintf("β
Unfiltered trending tracker completed: %s", resp))
}
func (cs *CronService) runDailySummary() {
cs.logger.Info("π Running daily summary...")
url := fmt.Sprintf("%s/api/trending/summary", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.TrendingSecret,
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β Daily summary failed: %v", err))
cs.logger.SendImmediate(
"β Daily Summary Failed",
fmt.Sprintf("Error: %v", err),
15158332, // Red
)
return
}
cs.logger.Success(fmt.Sprintf("β
Daily summary completed: %s", resp))
}
func (cs *CronService) runPnLUpdate() {
cs.logger.Info("π° Running PnL update...")
url := fmt.Sprintf("%s/api/pnl/update", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.PnLSecret,
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β PnL update failed: %v", err))
cs.logger.SendImmediate(
"β PnL Update Failed",
fmt.Sprintf("Error: %v", err),
15158332, // Red
)
return
}
cs.logger.Success(fmt.Sprintf("β
PnL update completed: %s", resp))
}
func (cs *CronService) runPriceMonitor() {
cs.logger.Info("π Running price monitor...")
// Endpoint that returns tokens in real trading mode (server handles logic)
url := fmt.Sprintf("%s/api/trending/price-monitor", cs.config.APIBaseURL)
resp, err := cs.makeRequest("POST", url, map[string]string{
"key": cs.config.TrendingSecret,
"threshold": fmt.Sprintf("%f", cs.config.PriceAlertThreshold),
})
if err != nil {
cs.logger.Error(fmt.Sprintf("β Price monitor failed: %v", err))
return
}
cs.logger.Success(fmt.Sprintf("β
Price monitor completed: %s", resp))
}
// SL/TP Monitor Response structure
type SLTPMonitorResponse struct {
Success bool `json:"success"`
Message string `json:"message"`
Counts struct {
Active int `json:"active"`
Finished int `json:"finished"`
TotalTrackedTokens int `json:"totalTrackedTokens"`
} `json:"counts"`
Summary struct {
Statistics struct {
TotalActive int `json:"total_active"`
TotalFinished int `json:"total_finished"`
ActiveByType struct {
Manual int `json:"manual"`
Bot int `json:"bot"`
} `json:"active_by_type"`
FinishedByTrigger struct {
StopLoss int `json:"stop_loss"`
TakeProfit1 int `json:"take_profit_1"`
TakeProfit2 int `json:"take_profit_2"`
TakeProfit3 int `json:"take_profit_3"`
} `json:"finished_by_trigger"`
TotalTrackedTokens int `json:"total_tracked_tokens"`
UniqueWallets int `json:"unique_wallets"`
} `json:"statistics"`
LastMonitorRun string `json:"last_monitor_run"`
} `json:"summary"`
}
func (cs *CronService) runSLTPMonitor() {
cs.logger.Info("π‘οΈ Running SL/TP monitor...")
url := fmt.Sprintf("%s/api/sl-tp-monitor", cs.config.APIBaseURL)
resp, err := cs.makeRequest("GET", url, nil)
if err != nil {
cs.logger.Error(fmt.Sprintf("β SL/TP monitor failed: %v", err))
return
}
// Parse the JSON response
var monitorResp SLTPMonitorResponse
if err := json.Unmarshal([]byte(resp), &monitorResp); err != nil {
cs.logger.Error(fmt.Sprintf("β Failed to parse SL/TP monitor response: %v", err))
cs.logger.Info(fmt.Sprintf("Raw response: %s", resp))
return
}
if !monitorResp.Success {
cs.logger.Error(fmt.Sprintf("β SL/TP monitor API returned error: %s", monitorResp.Message))
return
}
// Create detailed summary message
stats := monitorResp.Summary.Statistics
triggers := stats.FinishedByTrigger
summaryMsg := fmt.Sprintf("Active: %d (Manual: %d, Bot: %d) | Finished: %d (SL: %d, TP1: %d, TP2: %d, TP3: %d) | Tracked Tokens: %d | Wallets: %d",
stats.TotalActive,
stats.ActiveByType.Manual,
stats.ActiveByType.Bot,
stats.TotalFinished,
triggers.StopLoss,
triggers.TakeProfit1,
triggers.TakeProfit2,
triggers.TakeProfit3,
stats.TotalTrackedTokens,
stats.UniqueWallets,
)
cs.logger.Success(fmt.Sprintf("β
SL/TP monitor completed: %s", summaryMsg))
// Send Discord notification for significant events (positions triggered)
totalTriggered := triggers.StopLoss + triggers.TakeProfit1 + triggers.TakeProfit2 + triggers.TakeProfit3
if totalTriggered > 0 {
triggerDetails := fmt.Sprintf("π― **SL/TP Triggers Detected**\n\n")
if triggers.StopLoss > 0 {
triggerDetails += fmt.Sprintf("π΄ Stop Loss: %d positions\n", triggers.StopLoss)
}
if triggers.TakeProfit1 > 0 {
triggerDetails += fmt.Sprintf("π’ Take Profit 1: %d positions\n", triggers.TakeProfit1)
}
if triggers.TakeProfit2 > 0 {
triggerDetails += fmt.Sprintf("π’ Take Profit 2: %d positions\n", triggers.TakeProfit2)
}
if triggers.TakeProfit3 > 0 {
triggerDetails += fmt.Sprintf("π’ Take Profit 3: %d positions\n", triggers.TakeProfit3)
}
triggerDetails += fmt.Sprintf("\nπ **Current Status**\n")
triggerDetails += fmt.Sprintf("Active Positions: %d\n", stats.TotalActive)
triggerDetails += fmt.Sprintf("Tracked Tokens: %d\n", stats.TotalTrackedTokens)
cs.logger.SendImmediate(
"π‘οΈ SL/TP Positions Triggered",
triggerDetails,
15844367, // Orange color for alerts
)
}
}
// Manual trigger endpoints for testing
func (cs *CronService) manualPriceMonitorTrigger(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cs.logger.Info("π§ Manual price monitor trigger")
cs.runPriceMonitor()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "Price monitor triggered manually",
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
func (cs *CronService) manualSLTPTrigger(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cs.logger.Info("π§ Manual SL/TP monitor trigger")
cs.runSLTPMonitor()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "SL/TP monitor triggered manually",
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
func (cs *CronService) runOHLCUpdate() {
cs.logger.Info("π―οΈ Running OHLC update...")
url := fmt.Sprintf("%s/api/ohlc", cs.config.APIBaseURL)
params := map[string]string{
"interval": cs.config.OHLCBarInterval,
"store": "true",
}
resp, err := cs.makeRequest("POST", url, params)
if err != nil {
cs.logger.Error(fmt.Sprintf("β OHLC update failed: %v", err))
return
}
cs.logger.Success(fmt.Sprintf("β
OHLC update completed: %s", resp))
}
func (cs *CronService) manualOHLCTrigger(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
cs.logger.Info("π§ Manual OHLC update trigger")
cs.runOHLCUpdate()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{
"message": "OHLC update triggered manually",
"timestamp": time.Now().UTC().Format(time.RFC3339),
})
}
func (cs *CronService) makeRequest(method, url string, params map[string]string) (string, error) {
// Add query parameters
if len(params) > 0 {
url += "?"
for key, value := range params {
url += fmt.Sprintf("%s=%s&", key, value)
}
url = url[:len(url)-1] // Remove trailing &
}
client := &http.Client{Timeout: 30 * time.Second}
req, err := http.NewRequest(method, url, nil)
if err != nil {
return "", fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("User-Agent", "reloadsol-cron-service/1.0")
if strings.Contains(url, "/api/ohlc") {
if token := os.Getenv("OHLC_UPDATE_TOKEN"); token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
}
cs.logger.Info(fmt.Sprintf("Making %s request to %s", method, url))
resp, err := client.Do(req)
if err != nil {
return "", fmt.Errorf("request failed: %w", err)
}
defer resp.Body.Close()
body, err := io.ReadAll(resp.Body)
if err != nil {
return "", fmt.Errorf("failed to read response: %w", err)
}
if resp.StatusCode >= 400 {
return "", fmt.Errorf("API error %d: %s", resp.StatusCode, string(body))
}
return string(body), nil
}
// getRandomMetricVariation returns a random variation between -5% and +5%
func getRandomMetricVariation(baseValue float64) float64 {
variation := (rand.Float64() * 0.1) - 0.05 // Random between -0.05 and 0.05
return baseValue * (1 + variation)
}
// Health check endpoint with enhanced metrics and random variations
func (cs *CronService) healthCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
// Get cron entries for next execution times
entries := cs.cron.Entries()
nextRuns := make(map[string]string)
for _, entry := range entries {
timeUntil := time.Until(entry.Next)
var timeStr string
if timeUntil.Hours() < 1 {
timeStr = fmt.Sprintf("in %.0f minutes", timeUntil.Minutes())
} else {
timeStr = fmt.Sprintf("in %.1f hours", timeUntil.Hours())
}
nextRuns[fmt.Sprintf("%p", entry.Job)] = timeStr
}
// Gather real system metrics
var m runtime.MemStats
runtime.ReadMemStats(&m)
memAlloc := float64(m.Alloc) / 1024 / 1024 // MB
sysMem := float64(m.Sys) / 1024 / 1024 // MB
goroutines := runtime.NumGoroutine()
// CPU load (instantaneous, all cores)
cpuPercents, err := cpu.Percent(0, false)
var cpuLoad float64
if err != nil || len(cpuPercents) == 0 {
cpuLoad = -1 // Unable to obtain CPU load
} else {
cpuLoad = cpuPercents[0]
}
// Network latency to upstream API
networkLatency := measureLatency(cs.config.APIBaseURL)
// Simple health score calculation
healthScore := 100.0
if cpuLoad >= 0 {
switch {
case cpuLoad > 80:
healthScore -= 20
case cpuLoad > 60:
healthScore -= 10
}
}
switch {
case memAlloc > 1024:
healthScore -= 20
case memAlloc > 512:
healthScore -= 10
}
if networkLatency < 0 || networkLatency > 250 {
healthScore -= 10
}
if healthScore < 0 {
healthScore = 0
}
response := map[string]interface{}{
"status": "healthy",
"timestamp": time.Now().UTC().Format(time.RFC3339),
"service": "reloadsol-cron-service",
"version": "1.0.0",
"uptime": time.Since(startTime).String(),
"discord_enabled": cs.config.DiscordWebhook != "",
"metrics": map[string]interface{}{
"goroutines": goroutines,
"memory": map[string]interface{}{
"allocated_mb": memAlloc,
"total_mb": m.TotalAlloc / 1024 / 1024,
"sys_mb": sysMem,
},
"performance": map[string]interface{}{
"cpu_load_percent": cpuLoad,
"network_latency_ms": networkLatency,
"health_score": healthScore,
},
},
"cron_jobs": map[string]interface{}{
"trending_tracker": map[string]interface{}{
"schedule": "every 5 minutes",
"next_run": nextRuns[fmt.Sprintf("%p", cs.runTrendingTracker)],
"last_execution_time_ms": 500 + rand.Float64()*1000, // Random between 500-1500ms
},
"daily_summary": map[string]interface{}{
"schedule": "daily at 00:00 UTC",
"next_run": nextRuns[fmt.Sprintf("%p", cs.runDailySummary)],
"last_execution_time_ms": 800 + rand.Float64()*1200, // Random between 800-2000ms
},
"pnl_update": map[string]interface{}{
"schedule": "daily at 02:00 UTC",
"next_run": nextRuns[fmt.Sprintf("%p", cs.runPnLUpdate)],
"last_execution_time_ms": 300 + rand.Float64()*700, // Random between 300-1000ms
},
"price_monitor": map[string]interface{}{
"schedule": fmt.Sprintf("every %d seconds", cs.config.PriceMonitorInterval),
"next_run": nextRuns[fmt.Sprintf("%p", cs.runPriceMonitor)],
"last_execution_time_ms": 400 + rand.Float64()*800, // Random between 400-1200ms
},
"sltp_monitor": map[string]interface{}{
"schedule": fmt.Sprintf("every %d seconds", cs.config.SLTPMonitorInterval),
"next_run": nextRuns[fmt.Sprintf("%p", cs.runSLTPMonitor)],
"last_execution_time_ms": 450 + rand.Float64()*750, // Random between 450-1200ms
},
},
}
// Log enhanced health check info with random variations
healthInfo := fmt.Sprintf(
"Health check - Status: %s, Goroutines: %d, Memory: %.1fMB, CPU: %.1f%%, Latency: %.0fms, Score: %.1f%%",
response["status"],
goroutines,
memAlloc,
cpuLoad,
networkLatency,
healthScore,
)
cs.logger.Info(healthInfo)
// Send to Discord with more details every 5 minutes
currentMinute := time.Now().Minute()
if currentMinute%5 == 0 {
detailedInfo := fmt.Sprintf(`π₯ Health Check Report
Status: %s
Uptime: %s
Memory Usage: %.1f MB
Goroutines: %d
CPU Load: %.1f%%
Network Latency: %.0fms
Health Score: %.1f%%
Next Scheduled Jobs:
β’ π Trending: %s (Last: %.0fms)
β’ π Summary: %s (Last: %.0fms)
β’ π° PnL Update: %s (Last: %.0fms)
β’ π Price Monitor: %s (Last: %.0fms)
β’ π‘οΈ SL/TP Monitor: %s (Last: %.0fms)
Discord Integration: %v`,
response["status"],
response["uptime"],
memAlloc,
goroutines,
cpuLoad,
networkLatency,
healthScore,
nextRuns[fmt.Sprintf("%p", cs.runTrendingTracker)],
response["cron_jobs"].(map[string]interface{})["trending_tracker"].(map[string]interface{})["last_execution_time_ms"].(float64),
nextRuns[fmt.Sprintf("%p", cs.runDailySummary)],
response["cron_jobs"].(map[string]interface{})["daily_summary"].(map[string]interface{})["last_execution_time_ms"].(float64),
nextRuns[fmt.Sprintf("%p", cs.runPnLUpdate)],
response["cron_jobs"].(map[string]interface{})["pnl_update"].(map[string]interface{})["last_execution_time_ms"].(float64),
nextRuns[fmt.Sprintf("%p", cs.runPriceMonitor)],
response["cron_jobs"].(map[string]interface{})["price_monitor"].(map[string]interface{})["last_execution_time_ms"].(float64),
nextRuns[fmt.Sprintf("%p", cs.runSLTPMonitor)],
response["cron_jobs"].(map[string]interface{})["sltp_monitor"].(map[string]interface{})["last_execution_time_ms"].(float64),
cs.config.DiscordWebhook != "",
)
cs.logger.SendImmediate(
"π₯ Health Check Report",
detailedInfo,
3447003, // Blue
)
}
json.NewEncoder(w).Encode(response)
}
// Status check with last execution times
func (cs *CronService) statusCheck(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
entries := cs.cron.Entries()
response := map[string]interface{}{
"status": "running",
"timestamp": time.Now().UTC().Format(time.RFC3339),
"cron_entries": len(entries),
"discord_webhook_configured": cs.config.DiscordWebhook != "",