-
Notifications
You must be signed in to change notification settings - Fork 18
/
stonky.c
3310 lines (3036 loc) · 119 KB
/
stonky.c
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
/* Copyright (c) 2021, Salvatore Sanfilippo <antirez at gmail dot com>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of Redis nor the names of its contributors may be used
* to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
/* Adding these for portablity */
#define _BSD_SOURCE
#if defined(__linux__)
#define _GNU_SOURCE
#define _DEFAULT_SOURCE
#endif
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <stdlib.h>
#include <stdarg.h>
#include <pthread.h>
#include <ctype.h>
#include <unistd.h>
#include <math.h>
#include <curl/curl.h>
#include <sqlite3.h>
#include "sds.h"
#include "cJSON.h"
#include "canvas.h"
/* Note that C_OK is 1 and C_ERR is 0, so if functions return success
* it is possible to do things like: if (function()) {... do on success ...} */
#define C_OK 1
#define C_ERR 0
#define UNUSED(V) ((void) V)
/* Flags potentially used for multiple functions. */
#define STONKY_NOFLAGS 0 /* No special flags. */
#define STONKY_SHORT (1<<0) /* Use short form for some output. */
#define STONKY_VERY_SHORT (1<<1) /* Use even less space. */
int AutoListsMode = 1; /* Scan to populate auto lists. */
int DebugMode = 0; /* If true enables debugging info (--debug option).
This gets incremented by one at every successive
--debug, so that very verbose stuff are only
enabled with a few --debug calls. */
int VerboseMode = 0; /* If true enables verbose info (--verbose && --debug) */
char *DbFile = "./stonky.sqlite"; /* Change with --dbfile. */
char *AdminPass = NULL; /* Admin password. */
_Thread_local sqlite3 *DbHandle = NULL; /* Per-thread sqlite handle. */
sds BotApiKey = NULL; /* Telegram API key for the bot. */
sds *Symbols; /* Global list of symbols loaded from marketdata/symbols.txt */
int NumSymbols; /* Number of elements in Symbols. */
sds *Fortune; /* Stock market famous quotes. */
int NumFortune; /* Number of elements in Fortune. */
_Atomic double EURUSD = 0; /* EURUSD change, refreshed in background. */
int ScanPause = 1000000; /* In microseconds. Default 1 second. */
int CacheYahoo = 0; /* Perform Yahoo queries caching. */
int NoEvictMode = 0; /* Don't perform cache eviction nor care about
TTL of things on the cache. This is useful
in order to just use the local DB for scanning. */
_Atomic int64_t ActiveChannels[64]; /* Channels we received a message from. */
_Atomic int64_t ActiveChannelsLast[64]; /* Timestamp of last msg. */
int ActiveChannelsCount = 0; /* Number of active channels. */
/* Global stats. Sometimes we access such stats from threads without caring
* about race conditions, since they in practice are very unlikely to happen
* in most archs with this data types, and even so we don't care.
* This stuff is reported by the bot when the $$ info command is used. */
struct {
time_t start_time; /* Unix time the bot was started. */
uint64_t queries; /* Number of queries received. */
uint64_t scanned; /* Number of stocks scanned by the BG thread. */
} botStats;
int kvSetLen(const char *key, const char *value, size_t vlen, int64_t expire);
int kvSet(const char *key, const char *value, int64_t expire);
sds kvGet(const char *key);
sds genBigMoversMessage(int count);
/* ============================================================================
* Allocator wrapper: we want to exit on OOM instead of trying to recover.
* ==========================================================================*/
void *xmalloc(size_t size) {
void *p = malloc(size);
if (p == NULL) {
printf("Out of memory: malloc(%zu)", size);
exit(1);
}
return p;
}
void *xrealloc(void *ptr, size_t size) {
void *p = realloc(ptr,size);
if (p == NULL) {
printf("Out of memory: realloc(%zu)", size);
exit(1);
}
return p;
}
void xfree(void *ptr) {
free(ptr);
}
/* ============================================================================
* Utility funcitons.
* ==========================================================================*/
/* Glob-style pattern matching. Return 1 on match, 0 otherwise. */
int strmatch(const char *pattern, int patternLen,
const char *string, int stringLen, int nocase)
{
while(patternLen && stringLen) {
switch(pattern[0]) {
case '*':
while (patternLen && pattern[1] == '*') {
pattern++;
patternLen--;
}
if (patternLen == 1)
return 1; /* match */
while(stringLen) {
if (strmatch(pattern+1, patternLen-1,
string, stringLen, nocase))
return 1; /* match */
string++;
stringLen--;
}
return 0; /* no match */
break;
case '?':
string++;
stringLen--;
break;
case '[':
{
int not, match;
pattern++;
patternLen--;
not = pattern[0] == '^';
if (not) {
pattern++;
patternLen--;
}
match = 0;
while(1) {
if (pattern[0] == '\\' && patternLen >= 2) {
pattern++;
patternLen--;
if (pattern[0] == string[0])
match = 1;
} else if (pattern[0] == ']') {
break;
} else if (patternLen == 0) {
pattern--;
patternLen++;
break;
} else if (patternLen >= 3 && pattern[1] == '-') {
int start = pattern[0];
int end = pattern[2];
int c = string[0];
if (start > end) {
int t = start;
start = end;
end = t;
}
if (nocase) {
start = tolower(start);
end = tolower(end);
c = tolower(c);
}
pattern += 2;
patternLen -= 2;
if (c >= start && c <= end)
match = 1;
} else {
if (!nocase) {
if (pattern[0] == string[0])
match = 1;
} else {
if (tolower((int)pattern[0]) == tolower((int)string[0]))
match = 1;
}
}
pattern++;
patternLen--;
}
if (not)
match = !match;
if (!match)
return 0; /* no match */
string++;
stringLen--;
break;
}
case '\\':
if (patternLen >= 2) {
pattern++;
patternLen--;
}
/* fall through */
default:
if (!nocase) {
if (pattern[0] != string[0])
return 0; /* no match */
} else {
if (tolower((int)pattern[0]) != tolower((int)string[0]))
return 0; /* no match */
}
string++;
stringLen--;
break;
}
pattern++;
patternLen--;
if (stringLen == 0) {
while(*pattern == '*') {
pattern++;
patternLen--;
}
break;
}
}
if (patternLen == 0 && stringLen == 0)
return 1;
return 0;
}
/* Given a stock price change, return an appropriate (LOL) emoji to
* visually represent such change. The returned string is statically
* allocated so the function is thread safe. */
const char *priceChangeToEmoji(double change) {
int emoidx = 0;
static const char *emoset[] = {"⚰️","🔴","🟢","🚀"};
/* Note: ordering of the followign if statements is important. */
if (change < 0) emoidx = 1;
if (change < -8) emoidx = 0;
if (change >= 0) emoidx = 2;
if (change > 8) emoidx = 3;
return emoset[emoidx];
}
/* ============================================================================
* JSON selector implementation: cJSON is a bit too raw...
* ==========================================================================*/
/* You can select things like this:
*
* cJSON *json = cJSON_Parse(myjson_string);
* cJSON *width = cJSON_Select(json,".features.screens[*].width",4);
* cJSON *height = cJSON_Select(json,".features.screens[4].*","height");
* cJSON *price = cJSON_Select(json,".features.screens[4].price_*",
* price_type == EUR ? "eur" : "usd");
*
* You can use a ":<type>" specifier, usually at the end, in order to
* check the type of the final JSON object selected. If the type will not
* match, the function will return NULL. For instance the specifier:
*
* ".foo.bar:s"
*
* Will not return NULL only if the root object has a foo field, that is
* an object with a bat field, that contains a string. This is the full
* list of selectors:
*
* ".field", select the "field" of the current object.
* "[1234]", select the specified index of the current array.
* ":<type>", check if the currently selected type is of the specified type,
* where the type is a single letter that can be:
* "s" for string
* "n" for number
* "a" for array
* "o" for object
* "b" for boolean
* "!" for null
*
* Selectors can be combined, and the special "*" can be used in order to
* fetch array indexes or field names from the arguments:
*
* cJSON *myobj = cJSON_Parse(root,".properties[*].*", index, fieldname);
*/
#define JSEL_INVALID 0
#define JSEL_OBJ 1 /* "." */
#define JSEL_ARRAY 2 /* "[" */
#define JSEL_TYPECHECK 3 /* ":" */
#define JSEL_MAX_TOKEN 256
cJSON *cJSON_Select(cJSON *o, const char *fmt, ...) {
int next = JSEL_INVALID; /* Type of the next selector. */
char token[JSEL_MAX_TOKEN+1]; /* Current token. */
int tlen; /* Current length of the token. */
va_list ap;
va_start(ap,fmt);
const char *p = fmt;
tlen = 0;
while(1) {
/* Our four special chars (plus the end of the string) signal the
* end of the previous token and the start of the next one. */
if (tlen && (*p == '\0' || strchr(".[]:",*p))) {
token[tlen] = '\0';
if (next == JSEL_INVALID) {
goto notfound;
} else if (next == JSEL_ARRAY) {
if (!cJSON_IsArray(o)) goto notfound;
int idx = atoi(token); /* cJSON API index is int. */
if ((o = cJSON_GetArrayItem(o,idx)) == NULL)
goto notfound;
} else if (next == JSEL_OBJ) {
if (!cJSON_IsObject(o)) goto notfound;
if ((o = cJSON_GetObjectItemCaseSensitive(o,token)) == NULL)
goto notfound;
} else if (next == JSEL_TYPECHECK) {
if (token[0] == 's' && !cJSON_IsString(o)) goto notfound;
if (token[0] == 'n' && !cJSON_IsNumber(o)) goto notfound;
if (token[0] == 'o' && !cJSON_IsObject(o)) goto notfound;
if (token[0] == 'a' && !cJSON_IsArray(o)) goto notfound;
if (token[0] == 'b' && !cJSON_IsBool(o)) goto notfound;
if (token[0] == '!' && !cJSON_IsNull(o)) goto notfound;
}
} else if (next != JSEL_INVALID) {
/* Otherwise accumulate characters in the current token, note that
* the above check for JSEL_NEXT_INVALID prevents us from
* accumulating at the start of the fmt string if no token was
* yet selected. */
if (*p != '*') {
token[tlen] = *p++;
tlen++;
if (tlen > JSEL_MAX_TOKEN) goto notfound;
continue;
} else {
/* The "*" character is special: if we are in the context
* of an array, we read an integer from the variable argument
* list, then concatenate it to the current string.
*
* If the context is an object, we read a string pointer
* from the variable argument string and concatenate the
* string to the current token. */
int len;
char buf[64];
char *s;
if (next == JSEL_ARRAY) {
int idx = va_arg(ap,int);
len = snprintf(buf,sizeof(buf),"%d",idx);
s = buf;
} else if (next == JSEL_OBJ) {
s = va_arg(ap,char*);
len = strlen(s);
} else {
goto notfound;
}
/* Common path. */
if (tlen+len > JSEL_MAX_TOKEN) goto notfound;
memcpy(token+tlen,buf,len);
tlen += len;
p++;
continue;
}
}
/* Select the next token type according to its type specifier. */
if (*p == ']') p++; /* Skip closing "]", it's just useless syntax. */
if (*p == '\0') break;
else if (*p == '.') next = JSEL_OBJ;
else if (*p == '[') next = JSEL_ARRAY;
else if (*p == ':') next = JSEL_TYPECHECK;
else goto notfound;
tlen = 0; /* A new token starts. */
p++; /* Token starts at next character. */
}
cleanup:
va_end(ap);
return o;
notfound:
o = NULL;
goto cleanup;
}
/* ============================================================================
* SQLite abstraction
* ==========================================================================*/
#define SQL_MAX_SPEC 32 /* Maximum number of ?... specifiers per query. */
/* The sqlCol and sqlRow structures are used in order to return rows. */
typedef struct sqlCol {
int type;
int64_t i; /* Integer or len of string/blob. */
const char *s; /* String or blob. */
double d; /* Double. */
} sqlCol;
typedef struct sqlRow {
sqlite3_stmt *stmt; /* Handle for this query. */
int cols; /* Number of columns. */
sqlCol *col; /* Array of columns. Note that the first time this
will be NULL, so we now we don't need to call
sqlite3_step() since it was called by the
query function. */
} sqlRow;
/* This is the low level function that we use to model all the higher level
* functions. It is based on the idea that DbHandle is a per-thread SQLite
* handle already available: the rest of the code will ensure this.
*
* Queries can contain ?s ?b ?i and ?d special specifiers that are bound to
* the SQL query, and must be present later as additional arguments after
* the 'sql' argument.
*
* ?s -- TEXT field: char* argument.
* ?b -- Blob field: char* argument followed by size_t argument.
* ?i -- INT field : int64_t argument.
* ?d -- REAL field: double argument.
*
* The function returns the return code of the last SQLite query that
* failed on error. On success it returns what sqlite3_step() returns.
* If the function returns SQLITE_ROW, that is, if the query is
* returning data, the function returns, by reference, a sqlRow object
* that the caller can use to get the current and next rows.
*
* The user needs to later free this sqlRow object with sqlEnd() (but this
* is done automatically if all the rows are consumed with sqlNextRow()).
* Note that is valid to call sqlEnd() even if the query didn't return
* SQLITE_ROW, since in such case row->stmt is set to NULL.
*/
int sqlGenericQuery(sqlRow *row, const char *sql, va_list ap) {
int rc = SQLITE_ERROR;
sqlite3_stmt *stmt = NULL;
sds query = sdsempty();
if (row) row->stmt = NULL; /* On error sqlNextRow() should return false. */
/* We need to build the query, substituting the following three
* classes of patterns with just "?", remembering the order and
* type, and later using the sql3 binding API in order to prepare
* the query:
*
* ?s string
* ?b blob (varargs must have char ptr and size_t len)
* ?i int64_t
* ?d double
*/
char spec[SQL_MAX_SPEC];
int numspec = 0;
const char *p = sql;
while(p[0]) {
if (p[0] == '?') {
if (p[1] == 's' || p[1] == 'i' || p[1] == 'd' || p[1] == 'b') {
if (numspec == SQL_MAX_SPEC) goto error;
spec[numspec++] = p[1];
} else {
goto error;
}
query = sdscatlen(query,"?",1);
p++; /* Skip the specifier. */
} else {
query = sdscatlen(query,p,1);
}
p++;
}
/* Prepare the query and bind the query arguments. */
rc = sqlite3_prepare_v2(DbHandle,query,-1,&stmt,NULL);
if (rc != SQLITE_OK) {
if (VerboseMode) printf("%p: Query error: %s: %s\n",
(void*)DbHandle,
query,
sqlite3_errmsg(DbHandle));
goto error;
}
for (int j = 0; j < numspec; j++) {
switch(spec[j]) {
case 'b': {
char *blobptr = va_arg(ap,char*);
size_t bloblen = va_arg(ap,size_t);
rc = sqlite3_bind_blob64(stmt,j+1,blobptr,bloblen,NULL);
}
break;
case 's': rc = sqlite3_bind_text(stmt,j+1,va_arg(ap,char*),-1,NULL);
break;
case 'i': rc = sqlite3_bind_int64(stmt,j+1,va_arg(ap,int64_t));
break;
case 'd': rc = sqlite3_bind_double(stmt,j+1,va_arg(ap,double));
break;
}
if (rc != SQLITE_OK) goto error;
}
/* Execute. */
rc = sqlite3_step(stmt);
if (rc == SQLITE_ROW) {
if (row) {
row->stmt = stmt;
row->cols = 0;
row->col = NULL;
stmt = NULL; /* Don't free it on cleanup. */
}
}
error:
if (stmt) sqlite3_finalize(stmt);
sdsfree(query);
return rc;
}
/* This function should be called only if you don't get all the rows
* till the end. It is safe to call anyway. */
void sqlEnd(sqlRow *row) {
if (row->stmt == NULL) return;
xfree(row->col);
sqlite3_finalize(row->stmt);
row->col = NULL;
row->stmt = NULL;
}
/* After sqlGenericQuery() returns SQLITE_ROW, you can call this function
* with the 'row' object pointer in order to get the rows composing the
* result set. It returns 1 if the next row is available, otherwise 0
* is returned (and the row object is freed). If you stop the iteration
* before all the elements are used, you need to call sqlEnd(). */
int sqlNextRow(sqlRow *row) {
if (row->stmt == NULL) return 0;
if (row->col != NULL) {
if (sqlite3_step(row->stmt) != SQLITE_ROW) {
sqlEnd(row);
return 0;
}
}
xfree(row->col);
row->cols = sqlite3_data_count(row->stmt);
row->col = xmalloc(row->cols*sizeof(sqlCol));
for (int j = 0; j < row->cols; j++) {
row->col[j].type = sqlite3_column_type(row->stmt,j);
if (row->col[j].type == SQLITE_INTEGER) {
row->col[j].i = sqlite3_column_int64(row->stmt,j);
} else if (row->col[j].type == SQLITE_FLOAT) {
row->col[j].d = sqlite3_column_double(row->stmt,j);
} else if (row->col[j].type == SQLITE_TEXT) {
row->col[j].s = (char*)sqlite3_column_text(row->stmt,j);
row->col[j].i = sqlite3_column_bytes(row->stmt,j);
} else if (row->col[j].type == SQLITE_BLOB) {
row->col[j].s = sqlite3_column_blob(row->stmt,j);
row->col[j].i = sqlite3_column_bytes(row->stmt,j);
} else {
/* SQLITE_NULL. */
row->col[j].s = NULL;
row->col[j].i = 0;
row->col[j].d = 0;
}
}
return 1;
}
/* Wrapper for sqlGenericQuery() returning the last inserted ID or 0
* on error. */
int sqlInsert(const char *sql, ...) {
int64_t lastid = 0;
va_list ap;
va_start(ap,sql);
int rc = sqlGenericQuery(NULL,sql,ap);
if (rc == SQLITE_DONE) lastid = sqlite3_last_insert_rowid(DbHandle);
va_end(ap);
return lastid;
}
/* Wrapper for sqlGenericQuery() returning 1 if the query resulted in
* SQLITE_DONE, otherwise zero. This is good for UPDATE and DELETE
* statements. */
int sqlQuery(const char *sql, ...) {
int64_t retval = 0;
va_list ap;
va_start(ap,sql);
int rc = sqlGenericQuery(NULL,sql,ap);
retval = (rc == SQLITE_DONE);
va_end(ap);
return retval;
}
/* Wrapper for sqlGenericQuery() using varialbe number of args.
* This is what you want when doing SELECT queries. */
int sqlSelect(sqlRow *row, const char *sql, ...) {
va_list ap;
va_start(ap,sql);
int rc = sqlGenericQuery(row,sql,ap);
va_end(ap);
return rc;
}
/* Wrapper for sqlGenericQuery() using variable number of args.
* This is what you want when doing SELECT queries that return a
* single row. This function will care to also call sqlNextRow() for
* you in case the return value is SQLITE_ROW. */
int sqlSelectOneRow(sqlRow *row, const char *sql, ...) {
va_list ap;
va_start(ap,sql);
int rc = sqlGenericQuery(row,sql,ap);
if (rc == SQLITE_ROW) sqlNextRow(row);
va_end(ap);
return rc;
}
/* Wrapper for sqlGenericQuery() to do a SELECT and return directly
* the integer of the first row, or zero on error. */
int64_t sqlSelectInt(const char *sql, ...) {
sqlRow row;
int64_t i = 0;
va_list ap;
va_start(ap,sql);
int rc = sqlGenericQuery(&row,sql,ap);
if (rc == SQLITE_ROW) {
sqlNextRow(&row);
i = row.col[0].i;
sqlEnd(&row);
}
va_end(ap);
return i;
}
/* ============================================================================
* HTTP interface abstraction
* ==========================================================================*/
/* The callback concatenating data arriving from CURL http requests into
* a target SDS string. */
size_t makeHttpCallWriter(char *ptr, size_t size, size_t nmemb, void *userdata)
{
UNUSED(size);
sds *body = userdata;
*body = sdscatlen(*body,ptr,nmemb);
return nmemb;
}
/* Request the specified URL in a blocking way, returns the content (or
* error string) as an SDS string. If 'resptr' is not NULL, the integer
* will be set, by referece, to C_OK or C_ERR to indicate error or success.
* The returned SDS string must be freed by the caller both in case of
* error and success. */
sds makeHttpCall(const char *url, int *resptr) {
if (DebugMode) printf("HTTP GET %s\n", url);
CURL* curl;
CURLcode res;
sds body = sdsempty();
curl = curl_easy_init();
if (curl) {
curl_easy_setopt(curl, CURLOPT_URL, url);
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, makeHttpCallWriter);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 1L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 15);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 15);
/* Perform the request, res will get the return code */
res = curl_easy_perform(curl);
if (resptr) *resptr = res == CURLE_OK ? C_OK : C_ERR;
/* Check for errors */
if (res != CURLE_OK) {
const char *errstr = curl_easy_strerror(res);
body = sdscat(body,errstr);
} else {
/* Return C_ERR if the request worked but returned a 500 code. */
long code;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
if (code == 500 && resptr) *resptr = C_ERR;
}
/* always cleanup */
curl_easy_cleanup(curl);
}
return body;
}
/* Like makeHttpCall(), but the list of options will be concatenated to
* the URL as a query string, and URL encoded as needed.
* The option list array should contain optnum*2 strings, alternating
* option names and values. */
sds makeHttpCallOpt(const char *url, int *resptr, char **optlist, int optnum) {
sds fullurl = sdsnew(url);
if (optnum) fullurl = sdscatlen(fullurl,"?",1);
CURL *curl = curl_easy_init();
for (int j = 0; j < optnum; j++) {
if (j > 0) fullurl = sdscatlen(fullurl,"&",1);
fullurl = sdscat(fullurl,optlist[j*2]);
fullurl = sdscatlen(fullurl,"=",1);
char *escaped = curl_easy_escape(curl,
optlist[j*2+1],strlen(optlist[j*2+1]));
fullurl = sdscat(fullurl,escaped);
curl_free(escaped);
}
curl_easy_cleanup(curl);
sds body = makeHttpCall(fullurl,resptr);
sdsfree(fullurl);
return body;
}
/* Make an HTTP request to the Telegram bot API, where 'req' is the specified
* action name. This is a low level API that is used by other bot APIs
* in order to do higher levle work. 'resptr' works the same as in
* makeHttpCall(). */
sds makeBotRequest(const char *action, int *resptr, char **optlist, int numopt)
{
sds url = sdsnew("https://api.telegram.org/bot");
url = sdscat(url,BotApiKey);
url = sdscatlen(url,"/",1);
url = sdscat(url,action);
sds body = makeHttpCallOpt(url,resptr,optlist,numopt);
sdsfree(url);
return body;
}
/* =============================================================================
* Yahoo financial API.
* ===========================================================================*/
/* The following structure is returned by the getYahooData() function,
* and is later freed by freeYahooData(). */
#define YDATA_QUOTE 0 /* Quote data. */
#define YDATA_TS 1 /* Historical time series data. */
#define YDATA_INFO 2 /* Company general information. */
typedef struct ydata {
int type; /* YDATA_QUOTE or YDATA_TS. */
/* === Data filled for YDATA_QUOTE === */
sds symbol; /* Company stock symbol (also available for TS queries). */
sds name; /* Company name. */
float pre; /* Pre market price or zero. */
float post; /* Post market price or zero. */
float reg; /* Regular market price (also available for TS queries). */
time_t pretime;
time_t posttime;
time_t regtime;
float cap; /* Total market cap. */
/* Market percentage change, as a string. */
sds prechange;
sds postchange;
sds regchange;
sds exchange; /* Exchange name. */
int delay; /* Data source delay. */
sds csym; /* Currency symbol. */
/* === Data filled for YDATA_TS === */
int ts_len; /* Number of samples. */
float *ts_data; /* Samples. */
float ts_min; /* Min sample value. */
float ts_max; /* Max sample value. */
/* === Data converted by yahooDataToPriceChanges() === */
int ts_clen; /* Number of converted samples. */
int64_t pdays; /* Days with a profit. */
int64_t ldays; /* Days with a loss. */
double avgp; /* Average profit of days with a profit. */
double avgl; /* Average loss of days with a loss. */
double maxp; /* Max profit in a day. */
double maxl; /* Max loss in a day. */
/* === Data filled for YDATA_INFO === */
sds summary; /* Business description. */
sds country; /* Business country. */
sds industry; /* Business industry. */
int employees; /* Number of employees. */
double lastdiv; /* Last dividend value per share. */
sds exdivdate; /* Next ex-dividend date. */
} ydata;
/* Free the ydata result structure. */
void freeYahooData(ydata *y) {
if (y == NULL) return;
sdsfree(y->symbol);
sdsfree(y->name);
sdsfree(y->prechange);
sdsfree(y->postchange);
sdsfree(y->regchange);
sdsfree(y->csym);
sdsfree(y->exchange);
sdsfree(y->summary);
sdsfree(y->country);
sdsfree(y->industry);
sdsfree(y->exdivdate);
free(y->ts_data);
free(y);
}
/* Perform queries to the Yahoo API: returns NULL on error, or a structure
* representing the obtained data on success. The returned structure should
* be freed calling freeYahooData().
*
* The 'type' argument is the request type: YDATA_QUOTE or YDATA_TS, to obtain
* quote data or time series of historical data.
*
* The 'range' and 'interval' arguments are both strings in the Yahoo API format
* of a single digit followed by a one or two chars, in order to specify a time
* interval. For instance 1s means one second, 6mo six months, and so forth.
* Such arguments are only used for YDATA_TS queries.
*
* The range tells how much backlog of data is requested, while the interval
* tells the granularity of the data. Not all combinations are valid.
*
* Valid ranges are: 1d, 5d, 1mo, 3mo, 6mo, 1y, 2y, 5y, 10y, ytd, max.
*
* Valid intervals are: 1m, 2m, 5m, 15m, 30m, 60m, 90m, 1h, 1d, 5d, 1wk,
* 1mo, 3mo.
*
* Note all range and interval combinations are valid.
*
* The 'ttl' argument is only used when the Stonky --cache option is enabled.
* It is used in order to cache the Yahoo API replies into the local SQLite
* database. This is useful for two reasons: if you are deploying a bot
* that serves an high number of users and don't want to hit the Yahoo
* API limit, or in case you want to test the auto lists (background scanning
* for interesting stocks) doing a full cycle in just a few seconds, especially
* if the --noevict option is also used.
*
* The 'ttl' is specified in seconds, the cached information is retained
* for no more than the specified 'ttl'. If 'ttl' is zero, no caching is
* used for the call. */
ydata *getYahooData(int type, const char *symbol, const char *range, const char *interval, int ttl) {
const char *apihost = "https://query2.finance.yahoo.com";
sds url;
/* Build the query according to the requested data. */
if (type == YDATA_TS) {
url = sdsnew(apihost);
url = sdscat(url,"/v8/finance/chart/");
url = sdscat(url,symbol);
url = sdscatprintf(url,"?range=%s&interval=%s&includePrePost=false",
range,interval);
} else if (type == YDATA_QUOTE || type == YDATA_INFO) {
/* For pricing data we have to abuse the chart API, since Yahoo
* in late 2023 stopped providing a real time API and the
* quoteSummary API no logner works. Not everything is available
* here, but we try to do our best. */
url = sdsnew(apihost);
url = sdscat(url,"/v8/finance/chart/");
url = sdscat(url,symbol);
url = sdscatprintf(url,"?interval=1d");
} else {
return NULL;
}
/* Get data via a blocking HTTP request. We try to perform more than
* a single query since sometimes the Yahoo API will return a 500
* error without any reason, but will work again immediately after. */
int attempt = 0, maxattempts = 5;
int res = C_ERR;
/* Try using the cache if possible. */
sds body = (ttl && CacheYahoo) ? kvGet(url) : NULL;
int cached = body != NULL;
if (body == NULL) {
/* No caching or no cached version found? Fetch it from the
* Yahoo servers. */
while(attempt < maxattempts && res == C_ERR) {
if (attempt > 0) usleep(100000);
sdsfree(body);
body = makeHttpCall(url,&res);
attempt++;
}
} else {
if (DebugMode) printf("Using cached version of %s\n", url);
res = C_OK;
}
/* If we are using caching, and we just fetched a fresh version,
* set it on the cache. */
if (ttl && CacheYahoo && !cached) {
kvSet(url,body,ttl);
}
sdsfree(url);
if (res != C_OK) {
sdsfree(body);
return NULL;
}
/* Setup the empty object. */
ydata *yd = malloc(sizeof(*yd));
memset(yd,0,sizeof(*yd));
yd->type = type;
/* Extract the JSON fields and fills the data object. */
cJSON *json = cJSON_Parse(body);
sdsfree(body);
if (type == YDATA_QUOTE || type == YDATA_INFO) {
cJSON *meta = cJSON_Select(json,".chart.result[0].meta");
cJSON *aux;
if (meta == NULL) goto fmterr;
if ((aux = cJSON_Select(meta,".symbol:s")) != NULL)
yd->symbol = sdsnew(aux->valuestring);
if ((aux = cJSON_Select(meta,".regularMarketPrice:n")) != NULL)
yd->reg = aux->valuedouble;
if ((aux = cJSON_Select(meta,".chartPreviousClose:n")) != NULL)
{
/* Compute the price change in percentage. */
double prev_close = aux->valuedouble;
double change = (yd->reg - prev_close) / prev_close * 100;
yd->regchange = sdscatprintf(sdsempty(),"%02.g%%",change);
}
if ((aux = cJSON_Select(meta,".symbol:s")) != NULL)
yd->name = sdsnew(aux->valuestring);
if ((aux = cJSON_Select(meta,".exchangeName:s")) != NULL)
yd->exchange = sdsnew(aux->valuestring);
if ((aux = cJSON_Select(meta,".currency:s")) != NULL)
yd->csym = sdsnew(aux->valuestring);
/* Certain times tha Yahoo API is unable to return actual info
* from a stock, even if it returns success. */
if (yd->regchange == NULL) goto fmterr;
} else {
cJSON *meta = cJSON_Select(json,".chart.result[0].meta");
cJSON *aux;
if (meta == NULL) goto fmterr;
if ((aux = cJSON_Select(meta,".symbol:s")) != NULL)
yd->symbol = sdsnew(aux->valuestring);
cJSON *data = cJSON_Select(json,
".chart.result[0].indicators.quote[0].close:a");
if (data == NULL) goto fmterr;
/* Count the items, so that we can size our timestamp array. */
int len = 0;
aux = data->child;
while(aux != NULL) {
len++;
aux = aux->next;
}
yd->ts_len = len;
yd->ts_data = malloc(sizeof(float)*len);
/* Load data into array. */
int idx = 0;
aux = data->child;
while(aux != NULL) {
float v = aux->valuedouble;
if (cJSON_IsNumber(aux))
yd->ts_data[idx] = v;
else
yd->ts_data[idx] = 0;
if (idx == 0 || v < yd->ts_min) yd->ts_min = v;
if (idx == 0 || v > yd->ts_max) yd->ts_max = v;
idx++;
aux = aux->next;
}
}
cJSON_Delete(json);
return yd;
fmterr:
cJSON_Delete(json);
freeYahooData(yd);
return NULL;
}
/* Turns a yahoo data time series result, obtained using getYahooData with
* the YDATA_TS argument, and turn the prices of the last 'range+1' days
* in the corresponding 'range' price percentage changes.
*
* While doing so, compute some volatility statistics. It uses a different
* approach compared to the classical one, by checking what is the average
* percentage the stock gains, when it gains, loses, with it loses, and
* also taking into account what is the maximum loss and gain in percentage
* on the specified last "range" days of trading.
*
* The final results are stored in the additinal fields of the 'yd'
* structure. The price changes replace the ts_data array itself.
*
* When broken data is detected and the calculation is impossible, the
* corresponding value is set to -inf.
*/
void yahooDataToPriceChanges(ydata *yd, int range) {
if (range >= yd->ts_len) range = yd->ts_len-1;
if (range <= 0) return;
/* Intialize the result set. */
yd->pdays = 0;