forked from frittna/Crypto_Coin_Ticker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCrypto_Coin_Ticker.ino
2521 lines (2391 loc) · 131 KB
/
Crypto_Coin_Ticker.ino
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
//----------------------------------------------------------------------------------------------------------------------------
// CRYPTO CURRENCY PRICE TICKER with 24 candlesticks chart for M5Stack
//
// ###SD-Card Version with configuation file###
// only needs config file "ccticker.cfg" on root of SD-Card
//
// receiving WiFi data from Binance API/Websocket_v3 - by frittna (https://github.com/frittna/Crypto_Coin_Ticker)
//
// This will show 24 candles, the min/max price and the volume as line, date and time are from time.nist.gov timeserver.
// For M5-Stack MCU , coded in ArduinoIDE 1.8.13 - last modified Nov.20.2021 15:20 CET - Version 1.0.53fix using spiffs + SDconfig
//
//
//
// last edits: -> added cycling function (ButtonA+ButtonC together) which steps through your currencies after a certain time (default: 15sec for each)
// -> added Timezone for Singapore (UTC+8)
// -> minor changings: - code merged to one version, so there is no need to have different versions anymore !
// - autodetect the optional room sensor and show a 12x high sensor panel in case
// - temperature unit C or F and an temperature offset is set from SD-Config file and not hardcoded anymore
// (because the M5-Stack is heating up itself it will never be accurate and has only limited expressiveness)
//
//
//
// ----------------------------------------------------------------------------------------------------------------------------
// #Using the App:
// ###############
// This version needs a SD-Card whith the your WiFi credentials, favourite coinpairs, timezone and language(eng/ger/esp) in a textfile - see installation
// ButtonA: switches through your favourite Coinpair (as many you want) e.g: BTC/USDT etc. which are available on Binance.com
// ButtonB: changes the LCD-Brightness in 4 levels
// ButtonC: 9 changeable Timeframes from 1 Minute to 1 Month
// turn OFF the device pressing the red Button once OR by holding ButtonC for over 1 second
// Press ButtonC, then, within 2 sec press ButtonA to switch down, or ButtonB to switch up through the timeframes: 1min->15mins->1hour->..
// available timeframes are 1minute, 3m, 5m, 15m, 1h, 4h, 1d, 1w, 1Month
// if you hold ButtonC at Startup: it will start with alternative SSID2/WiFi2-password instead (e.g your mobile phone's hotspot)
// press ButtonA and ButtonC together to enable/disable cycling through all currencies after a set time (default:off, when turned on default:15sec)
// #Further description:
// #####################
// The top infoPanel shows the WiFi-strength, batterylevel, colored indicators for "busy", SleepTimer, price moving and if charging from usb (can have delay up to 30s)
// right now: english, german, spanish Language (day and month names)
// SleepTimer: when holding ButtonB longer than 1,5 seconds it will start a user defined timer to powerOFF the device
// If WiFi is failing more than 2 minutes it reduces the reconnect interval and brightness level, after 10 minutes -> shutdown device
// Menu Loader compatible, if SD-Updater (menu.bin) is installed in your SD-Card hold ButtonA while booting up to start MenuLoader to load your apps
// It is prepared for the use of a Neopixel RGB-LED bar (i use the built-in one in the Battery-Bottom Module for M5Stack/Fire with rgb 10 LEDs)
// All settings will remain stored in internal memory after a reset so you can eject the SD-Card after setting up you favourites.
// If you want to clear all stored settings from internal memory hold ButtonB at start-up.
// If M5-Stack is in his BTC stand (the original grey vertical stand) the internal room sensor is found and shows temp and humidity.
// INSTALLATION INSTRUCTIONS
// #########################
// - find a way to transfer this APP into your M5 Device. A very easy way is to load "M5Burner_Crypto_Coin_Ticker.zip" from https://github.com/frittna/Crypto_Coin_Ticker
// - ! IMPORTANT ! - To run the app correctly you have to put "ccticker.cfg" into the root of your SD-Card. (FAT32 filesystem is good)
// Modify "ccticker.cfg" with your personal wifi ssid/password, timezone, favorite currency pair - use a simple text editor
// On the SD-Card you should have something like "G:\ccticker.cfg"
// - When you're done, safe-remove the SD-Card and insert into the M5Stack -> go, boot it up.
// - You can eject the SD-Card after the use, the settings will be stored until you update them again with SD-Card
// (*INSTALLATION INSTRUCTIONS from skratch) ->> only for those who compile by their own in Arduino IDE <<--
// note: you can adjust basically all main settings in the conig file from SD-Card. But if you want to build
// it on your own or if you want to modify something special or even extend this cool gadget go for it!
// - download Arduino IDE from their homepage https://www.arduino.cc/en/Main/Software
// - like instructed in the M5-Stack mini-manual be sure to add the additional boards manager url at Arduino preferencies:
// file -> preferencies: https://dl.espressif.com/dl/package_esp32_index.json - then restart Arduino
// - install the M5-Stack board in Arduino: Tools -> Board -> Boards Manager -> search for esp32 and install ver.1.0.4
// ---> !! use ESP32 Board Manager Version 1.0.4 since higher versions are reported to fail !! <<---
// afterwards select the right board at the tools menu called M5-Stack-Core-ESP32, then select your actual COM port (restart Arduino
// with USB connected to your M5-Stack if no COM-port is shown, also be shure to try the USB connector the other way round if you can't get it done)
// - open new sketch, save it to create a sketch folder and paste all of this code into the code window
// - install all included librarys in your Arduino: Sketch -> Include Library -> Manage Libraries -> search for the correct ones (look very carefully)
// - for the esp32fs tool (for uploading the SPIFFS data files) you have to search with google or use the github link https://github.com/me-no-dev/arduino-esp32fs-plugin,
// (i have also put all needed files into a folder called "public" on my github site)
// - to install the esp32fs tool correctly you have to copy the folder called ESP32FS inside the ESP32FS-1.0.zip archive into your Arduino's sketchbook folder
// so first create a tools folder if there is no and paste the ESP32FS folder in it (it should look like C:\Users\yourName\Documents\Arduino\tools\ESP32FS\tool\esp32fs.jar )
// (for the standalone verion of Arduino put the esp32fs tool into your current arduino program folder like C:\arduino-1.8.13\tools\ESP32FS\tool\esp32fs.jar )
// - if esp32fs is loaded correctly you can see after a restart of Arduino a tool called "ESP32 Sketch Data Uploader" in you tools menu
// - you have to download all my png picture files from my "data" folder on github and put it into your sketch subfolder "data". (open your sketch folder quickly with CTRL+K)
// - click verify, afterwards you can click "ESP32 Sketch Data Uploader" from the tools menu to flash the data into the M5Stack embedded memory
// - when you followed everything click compile, when finished upload
// - last step is to see the instructions for adjusting the personal configuration file "ccticker.cfg"
// --------------------------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------
// The core for the candlestick view and binance api was from: https://github.com/olbed/bitcoin-ticker on SPI TFT display ILI9341 and NodeMCU Board, from 2019
// Known bugs to fix: ButtonC debouncing, battery symbol could be more precise, untested format if price will pass the 100k ;)
// maybe some inefficient code since this is my first public release
//------------------------------------------------------------------------------------------------------------------------------------
//------------------------------------------------------------------------------------------------------------------------------------
// ##BEGIN##
// ---->> for THIS SD-Card Version nothing has to be edited here - use the "ccticker.cfg" textfile on the SD-Card root folder <<----
// Wi-Fi connection settings:
String ssid = ""; // change here to "myName" or whatever you have as Wifi SSID name (127 characters max.)
String password = ""; // enter your password like "myPassword"
//optional:
String ssid2 = ""; // alternative wi-fi network to connect when ButtonC is held at startup
String password2 = ""; //
// name: from: version search library manager exactly for:
// ---------------------------------------+------------------------------------------+------ + --------------------------------------------------------------|
#include "Free_Fonts.h" // Library | Arduino built-in | | |
#include <Preferences.h> // Library | Arduino built-in | | |
#include <WiFi.h> // Board-pkg| ESP32 Board Manager -> problems on start?|1.0.4**| |
#include <SDConfig.h> // Library | Arduino Librarymanager Claus Mancini | 1.1.0 | "SDConfig" |
#include <M5Stack.h> // Library | Arduino Librarymanager M5Stack | 0.3.1 | "M5Stack" |
#include <Timezone.h> // Library | Arduino Librarymanager Jack Christensen | 1.2.4 | "Timezone" |
#include <time.h> // Library | Arduino Librarymanager Michael Margolis | 1.6 | "timekeeping" |
#include <WebSocketsClient.h> // Library | Arduino Librarymanager Markus Sattler | 2.3.0 | "Websockets" |
#include <ArduinoJson.h> // Library | Arduino Librarymanager Benoit Blanchon | 6.17.3| "ArduinoJson" |
#include "M5StackUpdater.h" // Library | Arduino Librarymanager SD-Menu Loader | 0.5.2!| "M5Stack SD" i use 0.5.2 , not new 1.0.2 because of problems |
#include <Adafruit_NeoPixel.h>// Library | Arduino Librarymanager Adafruit NeoPixel | 1.7.0 | "Adafriut Neopixel" |
#include "FS.h" // Prog-Tool| github: esp32fs for SPIFFS filesystem | 1.0 | https://github.com/me-no-dev/arduino-esp32fs-plugin |
#include "SHT3X.h" // Library | M5Stack-Examples for base with SHT30
// ---------------------------------------+------------------------------------------+-------+----------------------------------------------------------------
// **if you compile and have problems resulting a reset or no proper connection to WiFi after powering up you schould check
// all versions again if they are really identical to the ones from this instruction above.
// ---->> especially for the ESP32 Board Manager use Version 1.0.4 since higher versions are reported to fail !!
//NOTE: all settings below are only the default values when no configurations are loaded from SD-Card (the ccticker.cfg file), no change needed here in the Code!
char configFile[] = "/ccticker.cfg"; // filename for configuration file on root of your SD-Card - if no file/card is found last settings will be loaded
char* welcome = "Hey You! ;)";
int myTimeZone = 4; //use 4 if nothing else instructed = US Eastern Time Zone EST (New York, Detroit)
int myLanguage = 0; //use 0 if nothing else instructed = english
int pairs = 4; //total numbers of coin pairs to load, default: 4, max. 25
const int max_pairs_arrsize = 25; // number of max.possible coinpairs recognized by configuration file (do not adjust this without extendig the routine for SD-Card reading)
String pair_STRING[max_pairs_arrsize] = {"BTCUSDT", "ETHUSDT", "DOTUSDT", "LINKUSDT"}; //default values if no external config file exists
String pair_name[max_pairs_arrsize] = {" Bitcoin", " ETH", " DOT", " LINK" };
String pair_col_str[max_pairs_arrsize] = {"0xFD20", "0x03EF", "0xC618", "0x001F" };
uint16_t rgb565_pair_color[max_pairs_arrsize] = { 0xFD20, 0x03EF, 0xC618, 0x001F };
// Notes for color names: use hex in rgb565 format like: 0x07FF not rgb888 0x07FF88
const char* weekDay_Language0[] = {"", "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa"}; // english language
const char* monthName_Language0[] = {"", "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"}; // english language
const char* weekDay_Language1[] = {"", "So", "Mo", "Di", "Mi", "Do", "Fr", "Sa"}; // translated to german
const char* monthName_Language1[] = {"", "Jan", "Feb", "Mar", "Apr", "Mai", "Jun", "Jul", "Aug", "Sep", "Okt", "Nov", "Dez"}; // translated to german
const char* weekDay_Language2[] = {"", "do", "lu", "ma", "mi", "ju", "vi", "sá"}; // translated to spanish
const char* monthName_Language2[] = {"", "ene", "feb", "mar", "abr", "may", "jun", "jul", "ago", "sep", "oct", "nov", "dic"}; // translated to spanish
const byte timeframes = 9;
const char* candlesTimeframes[timeframes] = {"1m", "3m", "5m", "15m", "1h", "4h", "1d", "1w", "1M"};
const char* weekDay_MyLang[8];
const char* monthName_MyLang[13];
// you can define your own color names for use in code only. with #define my_col M5.Lcd.color565(80,50,125) /* uint16_t color565(0-255, 0-255, 0-255) for RGB, */
#define DARKERGREEN M5.Lcd.color565(146,217,0) /* uint16_t color565(uint8_t r, uint8_t g, uint8_t b), */
#define MYRED M5.Lcd.color565(255,0,28) /* uint16_t color565(uint8_t r, uint8_t g, uint8_t b), */
int pinSelectSD = 4; // SD shield Chip Select pin. (4 for M5Stack)
boolean readConfiguration();
int maxLineLength = 127; //Length of the longest line expected in the config file
// REST API DOCS: https://github.com/binance-exchange/binance-official-api-docs/blob/master/rest-api.md
const char* restApiHost = "api.binance.com";
const byte candlesLimit = 24;
String pair_STRING_mem[max_pairs_arrsize];
String pair_name_mem[max_pairs_arrsize];
String pair_col_str_mem[max_pairs_arrsize];
String pair_string[max_pairs_arrsize];
int current_Currency;
byte current_Timeframe;
byte custom_Timezone = 8; // if no timezone matches you can set a custom difference from utc in hours (+ or -) When this is used there is no summer / standart time change rule!
unsigned int last_stored_Brightness_value;
unsigned int last_stored_Brightness_level;
unsigned int last_stored_Currency;
unsigned int last_stored_Timeframe;
String ssid_mem;
String ssid2_mem;
String password_mem;
String password2_mem;
int mySleeptime_mem;
int myTimeZone_mem;
int myTempUnit; //if 1 is read from sd-card config use for Fahrenheit, otherwise use Celsius as default temperature unit
int myTempOffset;
int myCyclingIntervall;
int myTempUnit_mem;
float myTempOffset_mem;
int myCyclingIntervall_mem;
int myLanguage_mem;
int pairs_mem;
int change_count = 0;
const uint32_t volColor = 0x22222a;
// WS API DOCS: https://github.com/binance-exchange/binance-official-api-docs/blob/master/web-socket-streams.md
const char* wsApiHost = "stream.binance.com";
const int wsApiPort = 9443;
// Layout: The space between the info and the bottom panel is for candlechart => 240px minus top+info+bottom
const byte topPanel = 20;
const byte infoPanel = 16; //16px in height;
byte sensorPanel; //16px or 0px in height when no sensor found
const byte bottomPanel = 36;
Preferences preferences; //the last read-in SD-Card settings are saved in internal memory
WiFiClient client;
WebSocketsClient webSocket;
StaticJsonDocument<8750> jsonDoc;
TimeChangeRule summer_aedt = {"AEDT", First, Sun, Oct, 2, 660}; // 0: Australia Eastern Time Zone (Sydney, Melbourne)
TimeChangeRule standard_aest = {"AEST", First, Sun, Apr, 3, 600};
TimeChangeRule summer_bst = {"BST", Last, Sun, Mar, 1, 60}; // 1: United Kingdom (London, Belfast)
TimeChangeRule standard_gmt = {"GMT", Last, Sun, Oct, 2, 0};
TimeChangeRule summer_eest = {"EEST", Last, Sun, Mar, 3, 180}; // 2: Eastern European Time (Bulgaria, Greece, Romania, Ukraine, Egypt)
TimeChangeRule standard_eet = {"EET ", Last, Sun, Oct, 4, 120};
TimeChangeRule summer_cest = {"CEST", Last, Sun, Mar, 2, 120}; // 3: Central European Time Zone (Frankfurt, Paris)
TimeChangeRule standard_cet = {"CET ", Last, Sun, Oct, 3, 60};
TimeChangeRule summer_edt = {"EDT", Second, Sun, Mar, 2, -240}; // 4: US Eastern Time Zone (New York, Detroit)
TimeChangeRule standard_est = {"EST", First, Sun, Nov, 2, -300};
TimeChangeRule summer_cdt = {"CDT", Second, dowSunday, Mar, 2, -300}; // 5: US Central Time Zone (Chicago, Houston)
TimeChangeRule standard_cst = {"CST", First, dowSunday, Nov, 2, -360};
TimeChangeRule summer_mdt = {"MDT", Second, dowSunday, Mar, 2, -360}; // 6: US Mountain Time Zone (Denver, Salt Lake City)
TimeChangeRule standard_mst = {"MST", First, dowSunday, Nov, 2, -420};
TimeChangeRule summer_pdt = {"PDT", Second, dowSunday, Mar, 2, -420}; // 7: US Pacific Time Zone (Las Vegas, Los Angeles);
TimeChangeRule standard_pst = {"PST", First, dowSunday, Nov, 2, -480};
TimeChangeRule summer_sgt = {"SGT", Last, Sun, Oct, 4, 480}; // 8: Singapore Time Zone (UTC + 8) - no TimeChange for Summer/Standart Time
TimeChangeRule standard_sgt = {"SGT", Last, Sun, Mar, 3, 480};
Timezone myTZ0(summer_aedt, standard_aest); // myTZ0: 0 Australia Eastern Time Zone (Sydney, Melbourne)
Timezone myTZ1(summer_bst, standard_gmt); // myTZ1: 1 United Kingdom (London, Belfast)
Timezone myTZ2(summer_eest, standard_eet); // myTZ2: 2 Eastern European Time (Bulgaria, Greece, Romania, Ukraine, Egypt)
Timezone myTZ3(summer_cest, standard_cet); // myTZ3: 3 Central European Time Zone (Frankfurt, Paris)
Timezone myTZ4(summer_edt, standard_est); // myTZ4: 4 US Eastern Time Zone (New York, Detroit)
Timezone myTZ5(summer_cdt, standard_cst); // myTZ5: 5 US Central Time Zone (Chicago, Houston)
Timezone myTZ6(summer_mdt, standard_mst); // myTZ6: 6 US Mountain Time Zone (Denver, Salt Lake City)
Timezone myTZ7(summer_pdt, standard_pst); // myTZ7: 7 US Pacific Time Zone (Las Vegas, Los Angeles);
Timezone myTZ8(summer_sgt, standard_sgt); // myTZ8: 8 Singapore Time Zone UTC +8
// LED-Pixel bar(see bottom of this file for further details)
#define PIN 15 // use the built-in LED bar in the M5-Stack/Fire Battery-Bottom-Module (10xLED on Pin15)
#define NUMPIXELS 10 // 10 LEDs
Adafruit_NeoPixel LEDbar(NUMPIXELS, PIN, NEO_GRB + NEO_KHZ800);
int mySleeptime = 45;
unsigned long sleeptime = mySleeptime * 60; // SLEEPTIMER: in minutes - hold ButtonB long for sleeptimer to start or stop
unsigned long currentMs;
byte Brightness_level;
int Brightness_value;
unsigned long sleeptimer_counter;
bool sleeptimer_bool;
unsigned int lastPrintTime;
float lastPrice = -1;
float lastLow = -1;
float lastHigh = -1;
bool candleIsNew;
float openTime;
float last_correct_openTime;
float w = 320.0 / candlesLimit;
float center;
int lastTimeframe = -1;
unsigned int wsFails;
byte empty_candles;
unsigned int currency_cycling_counter;
bool currency_cycling = false;
bool cycling_change_triggered = false;
bool current_Currency_changed;
bool current_bright_changed;
bool current_timeframe_changed;
bool timeframe_really_changed;
unsigned long currency_btn_timeout_counter = 4294966295; // = max
unsigned long bright_btn_timeout_counter = 4294966295;
unsigned long timeframe_btn_timeout_counter1 = 4294966295;
unsigned long timeframe_btn_timeout_counter2 = 4294966295;
String strname_api;
String strname_ws;
String strname_currency;
uint16_t strname_color;
int err_count;
long multi = 1;
byte multi_level;
bool ws_error;
bool alt_hotspot = false;
bool wifi_error;
typedef struct {
float l; // Low
float h; // High
float o; // Open
float c; // Close
float v; // Volume
} Candle;
Candle candles[candlesLimit];
float lastCandleOpenTime;
float ph; // Price High
float pl; // Price Low
float vh; // Volume High
float vl; // Volume Low
SHT3X sht30; // (optional) for the grey vertical base with built in sensor
float tmpC = 0.0; // for temperature sensor Celsius
float tmpF = 0.0; // for temperature sensor Fahrenheit
float hum = 0.0; // for humidity sensor
//-----------------------------------------------------------------------------------------------------------------------------
void setup() {
M5.begin();
Wire.begin();
M5.lcd.setBrightness(0);
Serial.begin(115200);
pinMode(pinSelectSD, OUTPUT);
// an additional sensorPanel between topPanel and infoPanel is visible if room sensor is found
if (sht30.get() == 0) {
sensorPanel = 16;
} else (sensorPanel = 0);
// Setup the SD-Card
delay(200);
Serial.println();
Serial.println ("POWER ON DEVICE");
Serial.println();
Serial.println ("accessing SD-Card..");
if (!SD.begin(pinSelectSD)) {
Serial.println("SD-Card access failed !");
Serial.println("is card inserted ?");
Serial.println("supported: FAT&FAT32 only");
}
Serial.println ("successfully..");
// spiffs filesystem for pictures or maybe sound data
if (!SPIFFS.begin(true)) {
Serial.println("SPIFFS Mount Failed");
return;
}
// setting alternative WiFi2-settings
if (digitalRead(BUTTON_C_PIN) == 0) {
alt_hotspot = true;
}
// for optional M5 Stack SD-Menu-Loader
if (digitalRead(BUTTON_A_PIN) == 0) {
Serial.println("Will Load menu binary");
updateFromFS(SD);
ESP.restart();
}
M5.update();
// startup with splashscreen on LCD Display and start up RGB LCD-pixel-bar (Neopixel)
M5.Lcd.drawPngFile(SPIFFS, "/m5_logo_dark.png", 0, 0);
for (int i = 0; i < 22 ; i++) {
Brightness_value += 1;
M5.lcd.setBrightness(Brightness_value);
delay(45); // end of fading-in Lcd brightness
} M5.Lcd.fillScreen(TFT_BLACK);
LEDbar.begin();
LEDbar.setBrightness(35); // Set LED BRIGHTNESS to about 1/5 (max = 255)
LEDbar.clear();
colorWipe(LEDbar.Color( 0, 255, 0), 30); // Green // fill LEDbar in various colors...(delay in ms)
LEDbar.clear();
rainbow_effect(3); // Rainbow cycle along the LEDbar..(delay in ms)
LEDbar.clear();
LEDbar.show(); // update LED status
M5.Lcd.setTextDatum(MC_DATUM);
M5.Lcd.setTextSize(1); M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.setFreeFont(FSS12);
M5.Lcd.setTextWrap(false);
// update settings if SD config file is found
updateSDSettings();
M5.lcd.setBrightness(Brightness_value);
yield();
// Setting Power: see for details: https://github.com/m5stack/m5-docs/blob/master/docs/en/api/power.md
if (!M5.Power.canControl()) M5.Lcd.printf("IP5306 is not i2c version\n");
M5.Power.setPowerBtnEn(true); //allow red power Button
M5.Power.setPowerBoostSet(true); //one press on red turns on/off device
M5.Power.setPowerVin(false); //no reset when usb calbe is plugged in
// Connecting to WiFi:
M5.Lcd.print("\n\nConnecting to ");
if (alt_hotspot == false) {
M5.Lcd.println(ssid);
WiFi.begin(ssid.c_str(), password.c_str());
}
else {
M5.Lcd.println(ssid2);
WiFi.begin(ssid2.c_str(), password2.c_str());
}
while (WiFi.status() != WL_CONNECTED) {
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_RED); //busy light red
M5.Lcd.setTextWrap(true);
M5.Lcd.print(".");
err_count ++;
// Power Off Button (ButtonC long press) - needed because on usb power, depending on the type of battery bottom you maybe cant turn off with red Button as usual
if (M5.BtnC.pressedFor(1333)) {
M5.Lcd.drawPngFile(SPIFFS, "/m5_logo_dark.png", 0 , 0);
delay(500);
for (int i = Brightness_value; i > 0 ; i--) { // dimm LCD slowly before shutdown
Brightness_value -= 1;
M5.lcd.setBrightness(Brightness_value);
delay(50);
}
M5.Lcd.fillScreen(TFT_BLACK);
delay(500);
M5.Power.powerOFF();
}
if (err_count > 288) { // if 10 minutes no wifi -> power off device !
M5.Lcd.drawPngFile(SPIFFS, "/m5_logo_dark.png", 0 , 0);
delay(1000);
M5.Lcd.fillScreen(TFT_BLACK);
delay(1000);
M5.Power.powerOFF(); // shut down
}
else if (err_count > 240) { // if 2 minutes no wifi error persists reduce
LEDbar.clear();
colorWipe(LEDbar.Color(255, 255, 0), 30); // flash yellow twice with LED bar every 10s
LEDbar.show(); // update LED status
LEDbar.clear();
LEDbar.show(); // update LED status
delay(100);
colorWipe(LEDbar.Color(255, 255, 0), 30);
LEDbar.show(); // update LED status
LEDbar.clear();
LEDbar.show(); // update LED status
delay(10000); // the reconnect interval from 0.5s to 10s
M5.lcd.setBrightness(1); // and lower the LCD brighness to lowest value (1)
} else {
delay(500);
}
}
showWifiStrength();
err_count = 0;
M5.lcd.setBrightness(Brightness_value);
M5.Lcd.println("\nWiFi connected");
M5.Lcd.setTextWrap(false);
// startup promt to lcd:
M5.Lcd.println("getting time");
M5.Lcd.println("drawing chart");
if (!SD.begin(pinSelectSD)) {
M5.Lcd.println();
M5.Lcd.println("no SD-Card used");
}
else {
M5.Lcd.println();
M5.Lcd.println("..reading SD-Card");
}
// Setting time:
configTime(0, 0, "pool.ntp.org", "time.nist.gov");
while (true) {
time_t now = time(nullptr);
if (now && year(now) > 2017) break;
}
delay(400);
M5.Lcd.fillScreen(TFT_BLACK);
yield();
showWifiStrength();
printTime(); //routine to print the time on lcd screen, adjusted to your local timzone
// load battery meter and draw all candles, and sensor values
showBatteryLevel();
while (!requestRestApi()) {}
drawCandles();
drawSensorValues();
// Connecting to WS:
webSocket.beginSSL(wsApiHost, wsApiPort, getWsApiUrl());
webSocket.onEvent(webSocketEvent);
webSocket.setReconnectInterval(1000);
}
// ***************************************BEGIN LOOP**************************************************
void loop()
{
currentMs = millis();
buttonActions(); // check for Buttons
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_BLACK); //reset busy light
if (currency_cycling) {
if (currentMs - currency_cycling_counter >= (4 + myCyclingIntervall) * 1000) { //change every x (user defined) seconds, adds +4s to intervall the long loading time
currency_cycling_counter = currentMs;
cycling_change_triggered = true;
}
}
if (currentMs - lastPrintTime >= 35000 && second(time(nullptr)) < 25) { // draw new date and candles regularly
lastPrintTime = currentMs;
printTime();
drawSensorValues();
multi_level = 0;
webSocket.disconnect();
webSocket.beginSSL(wsApiHost, wsApiPort, getWsApiUrl());
while (!requestRestApi()) {}
drawCandles();
showBatteryLevel();
}
webSocket.loop();
M5.update(); // update Button checks
}
// ****************************************END LOOP***************************************************
void printTime() {
M5.Lcd.fillRect(0, 0, 320, topPanel - 1, TFT_BLACK); M5.Lcd.setFreeFont(FSSB12);
M5.Lcd.setCursor(1, 19); M5.Lcd.setTextSize(1); M5.Lcd.setTextColor(strname_color);
M5.Lcd.print(strname_currency);
M5.Lcd.setFreeFont(FMB12); M5.Lcd.setCursor(111, 14); M5.Lcd.setTextColor(TFT_LIGHTGREY);
TimeChangeRule *tcr;
if (myTimeZone == 0) {
time_t now = myTZ0.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 1) {
time_t now = myTZ1.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 2) {
time_t now = myTZ2.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 3) {
time_t now = myTZ3.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 4) {
time_t now = myTZ4.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 5) {
time_t now = myTZ5.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 6) {
time_t now = myTZ6.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 7) {
time_t now = myTZ7.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else if (myTimeZone == 99) {
time_t now = myTZ8.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
} else { // default: MyTZ4 english
time_t now = myTZ4.toLocal(time(nullptr), &tcr);
M5.Lcd.printf("%s %2d.%s %02d:%02d", weekDay_MyLang[weekday(now)], day(now), monthName_MyLang[month(now)], hour(now), minute(now));
}
}
String getRestApiUrl() {
return "/api/v3/klines?symbol=" + strname_api + "&interval=" + String(candlesTimeframes[current_Timeframe]) +
"&limit=" + String(candlesLimit);
}
String getWsApiUrl() {
return "/ws/" + strname_ws + "@kline_" + String(candlesTimeframes[current_Timeframe]);
}
void webSocketEvent(WStype_t type, uint8_t * payload, size_t length) {
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_DARKGREY); //busy light darkgrey
showWifiStrength();
switch (type) {
case WStype_DISCONNECTED:
wsFails++;
if (wsFails > 3) error("WS disconnected!");
ws_error = true;
break;
case WStype_CONNECTED:
break;
case WStype_TEXT:
wsFails = 0;
DeserializationError err = deserializeJson(jsonDoc, payload);
if (err) {
error(err.c_str());
ws_error = true;
break;
}
openTime = jsonDoc["k"]["t"];
openTime = openTime / 1000; // opentime is sent in milliseconds
if (openTime == 0) {
error("empty WS object");
break;
}
candleIsNew = openTime > lastCandleOpenTime;
if (candleIsNew) {
lastCandleOpenTime = openTime;
for (int i = 1; i < candlesLimit; i++) {
candles[i - 1] = candles[i];
}
}
candles[candlesLimit - 1].o = jsonDoc["k"]["o"];
candles[candlesLimit - 1].h = jsonDoc["k"]["h"];
candles[candlesLimit - 1].l = jsonDoc["k"]["l"];
candles[candlesLimit - 1].c = jsonDoc["k"]["c"];
candles[candlesLimit - 1].v = jsonDoc["k"]["v"];
// If we get new low/high we need to redraw all candles, otherwise just last one:
if (candleIsNew ||
candles[candlesLimit - 1].l < pl || candles[candlesLimit - 1].h > ph ||
candles[candlesLimit - 1].v < vl || candles[candlesLimit - 1].v > vh)
{
drawCandles();
} else {
drawPrice();
drawCandle(candlesLimit - 1);
}
break;
}
}
bool requestRestApi() {
WiFiClientSecure client;
if (!client.connect(restApiHost, 443)) {
error("\n\nWiFi connection lost!");
wifi_error = true;
return false;
}
client.print("GET " + getRestApiUrl() + " HTTP/1.1\r\n" +
"Host: " + restApiHost + "\r\n" +
"Accept: application/json\r\n" +
"User-Agent: BuildFailureDetectorESP8266\r\n" +
"Connection: close\r\n\r\n");
while (client.connected()) {
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_YELLOW); //busy light yellow
String line = client.readStringUntil('\r');
line.trim();
if (line.startsWith("[") && line.endsWith("]")) {
DeserializationError err = deserializeJson(jsonDoc, line);
if (err) {
error(err.c_str());
ws_error = true;
return false;
} else if (jsonDoc.as<JsonArray>().size() == 0) {
error("Empty JSON array");
ws_error = true;
return false;
}
// Data format: [[TS, OPEN, HIGH, LOW, CLOSE, VOL, ...], ...]
JsonArray _candles = jsonDoc.as<JsonArray>() ;
for (int i = 0; i < candlesLimit; i++) {
candles[i].o = _candles[i][1];
candles[i].h = _candles[i][2];
candles[i].l = _candles[i][3];
candles[i].c = _candles[i][4];
candles[i].v = _candles[i][5];
}
// if pair is not listed long enought to draw all requested candles take only the last valid values to not get confused with zeros
empty_candles = 0;
for (int i = 0; i < candlesLimit; i++) {
if (candles[i].c == 0) {
empty_candles++;
candles[i].o = candles[i - 1].o;
candles[i].h = candles[i - 1].h;
candles[i].l = candles[i - 1].l;
candles[i].c = candles[i - 1].c;
candles[i].v = candles[i - 1].v;
openTime = last_correct_openTime;
} else {
last_correct_openTime = openTime;
}
}
lastCandleOpenTime = _candles[candlesLimit - 1 - empty_candles][0];
lastCandleOpenTime = lastCandleOpenTime / 1000; // because time is sent in milliseconds !
return true;
}
}
ws_error = true;
error("no JSON in response");
}
// format price:
void formatPrice() {
for (int i = 0; i < candlesLimit; i++) {
if (multi_level == 0) {
if (candles[i].l < 0.001) {
multi = 100000000; // if old price is under 0.001$ use exponent format X.XXe-XX
multi_level = 3;
}
}
if (multi_level < 3) {
if (candles[i].l < 1) {
multi = 100000; // multiply old price if price is under 1$ for higher resolution
multi_level = 2;
}
}
if (multi_level < 2) {
if (candles[i].l < 1000) {
multi = 100; // multiply old price if price is under 1000$ for higher resolution
multi_level = 1;
}
}
if (multi_level < 1) {
if (candles[i].l > 1000) {
multi = 1; // if old price is over 1000$? change nothing
multi_level = 0;
}
}
}
}
void drawCandles() {
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_MAGENTA); //busy light magenta
// Find highs and lows
ph = candles[0 + empty_candles].h;
pl = candles[0 + empty_candles].l;
vh = candles[0 + empty_candles].v;
vl = candles[0 + empty_candles].v;
for (int i = 0; i < candlesLimit; i++) {
if (candles[i].h > ph) ph = candles[i].h;
if (candles[i].l < pl) pl = candles[i].l;
if (candles[i].v > vh) vh = candles[i].v;
if (candles[i].v < vl) vl = candles[i].v;
}
// format Price for candle drawing if over 1000, under 1000, under 1, or under 0.001
formatPrice();
// Draw bottom panel with price, high and low:
drawPrice();
// Draw empty candle:
for (int i = 0; i < empty_candles; i++) {
drawEmptyCandle(i);
}
// Draw candles:
for (int i = 0; i < candlesLimit - empty_candles; i++) {
drawCandle(i);
}
M5.Lcd.fillCircle(101, topPanel + ((infoPanel + sensorPanel) / 2 - 7), 4, TFT_DARKGREY); // reset magenta busy light;
}
// Remap dollars data to pixels
int getY(float val, float minVal, float maxVal) {
// function copied from of 'map' math function (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min
return round((val - minVal) * (topPanel + infoPanel + sensorPanel + 2 - 162 - bottomPanel) / (maxVal - minVal) + 235 - bottomPanel);
}
void drawEmptyCandle(int i) {
center = w / 2.0;
center += ((i) * w);
M5.Lcd.fillRect((center - w) + 5, topPanel + infoPanel + sensorPanel, ceil(w), 240 - (topPanel + infoPanel + sensorPanel + bottomPanel), TFT_BLACK);
}
// Data format: [[TS, OPEN, HIGH, LOW, CLOSE, VOL, ...]]
void drawCandle(int i) {
int oy = getY(candles[i].o * multi, pl * multi, ph * multi);
int hy = getY(candles[i].h * multi, pl * multi, ph * multi);
int ly = getY(candles[i].l * multi, pl * multi, ph * multi);
int cy = getY(candles[i].c * multi, pl * multi, ph * multi);
int vy = getY(candles[i].v, vl , vh);
int prevVY = vy;
if (i != 0) {
prevVY = getY(candles[i - 1].v, vl, vh);
}
center = w / 2.0;
center += ((i + empty_candles) * w);
uint32_t color = cy < oy ? DARKERGREEN : MYRED;
// Background:
M5.Lcd.fillRect((center - w) + 5, topPanel + infoPanel + sensorPanel, ceil(w), 240 - (topPanel + infoPanel + sensorPanel + bottomPanel), TFT_BLACK);
// Volume line:
M5.Lcd.drawLine((center - w) + 5, prevVY, center - 5, vy, volColor);
M5.Lcd.drawLine(center - 4, vy, center + 4, vy, volColor);
if (i == candlesLimit - 1) {
M5.Lcd.fillRect(center + 5, topPanel + infoPanel + sensorPanel, w / 2, 240 - (topPanel + infoPanel + bottomPanel), TFT_BLACK);
M5.Lcd.drawLine(center + 5, vy, 320, vy, volColor);
}
// Head and tail:
M5.Lcd.drawLine(center, hy, center, ly, color);
// Candle body:
int bodyHeight = abs(cy - oy);
if (bodyHeight < 1) bodyHeight = 1; // show at least 1px, if candle body was not formed yet
M5.Lcd.fillRect(center - 3, min(oy, cy), 7, bodyHeight, color);
// show actual price as small line in the last candle
if (i + empty_candles == candlesLimit - 1) M5.Lcd.drawLine(center - 4, cy, center + 4, cy, TFT_WHITE);
// calculate PrizeChanings for the infoPanel
PriceChangings();
}
// show remaining battery power (0-100) and draw the matching battery status picture
void showBatteryLevel() {
uint8_t battery = M5.Power.getBatteryLevel();
M5.Lcd.fillRect(34, topPanel + 2, 60, infoPanel + sensorPanel, TFT_BLACK);
if (M5.Power.isCharging())M5.Lcd.drawPngFile(SPIFFS, "/batt_gre.png", 34, topPanel + 2); // show a green battery icon
else M5.Lcd.drawPngFile(SPIFFS, "/batt_gry.png", 34, topPanel + 2); // show a grey battery icon
if (battery == -1) M5.Lcd.drawPngFile(SPIFFS, "/batt_nc.png", 34, topPanel + 2); // 60 x 60 px
else if (battery < 12) M5.Lcd.drawPngFile(SPIFFS, "/batt0.png", 34, topPanel + 2);
else if (battery < 32) M5.Lcd.drawPngFile(SPIFFS, "/batt25.png", 34, topPanel + 2);
else if (battery < 64) M5.Lcd.drawPngFile(SPIFFS, "/batt50.png", 34, topPanel + 2);
else if (battery < 78) M5.Lcd.drawPngFile(SPIFFS, "/batt75.png", 34, topPanel + 2);
else if (battery > 90) M5.Lcd.drawPngFile(SPIFFS, "/batt100.png", 34, topPanel + 2);
}
void drawPrice() {
float price = (candles[candlesLimit - 1].c);
float oy_var2 (candles[candlesLimit - 1].o);
if (lastPrice != price) {
M5.Lcd.fillRect(0, 240 - bottomPanel, 202, bottomPanel, TFT_BLACK); M5.Lcd.setTextSize(1);
M5.Lcd.setFreeFont(FSSB24); M5.Lcd.setCursor(0, 273 - bottomPanel);
M5.Lcd.setTextColor(price > oy_var2 ? DARKERGREEN : MYRED);
lastPrice = price;
if (multi_level == 1) {
M5.Lcd.printf("%.4f", price);
}
else if (multi_level == 2) {
M5.Lcd.printf("%.6f", price);
}
else if (multi_level == 3) {
M5.Lcd.printf("%.2e", price);
} else {
M5.Lcd.printf("%.2f", price);
}
}
if (ph != lastHigh) {
M5.Lcd.fillRect(202, 240 - bottomPanel, 99, bottomPanel / 2, TFT_BLACK); M5.Lcd.setTextColor(DARKERGREEN);
M5.Lcd.setFreeFont(FSSB9); M5.Lcd.setCursor(202, 254 - bottomPanel); M5.Lcd.setTextSize(1);
lastHigh = ph;
if (multi == 100) {
M5.Lcd.printf("H %.4f", ph);
}
else if (multi == 100000) {
M5.Lcd.printf("H %.6f", ph);
}
else if (multi == 100000000) {
M5.Lcd.printf("H %.2e", ph);
} else {
M5.Lcd.printf("H %.2f", ph);
}
}
if (pl != lastLow) {
M5.Lcd.fillRect(202, 240 - bottomPanel / 2, 99, bottomPanel / 2, TFT_BLACK); M5.Lcd.setTextColor(MYRED);
M5.Lcd.setFreeFont(FSSB9); M5.Lcd.setCursor(202, 256 - floor(bottomPanel / 2)); M5.Lcd.setTextSize(1);
lastLow = pl;
if (multi == 100) {
M5.Lcd.printf("L %.4f", pl);
}
else if (multi == 100000) {
M5.Lcd.printf("L %.6f", pl);
}
else if (multi == 100000000) {
M5.Lcd.printf("L %.2e", pl);
} else {
M5.Lcd.printf("L %.2f", pl);
}
}
if (lastTimeframe != current_Timeframe) {
lastTimeframe = current_Timeframe;
String timeframe = candlesTimeframes[current_Timeframe];
M5.Lcd.fillRect(301, 240 - bottomPanel, 19, bottomPanel, TFT_BLACK); M5.Lcd.setFreeFont(FSSB9);
M5.Lcd.setTextSize(1); M5.Lcd.setTextColor(TFT_CYAN); M5.Lcd.setCursor(301, 254 - bottomPanel);
M5.Lcd.print(timeframe[0]);
M5.Lcd.setCursor(301, 255 - floor(bottomPanel / 2));
M5.Lcd.print(timeframe[1]);
}
}
// price changings for info panel: changings relative to the 24th past candles close price in percent (with exceptions):
void PriceChangings() {
if (!timeframe_really_changed) {
M5.Lcd.fillRect(108, topPanel + sensorPanel , 212, infoPanel, TFT_BLACK);
M5.Lcd.setFreeFont(FM9); M5.Lcd.setCursor(108, topPanel + sensorPanel + infoPanel - 3); M5.Lcd.setTextSize(1);
if (current_Timeframe == 0) { //1m
if (candles[candlesLimit - 1].c > candles[candlesLimit - 21].c) {
M5.Lcd.setTextColor(DARKERGREEN);
if (multi_level == 1) {
M5.Lcd.printf("+%.3f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c); //+%.1f shows prefix even if positive with 1 digit after comma
} else if (multi_level == 2) {
M5.Lcd.printf("+%.5f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
} else if (multi_level == 3) {
M5.Lcd.printf("+%.1e", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
} else {
M5.Lcd.printf("+%4.1f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 21].c / (candles[candlesLimit - 1].c - candles[candlesLimit - 21].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":20m");
} else {
M5.Lcd.setTextColor(MYRED);
if (multi_level == 1) {
M5.Lcd.printf("-%.3f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else if (multi_level == 2) {
M5.Lcd.printf("-%.5f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else if (multi_level == 3) {
M5.Lcd.printf("-%.1e", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else {
M5.Lcd.printf("-%4.1f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 21].c / (candles[candlesLimit - 21].c - candles[candlesLimit - 1].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":20m");
}
}
else if (current_Timeframe == 1) { //3m
if (candles[candlesLimit - 1].c > candles[candlesLimit - 21].c) {
M5.Lcd.setTextColor(DARKERGREEN);
if (multi_level == 1) {
M5.Lcd.printf("+%.3f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
} else if (multi_level == 2) {
M5.Lcd.printf("+%.5f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
} else if (multi_level == 3) {
M5.Lcd.printf("+%.1e", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
} else {
M5.Lcd.printf("+%4.1f", candles[candlesLimit - 1].c - candles[candlesLimit - 21].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 21].c / (candles[candlesLimit - 1].c - candles[candlesLimit - 21].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":60m");
} else {
M5.Lcd.setTextColor(MYRED);
if (multi_level == 1) {
M5.Lcd.printf("-%.3f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else if (multi_level == 2) {
M5.Lcd.printf("-%.5f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else if (multi_level == 3) {
M5.Lcd.printf("-%.1e", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
} else {
M5.Lcd.printf("-%4.1f", candles[candlesLimit - 21].c - candles[candlesLimit - 1].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 21].c / (candles[candlesLimit - 21].c - candles[candlesLimit - 1].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":60m");
}
}
else if (current_Timeframe == 2) { //5m
if (candles[candlesLimit - 1].c > candles[candlesLimit - 24].c) {
M5.Lcd.setTextColor(DARKERGREEN);
if (multi_level == 1) {
M5.Lcd.printf("+%.3f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else if (multi_level == 2) {
M5.Lcd.printf("+%.5f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else if (multi_level == 3) {
M5.Lcd.printf("+%.1e", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else {
M5.Lcd.printf("+%4.1f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 24].c / (candles[candlesLimit - 1].c - candles[candlesLimit - 24].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":2h");
} else {
M5.Lcd.setTextColor(MYRED);
if (multi_level == 1) {
M5.Lcd.printf("-%.3f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else if (multi_level == 2) {
M5.Lcd.printf("-%.5f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else if (multi_level == 3) {
M5.Lcd.printf("-%.1e", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else {
M5.Lcd.printf("-%4.1f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 24].c / (candles[candlesLimit - 24].c - candles[candlesLimit - 1].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":2h");
}
}
else if (current_Timeframe == 3) { //15m
if (candles[candlesLimit - 1].c > candles[candlesLimit - 24].c) {
M5.Lcd.setTextColor(DARKERGREEN);
if (multi_level == 1) {
M5.Lcd.printf("+%.3f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else if (multi_level == 2) {
M5.Lcd.printf("+%.5f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else if (multi_level == 3) {
M5.Lcd.printf("+%.1e", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
} else {
M5.Lcd.printf("+%4.1f", candles[candlesLimit - 1].c - candles[candlesLimit - 24].c);
}
M5.Lcd.printf("(%4.1f", (1 / (candles[candlesLimit - 24].c / (candles[candlesLimit - 1].c - candles[candlesLimit - 24].c)) * 100));
M5.Lcd.print("%)");
M5.Lcd.setTextColor(TFT_WHITE);
M5.Lcd.print(":6h");
} else {
M5.Lcd.setTextColor(MYRED);
if (multi_level == 1) {
M5.Lcd.printf("-%.3f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else if (multi_level == 2) {
M5.Lcd.printf("-%.5f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else if (multi_level == 3) {
M5.Lcd.printf("-%.1e", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
} else {
M5.Lcd.printf("-%4.1f", candles[candlesLimit - 24].c - candles[candlesLimit - 1].c);
}