Crypto backtesting
Loading...
Searching...
No Matches
core.h
Go to the documentation of this file.
1#pragma once
2
3#include "constants.h"
4#include <algorithm>
5#include <cassert>
6#include <cmath>
7#include <ranges>
8
9/// Core routines that don't depend on any other fx routines
10namespace fx {
11
12/// Calculate size of a series, return type depends on input param
13template <typename T = size_t>
14constexpr T to_size(std::ranges::range auto &&xs) {
15 return static_cast<T>(std::ranges::size(xs));
16}
17
18/// Return the first entry in a series
19constexpr auto to_first(std::ranges::range auto &&xs) {
20 assert(not std::ranges::empty(xs));
21 return xs[0];
22}
23
24/// Return the last entry in a series
25constexpr auto to_last = [](std::ranges::range auto &&xs) {
26 assert(not std::ranges::empty(xs));
27 return xs[to_size(xs) - 1uz];
28};
29
30/// Calculate sum of series
31constexpr auto to_sum(std::ranges::range auto &&xs) {
32 return std::ranges::fold_left(
33 xs, 0.0, [](const double acc, double x) { return acc + x; });
34}
35
36/// Calculate sum of series
37constexpr auto to_sum2(std::ranges::range auto &&xs) {
38 assert(not std::ranges::empty(xs));
39
40 const auto &&sum = std::ranges::fold_left(
41 xs, decltype(xs[0]){}, [](auto acc, auto &&x) { return acc + x; });
42
43 // Check the type of the first element is the same as the sum
44 static_assert(std::is_same_v<std::remove_cvref_t<decltype(xs[0])>,
45 std::remove_cvref_t<decltype(sum)>>);
46
47 return sum;
48}
49
50/// Just passing through
51constexpr auto identity = [](auto &&xs) { return xs; };
52
53/// Just passing through
54constexpr auto identity2 = [](auto &&xs) {
55 return std::forward<decltype(xs)>(xs);
56};
57
58/// Calculate profit from a trade
59constexpr auto to_profit(auto &&entry, auto &&exit) {
60 auto &&profit = decltype(entry){100.0f} * (exit - entry) / entry;
61
62 static_assert(std::is_same_v<decltype(entry), decltype(exit)>);
63 static_assert(std::is_same_v<decltype(profit), decltype(entry)>);
64
65 return profit;
66}
67
68} // namespace fx
Core routines that don't depend on any other fx routines.
Definition constants.h:3
constexpr auto to_first(std::ranges::range auto &&xs)
Return the first entry in a series.
Definition core.h:19
constexpr auto to_sum2(std::ranges::range auto &&xs)
Calculate sum of series.
Definition core.h:37
constexpr auto to_last
Return the last entry in a series.
Definition core.h:25
constexpr auto to_profit(auto &&entry, auto &&exit)
Calculate profit from a trade.
Definition core.h:59
constexpr auto identity2
Just passing through.
Definition core.h:54
constexpr auto to_sum(std::ranges::range auto &&xs)
Calculate sum of series.
Definition core.h:31
constexpr auto identity
Just passing through.
Definition core.h:51
constexpr T to_size(std::ranges::range auto &&xs)
Calculate size of a series, return type depends on input param.
Definition core.h:14