forked from curvefi/cryptopool-simulator
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
1786 lines (1610 loc) · 56 KB
/
main.cpp
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
#include <cassert>
#include <cstdio>
#include <map>
#include <string>
#include <cstdlib>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <utility>
#include <sys/fcntl.h>
#include <sys/mman.h>
#include <stdexcept>
#include <cmath>
#include <fstream>
#include <iomanip>
#include "json.hpp"
#include <queue>
#include <pthread.h>
#include <sys/time.h>
#include <sys/resource.h>
#ifndef MAP_NOCACHE
#define MAP_NOCACHE 0
#endif
using nlohmann::json;
//#include "bn_fixed.h"
#define DEBUG 0
static int trace = DEBUG;
#if DEBUG > 1
#define T printf("Entering %s\n", __PRETTY_FUNCTION__)
#define DBG printf("Now in %s line %d\n", __PRETTY_FUNCTION__ , __LINE__)
#define E printf("Leaving %s\n", __PRETTY_FUNCTION__)
#else
#define T
#define DBG
#define E
#endif
#if DEBUG > 0
#define P(x) if (trace) printf("[%d] %s::%s=%s ", __LINE__, __FUNCTION__, #x, x.to_string(10).c_str())
#define DP(x) if (trace) printf("[%d] %s::%s=%.12Lf ", __LINE__, __FUNCTION__, #x, (long double)x)
#define P256(x) if (trace) { printf("[%d] %s::%s={", __LINE__, __FUNCTION__, #x); for (size_t i = 0; i < x.size(); i++) printf("%s ", x[i].to_string(10).c_str()); printf("}\n"); }
#define EOL if (trace) printf("\n")
#else
#define P(x)
#define DP(x)
#define P256(x)
#define EOL
#endif
using std::vector, std::string, std::pair, std::sort, std::map, std::min, std::max;
using u64 = unsigned long long;
using money = long double;
static const int MAX_ARRAY = 3;
#ifdef __MACH__
#include <mach/mach_init.h>
#include <mach/thread_act.h>
#include <mach/mach_port.h>
static double get_thread_time() {
mach_port_t thread;
kern_return_t kr;
mach_msg_type_number_t count;
thread_basic_info_data_t info;
thread = mach_thread_self();
count = THREAD_BASIC_INFO_COUNT;
kr = thread_info(thread, THREAD_BASIC_INFO, (thread_info_t) &info, &count);
double ret = 0;
if (kr == KERN_SUCCESS && (info.flags & TH_FLAGS_IDLE) == 0) {
ret += info.user_time.seconds;
ret += info.user_time.microseconds / 1000000.;
ret += info.system_time.seconds;
ret += info.system_time.microseconds / 1000000.;
}
else {
abort();
}
mach_port_deallocate(mach_task_self(), thread);
return ret;
}
#else
static double get_thread_time() {
struct rusage usage;
getrusage (RUSAGE_THREAD, &usage);
double ret = 0.;
ret += usage.ru_utime.tv_sec;
ret += usage.ru_utime.tv_usec / 1000000.;
ret += usage.ru_stime.tv_sec;
ret += usage.ru_stime.tv_usec / 1000000.;
return ret;
}
#endif
static double get_total_time() {
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
double ret = 0.;
ret += usage.ru_utime.tv_sec;
ret += usage.ru_utime.tv_usec / 1000000.;
ret += usage.ru_stime.tv_sec;
ret += usage.ru_stime.tv_usec / 1000000.;
return ret;
}
static double get_wall_time() {
struct timeval tv;
gettimeofday(&tv, nullptr);
double ret = 0.;
ret += tv.tv_sec;
ret += tv.tv_usec / 1000000.;
return ret;
}
static void print_clock(string const &mesg, double start, double end) {
printf("%s %.3lf sec\n", mesg.c_str(), double(end - start));
}
struct trade_data {
u64 t = 0; // 0
money open = 0; // 1
money high = 0; // 2
money low = 0; // 3
money close = 0; // 4
money volume = 0; // 5
pair<int,int> pair1 = {0,0};
void print() const {
printf("{ open: %.6Lf, high: %.6Lf low: %.6Lf close: %.6Lf t: %llu, volume: %.6Lf pair: (%d,%d)} ",
this->open, this->high, this->low, this->close, this->t, this->volume, this->pair1.first, this->pair1.second);
}
};
struct trade_one {
u64 t;
trade_data trade;
};
money mabs(money val) noexcept {
return val >= 0 ? val : -val;
}
struct mapped_file {
int fd;
unsigned char *base = nullptr;
size_t size = 0;
string name;
explicit mapped_file() {}
bool map(string const &name) {
fd = open(name.c_str(), O_RDONLY);
if (fd < 0) return false;
lseek(fd, 0, SEEK_END);
size = lseek(fd, 0, SEEK_CUR);
base = (unsigned char *)::mmap(nullptr, size, PROT_READ, MAP_NOCACHE|MAP_FILE|MAP_SHARED, fd, 0);
printf("mapped_file::open: base=%p\n", base);
if (base == MAP_FAILED) {
perror(name.c_str());
base = nullptr;
return false;
}
this->name = name;
return true;
}
~mapped_file() {
if (base != nullptr) {
::munmap(base, size);
}
if (fd >= 0) {
close(fd);
}
}
};
// py: returns list of dicts ['t'->u64, 'open'->float, 'high'->float, 'low'->float, 'close'->float, 'volume'->float]
// c++ returns vector of struct datum
vector<trade_data> get_data(std::string const &fname) {
auto start_time = get_thread_time();
auto name_to_open = "download/" + fname + ".json";
printf("parsing %s\n", name_to_open.c_str());
mapped_file mf;
if (!mf.map(name_to_open)) {
printf("failed to open '%s'\n", name_to_open.c_str());
abort();
}
vector<trade_data> ret;
auto p = mf.base;
if (*p == '[') p++; // skip initial '[';
auto scan_double = [] (unsigned char *p, long double *d) {
if (*p == '"') p++;
*d = atof((char *)p);
while (*p != '"' && *p!= ' ' && *p != ',' && *p != ']') p++;
while (*p == ',' || *p == ' ' || *p == '"') p++;
return p;
};
auto scan_u64 = [] (unsigned char *p, u64 *d) {
u64 ret = 0;
while (*p >= '0' && *p <= '9') {
ret = ret * 10 + *p - '0';
p++;
}
while (*p == ',' || *p == ' ') p++;
*d = ret;
return p;
};
while (*p != ']') {
// [1503443580000, "3984.00000000", "3984.00000000", "3984.00000000", "3984.00000000", "0.46619400", 1503443639999, "1857.31689600", 2, "0.00000000", "0.00000000", "11761.90492277"],
if (*p == '[') {
trade_data d;
p++;
p = scan_u64(p, &d.t);
if (d.t > 10000000000) {
d.t /= 1000;
}
p = scan_double(p, &d.open);
p = scan_double(p, &d.high);
p = scan_double(p, &d.low);
p = scan_double(p, &d.close);
p = scan_double(p, &d.volume);
ret.push_back(d);
while (*p != ']') p++;
p++; // skip ']'
} else p++;
}
auto end_time = get_thread_time();
printf("%s: load %zu elements\n", name_to_open.c_str(), ret.size());
print_clock("parsing took", start_time, end_time);
return ret;
}
auto get_price_vector(int n, vector<trade_data> const &data) {
vector<money> p(n);
p[0] = 1.L;
for (auto const &d: data) {
if (d.pair1.first == 0) {
p[d.pair1.second] = d.close;
}
bool zeros = false;
for (auto x: p) {
zeros |= x == 0;
}
if (!zeros) {
for (auto q: p) {
printf("%.16Lf ", q);
}
printf("\n");
return p;
}
}
return p;
}
bool get_all(json const &jin, int last_elems, vector<money> & price_vector, mapped_file &mf) {
// 0 - usdt
// 1 - btc
// 2 - eth
size_t N = jin["datafile"].size();
if (N == 1) N = 2;
assert(N == 2 || N == 3);
vector<string> names;
map<string, vector<trade_data>> all_trades;
vector<pair<int, int>> pairs;
if (N == 2) {
pairs.push_back({0, 1});
string name = jin["datafile"][0];
auto d0 = get_data(name);
all_trades[name] = d0;
names.resize(1);
printf("using file '%s'\n", name.c_str());
names[0] = name;
} else {
pairs.push_back({0, 1});
pairs.push_back({0, 2});
pairs.push_back({1, 2});
names.resize(3);
names[0] = jin["datafile"][0];
auto d0 = get_data(names[0]);
names[1] = jin["datafile"][1];
auto d1 = get_data(names[1]);
names[2] = jin["datafile"][2];
auto d2 = get_data(names[2]);
all_trades[names[0]] = d0;
all_trades[names[1]] = d1;
all_trades[names[2]] = d2;
}
u64 min_time = 1ull << 63;
u64 max_time = 0;
for (auto name: names) {
for (auto const &t: all_trades[name]) {
min_time = min(min_time, t.t);
max_time = max(max_time, t.t);
}
}
vector<trade_one> out;
for (size_t i = 0; i < names.size(); i++) {
auto &trades = all_trades[names[i]];
for (auto &trade: trades) {
if (trade.t >= min_time && trade.t <= max_time) {
trade.pair1 = pairs[i];
trade_data trade_min;
trade_data trade_max;
// t, open, high, low, close, volume, pair1
// (1, 2) min
// (0, 2) min
// (0, 1) min
// (0, 1) max
// (0, 2) max
// (1, 2) max
trade_min.t = trade.t - (trade.pair1.first + trade.pair1.second) * 10 + 5;
trade_max.t = trade.t + (trade.pair1.first + trade.pair1.second) * 10 - 5;
trade_min.open = trade.open;
trade_max.close = trade.close;
trade_min.pair1 = trade.pair1;
trade_max.pair1 = trade.pair1;
trade_min.volume = trade.volume / 2;
trade_max.volume = trade.volume / 2;
if (mabs(trade.open - trade.low) + mabs(trade.close - trade.high) < mabs(trade.open - trade.high) + mabs(trade.close - trade.low)) {
trade_min.high = trade.low;
trade_min.low = trade.low;
trade_min.close = trade.low;
trade_max.open = trade.high;
trade_max.high = trade.high;
trade_max.low = trade.high;
} else {
trade_min.high = trade.high;
trade_min.low = trade.high;
trade_min.close = trade.high;
trade_max.open = trade.low;
trade_max.high = trade.low;
trade_max.low = trade.low;
}
out.push_back({trade.t - (trade.pair1.first + trade.pair1.second) * 10 + 5, trade_min});
out.push_back({trade.t + (trade.pair1.first + trade.pair1.second) * 10 - 5, trade_max});
}
}
}
auto start_time = get_thread_time();
//debug_print("out first 5", out, 5);
//debug_print("out last 5", out, -5);
sort(out.begin(), out.end(), [](trade_one const &l, trade_one const &r) {
return l.t < r.t;
});
auto end_time = get_thread_time();
//debug_print("sorted out first 5", out, 5);
//debug_print("sorted out last 5", out, -5);
vector<trade_data> ret;
for (auto &q: out) {
ret.push_back(q.trade);
}
//printf("total %zu elements\n", ret.size());
print_clock("sorting took", start_time, end_time);
if (last_elems > 0) {
printf("Trimming: use last %d elements\n", last_elems);
ret.erase(ret.begin(), ret.begin() + ret.size() - last_elems);
}
price_vector = get_price_vector(N, ret);
string tmp_name = "_tmp." + std::to_string(getpid());
FILE *tmp = fopen(tmp_name.c_str(), "w+");
if (tmp == nullptr) {
printf("Temp file '%s' is not available\n", tmp_name.c_str());
return false;
}
printf("Using temp file '%s' as interprocedural connect\n", tmp_name.c_str());
fwrite(&ret[0], sizeof(trade_data), ret.size(), tmp);
//unlink(tmp_name.c_str()); // Does not work in Windows
mf.map(tmp_name);
return true;
}
money geometric_mean_2(money const *x) {
return sqrtl(x[0] * x[1]);
}
money geometric_mean_3(money const *x) {
// {0,1,2} {0,2,1} {1,0,2} {1,2,0} {2,0,1} {2,1,0}
auto median = [&x] {
money D = x[0];
if (x[0] >= x[1]) {
// {1,0,2} {2,0,1} {2,1,0}
if (x[0] >= x[2]) {
// {2,0,1} {2,1,0}
if (x[1] >= x[2]) D = x[2];
else D = x[1];
} // else {1,0,2}
} else {
// {0,1,2} {0,2,1} {1,2,0}
if (x[0] < x[2]) {
// {0,1,2} {0,2,1}
if (x[1] >= x[2]) D = x[2];
else D = x[1];
} // else {1,2,0}
}
};
auto min_max_mean = [&x] {
if (x[0] >= x[1]) {
// {1,0,2} {2,0,1} {2,1,0}
if (x[0] >= x[2]) {
// {2,0,1} {2,1,0}
if (x[1] >= x[2]) return sqrtl(x[0]*x[1]);
else return sqrtl(x[0]*x[2]);
}
return sqrtl(x[1]*x[2]);
} else {
// {0,1,2} {0,2,1} {1,2,0}
if (x[0] < x[2]) {
// {0,1,2} {0,2,1}
if (x[1] >= x[2]) return sqrtl(x[0]*x[1]);
else return sqrtl(x[0]*x[2]);
}
return sqrtl(x[1]*x[2]); // else {1,2,0}
}
};
//money MAX = max(x[0], max(x[1], x[2]));
money prod = x[0] * x[1] * x[2];
//money MIN = min(x[0], min(x[1], x[2]));
//money D = sqrtl(MAX * MIN);
auto D = min_max_mean();
for (int i = 0; i < 255; i++) {
money D_prev = D;
D = (D + D + prod / D / D) *0.333333333333333333333333L;
auto diff = mabs(D - D_prev);
if (diff <= 1E-12 or diff * 1E12L < D) {
return D;
}
}
throw std::logic_error("geometric_mean: Did not converge");
}
auto reduction_coefficient_3(money const *x, money gamma) {
money K = 27.L;
money S = x[0] + x[1] + x[2];
for (size_t i = 0; i < 3; i++) {
K *= x[i] / S;
}
if (gamma > 0) {
K = gamma / (gamma + 1.L - K);
}
return K;
}
auto reduction_coefficient_2(money const *x, money gamma) {
money K = 1.L;
money S = 0.L;
for (size_t i = 0; i < 2; i++) S += x[i]; // = sum(x)
for (size_t i = 0; i < 2; i++) {
K *= 2 * x[i] / S;
}
if (gamma > 0) {
K = gamma / (gamma + 1.L - K);
}
return K;
}
void print(money const *x, size_t N) {
printf("[");
for (size_t i = 0; i < N; i++) {
printf("%.16Lf ", x[i]);
}
printf("]\n");
}
auto newton_D_2(money A, money gamma, money const *xx, money D0) {
money D = D0;
money S = 0;
const size_t N = 2;
money x[2];
for (size_t i = 0; i < N; i++) {
S += x[i] = xx[i];
}
sort(x+0, x+N, [](money l, money r) { return l > r; });
auto NN = 1.L;
for (size_t j = 0; j < N; j++) { // XXX or just set A to be A*N**N?
NN *= N;
}
A *= NN;
money rev_gamma = 1.L / gamma;
money gamma_1 = 1.L + gamma;
//for (size_t j = 0; j < N; j++) { // XXX or just set A to be A*N**N?
// A = A * N;
//}
for (int i = 0; i < 255; i++) {
money D_prev = D;
money K0 = NN;
for (auto const &_x: x) {
K0 = K0 * _x / D;
}
money _g1k0 = mabs((gamma_1 - K0));
// # D / (A * N**N) * _g1k0**2 / gamma**2
money mul1 = D * rev_gamma * _g1k0 * rev_gamma * _g1k0 / A;
// # 2*N*K0 / _g1k0
money mul2 = 2.L * N * K0 / _g1k0;
money neg_fprime = (S + S * mul2) + mul1 * N / K0 - mul2 * D;
assert (neg_fprime > 0); // # Python only: -f' > 0
// # D -= f / fprime
D = (D * neg_fprime + D * S - D * D) / neg_fprime - D * (mul1 / neg_fprime) * (1.L - K0) / K0;
if (D < 0) {
D = mabs(D) / 2.L;
}
if (mabs(D - D_prev) <= max(1e-16L, D / 1e14L)) {
return D;
}
}
throw std::logic_error("Newton_D: did not converge");
}
auto newton_D_3(money A, money gamma, money const *xx, money D0) {
money D = D0;
money S = 0;
money x[3];
for (size_t i = 0; i < 3; i++) {
S += x[i] = xx[i];
}
if (x[0] < x[1]) std::swap(x[0],x[1]);
if (x[1] < x[2]) std::swap(x[1],x[2]);
if (x[0] < x[1]) std::swap(x[0],x[1]);
// sort(x+0, x+3, [](money l, money r) { return l > r; });
A *= 27.L;
//for (size_t j = 0; j < N; j++) { // XXX or just set A to be A*N**N?
// A = A * N;
//}
money rev_gamma = 1.L / gamma;
money gamma_1 = 1.L + gamma;
for (int i = 0; i < 255; i++) {
money D_prev = D;
money K0 = 27.L;
for (auto const &_x: x) {
K0 = K0 * _x / D;
}
money _g1k0 = mabs((gamma + 1.L - K0));
// # D / (A * N**N) * _g1k0**2 / gamma**2
money mul1 = D / gamma * _g1k0 / gamma * _g1k0 / A;
// # 2*N*K0 / _g1k0
money mul2 = 2.L * 3.L * K0 / _g1k0;
money neg_fprime = (S + S * mul2) + mul1 * 3.L / K0 - mul2 * D;
assert (neg_fprime > 0); // # Python only: -f' > 0
// # D -= f / fprime
D = (D * (neg_fprime + S - D)) / neg_fprime - D * (mul1 / neg_fprime) * (1.L - K0) / K0;
if (D < 0) {
D = mabs(D) / 2.L;
}
if (mabs(D - D_prev) <= max(1e-16L, D / 1e14L)) {
return D;
}
}
throw std::logic_error("Newton_D: did not converge");
}
auto newton_y(money A, money gamma, money const *x, size_t N, money D, int i) {
money y = D / N;
money K0_i = 1.;
money S_i = 0.;
money x_sorted[N - 1];
for (int j = 0, cnt = 0; j < N; j++) {
if (j != i) x_sorted[cnt++] = x[j];
}
sort(x_sorted+0, x_sorted+N-1);
money max_x_sorted = x_sorted[N-2];
money convergence_limit = max(max_x_sorted / 1E14L, D / 1E14L);
convergence_limit = max(convergence_limit, 1E-16L);
for (auto const &_x: x_sorted) {
y = y * D / (_x * N); // # Small _x first
S_i += _x;
K0_i = K0_i * _x * N / D; // # Large _x first
}
auto NN = 1.;
for (size_t j = 0; j < N; j++) { // in range(N): # XXX or just set A to be A*N**N?
NN *= N;
}
A = A * NN;
auto g2a = (gamma * gamma * A);
for (size_t j = 0; j < 255; j++) {
money y_prev = y;
money K0 = K0_i * y * N / D;
money K0_1 = 1.L - K0;
money S = S_i + y;
money _g1k0 = mabs((gamma + K0_1));
// D / (A * N**N) * _g1k0**2 / gamma**2
//money mul1 = D / gamma * _g1k0 / gamma * _g1k0 / A;
money mul1 = D * _g1k0 * _g1k0 / g2a;
// 2*K0 / _g1k0
money mul2 = 1.L + (K0 + K0) / _g1k0;
// money yfprime = y + S * mul2 + mul1 - D * mul2;
money yfprime = y + mul1 + (S - D) * mul2;
money fprime = yfprime / y;
assert (fprime > 0) ; //# Python only: f' > 0
// y -= f / f_prime; y = (y * fprime - f) / fprime
// y = (yfprime + D - S) / fprime + mul1 / fprime * K0_1 / K0;
y = ((yfprime + D - S) + mul1 * K0_1 / K0) / fprime;
if (j > 100) { // # Just logging when doesn't converge
printf("%zu %.6Lf %.16Lf ", j, y, D);
print(x, N);
}
if (y < 0 or fprime < 0) {
y = y_prev / 2.L;
}
if (mabs(y - y_prev) <= max(convergence_limit, y / 1e14L)) {
return y;
}
}
throw std::logic_error("Did not converge");
}
auto newton_y_3(money A, money gamma, money const *x, money D, int i) {
money y = D / 3.;
money K0_i = 1.;
money S_i = 0.;
money x_sorted[2];
switch (i) {
case 0:
if (x[1] < x[2]) {
x_sorted[0] = x[1];
x_sorted[1] = x[2];
} else {
x_sorted[1] = x[1];
x_sorted[0] = x[2];
}
break;
case 1:
if (x[0] < x[2]) {
x_sorted[0] = x[0];
x_sorted[1] = x[2];
} else {
x_sorted[1] = x[0];
x_sorted[0] = x[2];
}
break;
case 2:
if (x[0] < x[1]) {
x_sorted[0] = x[0];
x_sorted[1] = x[1];
} else {
x_sorted[1] = x[0];
x_sorted[0] = x[1];
}
break;
default:
abort();
}
money max_x_sorted = x_sorted[1];
money convergence_limit = max(max_x_sorted * 1E-14L, D * 1E-14L);
convergence_limit = max(convergence_limit, 1E-16L);
y = y * D / (x_sorted[0] * 3);
S_i += x_sorted[0];
K0_i = K0_i * x_sorted[0] * 3 / D;
y = y * D / (x_sorted[1] * 3);
S_i += x_sorted[1];
K0_i = K0_i * x_sorted[1] * 3 / D;
A = A * 27.L;
auto g2a = (gamma * gamma * A);
for (size_t j = 0; j < 255; j++) {
money y_prev = y;
money K0 = K0_i * y * 3 / D;
money K0_1 = 1.L - K0;
money S = S_i + y;
money _g1k0 = mabs((gamma + K0_1));
// D / (A * N**N) * _g1k0**2 / gamma**2
//money mul1 = D / gamma * _g1k0 / gamma * _g1k0 / A;
money mul1 = D * _g1k0 * _g1k0 / g2a;
// 2*K0 / _g1k0
money mul2 = 1.L + (K0 + K0) / _g1k0;
// money yfprime = y + S * mul2 + mul1 - D * mul2;
money yfprime = y + mul1 + (S - D) * mul2;
money fprime = yfprime / y;
assert (fprime > 0) ; //# Python only: f' > 0
// y -= f / f_prime; y = (y * fprime - f) / fprime
// y = (yfprime + D - S) / fprime + mul1 / fprime * K0_1 / K0;
y = ((yfprime + D - S) + mul1 * K0_1 / K0) / fprime;
if (j > 100) { // # Just logging when doesn't converge
printf("%zu %.6Lf %.16Lf ", j, y, D);
print(x, 3);
}
if (y < 0 or fprime < 0) {
y = y_prev * 0.5L;
}
if (mabs(y - y_prev) <= max(convergence_limit, y * 1e-14L)) {
return y;
}
}
throw std::logic_error("Did not converge");
}
money solve_x(money A, money gamma, money const *x, size_t N, money D, int i) {
if (N == 3) return newton_y_3(A, gamma, x, D, i);
else return newton_y(A, gamma, x, N, D, i);
}
auto solve_D(money A, money gamma, money const *x, size_t N) {
if (N == 3) {
auto D0 = 3 * geometric_mean_3(x); // # <- fuzz to make sure it's ok XXX
return newton_D_3(A, gamma, x, D0);
} else {
auto D0 = 2 * geometric_mean_2(x); // # <- fuzz to make sure it's ok XXX
return newton_D_2(A, gamma, x, D0);
}
}
struct Curve {
Curve(json const &jconf, vector<money> const &p) {
this->A = jconf["A"];
this->gamma = jconf["gamma"];
money D = jconf["D"];
this->n = jconf["n"];
if (!p.empty()) {
this->p = p;
} else {
this->p.resize(n, 1.L);
}
this->x.resize(n);
for(int i = 0; i < n; i++) {
x[i] = D / n / p[i];
}
}
auto xp_3(money *ret) const {
for (int i = 0; i < 3; i++) {
ret[i] = x[i] * p[i];
assert(x[i] > 0);
}
}
auto xp_2(money *ret) const {
for (int i = 0; i < 2; i++) {
ret[i] = x[i] * p[i];
assert(x[i] > 0);
}
}
auto D_3() const {
money xp[3];
this->xp_3(xp);
auto ret = solve_D(A, gamma, xp, n);
return ret;
}
auto D_2() const {
money xp[2];
this->xp_2(xp);
auto ret = solve_D(A, gamma, xp, n);
return ret;
}
money y_3(money x, int i, int j) {
money xp[3];
this->xp_3(xp);
xp[i] = x * this->p[i];
auto yp = solve_x(A, gamma, xp, n, this->D_3(), j);
auto ret = yp / this->p[j];
return ret;
}
money y_2(money x, int i, int j) {
money xp[2];
this->xp_2(xp);
xp[i] = x * this->p[i];
auto yp = solve_x(A, gamma, xp, n, this->D_2(), j);
auto ret = yp / this->p[j];
return ret;
}
money A;
money gamma;
size_t n;
vector<money> p;
vector<money> x;
};
struct extra_data {
money APY = 0;
money liq_density = 0;
money slippage = 0;
money volume = 0;
};
struct simulation_data {
int num = 0;
json const *jconf = nullptr;
vector<money> const *price_vector = nullptr;
mapped_file const *test_data = nullptr;
extra_data result;
size_t total = 0;
size_t current = 0;
};
struct Trader {
Trader(json const &jconf, vector<money> const &p0) : curve(jconf, p0) {
money A = jconf["A"];
money gamma = jconf["gamma"];
money D = jconf["D"];
int n = jconf["n"];
mid_fee = jconf["mid_fee"];
out_fee = jconf["out_fee"];
fee_gamma = jconf["fee_gamma"];
adjustment_step = jconf["adjustment_step"];
allowed_extra_profit = jconf["allowed_extra_profit"];
ma_half_time = jconf["ma_half_time"];
this->ext_fee = jconf["ext_fee"];
this->gas_fee = jconf["gas_fee"];
log = jconf["log"];
this->p0 = p0;
this->price_oracle = this->p0;
this->last_price = this->p0;
// this->curve = Curve(A, gamma, D, n, p0);
this->dx = D * 1e-8L;
this->D0 = n == 3 ? this->curve.D_3() : this->curve.D_2();
this->xcp_0 = n == 3 ? this->get_xcp_3() : this->get_xcp_2();
this->xcp_profit = 1.L;
this->xcp_profit_real = 1.L;
this->xcp = this->xcp_0;
this->total_vol = 0.0;
this->slippage = 0;
this->antislippage = 0;
this->slippage_count = 0;
this->volume = 0;
this->not_adjusted = false;
this->heavy_tx = 0;
this->light_tx = 0;
this->is_light = false;
this->t = 0;
}
auto fee_3() {
money xp[3];
curve.xp_3(xp);
auto f = reduction_coefficient_3(xp, fee_gamma);
return (mid_fee * f + out_fee * (1.L - f));
}
auto fee_2() {
money xp[2];
curve.xp_2(xp);
auto f = reduction_coefficient_2(xp, fee_gamma);
return (mid_fee * f + out_fee * (1.L - f));
}
money get_xcp_3() const {
// First calculate the ideal balance
// Then calculate, what the constant-product would be
auto D = curve.D_3();
size_t N = 3;
money X[3];
for (size_t i = 0; i < 3; i++) {
X[i] = D / (3 * curve.p[i]);
}
return geometric_mean_3(X);
}
money get_xcp_2() const {
// First calculate the ideal balance
// Then calculate, what the constant-product would be
auto D = curve.D_2();
size_t N = 2;
money X[2];
for (size_t i = 0; i < 2; i++) {
X[i] = D / (2 * curve.p[i]);
}
return geometric_mean_2(X);
}
auto price_3(int i, int j) {
auto dx_raw = dx / curve.p[i];
auto curve_res = curve.y_3(curve.x[i] + dx_raw, i, j);
auto ret = dx_raw / (curve.x[j] - curve_res);
return ret;
}
auto price_2(int i, int j) {
auto dx_raw = dx / curve.p[i];
auto curve_res = curve.y_2(curve.x[i] + dx_raw, i, j);
auto ret = dx_raw / (curve.x[j] - curve_res);
return ret;
}
auto step_for_price_3(money p_min, money p_max, pair<int, int> p, money vol, money ext_vol) {
money x0[3];
copy_money_3(x0, &curve.x[0]);
auto step0 = dx / curve.p[p.first]; // step in units of 1st currency
auto step = step0;
money _dx = 0;
money _dy = 0;
money x = 0;
money y = 0;
money price = 0;
money gas = gas_fee / curve.p[p.first];
bool good_with_gas = false;
money trade_sign = 1;
if (p_min > 0) {
trade_sign = -1;
}
auto fee = this->fee_3();
// printf("---\n");
// +
while (true) {
auto _dx_prev = _dx;
auto _dy_prev = _dy;
_dx += step;
x = x0[p.first] + trade_sign * _dx;
y = curve.y_3(x, p.first, p.second);
_dy = (x0[p.second] - y) * trade_sign;
_dy = _dy * (1.L - fee * trade_sign);
curve.x[p.first] += _dx * trade_sign;
curve.x[p.second] -= _dy * trade_sign;
price = _dx / _dy;
auto price_with_gas = (_dx + trade_sign*gas) / _dy;
auto v = vol + _dy * curve.p[p.second];
// Needed to prevent resonant trading which doesn't happen in reality
auto inst_price = price_3(p.first, p.second);
copy_money_3(&curve.x[0], x0);
// printf("::: %Lf %Lf %Lf %Lf\n", price, inst_price, p_min, p_max);
if ((p_min > 0 and (price_with_gas >= p_min) and inst_price >= p_min) or (p_max > 0 and (price_with_gas <= p_max) and inst_price <= p_max)) {
good_with_gas = true;
} else {
if (good_with_gas) {
_dx = _dx_prev;
_dy = _dy_prev;
break;
}
}
if ((p_min > 0 and (price < p_min or inst_price < p_min)) or (p_max > 0 and (price > p_max or inst_price > p_max)) or (v > ext_vol / 2.L)) {
_dx = _dx_prev;
_dy = _dy_prev;
break;
}
// printf("*** price=%Lf, min=%Lf, max=%Lf, _dx=%Lf\n", price, p_min, p_max, _dx);
step += step;
}
// -
while (true) {
auto _dx_prev = _dx;
auto _dy_prev = _dy;
step /= 2;
if (step < step0) {
break;
}
_dx += step;
x = x0[p.first] + _dx * trade_sign;
y = curve.y_3(x, p.first, p.second);
_dy = (x0[p.second] - y) * trade_sign;
_dy = _dy * (1.L - fee * trade_sign);
curve.x[p.first] += _dx * trade_sign;
curve.x[p.second] -= _dy * trade_sign;
price = _dx / _dy;