Merge remote-tracking branch 'origin/spark_crypto_base.server' into spark_crypto_base.client_server_merge

This commit is contained in:
John Colvin committed 2021-11-22 19:57:53 -05:00
commit 75c0fee5bf
302 files changed
+32875 -15388

No files matched your search

+3
View File
@@ -4,3 +4,6 @@ BinPackParameters: false
AlignAfterOpenBracket: AlwaysBreak
AlwaysBreakTemplateDeclarations: true
PenaltyReturnTypeOnItsOwnLine: 140
---
Language: Proto
IndentWidth: 2
+5 -1
View File
@@ -2,6 +2,8 @@ nohup.out
build/
.build_proxy/
cmake-build-debug/
.cache/
.ipynb_checkpoints/
.idea/
.dir-locals.el
*.pyc
@@ -17,6 +19,8 @@ vcxproj.user
src/client/spark/Properties/launchSettings.json
compile_commands.json
.cquery_cached_index/
.cache/*
.clangd/*
src/client/sparkcmd/Properties/launchSettings.json
node_modules
paket-files
@@ -44,6 +48,6 @@ trace_data/
/src/.clang-format
/src/server/sparkd/cmds/spartan/analysis/.ipynb_checkpoints
/src/server/sparkd/cmds/spartan/analysis/data
.tmp/*
*.tmp/*
/.venv*/*
.cache/
+3
View File
@@ -7,3 +7,6 @@
[submodule "docker/windows"]
path = docker/windows
url = git@bitbucket.org:bluetradesys/windows_docker.git
[submodule "src/deribit-crypto-connector-demo-application"]
path = src/deribit-crypto-connector-demo-application
url = git@gitlab.com:cryptoexchanges1/deribit-crypto-connector-demo-application.git
+120
View File
@@ -0,0 +1,120 @@
FROM spark-crypto_18.04
RUN \
DEBIAN_FRONTEND=noninteractive apt-get update \
&& apt-get install -y \
htop \
locales \
source-highlight \
powerline \
fonts-powerline
# Hide these in the .docker directory to avoid conflicts with existing repos on
# this computer (in case a parent dir, such as $HOME, is mounted inside a
# container)
ARG repo_root="/home/john/Documents/repos/.docker"
# Create dirs for public/private repos
USER john
RUN \
mkdir -p $repo_root/public \
&& mkdir -p $repo_root/private
## Get latest fish (build from source)
# 1) get build deps
USER root
RUN \
DEBIAN_FRONTEND=noninteractive apt-get update \
&& apt-get install -y software-properties-common
RUN \
apt-add-repository ppa:fish-shell/release-3 \
&& sed -i "s/^# deb/deb/g" /etc/apt/sources.list
RUN DEBIAN_FRONTEND=noninteractive apt-get update && apt-get build-dep -y fish
# 2) Clone repo
USER john
RUN \
cd $repo_root/public \
&& git clone https://github.com/fish-shell/fish-shell.git
RUN \
cd $repo_root/public/fish-shell \
&& mkdir build \
&& cd build \
&& cmake -DCMAKE_BUILD_TYPE=Release -DBUILD_DOCS=0 .. \
&& cmake --build .
# Switch to root, rather than running inline w/ sudo cmd, to avoid having to
# enter a password
USER root
RUN \
cd $repo_root/public/fish-shell/build \
&& make install
USER john
## Get oh-my-fish
RUN \
cd $repo_root/public \
&& git clone https://github.com/oh-my-fish/oh-my-fish.git
RUN \
cd $repo_root/public/oh-my-fish \
&& ./bin/install --noninteractive --yes
## Get my fish config
RUN \
cd $repo_root/private \
&& git clone https://github.com/johncolvin-og/myfishconfig
RUN \
cd $repo_root/private/myfishconfig \
&& cp src/config.fish /home/john/.config/fish/ \
&& cp src/aliases.fish /home/john/.config/fish/ \
&& cp -r src/functions /home/john/.config/fish/ \
&& cp -r src/themes/johncolvin /home/john/.local/share/omf/themes/ \
&& fish --command "omf theme johncolvin"
## Get my bash config (back up existing)
RUN \
&& cd $repo_root/private \
&& git clone https://github.com/johncolvin-og/mybashconfig \
&& cd mybashconfig \
&& cp src/* /home/john/
# Get vim files/tools
USER root
RUN \
DEBIAN_FRONTEND=noninteractive apt-get update \
&& apt-get install -y curl
USER john
RUN curl -fLo home/john/.vim/autoload/plug.vim --create-dirs \
https://raw.githubusercontent.com/junegunn/vim-plug/master/plug.vim
# Some fonts look sketchy if the language isn't set to english:
# * The powerline git glyphs in the fish prompt are all displayed as question
# marks.
#
# * The shell confuses the position of the cursor, so characters are left
# around when they should have been cleared, and the cursor's home position
# is pushed one or two places to the right.
#
# * Most likely, the bad cursor position is caused by some dependencies the
# interpretation of escape sequences have on the language setting. At this
# point I don't even care anymore (literally took 8 hours to figure this
# out). I just know this shit is needed to make the prompt work correctly.
USER root
RUN locale-gen "en_US.UTF-8"
USER john
ENV LANG en_US.UTF-8
ENV LANGUAGE en_US:en
ENV LC_ALL en_US.UTF-8
RUN fc-cache -vf
+10
View File
@@ -0,0 +1,10 @@
#!/usr/bin/env fish
set image_name $argv[1]
if test (count $argv) -eq 0
set image_name_cmd (realpath (dirname (status -f)))"/docker_image_name.fish"
set image_name (eval $image_name_cmd)
end
echo $image_name
docker build -t $image_name .
+14
View File
@@ -0,0 +1,14 @@
#!/usr/bin/env fish
if test (count $argv) -gt 1
echo $argv[2]
exit 0
end
set image_name $argv[1]
if test (count $argv) -eq 0
set image_name_cmd (realpath (dirname (status -f)))"/docker_image_name.fish"
set image_name (eval $image_name_cmd)
end
echo $USER"s_"$image_name
+2
View File
@@ -0,0 +1,2 @@
#!/usr/bin/env fish
basename (git rev-parse --show-toplevel)"-dev"
+11
View File
@@ -0,0 +1,11 @@
#!/usr/bin/env fish
set inst_name $argv[1]
if test (count $argv) -eq 0
set script_dir (realpath (dirname (status -f)))
set inst_name (eval $script_dir"/docker_container_name.fish")
end
set working_dir (realpath (pwd))
echo $inst_name
docker exec -w $working_dir -it "$inst_name" bash
+3
View File
@@ -0,0 +1,3 @@
#!/usr/bin/env fish
echo Hello
+153
View File
@@ -0,0 +1,153 @@
#!/usr/bin/env fish
function print_help_and_exit
echo "\
Usage: setup_builds.sh [OPTIONS] compiler build-type
Positionals:
gcc Compile with gcc
clang Compile with clang
debug Build debug
release Build release
Options:
--compiler <clang|gcc> Specify the compiler
--type <debug|release> Specify the type of build
-f,--force Overwrite existing build directories
-h,--help Print this help message and exit
"
exit $argv[1]
end
function assert_dir
if test ! -d "$argv[1]"
if test -n "$argv[2]"
echo "Invalid variable "$argv[2]": '"$argv[1]"' is not a directory"
else
echo "'"$argv[1]"' is not a directory"
end
exit 1
end
end
# common variables
#set tools_path (readlink -f (pwd))
#set tools_path (cd (dirname (status --current-filename)); and pwd)
set tools_path (realpath (dirname (status -f)))
set spartan_path_cmd $tools_path/spartan_path.fish
set repo_root (eval $spartan_path_cmd "repo-root")
# Don't call 'spartan_path_cmd "build"' bc it returns specific build path
# (i.e., for a particular compiler/build type), not the root build path
# set build_root (eval $spartan_path_cmd "build")
set build_root "$repo_root"/"build"
mkdir -p "$build_root"
# Initialize the build directory. Expected arguments: <compiler>, <build_type>
# Note: this method assumes the variables 'repot_root' and 'build_root' have
# already been properly initialized
function setup_build
assert_dir $repo_root
assert_dir $build_root
set compiler "$argv[1]"
set build_type "$argv[2]"
if test \( -z "$build_type" \) -o \( \( "$build_type" != "debug" \) -a \( "$build_type" != "release" \) \)
print_help_and_exit 1
end
if test "$build_type" = "debug"
set build_type_arg "Debug"
if test "$compiler" = "gcc"
set compiler_arg "/usr/lib/ccache/g++"
else
set compiler_arg "/usr/lib/ccache/clang++"
end
else if test "$build_type" = "release"
set build_type_arg "Release"
if test "$compiler" = "gcc"
set compiler_arg "g++"
else
set compiler_arg "clang++"
end
end
if test \( -z "$compiler" \) -o \( \( "$compiler" != "gcc" \) -a \( "$compiler" != "clang" \) \)
print_help_and_exit 1
end
set build_dest $build_root"/"$compiler"/"$build_type
set conan_dest $repo_root"/conan/"$compiler"_"$build_type
echo "Set up build: "$compiler" "$build_type
if test \( -z "$force" \) -a \( -d $build_dest \)
echo "The build directory '"$build_dest"' already exists (use -f to overwrite)"
return 1
end
rm -rf "$build_dest"
mkdir -p "$build_dest"
mkdir -p "$conan_dest"
cd "$build_dest"
conan install --build missing --profile $conan_dest $repo_root
cmake -G Ninja -DCMAKE_BUILD_TYPE=$build_type_arg -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_CXX_COMPILER=$compiler_arg $repo_root
end
# The while loop below removes arguments (via shift) as it parses them.
# Additional information that needs to be extracted from the arguments must be
# done so before the loop is executed.
set i 1
while test $i -le (count $argv)
switch $argv[$i]
case '--compiler'
set i (math "$i + 1")
set compiler $argv[$i]
case 'clang'
set compiler 'clang'
case 'gcc'
set compiler 'gcc'
case '--type'
set i (math "$i + 1")
set build_type $argv[$i]
case 'release'
set build_type 'release'
case 'debug'
set build_type 'debug'
case '-f'
set force 1
case '--force'
set force 1
case '-h'
print_help_and_exit 0
case '--help'
print_help_and_exit 0
case '*'
print_help_and_exit 1
end
set i (math "$i + 1")
end
echo "compiler in "$compiler
echo "build type in "$build_type
if test -n "$compiler"
if test -n "$build_type"
setup_build $compiler $build_type
else
# all builds for the specified compiler
setup_build $compiler "debug"
setup_build $compiler "release"
end
else if test -n "$build_type"
# all builds for the specified build type
setup_build "gcc" $build_type
setup_build "clang" $build_type
else
# all builds
setup_build "gcc" "debug"
setup_build "gcc" "release"
setup_build "clang" "debug"
setup_build "clang" "release"
end
+92
View File
@@ -0,0 +1,92 @@
#!/usr/bin/env fish
#basename (git rev-parse --show-toplevel)
function print_help_and_exit
echo "\
Print paths to core parts of the repository
Usage: sparkd_path.sh SUBCOMMAND
Subcommands:
build Print build path
repo-root Print repo root path
"
exit $argv[1]
end
function print_build_help_and_exit
echo "\
Print build path
Usage: sparkd_path.sh build [OPTIONS] compiler build-type
Positionals:
gcc Print gcc build path
clang Print clang build path
debug Print debug build path
release Print release build path
Options:
--compiler <clang|gcc> Specify the compiler
--type <debug|release> Specify the type of build
-h,--help Print this help message and exit
"
exit $argv[1]
end
function print_repo_root
git rev-parse --show-toplevel
end
function run_repo_root
print_repo_root
end
function run_build
set compiler "gcc"
set build_type "release"
set i 1
while test $i -lt (count $argv)
switch $argv[$i]
case '--compiler'
set i (math "$i + 1")
set compiler $argv[$i]
case 'clang'
set compiler 'clang'
case 'gcc'
set compiler 'gcc'
case '--type'
set i (math "$i + 1")
set build_type $argv[$i]
case 'release'
set build_type 'release'
case 'debug'
set build_type 'debug'
'-h'
print_build_help_and_exit 0
'--help'
print_build_help_and_exit 0
'*'
print_build_help_and_exit 1
end
set i (math "$i + 1")
end
if test \( $compiler = "clang" \) -o \( $compiler = "gcc" \)
set comp_path $compiler
else
print_build_help_and_exit 1
end
set src_root (print_repo_root)
set build_root (readlink -f "$src_root""/build")
set build_dest $build_root"/"$compiler"/"$build_type
echo $build_dest
end
if test "$argv[1]" = "repo-root"
print_repo_root $argv[2..-1]
else if test "$argv[1]" = "build"
run_build $argv[2..-1]
else
print_help_and_exit 1
end
+43
View File
@@ -0,0 +1,43 @@
#!/usr/bin/env fish
set image_name $argv[1]
set cont_name $argv[2]
if test (count $argv) -lt 2
if test (count $argv) -lt 1
set image_name_cmd (realpath (dirname (status -f)))"/docker_image_name.fish"
set image_name (eval $image_name_cmd)
end
set cont_name_cmd (realpath (dirname (status -f)))"/docker_container_name.fish "$image_name
set cont_name (eval $cont_name_cmd)
end
set working_dir (realpath (pwd))
set home_path /home/john
set repo_path (git rev-parse --show-toplevel)
set repo_path_out /home/john/Documents/repos/private/(basename $repo_path)
set working_dir $repo_path_out
echo "starting docker instance '"$cont_name"' (image '"$image_name"')"
echo "working dir "$working_dir
docker run \
--rm \
--net host \
-h (hostname) \
-e "TZ=America/New_York" \
--cap-add=SYS_PTRACE \
--security-opt seccomp=unconfined \
--name $cont_name \
-v $repo_path:$repo_path_out \
-u (id -u $USER) \
-w $working_dir \
--shm-size=4024m \
-t \
-i \
-d \
-e DISPLAY="$DISPLAY" \
"$image_name" \
bash
+504 -390
View File
@@ -1,399 +1,513 @@
{
"version": "0.2.0",
"configurations": [
"version": "0.2.0",
"configurations": [
{
"name": "Spark Local",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build/gcc/debug/server/sparkd",
"args": [
"run",
"test",
"-a",
"OutrightVanillaOrder"
],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/build/gcc/debug/server/",
"environment": [
{
"name": "Spark Local",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build/ninja_debug/server/sparkd",
"args": [
"run",
"test",
"-a",
"OutrightVanillaOrder"
],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/build/ninja_debug/server/",
"environment": [
{ "name": "TZ", "value": "America/Chicago" }
],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
"name": "TZ",
"value": "America/Chicago"
}
],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "SparkVM Launch",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"-a",
"[ilink3]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
},
{
"name": "SparkVM Launch",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"args": [
"test",
"-a",
"[ilink3]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
},
{
"description": "Skip STL",
"text": "skip -gfi /usr/include/c++/7/bits/*.h",
"ignoreFailures": true
},
{
"description": "LD LIBRARY",
"text": "set env LD_LIBRARY_PATH=.",
"ignoreFailures": false
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
"description": "Skip STL",
"text": "skip -gfi /usr/include/c++/7/bits/*.h",
"ignoreFailures": true
},
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build/ninja_debug/server/sparkd/sparkd",
"args": [
"run"
],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/build/ninja_debug/src/server/sparkd",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
"description": "LD LIBRARY",
"text": "set env LD_LIBRARY_PATH=.",
"ignoreFailures": false
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "(gdb) Launch",
"type": "cppdbg",
"request": "launch",
"program": "${workspaceRoot}/build/gcc/debug/server/sparkd/sparkd",
"args": [
"run"
],
"stopAtEntry": false,
"cwd": "${workspaceRoot}/build/gcc/debug/src/server/sparkd",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
},
{
"name": "Client Launch",
"type": "clr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net471/spark.exe",
"args": [],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "SDK Launch",
"type": "clr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe",
"args": [
"md",
"GLBX",
"Future",
"CL",
"CLZ9",
"--user=bts",
"--pass="
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Excel Launch",
"type": "clr",
"request": "launch",
"program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE",
"args": [
"${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Client Tests",
"type": "clr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe",
"args": [
"test",
"ApiUpdateTests"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Client Attach",
"type": "clr",
"request": "attach",
"processId": "${command:pickProcess}"
},
{
"name": "Spreader Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"[spreader]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "MD Synthetic Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"[md][synthetic]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Spartan Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"[spartan_md]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Matcher Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"[matcher]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Admin Service Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/src/server/sparkd/sparkd",
"args": [
"test",
"[admin_service]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Limiter Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/src/server/sparkd/sparkd",
"args": [
"test",
"[limiter]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "MD Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/gcc/debug/server/sparkd",
"args": [
"test",
"[algo]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"name": "Client Launch",
"type": "coreclr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net5.0-windows/Spark.exe",
"args": ["-configserver","http://titan:8000/config"],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "SDK Launch",
"type": "clr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net471/spark_sdk.exe",
"args": [
"md",
"GLBX",
"Future",
"CL",
"CLZ9",
"--user=bts",
"--pass="
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Excel Launch",
"type": "clr",
"request": "launch",
"program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE",
"args": [
"${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Client Tests",
"type": "clr",
"request": "launch",
"program": "${workspaceRoot}/build/Debug/bin/net471/sparkcmd.exe",
"args": [
"test",
"ApiUpdateTests"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
"externalConsole": true,
"requireExactSource": false
},
{
"name": "Client Attach",
"type": "clr",
"request": "attach",
"processId": "${command:pickProcess}"
},
{
"name": "Spreader Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"args": [
"test",
"[spreader]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Admin Service Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"args": [
"test",
"[admin_service]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Limiter Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"args": [
"test",
"[limiter]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "enable pretty-printer",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "MD Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"args": [
"test",
"[algo]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
"preLaunchTask": "",
"logging": {
"engineLogging": false
},
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
},
{
"description": "Skip STL",
"text": "skip -gfi /usr/include/c++/7/bits/*.h",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "SparkVM attach",
"type": "cppdbg",
"request": "attach",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"processId": "${command:pickRemoteProcess}",
"MIMode": "gdb",
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"python": "${command:python.interpreterPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"args": [
"DEBUG"
],
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
},
{
"name": ".NET Core Remote Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickRemoteProcess}",
"pipeTransport": {
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/home/bts/vsdbg/vsdbg",
"pipeCwd": "${workspaceRoot}",
"quoteArgs": true
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
},
"justMyCode": true
},
{
"name": ".NET Core Remote Launch",
"type": "coreclr",
"request": "launch",
"program": "/usr/bin/dotnet",
"args": [
"sparkcmd.dll",
"test",
"test_join_create_and_takeout_market"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server",
"pipeTransport": {
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/home/bts/vsdbg/vsdbg",
"pipeCwd": "${workspaceRoot}",
"quoteArgs": true
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
},
"justMyCode": false
},
]
"description": "Skip STL",
"text": "skip -gfi /usr/include/c++/7/bits/*.h",
"ignoreFailures": true
}
],
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "SparkVM attach",
"type": "cppdbg",
"request": "attach",
"program": "/home/bts/spark/build/gcc/debug/src/server/sparkd/sparkd",
"processId": "${command:pickRemoteProcess}",
"MIMode": "gdb",
"pipeTransport": {
"pipeCwd": "${workspaceRoot}",
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/usr/bin/gdb"
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
}
},
{
"name": "Python",
"type": "python",
"request": "launch",
"stopOnEntry": false,
"python": "${command:python.interpreterPath}",
"program": "${file}",
"cwd": "${workspaceRoot}",
"env": {},
"envFile": "${workspaceRoot}/.env",
"args": [
"DEBUG"
],
"debugOptions": [
"WaitOnAbnormalExit",
"WaitOnNormalExit",
"RedirectOutput"
]
},
{
"name": ".NET Core Remote Attach",
"type": "coreclr",
"request": "attach",
"processId": "${command:pickRemoteProcess}",
"pipeTransport": {
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/home/bts/vsdbg/vsdbg",
"pipeCwd": "${workspaceRoot}",
"quoteArgs": true
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
},
"justMyCode": true
},
{
"name": ".NET Core Remote Launch",
"type": "coreclr",
"request": "launch",
"program": "/usr/bin/dotnet",
"args": [
"sparkcmd.dll",
"test",
"test_join_create_and_takeout_market"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/gcc/debug/server",
"pipeTransport": {
"pipeProgram": "c:\\program files\\git\\usr\\bin\\ssh.exe",
"pipeArgs": [
"bts@sparkvm"
],
"debuggerPath": "/home/bts/vsdbg/vsdbg",
"pipeCwd": "${workspaceRoot}",
"quoteArgs": true
},
"sourceFileMap": {
"/home/bts/spark/": "${workspaceRoot}"
},
"justMyCode": false
},
]
}
+40 -62
View File
@@ -1,63 +1,41 @@
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "client_build",
"type": "shell",
"command": ".\\tools\\buildspark.cmd",
"problemMatcher":"$msCompile",
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "shared"
},
"group": "build"
},
{
"label": "server_build",
"type": "shell",
"command": ".\\tools\\buildsparkd.cmd",
"problemMatcher": {
"base": "$gcc",
"owner": "cpp",
"fileLocation": [
"relative",
"${workspaceFolder}"
],
"pattern": {
"regexp": "(.?)(home)(.?)(bts)(.?)(spark)(.?)(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)",
"file": 8,
"line": 9,
"column": 10,
"severity": 11,
"message": 12
}
},
"presentation": {
"echo": true,
"reveal": "always",
"focus": false,
"panel": "new"
},
"group": {
"kind": "build",
"isDefault": true
}
},
{
"label": "linux build (Debug)",
"type": "shell",
"command": "cd build/ninja_debug; time ninja",
"group": {
"kind": "build",
"isDefault": true
},
"problemMatcher": [
"$gcc"
]
{
// See https://go.microsoft.com/fwlink/?LinkId=733558
// for the documentation about the tasks.json format
"version": "2.0.0",
"tasks": [
{
"label": "Touch CMakeLists.txt",
"type": "process",
"promptOnClose": false,
"isBackground": true,
"command": "touch",
"args": ["${workspaceRoot}/CMakeLists.txt"],
"problemMatcher": [],
"presentation": {
"echo": false,
"revealProblems": "onProblem",
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": false,
"clear": true
}
]
}
}
],
"inputs": [
{
"id": "build_configuration",
"type": "pickString",
"default": "debug",
"description": "Configuration:",
"options": ["debug", "release"]
},
{
"id": "compiler",
"type": "pickString",
"default": "gcc",
"description": "Compiler",
"options": ["clang", "gcc"]
}
]
}
+1 -1
View File
@@ -1 +1 @@
set(sources /home/ppinto/Dropbox/bts/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
set(sources /home/taha/spark/doc/user/build.sh;content/_index.md;content/bts_spark/Glossary/_index.md;content/bts_spark/Help/_index.md;content/bts_spark/Help/about_spark.png;content/bts_spark/Help/image39.png;content/bts_spark/Help/image58.png;content/bts_spark/Launcher/_index.md;content/bts_spark/Launcher/image38.png;content/bts_spark/Launcher/image68.png;content/bts_spark/Logging-In-to-the-System/_index.md;content/bts_spark/Logging-In-to-the-System/image3.png;content/bts_spark/Logging-In-to-the-System/image64.png;content/bts_spark/Market/_index.md;content/bts_spark/Market/change_securities.png;content/bts_spark/Market/image11.png;content/bts_spark/Market/image14.png;content/bts_spark/Market/image20.png;content/bts_spark/Market/image21.png;content/bts_spark/Market/image23.png;content/bts_spark/Market/image24.png;content/bts_spark/Market/image34.png;content/bts_spark/Market/image49.png;content/bts_spark/Market/image53.png;content/bts_spark/Market/image66.png;content/bts_spark/Market/image69.png;content/bts_spark/Market/market_view.png;content/bts_spark/Market/settings_icon.png;content/bts_spark/Market/time_and_sales.png;content/bts_spark/My-Windows/_index.md;content/bts_spark/My-Windows/image15.png;content/bts_spark/My-Windows/image16.png;content/bts_spark/My-Windows/image37.png;content/bts_spark/Settings/_index.md;content/bts_spark/Settings/image51.png;content/bts_spark/Settings/image9.png;content/bts_spark/Spreader/_index.md;content/bts_spark/Spreader/image10.png;content/bts_spark/Spreader/image13.png;content/bts_spark/Spreader/image18.png;content/bts_spark/Spreader/image19.png;content/bts_spark/Spreader/image28.png;content/bts_spark/Spreader/image29.png;content/bts_spark/Spreader/image31.png;content/bts_spark/Spreader/image35.png;content/bts_spark/Spreader/image40.png;content/bts_spark/Spreader/image43.png;content/bts_spark/Spreader/image54.png;content/bts_spark/Spreader/image55.png;content/bts_spark/Spreader/image56.png;content/bts_spark/Spreader/image6.png;content/bts_spark/Spreader/image7.png;content/bts_spark/Spreader/image70.png;content/bts_spark/Spreader/image72.png;content/bts_spark/Spreader/image8.png;content/bts_spark/Trading/OrderTypes/index.md;content/bts_spark/Trading/_index.md;content/bts_spark/Trading/algo_studio.png;content/bts_spark/Trading/collapse_all_icon.png;content/bts_spark/Trading/cover_algo_control.png;content/bts_spark/Trading/expand_all_icon.png;content/bts_spark/Trading/image1.png;content/bts_spark/Trading/image17.png;content/bts_spark/Trading/image2.png;content/bts_spark/Trading/image25.png;content/bts_spark/Trading/image27.png;content/bts_spark/Trading/image33.png;content/bts_spark/Trading/image42.png;content/bts_spark/Trading/image44.png;content/bts_spark/Trading/image47.png;content/bts_spark/Trading/image48.png;content/bts_spark/Trading/image5.png;content/bts_spark/Trading/image50.png;content/bts_spark/Trading/image52.png;content/bts_spark/Trading/image57.png;content/bts_spark/Trading/image59.png;content/bts_spark/Trading/image60.png;content/bts_spark/Trading/image61.png;content/bts_spark/Trading/image62.png;content/bts_spark/Trading/image73.png;content/bts_spark/Trading/image74.png;content/bts_spark/Trading/join_algo_control.png;content/bts_spark/Trading/ladder.png;content/bts_spark/Trading/ladder_badges.png;content/bts_spark/Trading/ladder_main_part.png;content/bts_spark/Trading/lean_algo_control.png;content/bts_spark/Trading/mini_orderbook.png;content/bts_spark/Trading/oco_algo_control.png;content/bts_spark/Trading/offset_algo_control.png;content/bts_spark/Trading/pnl_calculation.png;content/bts_spark/Trading/pnl_window.png;content/bts_spark/Trading/recreate_icon.png;content/bts_spark/Trading/settings_icon.png;content/bts_spark/Trading/spark_menu_order_book.png;content/bts_spark/Trading/top_algo_control.png;content/bts_spark/Trading/trigger_algo_control.png;content/bts_spark/_index.md;content/release_notes/_index.md;content/system_requirements/_index.md;static/book.js;static/favicon.ico;static/image.js;templates/index.html;templates/page.html;templates/section.html;templates/shortcodes/back_button.html)
+1 -1
View File
@@ -1 +1 @@
set(sources files/audit_ilink3.py;files/audit_upload.sh;files/audit_uploader.py;files/cert_secure_logon.txt;files/example.conf;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.APITest.xml.orig;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js;files/small_es.pcap.xz;files/spartan/create_polygon_books.sql;files/spartan/log.sql;files/spartan/md.sql;files/spartan/sim_db.sql)
set(sources files/audit_ilink3.py;files/audit_upload.sh;files/audit_uploader.py;files/cert_secure_logon.txt;files/example.conf;files/futures.coconut.xz;files/onixs_ice/ConnectivityConfiguration.APITest.xml;files/onixs_ice/ConnectivityConfiguration.PerfTest.xml;files/onixs_ice/ConnectivityConfiguration.Production.xml;files/perf_trace/compiled.css;files/perf_trace/index.html;files/perf_trace/jquery-3.3.1.min.js;files/perf_trace/main.js;files/perf_trace/perf_log.sql;files/perf_trace/perf_trace_analysis.sql;files/perf_trace/plotly-latest.min.js;files/small_es.pcap.xz;files/spartan/create_polygon_books.sql;files/spartan/log.sql;files/spartan/md.sql;files/spartan/sim_db.sql)
+1 -1
View File
@@ -1 +1 @@
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/AlgoTypes.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spartan.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokerProxy.cpp;mercury/broker/ILocalBroker.cpp;mercury/broker/IRemoteBroker.cpp;mercury/common/mercury_common.cpp;mercury/events/TimerEvent.cpp;mercury/executor/ExecutoLine truncated
set(sources api/apicore.proto;api/apigateway.proto;api/apioptions.proto;api/core/ApiClientInterop.cpp;api/core/ApiServerInterop.cpp;api/public/ApiServer.cpp;api/public/ClientChannel.cpp;api/public/QuickbusClientChannel.cpp;api/public/ServerChannel.cpp;api/public/ServiceContext.cpp;api/service_helpers/AdminServiceUtils.cpp;api/service_helpers/AlgoServiceUtils.cpp;api/service_helpers/PositionUtilities.cpp;api/services/AdminService.proto;api/services/AlgoDefinitionService.proto;api/services/AlgoService.proto;api/services/ApiUnitTestService.proto;api/services/AuthService.proto;api/services/BasePositionService.proto;api/services/ErrorReportService.proto;api/services/HelloService.proto;api/services/MBOService.proto;api/services/MarginService.proto;api/services/MarketDataAuxiliaryService.proto;api/services/MarketDataRelay.proto;api/services/MarketDataService.proto;api/services/MoneyFileService.proto;api/services/OrderService.proto;api/services/OutOfProcessURLListener.proto;api/services/PersistenceService.proto;api/services/PositionService.proto;api/services/ShellDiagnosticService.proto;api/services/ShellLatencyService.proto;api/services/SyntheticSecurityService.proto;api/test/ApiTests.cpp;api/test/HelloServiceServer.cpp;communincation/websockets/WebsocketClient.cpp;communincation/websockets/tests/WebsocketClientTests.cpp;communincation/websockets/tests/WebsocketSyncClientTests.cpp;config/ConfigCheck.cpp;config/ConfigDownloader.cpp;config/ConfigErrorCollector.cpp;config/ConfigLog.cpp;config/ConfigPropertyEvaluator.cpp;config/ConfigValueQueue.cpp;config/ConfigurationException.cpp;config/ConfigurationState.cpp;config/PreprocessInputStream.cpp;config/config.cpp;config/defaults/MarketData.conf;config/defaults/Ports.conf;config/defaults/Symbols.conf;config/defaults/cme_reference_data.conf;config/defaults/edge.conf;config/defaults/jetfix.conf;config/defaults/keycode.conf;config/defaults/logging.conf;config/defaults/orderman_cfg.conf;config/defaults/orders_fills_cleanup.conf;config/defaults/position_cfg.conf;config/defaults/span.conf;config/defaults/spreader.conf;config/defaults/testkeys.conf;config/defaults/threads.conf;config/defaults/toggles.conf;config/extensions/extensions.proto;config/invalid/invalid.proto;config/protos/AlgoTypes.proto;config/protos/ExchangeSimCfg.proto;config/protos/MarketData.proto;config/protos/Ports.proto;config/protos/Symbols.proto;config/protos/UI.proto;config/protos/cme_reference_data.proto;config/protos/jetfix.proto;config/protos/keycode.proto;config/protos/logging.proto;config/protos/mercury_cfg.proto;config/protos/orderman_cfg.proto;config/protos/orders_fills_cleanup.proto;config/protos/perflog_cfg.proto;config/protos/position_cfg.proto;config/protos/quickbus_cfg.proto;config/protos/span.proto;config/protos/spartan.proto;config/protos/spreader.proto;config/protos/subprocess.proto;config/protos/system.proto;config/protos/testkeys.proto;config/protos/threads.proto;config/protos/toggles.proto;config/tests/HTTPServer.cpp;config/tests/config_ref_tests.cpp;config/tests/config_tests.cpp;config/text_format/text_format.cpp;domain_model/Security.cpp;domain_model/Security.proto;domain_model/SecurityTests.cpp;domain_model/sod.cpp;domain_model/tests/domain_tests.cpp;expression/BooleanGrammar.cpp;expression/ExpressionEvaluator.cpp;expression/ParserExceptions.cpp;expression/Value.cpp;expression/tests/expression_parser_tests.cpp;jetfix/codec/FIXArray.cpp;jetfix/common/OutFIX.cpp;jetfix/connection/AsyncReader.cpp;jetfix/connection/IConnection.cpp;jetfix/connection/SocketConnection.cpp;jetfix/gateway/CoreGateway.cpp;jetfix/gateway/JetFIXGateway.cpp;jetfix/gateway/Session.cpp;jetfix/store/FIXFileStore.cpp;jetfix/store/session_name.cpp;jetfix/tests/async_reader_tests.cpp;jetfix/tests/decoding_tests.cpp;jetfix/tests/fix_encoding_stream_tests.cpp;jetfix/tests/fix_fragment_tests.cpp;jetfix/tests/jetfix_performance_tests.cpp;jetfix/tests/sample_fix.cpp;jetfix/tests/store_tests.cpp;logging/LoggerHub.cpp;logging/Sink.cpp;logging/logging.cpp;logging/tests/logging_tests.cpp;md/Diag/MDPeriodicDumper.cpp;md/Diag/ShmDumper.cpp;md/MBOProcessor.cpp;md/MBOServiceServer.cpp;md/MDClient.cpp;md/MDConsumer.cpp;md/MDConsumerHandle.cpp;md/MDConsumerInterop.cpp;md/MDProducer.cpp;md/MDProducerHandle.cpp;md/MemorySegmentUtils.cpp;md/PlatformLoader.cpp;md/PriceSize.cpp;md/Product.cpp;md/SecurityCache.cpp;md/SecurityDB.cpp;md/SecurityIDRecorder.cpp;md/SecurityMapper.cpp;md/SecurityOracle.cpp;md/SettlementRecorder.cpp;md/Shm/FixedSecurity.cpp;md/SyntheticSecurityService.cpp;md/cme/MDP3Utils.cpp;md/common.cpp;md/ice/ICEUtils.cpp;md/protos/co2.proto;md/relay/QueryServer.cpp;md/relay/RelayClient.cpp;md/relay/RelayRecorder.cpp;md/service/MarketDataServiceServer.cpp;md/test/Co2ManagedTestHelper.cpp;md/test/Co2TestInstrument.cpp;md/test/mbo_tests.cpp;md/test/md2_tests.cpp;md/test/md_test_utils.cpp;md/test/synthetic_book_merge_tests.cpp;md/vendor/OnixsUtils.cpp;mercury/actors/IPollableActor.cpp;mercury/broker/Broker.cpp;mercury/broker/BrokeLine truncated
-1
View File
@@ -138,7 +138,6 @@ else ()
Common++
ssh2
-lrt
-liml
-ldl
-lpcap
-static-libgcc
+8
View File
@@ -0,0 +1,8 @@
syntax = "proto3";
package bts.api.domain;
enum Currency {
BTC = 0;
ETH = 1;
USD = 3;
}
+10
View File
@@ -0,0 +1,10 @@
syntax = "proto3";
package bts.api.domain;
enum SecurityType {
UNSET = 0;
INDEX = 1;
FUTURE = 2;
SPREAD = 3;
OPTION = 4;
}
+17
View File
@@ -0,0 +1,17 @@
syntax = "proto3";
package bts.api.domain;
// IMPORTANT: Don't change the int value of any enum entries!
// The exchange enum value is encoded in the first 32 bits of our internal
// security keys. The remaining 32 bits (as the key is 64 bits) is then
// used to uniquely identify a security within an exchange context. For
// cross-exchange integration, it might be useful to associate an exchange
// with a security id.
enum Venue {
NONE = 0;
GLBX = 1;
DERIBIT = 2;
HUOBI = 3;
BINANCE = 4;
FTX = 5;
}
+15
View File
@@ -0,0 +1,15 @@
syntax = "proto3";
package bts.api.io;
message QueryParam {
string key = 1;
string value = 2;
}
message URL {
string protocol = 1;
string host = 2;
uint32 port = 3;
string path = 4;
repeated QueryParam query_params = 5;
}
@@ -0,0 +1,19 @@
syntax = "proto3";
import "lib/api/md/binance/BinanceMarketDataSubscriptionParams.proto";
import "lib/api/md/deribit/DeribitMarketDataSubscriptionParams.proto";
import "lib/api/md/ftx/FTXMarketDataSubscriptionParams.proto";
import "lib/api/md/glbx/GlbxMarketDataSubscriptionParams.proto";
import "lib/api/md/huobi/HuobiMarketDataSubscriptionParams.proto";
package bts.api.md;
message MarketDataSubscriptionParams {
oneof VenueParams {
bts.api.md.glbx.GlbxMarketDataSubscriptionParams glbx = 1;
bts.api.md.deribit.DeribitMarketDataSubscriptionParams deribit = 2;
bts.api.md.binance.BinanceMarketDataSubscriptionParams binance = 3;
bts.api.md.huobi.HuobiMarketDataSubscriptionParams huobi = 4;
bts.api.md.ftx.FTXMarketDataSubscriptionParams ftx = 5;
}
}
@@ -0,0 +1,19 @@
syntax = "proto3";
import "lib/api/io/URL.proto";
package bts.api.md.binance;
message BinanceDepthStreamParams {
bts.api.io.URL stream_url = 1;
bts.api.io.URL snapshot_url = 2;
repeated string symbols = 3;
// The number of book levels to observe. At the time of writing this comment,
// valid values are 1, 5, 10, 100, 1000, or unlimited (represented by 0).
// Check the binance api docs for updates.
uint32 num_levels = 4;
}
message BinanceMarketDataSubscriptionParams {
repeated BinanceDepthStreamParams depth_streams = 2;
}
@@ -0,0 +1,7 @@
syntax = "proto3";
package bts.api.md.deribit;
message DeribitMarketDataSubscriptionParams {
// TODO
}
@@ -0,0 +1,7 @@
syntax = "proto3";
package bts.api.md.ftx;
message FTXMarketDataSubscriptionParams {
// TODO
}
@@ -0,0 +1,7 @@
syntax = "proto3";
package bts.api.md.glbx;
message GlbxMarketDataSubscriptionParams {
// TODO
}
@@ -0,0 +1,7 @@
syntax = "proto3";
package bts.api.md.huobi;
message HuobiMarketDataSubscriptionParams {
// TODO
}
+1 -1
View File
@@ -1,4 +1,4 @@
#!/usr/bin/python
#!/usr/bin/env python
import os, sys
from collections import namedtuple
@@ -26,7 +26,7 @@ type {{name}} = unit
{{else}}
[<Pojo>]
type {{name}} =
{
{
{{#each field}}
{{#if type.isdict}}
{{fsescape nAme}} : JSMap<{{type.fstype}}>
@@ -99,4 +99,4 @@ module {{name}} =
)
|> unbox
{{/each}}
{{/each}}
+159
View File
@@ -0,0 +1,159 @@
#pragma once
#include <range/v3/view.hpp>
#include <range/v3/view/transform.hpp>
#include <string>
#include <variant>
#include <vector>
namespace bts::collections {
template <class Key, class Value>
class FlatUnorderedMap {
public:
using Container = std::vector<std::pair<std::string, std::string>>;
using Iterator = Container::iterator;
using ConstIterator = Container::const_iterator;
using ReverseIterator = Container::reverse_iterator;
using ConstReverseIterator = Container::const_reverse_iterator;
Value *get(const Key &key);
const Value *get(const Key &key) const;
template <class... Args>
std::pair<Iterator, bool> try_emplace(const Key &key, Args... args);
Iterator begin();
ConstIterator begin() const;
ReverseIterator rbegin();
ConstReverseIterator rbegin() const;
Iterator end();
ConstIterator end() const;
ReverseIterator rend();
ConstReverseIterator rend() const;
bool empty() const;
std::size_t size() const;
Value &operator[](const Key &key);
private:
std::vector<std::pair<std::string, std::string>> items_;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class Key, class Value>
Value *FlatUnorderedMap<Key, Value>::get(const Key &key) {
for (auto &qp : items_) {
if (qp.first == key) {
return &qp.second;
}
}
return nullptr;
}
template <class Key, class Value>
const Value *FlatUnorderedMap<Key, Value>::get(const Key &key) const {
for (auto &qp : items_) {
if (qp.first == key) {
return &qp.second;
}
}
return nullptr;
}
// template <class Key, class Value>
// std::pair<typename FlatUnorderedMap<Key, Value>::Iterator, bool>
// FlatUnorderedMap<Key, Value>::try_emplace(const Key &key) {
// for (auto it = items_.begin(); it != items_.end(); it++) {
// if (it->first == key) {
// return {it, false};
// }
// }
// return items_.emplace_back(key);
// }
template <class Key, class Value>
template <class... Args>
std::pair<typename FlatUnorderedMap<Key, Value>::Iterator, bool>
FlatUnorderedMap<Key, Value>::try_emplace(const Key &key, Args... args) {
for (auto it = items_.begin(); it != items_.end(); it++) {
if (it->first == key) {
return {it, false};
}
}
Value v(args...);
items_.emplace_back(key, std::move(v));
return {items_.end() - 1, true};
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::Iterator
FlatUnorderedMap<Key, Value>::begin() {
return items_.begin();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ConstIterator
FlatUnorderedMap<Key, Value>::begin() const {
return items_.begin();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ReverseIterator
FlatUnorderedMap<Key, Value>::rbegin() {
return items_.rbegin();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ConstReverseIterator
FlatUnorderedMap<Key, Value>::rbegin() const {
return items_.rbegin();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::Iterator
FlatUnorderedMap<Key, Value>::end() {
return items_.end();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ConstIterator
FlatUnorderedMap<Key, Value>::end() const {
return items_.end();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ReverseIterator
FlatUnorderedMap<Key, Value>::rend() {
return items_.rend();
}
template <class Key, class Value>
typename FlatUnorderedMap<Key, Value>::ConstReverseIterator
FlatUnorderedMap<Key, Value>::rend() const {
return items_.rend();
}
template <class Key, class Value>
bool FlatUnorderedMap<Key, Value>::empty() const {
return items_.empty();
}
template <class Key, class Value>
std::size_t FlatUnorderedMap<Key, Value>::size() const {
return items_.size();
}
template <class Key, class Value>
Value &FlatUnorderedMap<Key, Value>::operator[](const Key &key) {
return try_emplace(key).first->second;
}
} // namespace bts::collections
@@ -0,0 +1,201 @@
// #include "./root_certificates.hpp"
#include <boost/asio/ssl.hpp>
#include <boost/beast/core.hpp>
// #include <boost/beast/example/common/root_certificates.hpp>
#include <boost/beast/ssl.hpp>
#include <boost/beast/websocket.hpp>
#include <boost/beast/websocket/ssl.hpp>
#include <boost/asio/connect.hpp>
#include <boost/asio/ip/tcp.hpp>
#include <boost/asio/ssl/stream.hpp>
#include <catch/catch.hpp>
#include <cstdlib>
#include <functional>
#include <iostream>
#include <memory>
#include <string>
#include <thread>
namespace beast = boost::beast; // from <boost/beast.hpp>
namespace http = beast::http; // from <boost/beast/http.hpp>
namespace websocket = beast::websocket; // from <boost/beast/websocket.hpp>
namespace net = boost::asio; // from <boost/asio.hpp>
namespace ssl = boost::asio::ssl; // from <boost/asio/ssl.hpp>
using tcp = boost::asio::ip::tcp; // from <boost/asio/ip/tcp.hpp>
// Class to connect to a websocket endpoint and receive data continuously
// counterparty closes or stopped manually
class WebSocketSession : public std::enable_shared_from_this<WebSocketSession> {
net::io_context &_ioContext;
ssl::context &_sslContext;
tcp::resolver _tcpResolver;
std::shared_ptr<websocket::stream<beast::ssl_stream<tcp::socket>>> _ws;
beast::flat_buffer _buffer;
std::string _host;
char const *_port;
std::string _target;
std::string _hostAndPort;
std::string _text;
tcp::endpoint _tcpEndPoint;
bool _terminate = false;
void ConnectAndReceive() {
// Look up the domain name
auto const tcpResolverResults = _tcpResolver.resolve(_host, _port);
// Make the connection on the IP address we get from a lookup
_tcpEndPoint = net::connect(get_lowest_layer(*_ws), tcpResolverResults);
// Set SNI Hostname (many hosts need this to handshake successfully)
if (!SSL_set_tlsext_host_name(
_ws->next_layer().native_handle(), _host.c_str())) {
throw beast::system_error(
beast::error_code(
static_cast<int>(::ERR_get_error()),
net::error::get_ssl_category()),
"Failed to set SNI Hostname");
}
// Update the _host string. This will provide the value of the
// Host HTTP header during the WebSocket handshake.
// See https://tools.ietf.org/html/rfc7230#section-5.4
_hostAndPort = _host + ':' + std::to_string(_tcpEndPoint.port());
std::cout << "_hostAndPort:" << _hostAndPort << std::endl;
// Perform the SSL handshake
_ws->next_layer().handshake(ssl::stream_base::client);
// Set a decorator to change the User-Agent of the handshake
_ws->set_option(
websocket::stream_base::decorator([](websocket::request_type &req) {
req.set(
http::field::user_agent,
std::string(BOOST_BEAST_VERSION_STRING) +
" websocket-client-coro");
}));
// Perform the websocket handshake
std::cout << "sending handshake, _hostAndPort:" << _hostAndPort
<< " _target:" << _target << std::endl;
_ws->handshake(_hostAndPort, _target);
// Read Messages
try {
while (true) // expect to read continuously until a connection failure
{
if (!_terminate) {
_ws->read(_buffer);
if (_buffer.size() > 0) {
std::cout << beast::make_printable(_buffer.data())
<< std::endl;
}
_buffer.clear();
} else {
_ws->close(boost::beast::websocket::close_code::normal);
}
}
} catch (beast::system_error const &se) {
if (se.code() == websocket::error::closed) {
std::cout << "socket was closed." << std::endl;
} else {
std::cout << "exception: " << se.code() << ", "
<< se.code().message() << ", " << se.what();
}
} catch (std::exception &ex) {
std::cout << "exception: " << ex.what();
}
}
public:
// Resolver and socket require an io_context
explicit WebSocketSession(
net::io_context &ioc,
ssl::context &ctx,
char const *host,
char const *port,
char const *target)
: _ioContext(ioc), _sslContext(ctx), _tcpResolver(_ioContext),
_host(host), _port(port), _target(target), _hostAndPort() {}
void Stop() { _terminate = true; }
void Start() {
while (!_terminate) {
_ws = std::make_shared<
websocket::stream<beast::ssl_stream<tcp::socket>>>(
_ioContext, _sslContext);
try {
ConnectAndReceive(); // initalizes websocket and polls continuously
// for messages until socket closed or an
// exception occurs
} catch (beast::system_error const &se) {
std::cout << "exception: " << se.code() << ", "
<< se.code().message() << std::endl;
// Sleep(1000); // just wait a little while to not spam
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
}
_ws.reset();
}
// if we get to here process has been terminated
}
};
//------------------------------------------------------------------------------
TEST_CASE("WebsocketSyncClientTest", "[ws_ssl]") {
return;
auto host = "stream.binance.com";
auto port = "9443";
auto target = "/ws/btcusdt@depth@100ms"; // bitcoin full order book endpoint,
// 100ms updates
// auto text = "";
// The io_context is required for all I/O
net::io_context ioc;
// The SSL context is required, and holds certificates
ssl::context ctx{ssl::context::tlsv12_client};
ctx.set_verify_mode(ssl::verify_none);
// This holds the root certificate used for verification
// boost::asio::ssl::load_root_certificates(ctx);
// Run the I/O service. The call will return when
// the socket is closed.
ioc.run();
std::string inputStr;
std::thread t;
std::shared_ptr<WebSocketSession> websocketSession;
while (inputStr != "x") {
std::cout << "Press 'r' to run. Press 's' to stop. Press 'x' to Exit."
<< std::endl;
std::cin >> inputStr;
if (inputStr == "r") { // run
if (websocketSession.use_count() == 0) { // should not run twice
t = std::thread(
[&websocketSession, &ioc, &ctx, host, port, target] {
websocketSession = std::make_shared<WebSocketSession>(
ioc, ctx, host, port, target);
websocketSession->Start(); // within a thread so doesn't
// block
});
}
} else if (inputStr == "s" || inputStr == "x") { // stop & exit
if (websocketSession.use_count()) { // running
websocketSession->Stop();
t.join();
t.~thread();
websocketSession.reset();
}
}
}
}
-10
View File
@@ -70,16 +70,6 @@ SymbolLists
list
{
key: "ICE"
symbol: "BRN"
symbol: "WBS"
symbol: "OJ"
symbol: "G"
symbol: "KC"
symbol: "UHO"
symbol: "UHU"
symbol: "DX"
symbol: "*"
}
list
{
+7
View File
@@ -0,0 +1,7 @@
syntax='proto3';
package bts.config;
import "lib/api/md/MarketDataSubscriptionParams.proto";
message CryptoConfig {
repeated bts.api.md.MarketDataSubscriptionParams crypto_md = 1;
}
+1
View File
@@ -8,6 +8,7 @@
#include <boost/asio/read_until.hpp>
#include <boost/asio/streambuf.hpp>
#include <boost/asio/write.hpp>
#define BOOST_BIND_GLOBAL_PLACEHOLDERS
#include <boost/bind.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/scoped_ptr.hpp>
+1 -1
View File
@@ -351,7 +351,7 @@ TEST_CASE("Configuration Tests", "[config]") {
" \xA0 }"
"} ",
false);
} catch (const bts::config::ConfigurationException) {
} catch (const bts::config::ConfigurationException &) {
parse_error = true;
}
REQUIRE(parse_error);
+15
View File
@@ -0,0 +1,15 @@
#pragma once
#define BITWISE_OP(enum_type, numeric_type, op) \
enum_type operator op(enum_type lhs, enum_type rhs) noexcept { \
return static_cast<enum_type>(static_cast<numeric_type>(lhs) \
op static_cast<numeric_type>(rhs)); \
}
#define BITWISE_OPS(enum_type, numeric_type) \
BITWISE_OP(enum_type, numeric_type, |) \
BITWISE_OP(enum_type, numeric_type, &) \
BITWISE_OP(enum_type, numeric_type, ^)
#define HAS_FLAG(enum_value, flag) (enum_value & flag) == flag
#define STRIP_FLAG(enum_value, flag) (enum_value | flag) ^ flag
+220
View File
@@ -0,0 +1,220 @@
#pragma once
#include <cstddef>
#include <cstdint>
#include <functional>
#include <limits>
namespace bts::core {
/**
* Provides facilities to combine multiple hash codes into a single hash code.
*
* @remarks Employs techniques, such as modular arithmetic and bitwise shifts,
* to minimize and evenly distribute information loss to the [multiple] input
* hash codes in the [singular] output hash code.
*/
class HashPhaser {
public:
/**
* Combines the hash codes of several parameters into a single hash code.
*
* @param value One of the parameters whose hash to store
* @param next The other parameters whose hash to store
*
* @remarks A well-chosen modulus of each parameter's hash is stored in
* equally sized blocks of bits.
*/
template <class T, class... NextT>
static std::size_t auto_phase(T value, NextT... next);
/**
* Combines the hash codes of a limited number of elements into a single hash
* code.
*
* @param first Iterator pointing to the first element whose hash to store
* @param last Iterator pointing just after the last element whose hash to
* store
*
* @remarks A well-chosen modulus of each value's hash is stored in equally
* sized blocks of bits
*/
template <class Iter>
static std::size_t auto_phase_range(Iter first, Iter last);
/**
* Combines the hash codes of a limited number of elements into a single hash
* code.
*
* @param first Iterator pointing to the first element whose hash to store
* @param last Iterator pointing just after the last element whose hash to
* store
* @param hash The hash op to use
*
* @overload
*/
template <class Iter, class Hash>
static std::size_t auto_phase_range(Iter first, Iter last, Hash hash);
/**
* Combines the hash codes of several parameters into a single composite hash
* code.
*
* @param value One of the parameters whose hash to store
* @param hash_op The hash code operator to use for the 'value' parameter
* @param next The other parameters whose hash to store
*
* @remarks A well-chosen modulus of each parameter's hash is stored in
* equally sized blocks of bits.
*/
template <class T, class HashOp, class... NextT>
static std::size_t custom_phase(T value, HashOp hash_op, NextT... next);
private:
template <class T, class... NextT>
static void _auto_phase(
std::size_t &hash, std::uint16_t &depth, T value, NextT... next);
template <class T>
static void _auto_phase(std::size_t &hash, std::uint16_t &depth, T value);
template <class T, class HashOp, class... NextT>
static void _custom_phase(
std::size_t &hash, std::uint16_t &depth, T value, HashOp, NextT... next);
template <class T, class HashOp>
static void _custom_phase(
std::size_t &hash, std::uint16_t &depth, T value, HashOp);
/**
* Get the result of std::hash<T>()(value) without having to declare the
* template parameter T explicitly (helpful when using 'auto' variables).
*/
template <class T>
static std::size_t _default_hash(T value);
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class T, class HashOp, class... NextT>
std::size_t HashPhaser::custom_phase(T value, HashOp hash_op, NextT... next) {
std::size_t res = 0;
std::uint16_t depth = 0;
HashPhaser::_custom_phase(res, depth, value, hash_op, next...);
return res;
}
template <class T, class... NextT>
std::size_t HashPhaser::auto_phase(T value, NextT... next) {
std::size_t res = 0;
std::uint16_t depth = 0;
HashPhaser::_auto_phase(res, depth, value, next...);
return res;
}
template <class T>
inline std::size_t HashPhaser::_default_hash(T value) {
return std::hash<T>()(value);
}
template <class Iter>
std::size_t HashPhaser::auto_phase_range(Iter first, Iter last) {
if (first == last) {
return 0;
}
const std::uint16_t max_els = 8;
auto num_vals = std::distance(first, last);
std::uint16_t el_count =
num_vals > std::numeric_limits<std::uint16_t>::max()
? max_els
: std::max(static_cast<std::uint16_t>(num_vals), max_els);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / el_count;
std::size_t phase = 1U << (bits_per_hash - 1);
std::size_t composite_hash = 0;
auto el_rem = el_count;
while (first != last) {
std::size_t val_hash = _default_hash(*first);
composite_hash |= (val_hash % phase) << ((el_count - 1) * bits_per_hash);
if (--el_rem == 0) {
break;
}
}
return composite_hash;
}
template <class Iter, class Hash>
std::size_t HashPhaser::auto_phase_range(Iter first, Iter last, Hash hash) {
if (first == last) {
return 0;
}
const std::uint16_t max_els = 8;
auto num_vals = std::distance(first, last);
std::uint16_t el_count =
num_vals > std::numeric_limits<std::uint16_t>::max()
? max_els
: std::max(static_cast<std::uint16_t>(num_vals), max_els);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / el_count;
std::size_t phase = 1U << (bits_per_hash - 1);
std::size_t composite_hash = 0;
auto el_rem = el_count;
while (first != last) {
std::size_t val_hash = hash(*first);
composite_hash |= (val_hash % phase) << ((el_count - 1) * bits_per_hash);
if (--el_rem == 0) {
break;
}
}
return composite_hash;
}
template <class T, class... NextT>
void HashPhaser::_auto_phase(
std::size_t &composite_hash, std::uint16_t &depth, T value, NextT... next) {
auto m_depth = depth++;
_auto_phase(composite_hash, depth, next...);
auto val_hash = std::hash<T>()(value);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth;
std::size_t phase = 1U << (bits_per_hash - 1);
composite_hash |= (val_hash % phase) << (m_depth * bits_per_hash);
}
template <class T>
void HashPhaser::_auto_phase(
std::size_t &composite_hash, std::uint16_t &depth, T value) {
depth++;
std::size_t val_hash = std::hash<T>()(value);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth;
std::size_t phase = 1U << (bits_per_hash - 1);
composite_hash |= (val_hash % phase) << ((depth - 1) * bits_per_hash);
}
template <class T, class HashOp, class... NextT>
void HashPhaser::_custom_phase(
std::size_t &composite_hash,
std::uint16_t &depth,
T value,
HashOp hash_op,
NextT... next) {
auto m_depth = depth++;
_custom_phase(composite_hash, depth, next...);
auto val_hash = hash_op(value);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth;
std::size_t phase = 1U << (bits_per_hash - 1);
composite_hash |= (val_hash % phase) << (m_depth * bits_per_hash);
}
template <class T, class HashOp>
void HashPhaser::_custom_phase(
std::size_t &composite_hash,
std::uint16_t &depth,
T value,
HashOp hash_op) {
depth++;
std::size_t val_hash = hash_op(value);
auto bits_per_hash = (sizeof(std::size_t) * __CHAR_BIT__) / depth;
std::size_t phase = 1U << (bits_per_hash - 1);
composite_hash |= (val_hash % phase) << ((depth - 1) * bits_per_hash);
}
} // namespace bts::core
+54
View File
@@ -0,0 +1,54 @@
#pragma once
#include <google/protobuf/text_format.h>
#include <iostream>
namespace bts::core {
template <class T>
class ProtoPrinter {
public:
explicit ProtoPrinter(const T *message) noexcept;
static void print(const T &message, std::ostream &out = std::cout);
const T *message;
};
template <class T>
std::ostream &operator<<(
std::ostream &out, const ProtoPrinter<T> &printer) noexcept;
class ProtoPrinterFactory {
public:
template <class T>
static ProtoPrinter<T> create(const T *message);
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class T>
ProtoPrinter<T>::ProtoPrinter(const T *message) noexcept : message(message) {}
template <class T>
void ProtoPrinter<T>::print(const T &message, std::ostream &out) {
std::string str;
google::protobuf::TextFormat::PrintToString(message, &str);
out << str;
}
template <class T>
ProtoPrinter<T> ProtoPrinterFactory::create(const T *message) {
return ProtoPrinter<T>(message);
}
template <class T>
std::ostream &operator<<(
std::ostream &out, const ProtoPrinter<T> &printer) noexcept {
std::string str;
google::protobuf::TextFormat::PrintToString(*printer.message, &str);
out << str;
return out;
}
} // namespace bts::core
+27
View File
@@ -0,0 +1,27 @@
#pragma once
#include <cstdint>
namespace bts::core {
// I can send this whole class later but its a nice wrapper around the linux
// posix time
struct TimeStamp {
public:
constexpr TimeStamp() = default;
explicit constexpr TimeStamp(std::uint64_t value);
constexpr std::uint64_t nanos() const;
private:
// posix time
std::uint64_t value_{};
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr TimeStamp::TimeStamp(std::uint64_t value) : value_(value) {}
constexpr std::uint64_t TimeStamp::nanos() const { return value_; }
} // namespace bts::core
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
namespace bts::core {
template <class Tag, class ValueT>
using ValueWrapper = utils::ValueWrapper<Tag, ValueT>;
} // namespace bts::core
+56
View File
@@ -0,0 +1,56 @@
#pragma once
#include <unordered_map>
#include <vector>
namespace bts::core {
class VectorAdapter {
public:
template <class InT, class OutT, class Op>
static std::vector<OutT> to(const std::vector<InT> &source, Op op);
template <class T>
static std::vector<const T *> to_const_pointers(
const std::vector<T> &source);
template <class K, class V>
static std::vector<V> copy_values(const std::unordered_map<K, V> &source);
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class InT, class OutT, class Op>
std::vector<OutT> VectorAdapter::to(const std::vector<InT> &source, Op op) {
std::vector<OutT> result;
result.reserve(source.size());
for (const auto &value : source) {
result.push_back(op(value));
}
return result;
}
template <class T>
std::vector<const T *> VectorAdapter::to_const_pointers(
const std::vector<T> &source) {
std::vector<const T *> ptrs;
ptrs.reserve(source.size());
for (const auto &value : source) {
ptrs.push_back(&value);
}
return ptrs;
}
template <class K, class V>
std::vector<V> VectorAdapter::copy_values(
const std::unordered_map<K, V> &source) {
std::vector<V> values;
values.reserve(source.size());
for (const auto &p : source) {
values.push_back(p.second);
}
return values;
}
} // namespace bts::core
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
#include <cstdint>
namespace bts::domain {
using AccountID = utils::ValueWrapper<struct AccountIDTag, std::uint64_t>;
} // namespace bts::domain
+11
View File
@@ -0,0 +1,11 @@
#include "AggressorSide.h"
namespace bts::domain {
std::ostream &operator<<(
std::ostream &out, const AggressorSide &value) noexcept {
out << value.name();
return out;
}
} // namespace bts::domain
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include <ostream>
namespace bts::domain {
class AggressorSide {
public:
enum Value { None = 0, Buy = 1, Sell = 2 };
Value value;
constexpr const char *name() const noexcept;
};
std::ostream &operator<<(
std::ostream &out, const AggressorSide &value) noexcept;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr const char *AggressorSide::name() const noexcept {
switch (value) {
case AggressorSide::None:
return "None";
case AggressorSide::Buy:
return "Buy";
case AggressorSide::Sell:
return "Sell";
default:
return "Unknown";
}
}
} // namespace bts::domain
+165
View File
@@ -0,0 +1,165 @@
#pragma once
#include "BookLevel.h"
#include "BookLevelComp.h"
#include "BookSide.h"
#include "SecurityID.h"
#include "Side.h"
#include <boost/container/small_vector.hpp>
namespace bts::domain {
template <class BS>
class BookT {
public:
[[nodiscard]] static constexpr BookT<BS> empty() noexcept;
[[nodiscard]] static constexpr BookT<BS> empty(
SecurityID security_id) noexcept;
[[nodiscard]] static constexpr size_t max_depth();
[[nodiscard]] constexpr std::size_t size() const noexcept;
[[nodiscard]] SecurityID security_id() const;
void set_security_id(SecurityID);
template <class OtherBook>
void merge_with(OtherBook const &b);
void clear_to_end(std::size_t level = 0);
void clear_after_empty();
[[nodiscard]] bool is_sorted() const;
template <class OtherBook>
static BookT merge(BookT const & /*b1*/, OtherBook const & /*b2*/);
void reset_merged_quantity();
void reset_n_orders();
template <class Container>
void apply_changes(Side side, const Container &changes);
/**
* Removes price levels of the non-dominant side that cross the dominant
* side
*/
void remove_crosses(Side dominant_side);
BS &operator[](Side s);
const BS &operator[](Side s) const;
bool operator==(BookT const &rhs) const;
private:
SecurityID _security_id;
std::array<BS, 2> _books;
};
using Book = BookT<BookSide>;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <class BS>
constexpr BookT<BS> BookT<BS>::empty() noexcept {
// Be sure to change the impl if BookLevel is optimized such that
// the quantity no longer defaults to 0.
return {};
}
template <class BS>
constexpr BookT<BS> BookT<BS>::empty(SecurityID security_id) noexcept {
// Be sure to change the impl if BookLevel is optimized such that
// the quantity no longer defaults to 0.
auto rv = BookT<BS>::empty();
rv.set_security_id(security_id);
return rv;
}
template <class BS>
constexpr std::size_t BookT<BS>::max_depth() {
return BS::max_depth();
}
template <class BS>
constexpr std::size_t BookT<BS>::size() const noexcept {
return _books.size();
}
template <class BS>
SecurityID BookT<BS>::security_id() const {
return _security_id;
}
template <class BS>
void BookT<BS>::set_security_id(SecurityID id) {
_security_id = id;
}
template <class BS>
inline BS &BookT<BS>::operator[](Side s) {
return _books[s.as_index()];
}
template <class BS>
inline const BS &BookT<BS>::operator[](Side s) const {
return _books[s.as_index()];
}
template <class BS>
inline bool BookT<BS>::operator==(BookT const &rhs) const {
return _books == rhs._books;
}
template <class BS>
template <class OtherBook>
void BookT<BS>::merge_with(OtherBook const &b) {
operator[](Side::Buy).merge_with(Side::Buy, b[Side::Buy]);
operator[](Side::Sell).merge_with(Side::Sell, b[Side::Sell]);
}
template <class BS>
template <class OtherBook>
BookT<BS> BookT<BS>::merge(BookT const &b1, OtherBook const &b2) {
auto result = b1;
result.merge_with(b2);
return result;
}
template <class BS>
void BookT<BS>::reset_merged_quantity() {
Side::foreach ([&](Side s) { operator[](s).reset_merged_quantity(); });
}
template <class BS>
void BookT<BS>::reset_n_orders() {
Side::foreach ([&](Side s) { operator[](s).reset_n_orders(); });
}
template <class BS>
void BookT<BS>::remove_crosses(Side dominant_side) {
(*this)[dominant_side.other()].remove_crosses(
dominant_side.other(), (*this)[dominant_side][0].price);
}
template <class BS>
void BookT<BS>::clear_to_end(std::size_t level) {
Side::foreach ([&](Side s) {
operator[](s).clear_to_end(static_cast<std::uint8_t>(level));
});
}
template <class BS>
void BookT<BS>::clear_after_empty() {
Side::foreach ([&](Side s) { operator[](s).clear_after_empty(); });
}
template <class BS>
bool BookT<BS>::is_sorted() const {
return Side::forboth([&](Side s) { return operator[](s).is_sorted(s); });
}
template <class BS>
template <class Container>
void BookT<BS>::apply_changes(Side side, const Container &changes) {
_books[static_cast<std::size_t>(side.value)].apply_changes(side, changes);
}
} // namespace bts::domain
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include "Price.h"
#include "Quantity.h"
#include <cstddef>
namespace bts::domain {
class BookLevel {
public:
Price price = {};
Quantity total_quantity = {};
Quantity direct_quantity = {};
std::size_t n_orders = {};
/**
* @brief Gets an empty book
*
* @details This method offers protection against changes to the default
* constructor. For example, the default constructor could be optimized
* one day so that members aren't initialized at all. No matter what
* changes the future brings, this method will always return an empty book.
*
* @return An empty BookLevel
*/
static constexpr BookLevel empty() noexcept;
constexpr Quantity implied_quantity() const;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr BookLevel BookLevel::empty() noexcept {
return {Price::nan(), Quantity{0}, Quantity{0}, 0};
}
constexpr Quantity BookLevel::implied_quantity() const {
return total_quantity - direct_quantity;
}
} // namespace bts::domain
+57
View File
@@ -0,0 +1,57 @@
#pragma once
#include "BookLevel.h"
#include "Side.h"
namespace bts::domain {
class BookLevelComp {
public:
explicit constexpr BookLevelComp(Side side);
constexpr bool operator()(const BookLevel &lhs, const BookLevel &rhs) const;
constexpr bool operator()(const BookLevel &lhs, Price rhs) const;
constexpr bool operator()(Price lhs, const BookLevel &rhs) const;
bool operator()(const BookLevel &lhs, double rhs) const;
bool operator()(double lhs, const BookLevel &rhs) const;
private:
Side side_;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr BookLevelComp::BookLevelComp(Side side) : side_(side) {}
constexpr bool BookLevelComp::operator()(
const BookLevel &lhs, const BookLevel &rhs) const {
if (lhs.price == rhs.price) {
return lhs.total_quantity > rhs.total_quantity;
}
return lhs.price.is_better(side_, rhs.price);
}
constexpr bool BookLevelComp::operator()(
const BookLevel &lhs, Price rhs) const {
return lhs.price.is_better(side_, rhs);
}
constexpr bool BookLevelComp::operator()(
Price lhs, const BookLevel &rhs) const {
return lhs.is_better(side_, rhs.price);
}
inline bool BookLevelComp::operator()(
const BookLevel &lhs, double rhs) const {
return operator()(lhs, Price::from_double(rhs));
}
inline bool BookLevelComp::operator()(
double lhs, const BookLevel &rhs) const {
return operator()(Price::from_double(lhs), rhs);
}
} // namespace bts::domain
+674
View File
@@ -0,0 +1,674 @@
#pragma once
#include "BookLevel.h"
#include "BookLevelComp.h"
#include "BookSide_PopulatedIterator.h"
#include "PriceComp.h"
#include "SecurityID.h"
#include "Side.h"
#include <algorithm>
#include <boost/container/small_vector.hpp>
#include <initializer_list>
#include <iostream>
#include <iterator>
#include <limits>
#include <random>
#include <vector>
namespace bts::domain {
template <std::size_t SZ>
class BookSideT {
public:
static constexpr size_t max_depth() noexcept;
using Container = std::array<BookLevel, SZ>;
using Iterator = typename Container::iterator;
using ConstIter = typename Container::const_iterator;
using PopulatedIterator = BookSide_PopulatedIterator<SZ, false>;
using ConstPopulatedIterator = BookSide_PopulatedIterator<SZ, true>;
using value_type = typename Container::value_type;
BookSideT() = default;
explicit BookSideT(Container levels);
BookSideT(const BookSideT &) noexcept = default;
BookSideT(BookSideT &&) noexcept = default;
BookSideT &operator=(const BookSideT &) noexcept = default;
BookSideT &operator=(BookSideT &&) noexcept = default;
~BookSideT() = default;
[[nodiscard]] constexpr BookLevel const &top() const;
constexpr BookLevel const &operator[](size_t i) const;
constexpr BookLevel &operator[](size_t i);
static constexpr BookSideT<SZ> empty() noexcept;
[[nodiscard]] constexpr ConstIter begin() const noexcept;
[[nodiscard]] constexpr ConstIter end() const noexcept;
constexpr Iterator begin() noexcept;
constexpr Iterator end() noexcept;
Iterator insert(Side side, BookLevel level);
Iterator insert(Iterator it, BookLevel level);
Iterator erase(Iterator it);
[[nodiscard]] Quantity total_depth() const;
[[nodiscard]] Quantity depth_at_price(Side s, Price p) const;
[[nodiscard]] constexpr std::size_t size() const noexcept;
constexpr bool operator==(BookSideT const &rhs) const;
constexpr bool operator!=(BookSideT const &rhs) const;
template <class OtherBookSide>
void merge_with(
Side s,
OtherBookSide const &other_book,
bool add_to_existing_merge_qty = false);
template <class OtherBookSideContainer>
static void merge_many(
Side side,
const OtherBookSideContainer &other_books,
BookSideT<SZ> &dest);
void reset_merged_quantity();
void reset_n_orders();
template <class OtherBookSide>
static BookSideT merge(
Side s, BookSideT const & /*b1*/, OtherBookSide const & /*b2*/);
[[nodiscard]] constexpr bool is_populated_at(
std::size_t level) const noexcept;
[[nodiscard]] constexpr bool is_populated() const noexcept;
constexpr PopulatedIterator begin_populated() noexcept;
[[nodiscard]] constexpr ConstPopulatedIterator
begin_populated() const noexcept;
PopulatedIterator end_populated() noexcept;
[[nodiscard]] ConstPopulatedIterator end_populated() const noexcept;
[[nodiscard]] std::size_t count_populated() const;
bool trim_quantity_front(Quantity quantity) noexcept;
// finds the target cummulative quantity and returns the price
// level and the cummulative quantity at that level. the return
// cummulative quantity could be less than the target if the
// quantity is not present
[[nodiscard]] std::tuple<Price, Quantity> find_cummulative_quantity(
Quantity target_quantity) const noexcept;
// finds the price and returns the index, quantity and cummulutative quantity
// at that level
[[nodiscard]] std::tuple<size_t, Quantity, Quantity> find_price(
Price price) const noexcept;
/**
* Counts the volume of consecutive equal price levels (from the top of the
* book) for this book and @p other
*
* @details Price levels are considered equal if they have the same
* `BookLevel::price` and `BookLevel::total_quantity`.
*/
template <class OtherBookSide>
[[nodiscard]] Quantity intersecting_front_quantity(
const OtherBookSide &other, std::size_t num_levels = max_depth()) const;
void clear_to_end(std::uint8_t level = 0);
void clear_after_empty();
/**
* Removes book levels that cross @p price
*/
void remove_crosses(Side side, Price price);
/**
* Sets the top of the book to another level (levels before that level are
* erased)
*/
void cover_top(std::size_t top_level);
[[nodiscard]] bool is_sorted(
Side side, bool stop_on_first_empty_level = true) const;
/**
* Compares the top @p n_levels of this book to those of another book
*
* @param[in] stop_on_first_empty_level Stop comparing price levels when the
* first empty level is reached (return true if both books are empty)
*/
[[nodiscard]] bool top_levels_equal(
const BookSideT<SZ> &other,
std::size_t n_levels,
bool stop_on_first_empty_level = false) const;
private:
Container _book;
};
template <size_t SZ>
inline std::ostream &operator<<(std::ostream &s, BookSideT<SZ> const &b);
using TopBookSide = BookSideT<1>;
using BookSide = BookSideT<10>;
using ImpliedBookSide = BookSideT<2>;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <std::size_t SZ>
BookSideT<SZ>::BookSideT(typename BookSideT<SZ>::Container levels)
: _book(std::move(levels)) {}
template <std::size_t SZ>
constexpr BookSideT<SZ> BookSideT<SZ>::empty() noexcept {
// BookLevel's quantity is initialized to 0 by default, so there is no need
// for this method to actually set the quantity at each level to 0.
// Note: there is a unit test to prevent regression, in case BookLevel is
// changed such that quantity no longer defaults to 0.
BookSideT<SZ> bk;
for (auto &l : bk) {
l = BookLevel::empty();
}
return bk;
}
template <std::size_t SZ>
constexpr bool BookSideT<SZ>::is_populated_at(
std::size_t level) const noexcept {
return level < BookSideT<SZ>::max_depth() && !(*this)[level].is_empty();
}
template <std::size_t SZ>
constexpr size_t BookSideT<SZ>::max_depth() noexcept {
return SZ;
}
template <std::size_t SZ>
constexpr const BookLevel &BookSideT<SZ>::top() const {
return _book[0];
}
template <std::size_t SZ>
constexpr const BookLevel &BookSideT<SZ>::operator[](std::size_t i) const {
return _book[i];
}
template <std::size_t SZ>
constexpr BookLevel &BookSideT<SZ>::operator[](std::size_t i) {
return _book[i];
}
template <std::size_t SZ>
constexpr typename BookSideT<SZ>::Iterator BookSideT<SZ>::begin() noexcept {
return _book.begin();
}
template <std::size_t SZ>
constexpr typename BookSideT<SZ>::Iterator BookSideT<SZ>::end() noexcept {
return _book.end();
}
template <std::size_t SZ>
constexpr typename BookSideT<SZ>::ConstIter
BookSideT<SZ>::begin() const noexcept {
return _book.begin();
}
template <std::size_t SZ>
constexpr typename BookSideT<SZ>::ConstIter
BookSideT<SZ>::end() const noexcept {
return _book.end();
}
template <std::size_t SZ>
constexpr size_t BookSideT<SZ>::size() const noexcept {
return _book.size();
}
template <std::size_t SZ>
constexpr bool BookSideT<SZ>::operator==(BookSideT const &rhs) const {
return _book == rhs._book;
}
template <std::size_t SZ>
constexpr bool BookSideT<SZ>::operator!=(BookSideT const &rhs) const {
return _book != rhs._book;
}
template <std::size_t SZ>
constexpr bool BookSideT<SZ>::is_populated() const noexcept {
return (*this)[0].total_quantity != 0;
}
template <std::size_t SZ>
constexpr BookSide_PopulatedIterator<SZ, false>
BookSideT<SZ>::begin_populated() noexcept {
return BookSide_PopulatedIterator<SZ, false>(_book);
}
template <std::size_t SZ>
constexpr BookSide_PopulatedIterator<SZ, true>
BookSideT<SZ>::begin_populated() const noexcept {
return BookSide_PopulatedIterator<SZ, true>(_book);
}
template <std::size_t SZ>
BookSide_PopulatedIterator<SZ, false> BookSideT<SZ>::end_populated() noexcept {
return BookSide_PopulatedIterator<SZ, false>::end(_book);
}
template <std::size_t SZ>
BookSide_PopulatedIterator<SZ, true>
BookSideT<SZ>::end_populated() const noexcept {
return BookSide_PopulatedIterator<SZ, true>::end(_book);
}
template <std::size_t SZ>
std::size_t BookSideT<SZ>::count_populated() const {
static_assert(SZ <= std::numeric_limits<std::int32_t>::max());
std::int32_t len = max_depth();
std::int32_t lo = 0;
while (len > 0) {
// NOLINTNEXTLINE
std::int32_t half = len >> 1;
if (_book[lo + half].is_empty()) {
len = half;
} else {
len = len - half - 1;
lo += half + 1;
}
}
return lo;
}
template <std::size_t N>
inline Quantity BookSideT<N>::total_depth() const {
std::uint32_t qty = 0;
for (auto const &level : *this) {
qty += level.total_quantity.value();
}
return Quantity{qty};
}
template <std::size_t N>
inline Quantity BookSideT<N>::depth_at_price(Side s, Price p) const {
uint32_t qty = 0;
for (auto const &level : *this) {
if (level.price.is_better_or_equal(s, p)) {
qty += level.total_quantity.value();
}
}
return Quantity{qty};
}
template <std::size_t SZ>
inline bool BookSideT<SZ>::trim_quantity_front(Quantity quantity) noexcept {
if (quantity == 0) {
return true;
}
bts_assert(quantity > 0);
for (std::size_t i = 0; is_populated_at(i); i++) {
if (_book[i].total_quantity <= quantity) {
quantity -= _book[i].total_quantity;
_book[i].total_quantity.value() = 0;
} else {
_book[i].total_quantity -= quantity;
quantity.value() = 0;
}
if (quantity == 0) {
if (_book[i].total_quantity == 0) {
i++;
}
std::size_t num_levels = 0;
for (std::size_t j = i; is_populated_at(j); j++) {
_book[j - i] = _book[j];
num_levels++;
}
// The last 'i' levels were shifted up to the front, so the book has at
// least 'max_depth() - i' fewer populated levels now. Set those
// levels' price, qty, and n_orders to nan, zero, and zero
// repsectively.
for (std::size_t j = num_levels; j < max_depth(); j++) {
_book[j].price = Price::nan();
_book[j].total_quantity.value() = 0;
_book[j].n_orders = 0;
}
return true;
}
}
return false;
}
template <std::size_t SZ>
inline std::tuple<Price, Quantity> BookSideT<SZ>::find_cummulative_quantity(
Quantity target_quantity) const noexcept {
auto out_price = Price::nan();
Quantity out_quantity{0};
for (const auto &lev : *this) {
if (lev.total_quantity == 0) {
break;
}
out_price = lev.price;
out_quantity += lev.total_quantity;
if (out_quantity >= target_quantity) {
// early break, we have already accumulated the target
// dont let it exceed the target qty
break;
}
}
return std::make_tuple(out_price, out_quantity);
}
template <std::size_t SZ>
inline std::tuple<size_t, Quantity, Quantity> BookSideT<SZ>::find_price(
Price price) const noexcept {
size_t lv = 0;
auto cumm_qty = Quantity(0);
for (const auto &bl : *this) {
cumm_qty += bl.total_quantity;
if (bl.price == price) {
return std::make_tuple(lv, bl.total_quantity, cumm_qty);
}
lv++;
}
return std::make_tuple((size_t)0, Quantity(0), Quantity(0));
}
template <std::size_t SZ>
inline std::ostream &operator<<(std::ostream &s, const BookSideT<SZ> &b) {
for (auto const &l : b) {
s << l << "\n";
}
return s;
}
template <size_t SZ>
template <class OtherBookSide>
void BookSideT<SZ>::merge_with(
Side s, OtherBookSide const &other_book, bool add_to_existing_merge_qty) {
boost::container::small_vector<
BookSide::value_type, max_depth() + OtherBookSide::max_depth()>
merged;
auto comp = [s](auto const &l1, auto const &l2) {
return l1.price.is_better(s, l2.price);
};
// Copy this to merged output
for (auto l : *this) {
if (l.total_quantity.value() == 0) {
break;
}
if (!add_to_existing_merge_qty) {
l.merged_quantity = Quantity{0};
}
merged.push_back(l);
}
// Now for each entry in the other book find either a matching
// entry or the entry where the level should be inserted
for (auto ol : other_book) {
if (ol.total_quantity.value() == 0) {
break;
}
auto it = std::lower_bound(merged.begin(), merged.end(), ol, comp);
if (it == merged.end()) {
// level is worse than the worst level so far, append
ol.merged_quantity = ol.total_quantity;
merged.push_back(ol);
} else if (it->price == ol.price) {
// level is the same as an existing level, merge
it->total_quantity.value() += ol.total_quantity.value();
it->n_orders += ol.n_orders;
if (add_to_existing_merge_qty) {
it->merged_quantity += ol.total_quantity;
} else {
it->merged_quantity = ol.total_quantity;
}
} else {
// level is better than what was there before, insert
ol.merged_quantity = ol.total_quantity;
merged.insert(it, ol);
}
}
std::copy(
merged.begin(), merged.begin() + std::min(merged.size(), size()),
_book.begin());
}
template <std::size_t SZ>
template <class OtherBookSideContainer>
void BookSideT<SZ>::merge_many(
Side side, const OtherBookSideContainer &other_books, BookSideT<SZ> &dest) {
// Determine the set of prices that will be used. Use the 'best' (i.e., most
// aggressive) prices for each side.
std::array<Price, SZ> prices;
auto last_price = prices.begin();
PriceComp price_comp(side);
for (const auto &bk : other_books) {
auto it = prices.begin();
for (const auto &bkl : bk) {
if (bkl.is_empty()) {
break;
}
it = std::lower_bound(it, last_price, bkl.price, price_comp);
if (std::distance(prices.begin(), it) ==
static_cast<std::int32_t>(SZ)) {
break;
}
// `it` == `last_price` means `it` hasn't been assigned a price yet.
// `it` != `bkl.price` means `bkl.price` is better than the price
// pointed to by `it`. If either is true, bkl.price should be added to
// `prices`
if (it == last_price || *it != bkl.price) {
for (auto copy_it = last_price; copy_it != it; copy_it--) {
*copy_it = *(copy_it - 1);
}
*it = bkl.price;
if (last_price != prices.end()) {
last_price++;
}
}
}
}
std::size_t insert_level = 0;
std::vector<std::uint8_t> cursors(other_books.size(), 0);
for (auto price_it = prices.begin(); price_it != last_price; price_it++) {
if (insert_level == SZ) {
break;
}
auto &merged_level = dest[insert_level];
merged_level.price = *price_it;
merged_level.total_quantity.value() = 0;
merged_level.merged_quantity.value() = 0;
merged_level.n_orders = 0;
for (std::size_t i = 0; i < other_books.size(); i++) {
const auto &bk = other_books[i];
auto &cursor = cursors[i];
if (bk[cursor].price == *price_it) {
merged_level.total_quantity += bk[cursor].total_quantity;
merged_level.merged_quantity += bk[cursor].merged_quantity;
merged_level.n_orders += bk[cursor].n_orders;
cursor++;
}
}
insert_level++;
}
dest.clear_to_end(insert_level);
}
template <std::size_t SZ>
inline void BookSideT<SZ>::reset_merged_quantity() {
for (auto &l : *this) {
l.merged_quantity = Quantity{0};
}
}
template <std::size_t SZ>
inline void BookSideT<SZ>::reset_n_orders() {
for (auto &l : *this) {
l.n_orders = 0;
}
}
template <size_t SZ>
template <class OtherBookSide>
BookSideT<SZ> BookSideT<SZ>::merge(
Side s, BookSideT const &b1, OtherBookSide const &b2) {
auto result = b1;
result.merge_with(s, b2);
return result;
}
template <std::size_t SZ>
template <class OtherBookSide>
Quantity BookSideT<SZ>::intersecting_front_quantity(
const OtherBookSide &other, std::size_t num_levels) const {
Quantity ifq{0};
auto it = begin();
auto oit = other.begin();
while (num_levels > 0 && it != end() && oit != other.end() &&
it->price == oit->price) {
if (it->total_quantity != oit->total_quantity) {
ifq += std::min(it->total_quantity, oit->total_quantity);
break;
}
ifq += it->total_quantity;
it++;
oit++;
num_levels--;
}
return ifq;
}
template <std::size_t SZ>
void BookSideT<SZ>::clear_to_end(std::uint8_t level) {
static_assert(SZ <= std::numeric_limits<std::uint8_t>::max());
while (level < SZ) {
_book[level++] = BookLevel::empty();
}
}
template <std::size_t SZ>
void BookSideT<SZ>::remove_crosses(Side side, Price price) {
if (price.is_nan()) {
return;
}
auto it = std::upper_bound(
_book.begin(),
_book.begin() + static_cast<std::int32_t>(count_populated()), price,
BookLevelComp{side});
cover_top(std::distance(_book.begin(), it));
}
template <std::size_t SZ>
void BookSideT<SZ>::cover_top(std::size_t level) {
if (level == 0) {
return;
}
for (auto it = _book.begin() + level; it != _book.end(); it++) {
*(it - level) = *it;
}
clear_to_end(max_depth() - level);
}
template <std::size_t SZ>
bool BookSideT<SZ>::is_sorted(Side side, bool stop_on_first_empty_level) const {
PriceComp cmp(side);
for (std::size_t i = 0; i < max_depth(); i++) {
const auto &better = _book.at(i);
if (better.is_empty()) {
if (stop_on_first_empty_level) {
return true;
}
continue;
}
for (std::size_t j = i + 1; j < max_depth(); j++) {
const auto &worse = _book.at(j);
if (worse.is_empty()) {
if (stop_on_first_empty_level) {
return true;
}
continue;
}
if (!better.price.is_better(side, worse.price)) {
return false;
}
}
}
return true;
}
template <std::size_t SZ>
bool BookSideT<SZ>::top_levels_equal(
const BookSideT<SZ> &other,
std::size_t n_levels,
bool stop_on_first_empty_level) const {
for (std::size_t i = 0; i < std::min(n_levels, max_depth()); i++) {
const auto &level = (*this)[i];
if (stop_on_first_empty_level && level.is_empty()) {
return other[i].is_empty();
}
if (level != other[i]) {
return false;
}
}
return true;
}
template <std::size_t SZ>
void BookSideT<SZ>::clear_after_empty() {
for (std::size_t i = 0; i < size(); i++) {
if (_book[i].is_empty()) {
while (++i != max_depth()) {
_book[i] = BookLevel::empty();
}
}
}
}
template <std::size_t SZ>
typename BookSideT<SZ>::Iterator BookSideT<SZ>::insert(
Side side, BookLevel level) {
BookLevelComp comp(side);
auto it = std::lower_bound(_book.begin(), _book.end(), level, comp);
if (it == _book.end()) {
return it;
}
if (it->price == level.price) {
*it = level;
return it;
}
return insert(it, level);
}
template <std::size_t SZ>
typename BookSideT<SZ>::Iterator BookSideT<SZ>::insert(
Iterator it, BookLevel level) {
if (it != _book.end()) {
for (auto copy_it = it + 1; copy_it != _book.end(); copy_it++) {
*copy_it = *(copy_it - 1);
}
*it = level;
}
return it;
}
template <std::size_t SZ>
typename BookSideT<SZ>::Iterator BookSideT<SZ>::erase(Iterator it) {
if (it != _book.end()) {
for (auto copy_it = it + 1; copy_it != _book.end(); copy_it++) {
*(copy_it - 1) = *copy_it;
}
}
return it;
}
} // namespace bts::domain
+201
View File
@@ -0,0 +1,201 @@
#pragma once
#include "BookLevel.h"
#include <array>
#include <type_traits>
namespace bts::domain {
template <std::size_t SZ, bool IsConst>
class BookSide_PopulatedIterator {
public:
using iterator_category = std::forward_iterator_tag;
using blah = std::true_type;
using difference_type = std::ptrdiff_t;
using source_type = typename std::conditional<
IsConst,
const std::array<BookLevel, SZ>,
std::array<BookLevel, SZ>>::type;
using value_type =
typename std::conditional<IsConst, const BookLevel, BookLevel>::type;
using pointer = value_type *;
using reference = value_type &;
using const_pointer = const value_type *;
using const_reference = const value_type &;
explicit constexpr BookSide_PopulatedIterator(source_type &source) noexcept;
constexpr BookSide_PopulatedIterator(
const BookSide_PopulatedIterator<SZ, IsConst> &) noexcept = default;
constexpr BookSide_PopulatedIterator(
BookSide_PopulatedIterator<SZ, IsConst> &&) noexcept = default;
~BookSide_PopulatedIterator() = default;
static constexpr BookSide_PopulatedIterator<SZ, IsConst> end(
source_type &source) noexcept;
reference operator*();
pointer operator->();
const_reference operator*() const;
const_pointer operator->() const;
BookSide_PopulatedIterator<SZ, IsConst> &operator++();
// NOLINTNEXTLINE
BookSide_PopulatedIterator<SZ, IsConst> operator++(int);
BookSide_PopulatedIterator<SZ, IsConst> &operator+=(int value);
BookSide_PopulatedIterator<SZ, IsConst> operator+(int value);
BookSide_PopulatedIterator<SZ, IsConst> &operator--();
// NOLINTNEXTLINE
BookSide_PopulatedIterator<SZ, IsConst> operator--(int);
BookSide_PopulatedIterator<SZ, IsConst> &operator-=(int value);
BookSide_PopulatedIterator<SZ, IsConst> operator-(int value);
template <bool OtherIsConst>
constexpr bool operator==(
const BookSide_PopulatedIterator<SZ, OtherIsConst> &other) const
noexcept;
template <bool OtherIsConst>
constexpr bool operator!=(
const BookSide_PopulatedIterator<SZ, OtherIsConst> &other) const
noexcept;
BookSide_PopulatedIterator<SZ, IsConst> &operator=(
const BookSide_PopulatedIterator<SZ, IsConst> &) noexcept = default;
BookSide_PopulatedIterator<SZ, IsConst> &operator=(
BookSide_PopulatedIterator<SZ, IsConst> &&) noexcept = default;
private:
constexpr BookSide_PopulatedIterator(
source_type &source, std::size_t cursor) noexcept;
source_type *_source;
std::size_t _cursor;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
template <std::size_t SZ, bool IsConst>
constexpr BookSide_PopulatedIterator<SZ, IsConst>::BookSide_PopulatedIterator(
source_type &source) noexcept
: _source(&source), _cursor(0) {}
template <std::size_t SZ, bool IsConst>
constexpr BookSide_PopulatedIterator<SZ, IsConst>::BookSide_PopulatedIterator(
source_type &source, std::size_t cursor) noexcept
: _source(&source), _cursor(cursor) {}
template <std::size_t SZ, bool IsConst>
constexpr BookSide_PopulatedIterator<SZ, IsConst>
BookSide_PopulatedIterator<SZ, IsConst>::end(source_type &source) noexcept {
BookSide_PopulatedIterator<SZ, IsConst> rv(source);
for (; rv._cursor < SZ; rv._cursor++) {
if (source[rv._cursor].total_quantity == 0) {
break;
}
}
return rv;
}
template <std::size_t SZ, bool IsConst>
typename BookSide_PopulatedIterator<SZ, IsConst>::reference
BookSide_PopulatedIterator<SZ, IsConst>::operator*() {
return (*_source)[_cursor];
}
template <std::size_t SZ, bool IsConst>
typename BookSide_PopulatedIterator<SZ, IsConst>::pointer
BookSide_PopulatedIterator<SZ, IsConst>::operator->() {
return &(*_source)[_cursor];
}
template <std::size_t SZ, bool IsConst>
typename BookSide_PopulatedIterator<SZ, IsConst>::const_reference
BookSide_PopulatedIterator<SZ, IsConst>::operator*() const {
return (*_source)[_cursor];
}
template <std::size_t SZ, bool IsConst>
typename BookSide_PopulatedIterator<SZ, IsConst>::const_pointer
BookSide_PopulatedIterator<SZ, IsConst>::operator->() const {
return &(*_source)[_cursor];
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst> &
BookSide_PopulatedIterator<SZ, IsConst>::operator++() {
_cursor++;
return *this;
}
template <std::size_t SZ, bool IsConst>
// NOLINTNEXTLINE
BookSide_PopulatedIterator<SZ, IsConst>
BookSide_PopulatedIterator<SZ, IsConst>::operator++(int) {
const BookSide_PopulatedIterator<SZ, IsConst> before(*this);
++(*this);
return before;
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst> &
BookSide_PopulatedIterator<SZ, IsConst>::operator+=(int value) {
_cursor += value;
return *this;
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst>
BookSide_PopulatedIterator<SZ, IsConst>::operator+(int value) {
return BookSide_PopulatedIterator<SZ, IsConst>(*_source, _cursor + value);
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst> &
BookSide_PopulatedIterator<SZ, IsConst>::operator--() {
_cursor--;
return *this;
}
template <std::size_t SZ, bool IsConst>
// NOLINTNEXTLINE
BookSide_PopulatedIterator<SZ, IsConst>
BookSide_PopulatedIterator<SZ, IsConst>::operator--(int) {
BookSide_PopulatedIterator<SZ, IsConst> before(*this);
--(*this);
return before;
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst> &
BookSide_PopulatedIterator<SZ, IsConst>::operator-=(int value) {
_cursor -= value;
return *this;
}
template <std::size_t SZ, bool IsConst>
BookSide_PopulatedIterator<SZ, IsConst>
BookSide_PopulatedIterator<SZ, IsConst>::operator-(int value) {
return BookSide_PopulatedIterator<SZ, IsConst>(*_source, _cursor - value);
}
template <std::size_t SZ, bool IsConst>
template <bool OtherIsConst>
constexpr bool BookSide_PopulatedIterator<SZ, IsConst>::operator==(
const BookSide_PopulatedIterator<SZ, OtherIsConst> &other) const noexcept {
return _cursor == other._cursor && _source == other._source;
}
template <std::size_t SZ, bool IsConst>
template <bool OtherIsConst>
constexpr bool BookSide_PopulatedIterator<SZ, IsConst>::operator!=(
const BookSide_PopulatedIterator<SZ, OtherIsConst> &other) const noexcept {
return !(*this == other);
}
} // namespace bts::domain
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
enum class Currency { BTC, EH, USD };
} // namespace bts::domain
+11
View File
@@ -0,0 +1,11 @@
#pragma once
#include "lib/core/TimeStamp.h"
namespace bts::domain {
class FutureSecurity {
public:
core::TimeStamp expiration;
};
} // namespace bts::domain
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class IndexSecurity {};
} // namespace bts::domain
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "Quantity.h"
#include "SecurityID.h"
#include "Side.h"
namespace bts::domain {
struct LegDefinition {
SecurityID security_id;
Quantity leg_mult;
Side side;
};
} // namespace bts::domain
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "BookLevel.h"
#include <array>
namespace bts::domain {
class BookSide {
public:
// compile time size for speed
using Container = std::array<BookLevel, 10>;
std::uint32_t num_populated_levels() const noexcept;
bool is_empty() const noexcept;
private:
// compile time size for speed
Container levels_;
};
} // namespace bts::domain
+10
View File
@@ -0,0 +1,10 @@
#include "NewOrder.h"
namespace bts::domain {
std::ostream &operator<<(std::ostream &out, const NewOrder &no) noexcept {
out << "price: " << no.price << "; qty: " << no.qty << "; " << no.order_def;
return out;
}
} // namespace bts::domain
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "OrderDefinition.h"
#include "Price.h"
#include "Quantity.h"
namespace bts::domain {
// Sent once per order, when the order is first launched (launching an order,
// placing, firing, sending all mean the same)
struct NewOrder {
OrderDefinition order_def;
domain::Price price;
domain::Quantity qty;
};
std::ostream &operator<<(std::ostream &out, const NewOrder &no) noexcept;
} // namespace bts::domain
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "lib/core/TimeStamp.h"
#include "lib/domain/Price.h"
namespace bts::domain {
class OptionSecurity {
public:
core::TimeStamp expiration;
domain::Price strike;
};
} // namespace bts::domain
+13
View File
@@ -0,0 +1,13 @@
#include "OrderDefinition.h"
namespace bts::domain {
std::ostream &operator<<(
std::ostream &out, const OrderDefinition &od) noexcept {
out << "side: " << od.side << "; sec: " << od.security_id
<< "; acc: " << od.account << "(" << od.account_id << ")"
<< "; user: " << od.user << "(" << od.user_id << ")";
return out;
}
} // namespace bts::domain
+34
View File
@@ -0,0 +1,34 @@
#pragma once
#include "AccountID.h"
#include "Price.h"
#include "Quantity.h"
#include "SecurityID.h"
#include "Side.h"
#include "TimeInForce.h"
#include "UserID.h"
#include "lib/domain/cme/GlbxOrderDefinition.h"
#include "lib/domain/deribit/DeribitOrderDefinition.h"
#include <string>
#include <variant>
namespace bts::domain {
// This contains the order parameters common to all exchanges. It is sent once
// when a new order is launched
struct OrderDefinition {
SecurityID security_id;
Side side;
std::string user;
UserID user_id;
std::string account;
AccountID account_id;
TimeInForce time_in_force;
// Exchange specific order definition (ex if a certain exchange offers
// Iceberg orders, this is where its parameters will be)
const std::variant<DeribitOrderDefinition, GlbxOrderDefinition>
exchange_order = {DeribitOrderDefinition{}};
};
std::ostream &operator<<(std::ostream &out, const OrderDefinition &od) noexcept;
} // namespace bts::domain
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
#include <cstdint>
namespace bts::domain {
using OrderKey = utils::ValueWrapper<struct OrderKeyTag, std::uint64_t>;
} // namespace bts::domain
+19
View File
@@ -0,0 +1,19 @@
#pragma once
#include "OrderStatus.h"
#include "Price.h"
#include "Quantity.h"
#include "lib/domain/cme/GlbxOrderState.h"
#include "lib/domain/deribit/DeribitOrderState.h"
#include <variant>
namespace bts::domain {
struct OrderState {
OrderStatus status;
Quantity total_fills;
Price avg_filled_price;
// If there is any exchange specific order state
std::variant<DeribitOrderState, GlbxOrderState> exchange_order_state;
};
} // namespace bts::domain
+10
View File
@@ -0,0 +1,10 @@
#include "OrderStatus.h"
namespace bts::domain {
std::ostream &operator<<(std::ostream &out, const OrderStatus &os) noexcept {
out << OrderStatus_name(os);
return out;
}
} // namespace bts::domain
+30
View File
@@ -0,0 +1,30 @@
#pragma once
#include <ostream>
namespace bts::domain {
// Order can be in one of these states
enum class OrderStatus { Working, Completed, Canceled };
constexpr const char *OrderStatus_name(OrderStatus os) noexcept;
std::ostream &operator<<(std::ostream &out, const OrderStatus &os) noexcept;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr const char *OrderStatus_name(OrderStatus os) noexcept {
switch (os) {
case OrderStatus::Working:
return "Working";
case OrderStatus::Completed:
return "Completed";
case OrderStatus::Canceled:
return "Canceled";
default:
return "Unknown";
}
}
} // namespace bts::domain
+11
View File
@@ -0,0 +1,11 @@
#include "OrderUpdate.h"
namespace bts::domain {
std::ostream &operator<<(std::ostream &out, const OrderUpdate &ou) noexcept {
out << "key: " << ou.order_key << "; price: " << ou.price
<< "; qty: " << ou.qty;
return out;
}
} // namespace bts::domain
+18
View File
@@ -0,0 +1,18 @@
#pragma once
#include "OrderKey.h"
#include "Price.h"
#include "Quantity.h"
namespace bts::domain {
// Structure for order modifications (also know as cancel-replace at some
// exchanges).
struct OrderUpdate {
OrderKey order_key;
Price price;
Quantity qty;
};
std::ostream &operator<<(std::ostream &out, const OrderUpdate &ou) noexcept;
} // namespace bts::domain
+501
View File
@@ -0,0 +1,501 @@
#pragma once
#include "Side.h"
#include "lib/utils/bts_assert.h"
#include <cmath>
#include <cstdint>
#include <limits>
#include <ostream>
#if bts_assert_msg
#define _ASSERT_MSG(EXP, msg) bts_assert_msg(EXP, msg)
#else
#define _ASSERT_MSG(EXP, msg) \
do { \
if (!(EXP)) { \
std::cerr << "Assert failure: " << std::string(#EXP) << " " << msg \
<< std::endl; \
if (is_debugger_present()) \
debug_break(); \
std::abort(); \
} \
} while (0)
#endif
#define _ASSERT(EXP) _ASSERT_MSG(EXP, "")
namespace bts::domain {
class Price {
public:
Price() = default;
explicit constexpr Price(
std::int64_t mantissa,
std::int8_t exponent = Price::exponent()) noexcept;
constexpr Price(Price const &) = default;
Price(Price &&) noexcept = default;
~Price() = default;
template <std::size_t PRECISION = 9>
static Price from_float(float price) noexcept;
[[nodiscard]] constexpr float to_float() const noexcept;
template <std::size_t PRECISION = 9>
static Price from_double(double price) noexcept;
[[nodiscard]] constexpr double to_double() const noexcept;
static constexpr Price zero() noexcept;
static constexpr Price nan() noexcept;
[[nodiscard]] constexpr Price abs() const noexcept;
[[nodiscard]] Price square() const noexcept;
[[nodiscard]] constexpr Price improve(Side s, Price by) const noexcept;
[[nodiscard]] constexpr Price worsen(Side s, Price by) const noexcept;
[[nodiscard]] constexpr bool is_nan() const noexcept;
[[nodiscard]] constexpr bool is_better(Side s, Price p2) const noexcept;
[[nodiscard]] static constexpr bool is_better(
Side s, double p1, double p2) noexcept;
[[nodiscard]] constexpr bool is_worse(Side s, Price p2) const noexcept;
[[nodiscard]] static constexpr bool is_worse(
Side s, double p1, double p2) noexcept;
[[nodiscard]] constexpr bool is_better_or_equal(
Side s, Price p2) const noexcept;
[[nodiscard]] static constexpr bool is_better_or_equal(
Side s, double p1, double p2) noexcept;
[[nodiscard]] constexpr bool is_worse_or_equal(
Side s, Price p2) const noexcept;
[[nodiscard]] static constexpr bool is_worse_or_equal(
Side s, double p1, double p2) noexcept;
[[nodiscard]] constexpr Price repl_nan(Price repl) const noexcept;
[[nodiscard]] constexpr Price get_min(Price other) const noexcept;
[[nodiscard]] constexpr Price get_max(Price other) const noexcept;
[[nodiscard]] constexpr Price get_better(
Side side, Price other) const noexcept;
[[nodiscard]] constexpr Price get_worse(
Side side, Price other) const noexcept;
template <class Iter>
static double get_mean(Iter first, Iter last, bool skip_nan = false);
template <class Range>
static double get_mean(Range range, bool skip_nan = false);
Price &operator=(Price const &) = default;
Price &operator=(Price &&) noexcept = default;
constexpr Price operator-() const noexcept;
constexpr bool operator==(Price factor) const noexcept;
constexpr bool operator!=(Price factor) const noexcept;
constexpr bool operator<(Price factor) const noexcept;
constexpr bool operator<=(Price factor) const noexcept;
constexpr bool operator>(Price factor) const noexcept;
constexpr bool operator>=(Price factor) const noexcept;
constexpr Price operator+(Price factor) const noexcept;
constexpr Price operator-(Price factor) const noexcept;
constexpr Price operator*(Price factor) const noexcept;
constexpr Price operator/(Price factor) const noexcept;
constexpr Price &operator+=(Price factor) noexcept;
constexpr Price &operator-=(Price factor) noexcept;
constexpr Price &operator*=(Price factor) noexcept;
constexpr Price &operator/=(Price factor) noexcept;
constexpr bool operator==(std::int64_t factor) const noexcept;
constexpr bool operator!=(std::int64_t factor) const noexcept;
constexpr bool operator<(std::int64_t factor) const noexcept;
constexpr bool operator<=(std::int64_t factor) const noexcept;
constexpr bool operator>(std::int64_t factor) const noexcept;
constexpr bool operator>=(std::int64_t factor) const noexcept;
constexpr Price operator+(std::int64_t factor) const noexcept;
constexpr Price operator-(std::int64_t factor) const noexcept;
constexpr Price operator*(std::int64_t factor) const noexcept;
constexpr Price operator/(std::int64_t factor) const noexcept;
constexpr Price &operator+=(std::int64_t factor) noexcept;
constexpr Price &operator-=(std::int64_t factor) noexcept;
constexpr Price &operator*=(std::int64_t factor) noexcept;
constexpr Price &operator/=(std::int64_t factor) noexcept;
[[nodiscard]] constexpr std::int64_t mantissa() const noexcept;
static constexpr std::int8_t exponent() noexcept;
private:
std::int64_t _mantissa;
static double _pow10() noexcept;
static double __pow10() noexcept; // NOLINT
};
std::ostream &operator<<(std::ostream &out, Price price) noexcept;
} // namespace bts::domain
namespace std {
template <>
struct hash<bts::domain::Price> { // NOLINT
constexpr size_t operator()(const bts::domain::Price &price) const noexcept;
};
} // namespace std
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
namespace bts::domain {
// NOLINTNEXTLINE
#define NAN_SENTINEL std::numeric_limits<std::int64_t>::min()
// NOLINTNEXTLINE
#define IS_NAN(x) (x == std::numeric_limits<std::int64_t>::min())
constexpr Price::Price(std::int64_t mantissa, std::int8_t exponent) noexcept
: _mantissa(mantissa) {
_ASSERT(exponent == Price::exponent());
}
template <std::size_t PRECISION>
inline Price Price::from_float(float price) noexcept {
return from_double(price);
}
constexpr float Price::to_float() const noexcept {
return static_cast<float>(to_double());
}
template <std::size_t PRECISION>
inline Price Price::from_double(double price) noexcept {
static_assert(PRECISION == -exponent());
if (std::isnan(price)) {
return nan();
}
double temp; // NOLINT
if (fabs(modf(price, &temp)) != 0.0) {
const double rounding = 0.5 * _pow10();
price += (price > 0) ? rounding : -rounding;
price *= __pow10();
return Price{(std::int64_t)price};
}
return Price{(std::int64_t)(price * __pow10())};
}
constexpr double Price::to_double() const noexcept {
return is_nan() ? std::numeric_limits<double>::quiet_NaN()
: _mantissa * _pow10(); // NOLINT
}
constexpr Price Price::zero() noexcept { return Price(0); }
constexpr Price Price::nan() noexcept { return Price(NAN_SENTINEL); }
constexpr std::int8_t Price::exponent() noexcept { return -9; }
constexpr std::int64_t Price::mantissa() const noexcept { return _mantissa; }
constexpr Price Price::abs() const noexcept {
if (_mantissa >= 0) {
return *this;
}
return Price{-_mantissa};
}
inline Price Price::square() const noexcept {
auto d = to_double();
return from_double(d * d);
}
constexpr Price Price::improve(Side s, Price by) const noexcept {
if (s == Side::Buy) {
return *this + by;
}
return *this - by;
}
constexpr Price Price::worsen(Side s, Price by) const noexcept {
if (s == Side::Buy) {
return *this - by;
}
return *this + by;
}
constexpr bool Price::is_nan() const noexcept { return IS_NAN(_mantissa); }
constexpr bool Price::is_better(Side s, Price p2) const noexcept {
if (is_nan()) {
return false;
}
if (p2.is_nan()) {
return true;
}
if (s == Side::Buy) {
return *this > p2;
}
return *this < p2;
}
constexpr bool Price::is_better(Side s, double p1, double p2) noexcept {
if (std::isnan(p1)) {
return false;
}
if (std::isnan(p2)) {
return true;
}
if (s == Side::Buy) {
return p1 > p2;
}
return p1 < p2;
}
constexpr bool Price::is_worse(Side s, Price p2) const noexcept {
return p2.is_better(s, *this);
}
constexpr bool Price::is_worse(Side s, double p1, double p2) noexcept {
return is_better(s, p2, p1);
}
constexpr bool Price::is_better_or_equal(Side s, Price p2) const noexcept {
if (is_nan()) {
// This case is always false (even if p2 is nan), because nan != nan.
return false;
}
if (p2.is_nan()) {
return true;
}
if (s == Side::Buy) {
return *this >= p2;
}
return *this <= p2;
}
constexpr bool Price::is_better_or_equal(
Side s, double p1, double p2) noexcept {
if (std::isnan(p1)) {
// This case is always false (even if p2 is nan), because nan != nan.
return false;
}
if (std::isnan(p2)) {
return true;
}
if (s == Side::Buy) {
return p1 >= p2;
}
return p1 <= p2;
}
constexpr bool Price::is_worse_or_equal(Side s, Price p2) const noexcept {
return p2.is_better_or_equal(s, *this);
}
constexpr bool Price::is_worse_or_equal(Side s, double p1, double p2) noexcept {
return is_better_or_equal(s, p2, p1);
}
constexpr Price Price::repl_nan(Price repl) const noexcept {
if (is_nan()) {
return repl;
}
return *this;
}
constexpr Price Price::get_min(Price other) const noexcept {
if (is_nan()) {
return other;
}
if (other.is_nan()) {
return *this;
}
if (*this < other) {
return *this;
}
return other;
}
constexpr Price Price::get_max(Price other) const noexcept {
if (is_nan()) {
return other;
}
if (other.is_nan()) {
return *this;
}
if (*this > other) {
return *this;
}
return other;
}
constexpr Price Price::get_better(Side side, Price other) const noexcept {
switch (side.value) {
case Side::Buy:
return get_max(other);
case Side::Sell:
return get_min(other);
default:
return nan();
}
}
constexpr Price Price::get_worse(Side side, Price other) const noexcept {
return get_better(side.other(), other);
}
template <class Iter>
inline double Price::get_mean(Iter first, Iter last, bool skip_nan) {
if (first == last) {
return std::numeric_limits<double>::quiet_NaN();
}
auto sum = zero();
std::int32_t n = 0;
do {
if (first->is_nan()) {
if (skip_nan) {
continue;
}
return std::numeric_limits<double>::quiet_NaN();
}
sum += *first;
n++;
first++;
} while (first != last);
if (n == 0) {
return std::numeric_limits<double>::quiet_NaN();
}
auto dsum = sum.to_double();
return dsum / n;
}
template <class Range>
inline double Price::get_mean(Range range, bool skip_nan) {
return get_mean(range.begin(), range.end(), skip_nan);
}
inline double Price::_pow10() noexcept { return std::pow(10.0, exponent()); }
inline double Price::__pow10() noexcept { return std::pow(10.0, -exponent()); }
constexpr Price Price::operator-() const noexcept {
if (is_nan()) {
return *this;
}
return Price{-_mantissa};
}
// If a number is nan, all comparisons are false. This is well-established
// behavior; even nan == nan evaluates to false.
// NOLINTNEXTLINE
#define PRICE_PRICE_COMPARISON(op, nan_part) \
constexpr bool Price::operator op(Price factor) const noexcept { \
return nan_part _mantissa op factor._mantissa; \
}
// NOLINTNEXTLINE
#define PRICE_PRICE_BIN_OP(op) \
constexpr Price Price::operator op(Price factor) const noexcept { \
if (is_nan() || factor.is_nan()) { \
return nan(); \
} \
return Price{_mantissa op factor._mantissa}; \
}
// NOLINTNEXTLINE
#define PRICE_PRICE_BIN_REF_OP(op) \
constexpr Price &Price::operator op(Price factor) noexcept { \
if (factor.is_nan()) { \
_mantissa = nan()._mantissa; \
} else if (!is_nan()) { \
_mantissa op factor._mantissa; \
} \
return *this; \
}
// NOLINTNEXTLINE
#define PRICE_INT64_COMPARISON(op, nan_part) \
constexpr bool Price::operator op(std::int64_t factor) const noexcept { \
return nan_part _mantissa op factor; \
}
// NOLINTNEXTLINE
#define PRICE_INT64_BIN_OP(op) \
constexpr Price Price::operator op(std::int64_t factor) const noexcept { \
if (is_nan()) { \
return *this; \
} \
return Price{_mantissa op factor}; \
}
// NOLINTNEXTLINE
#define PRICE_INT64_BIN_REF_OP(op) \
constexpr Price &Price::operator op(std::int64_t factor) noexcept { \
if (!is_nan()) { \
_mantissa op factor; \
} \
return *this; \
}
PRICE_PRICE_COMPARISON(!=, is_nan() ||)
PRICE_PRICE_COMPARISON(==, !is_nan() &&)
PRICE_PRICE_COMPARISON(<, !is_nan() &&)
PRICE_PRICE_COMPARISON(<=, !is_nan() &&)
PRICE_PRICE_COMPARISON(>, !is_nan() &&)
PRICE_PRICE_COMPARISON(>=, !is_nan() &&)
PRICE_PRICE_BIN_OP(+)
PRICE_PRICE_BIN_OP(-)
PRICE_PRICE_BIN_OP(*)
PRICE_PRICE_BIN_OP(/)
PRICE_PRICE_BIN_REF_OP(+=)
PRICE_PRICE_BIN_REF_OP(-=)
PRICE_PRICE_BIN_REF_OP(*=)
PRICE_PRICE_BIN_REF_OP(/=)
PRICE_INT64_COMPARISON(!=, is_nan() ||)
PRICE_INT64_COMPARISON(==, !is_nan() &&)
PRICE_INT64_COMPARISON(<, !is_nan() &&)
PRICE_INT64_COMPARISON(<=, !is_nan() &&)
PRICE_INT64_COMPARISON(>, !is_nan() &&)
PRICE_INT64_COMPARISON(>=, !is_nan() &&)
PRICE_INT64_BIN_OP(+)
PRICE_INT64_BIN_OP(-)
PRICE_INT64_BIN_OP(*)
PRICE_INT64_BIN_OP(/)
PRICE_INT64_BIN_REF_OP(+=)
PRICE_INT64_BIN_REF_OP(-=)
PRICE_INT64_BIN_REF_OP(*=)
PRICE_INT64_BIN_REF_OP(/=)
inline std::ostream &operator<<(std::ostream &out, Price p) noexcept {
out << p.to_double();
return out;
}
#undef NAN_SENTINEL
#undef IS_NAN
#undef PRICE_PRICE_COMPARISON
#undef PRICE_PRICE_BIN_OP
#undef PRICE_PRICE_BIN_REF_OP
#undef PRICE_INT64_COMPARISON
#undef PRICE_INT64_BIN_OP
#undef PRICE_INT64_BIN_REF_OP
} // namespace bts::domain
namespace std { // NOLINT
constexpr size_t hash<bts::domain::Price>::operator()(
const bts::domain::Price &price) const noexcept {
return price.mantissa();
}
} // namespace std
#undef _ASSERT
#undef _ASSERT_MSG
+33
View File
@@ -0,0 +1,33 @@
#pragma once
#include "Price.h"
#include "Side.h"
namespace bts::domain {
struct PriceComp {
constexpr PriceComp() = default;
constexpr PriceComp(Side side);
constexpr PriceComp(const PriceComp &other) = default;
constexpr bool operator()(const Price &lhs, const Price &rhs);
constexpr bool operator()(double lhs, double rhs);
private:
Side _side = Side::Buy;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr PriceComp::PriceComp(Side side) : _side(side) {}
constexpr bool PriceComp::operator()(const Price &lhs, const Price &rhs) {
return lhs.is_better(_side, rhs);
}
constexpr bool PriceComp::operator()(double lhs, double rhs) {
return Price::is_better(_side, lhs, rhs);
}
} // namespace bts::domain
+116
View File
@@ -0,0 +1,116 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
#include <cstdint>
namespace bts::domain {
using Quantity = utils::ValueWrapper<struct QuantityTag, std::uint32_t>;
constexpr Quantity operator-(Quantity);
constexpr Quantity operator+(Quantity, Quantity);
constexpr Quantity operator-(Quantity, Quantity);
constexpr Quantity operator*(Quantity, Quantity);
constexpr Quantity operator/(Quantity, Quantity);
constexpr Quantity operator%(Quantity, Quantity);
constexpr Quantity &operator+=(Quantity &, Quantity);
constexpr Quantity &operator-=(Quantity &, Quantity);
constexpr Quantity &operator*=(Quantity &, Quantity);
constexpr Quantity &operator/=(Quantity &, Quantity);
constexpr Quantity &operator%=(Quantity &, Quantity);
constexpr bool operator==(Quantity, std::uint32_t);
constexpr bool operator!=(Quantity, std::uint32_t);
constexpr bool operator<(Quantity, std::uint32_t);
constexpr bool operator<=(Quantity, std::uint32_t);
constexpr bool operator>(Quantity, std::uint32_t);
constexpr bool operator>=(Quantity, std::uint32_t);
constexpr Quantity operator+(Quantity, std::uint32_t);
constexpr Quantity operator-(Quantity, std::uint32_t);
constexpr Quantity operator*(Quantity, std::uint32_t);
constexpr Quantity operator/(Quantity, std::uint32_t);
Quantity &operator+=(Quantity &, std::uint32_t);
Quantity &operator-=(Quantity &, std::uint32_t);
Quantity &operator*=(Quantity &, std::uint32_t);
Quantity &operator/=(Quantity &, std::uint32_t);
std::uint32_t &operator+=(std::uint32_t &, Quantity);
std::uint32_t &operator-=(std::uint32_t &, Quantity);
std::uint32_t &operator*=(std::uint32_t &, Quantity);
std::uint32_t &operator/=(std::uint32_t &, Quantity);
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr Quantity operator-(Quantity qty) { return Quantity(-qty.value()); }
#define QTY_QTY_BIN_OP(result_t, op) \
constexpr result_t operator op(Quantity lhs, Quantity rhs) { \
return result_t(lhs.value() op rhs.value()); \
}
#define QTY_QTY_BIN_REF_OP(op) \
constexpr Quantity &operator op(Quantity &lhs, Quantity rhs) { \
lhs.value() op rhs.value(); \
return lhs; \
}
#define QTY_UINT32_BIN_OP(result_t, op) \
constexpr result_t operator op(Quantity lhs, std::uint32_t rhs) { \
return result_t(lhs.value() op rhs); /*NOLINT*/ \
} \
constexpr result_t operator op(std::uint32_t lhs, Quantity rhs) { \
return result_t(lhs op rhs.value()); \
}
#define QTY_UINT32_BIN_REF_OP(op) \
inline Quantity &operator op(Quantity &lhs, std::uint32_t rhs) { \
lhs.value() op rhs; \
return lhs; \
} \
inline std::uint32_t &operator op(std::uint32_t &lhs, Quantity rhs) { \
lhs op rhs.value(); \
return lhs; \
}
QTY_QTY_BIN_OP(Quantity, +)
QTY_QTY_BIN_OP(Quantity, -)
QTY_QTY_BIN_OP(Quantity, *)
QTY_QTY_BIN_OP(Quantity, /)
QTY_QTY_BIN_OP(Quantity, %)
QTY_QTY_BIN_REF_OP(+=)
QTY_QTY_BIN_REF_OP(-=)
QTY_QTY_BIN_REF_OP(*=)
QTY_QTY_BIN_REF_OP(/=)
QTY_QTY_BIN_REF_OP(%=)
QTY_UINT32_BIN_OP(bool, !=)
QTY_UINT32_BIN_OP(bool, ==)
QTY_UINT32_BIN_OP(bool, <)
QTY_UINT32_BIN_OP(bool, <=)
QTY_UINT32_BIN_OP(bool, >)
QTY_UINT32_BIN_OP(bool, >=)
QTY_UINT32_BIN_OP(Quantity, +)
QTY_UINT32_BIN_OP(Quantity, -)
QTY_UINT32_BIN_OP(Quantity, *)
QTY_UINT32_BIN_OP(Quantity, /)
QTY_UINT32_BIN_OP(Quantity, %)
QTY_UINT32_BIN_REF_OP(+=)
QTY_UINT32_BIN_REF_OP(-=)
QTY_UINT32_BIN_REF_OP(*=)
QTY_UINT32_BIN_REF_OP(/=)
QTY_UINT32_BIN_REF_OP(%=)
#undef QTY_QTY_BIN_OP
#undef QTY_QTY_BIN_REF_OP
#undef QTY_UINT32_BIN_OP
#undef QTY_UINT32_BIN_REF_OP
} // namespace bts::domain
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class RFQ {};
} // namespace bts::domain
+42
View File
@@ -0,0 +1,42 @@
#pragma once
#include "FutureSecurity.h"
#include "IndexSecurity.h"
#include "OptionSecurity.h"
#include "SecurityCommon.h"
#include "SpreadSecurity.h"
#include "lib/utils/overloaded.h"
#include <variant>
namespace bts::domain {
class Security {
public:
SecurityCommon security_common;
std::variant<IndexSecurity, FutureSecurity, SpreadSecurity, OptionSecurity>
security;
api::domain::SecurityType security_type() const;
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
inline api::domain::SecurityType Security::security_type() const {
return std::visit(
overloaded{[](const IndexSecurity &) {
return api::domain::SecurityType::INDEX;
},
[](const FutureSecurity &) {
return api::domain::SecurityType::FUTURE;
},
[](const SpreadSecurity &) {
return api::domain::SecurityType::SPREAD;
},
[](const OptionSecurity &) {
return api::domain::SecurityType::OPTION;
}},
security);
}
} // namespace bts::domain
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include "Currency.h"
#include "Price.h"
#include "SecurityID.h"
#include "lib/api/domain/Currency.pb.h"
#include "lib/api/domain/SecurityType.pb.h"
#include "lib/api/domain/Venue.pb.h"
#include <string>
namespace bts::domain {
// All the security common params, ie regardless of Future, Spot, Spread etc
class SecurityCommon {
public:
api::domain::Venue venue;
SecurityID id{};
api::domain::SecurityType type;
api::domain::Currency currency;
double display_factor{};
double cash_per_point{};
std::string symbol;
std::string group;
std::string asset;
std::string desc;
Price min_price_increment{};
double min_price_increment_ammount = 0;
bool implied_matching = false;
std::string cme_security_type;
};
} // namespace bts::domain
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
#include <cstdint>
namespace bts::domain {
using SecurityID = utils::ValueWrapper<struct SecuirtyIDTag, std::uint64_t>;
} // namespace bts::domain
@@ -0,0 +1,18 @@
#pragma once
#include "Price.h"
#include "Quantity.h"
#include "Security.h"
namespace bts::domain {
class SecurityMarketDataStatistics {
public:
SecurityID security_id;
Price low;
Price high;
Price open;
Price settle;
Quantity volume;
};
} // namespace bts::domain
+76
View File
@@ -0,0 +1,76 @@
#pragma once
#include "lib/domain/SecurityID.h"
#include "lib/domain/Venue.h"
#include <unordered_map>
#include <unordered_set>
#include <vector>
namespace bts::domain {
class SecurityResolver {
public:
static domain::Venue id_to_venue(domain::SecurityID id);
static domain::SecurityID symbol_to_id(
domain::Venue venue, const std::string &symbol);
static std::string id_to_symbol(domain::SecurityID id);
template <class IDs, class Venues = std::vector<domain::Venue>>
static std::vector<domain::SecurityID> ids_for_venue(
const IDs &ids, const Venues &venues);
template <class IDs>
static std::
unordered_map<domain::Venue, std::unordered_set<domain::SecurityID>>
map_venue_to_id(const IDs &ids);
};
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
inline domain::Venue SecurityResolver::id_to_venue(domain::SecurityID /*id*/) {
// TODO
return domain::Venue::None;
}
inline domain::SecurityID SecurityResolver::symbol_to_id(
domain::Venue /*venue*/, const std::string & /*symbol*/) {
// TODO
return domain::SecurityID{0};
}
inline std::string SecurityResolver::id_to_symbol(domain::SecurityID /*id*/) {
// TODO
return "";
}
template <class IDs, class Venues>
std::vector<domain::SecurityID> SecurityResolver::ids_for_venue(
const IDs &ids, const Venues &venues) {
std::vector<domain::SecurityID> rv;
for (auto id : ids) {
auto id_venue = id_to_venue(id);
for (auto venue : venues) {
if (id_venue == venue) {
rv.push_back(id);
break;
}
}
}
return rv;
}
template <class IDs>
std::unordered_map<domain::Venue, std::unordered_set<domain::SecurityID>>
SecurityResolver::map_venue_to_id(const IDs &ids) {
std::unordered_map<domain::Venue, std::unordered_set<domain::SecurityID>> rv;
for (auto id : ids) {
auto venue = id_to_venue(id);
rv[venue].insert(id);
}
return rv;
}
} // namespace bts::domain
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "SecurityID.h"
namespace bts::domain {
class SecurityState {
public:
enum class State { PREOPEN, OPEN };
State state = State::OPEN;
SecurityID security_id;
};
} // namespace bts::domain
+8
View File
@@ -0,0 +1,8 @@
#pragma once
namespace bts::domain {
// more types will be needed there like spots etc
enum class SecurityType { INDEX, FUTURE, SPREAD, OPTION };
} // namespace bts::domain
+10
View File
@@ -0,0 +1,10 @@
#include "Side.h"
namespace bts::domain {
std::ostream &operator<<(std::ostream &out, const Side &s) {
out << s.name();
return out;
}
} // namespace bts::domain
+155
View File
@@ -0,0 +1,155 @@
#pragma once
#include <ostream>
namespace bts::domain {
class Side {
public:
enum Value { Buy = 0, Sell = 1 };
Value value;
Side() = default;
constexpr Side(Side::Value value) noexcept; // NOLINT
Side(const Side &) noexcept = default;
Side(Side &&) noexcept = default;
Side &operator=(const Side &) noexcept = default;
Side &operator=(Side &&) noexcept = default;
~Side() = default;
static constexpr Side from_contract_flow(int flow);
[[nodiscard]] constexpr size_t as_index() const noexcept;
[[nodiscard]] constexpr int as_contract_flow() const noexcept;
[[nodiscard]] constexpr int as_cash_flow() const noexcept;
[[nodiscard]] constexpr const char *name() const noexcept;
[[nodiscard]] constexpr Side other() const noexcept;
template <class NumericT>
constexpr NumericT normalize(NumericT numeric) const noexcept;
template <class T>
[[nodiscard]] T &pick(T &pick_if_buy, T &pick_if_sell) const;
template <class T>
[[nodiscard]] const T &pick(
const T &pick_if_buy, const T &pick_if_sell) const;
template <class C>
static void foreach (C c);
template <class C>
static bool foreither(C c);
template <class C>
static bool forboth(C c);
};
constexpr bool operator==(Side lhs, Side rhs) noexcept;
constexpr bool operator==(Side lhs, Side::Value rhs) noexcept;
constexpr bool operator!=(Side lhs, Side rhs) noexcept;
constexpr bool operator!=(Side lhs, Side::Value rhs) noexcept;
constexpr Side operator*(Side lhs, Side rhs) noexcept;
constexpr Side operator*(Side lhs, Side::Value rhs) noexcept;
std::ostream &operator<<(std::ostream &out, const Side &s);
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr Side Side::from_contract_flow(int flow) {
if (flow > 0) {
return Side::Buy;
}
return Side::Sell;
}
constexpr Side::Side(Side::Value value) noexcept : value(value) {}
constexpr std::size_t Side::as_index() const noexcept { return (int)value; }
constexpr int Side::as_contract_flow() const noexcept {
if (value == Buy) {
return 1;
}
return -1;
}
constexpr int Side::as_cash_flow() const noexcept {
if (value == Buy) {
return -1;
}
return 1;
}
constexpr const char *Side::name() const noexcept {
if (value == Side::Buy) {
return "Buy";
}
return "Sell";
}
constexpr Side Side::other() const noexcept {
if (value == Side::Buy) {
return {Side::Sell};
}
return {Side::Buy};
}
template <class NumericT>
constexpr NumericT Side::normalize(NumericT numeric) const noexcept {
return value == Side::Buy ? numeric : -numeric;
}
template <class T>
T &Side::pick(T &pick_if_buy, T &pick_if_sell) const {
return value == Side::Buy ? pick_if_buy : pick_if_sell;
}
template <class T>
const T &Side::pick(const T &pick_if_buy, const T &pick_if_sell) const {
return value == Side::Buy ? pick_if_buy : pick_if_sell;
}
template <class C>
void Side::foreach (C c) {
c(Side(Side::Buy));
c(Side(Side::Sell));
}
template <class C>
bool Side::foreither(C c) {
return c(Side(Side::Buy)) || c(Side(Side::Sell));
}
template <class C>
bool Side::forboth(C c) {
return c(Side(Side::Buy)) && c(Side(Side::Sell));
}
constexpr bool operator==(Side lhs, Side rhs) noexcept {
return lhs.value == rhs.value;
}
constexpr bool operator==(Side lhs, Side::Value rhs) noexcept {
return lhs.value == rhs;
}
constexpr bool operator!=(Side lhs, Side rhs) noexcept {
return lhs.value != rhs.value;
}
constexpr bool operator!=(Side lhs, Side::Value rhs) noexcept {
return lhs.value != rhs;
}
constexpr Side operator*(Side lhs, Side rhs) noexcept {
return rhs == Side::Buy ? lhs : lhs.other();
}
constexpr Side operator*(Side lhs, Side::Value rhs) noexcept {
return rhs == Side::Buy ? lhs : lhs.other();
}
} // namespace bts::domain
+14
View File
@@ -0,0 +1,14 @@
#pragma once
#include "LegDefinition.h"
#include "SecurityCommon.h"
#include <vector>
namespace bts::domain {
class SpreadSecurity {
public:
SecurityCommon security_definition;
std::vector<LegDefinition> legs;
};
} // namespace bts::domain
+10
View File
@@ -0,0 +1,10 @@
#include "TimeInForce.h"
namespace bts::domain {
std::ostream &operator<<(std::ostream &out, const TimeInForce &tif) noexcept {
out << TimeInForce_name(tif);
return out;
}
} // namespace bts::domain
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <ostream>
namespace bts::domain {
enum class TimeInForce { Day = 48, GTC = 49, IOC = 51, Date = 52 };
constexpr const char *TimeInForce_name(TimeInForce tif);
std::ostream &operator<<(std::ostream &out, const TimeInForce &tif) noexcept;
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
constexpr const char *TimeInForce_name(TimeInForce tif) {
switch (tif) {
case TimeInForce::Day:
return "Day";
case TimeInForce::GTC:
return "GTC";
case TimeInForce::IOC:
return "IOC";
case TimeInForce::Date:
return "Date";
default:
return "Unknown";
}
}
} // namespace bts::domain
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include "SecurityID.h"
#include "lib/core/TimeStamp.h"
#include "AggressorSide.h"
#include "Quantity.h"
#include "Price.h"
namespace bts::domain {
class TradeRecord {
public:
SecurityID sec_id = {};
TimeStamp time_stamp = {};
AggressorSide agg_side = {};
Quantity trade_quantity;
Price trade_price;
};
} // namespace bts::domain
+9
View File
@@ -0,0 +1,9 @@
#pragma once
#include "lib/utils/ValueWrapper.h"
#include <cstdint>
namespace bts::domain {
using UserID = utils::ValueWrapper<struct UserIDTag, std::uint64_t>;
} // namespace bts::domain
+14
View File
@@ -0,0 +1,14 @@
#pragma once
namespace bts::domain {
enum class Venue {
None = 0,
Glbx = 1,
Deribit = 2,
Huobi = 3,
Binance = 4,
FTX = 5
};
} // namespace bts::domain
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class GlbxOrderDefinition {};
} // namespace bts::domain
+7
View File
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class GlbxOrderState {};
} // namespace bts::domain
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class DeribitOrderDefinition {};
} // namespace bts::domain
@@ -0,0 +1,7 @@
#pragma once
namespace bts::domain {
class DeribitOrderState {};
} // namespace bts::domain
+16
View File
@@ -0,0 +1,16 @@
#include "QueryParams.h"
#include <fmt/format.h>
#include <range/v3/view.hpp>
namespace bts::io {
std::string QueryParams::to_string() const {
std::string rv;
auto query_param_strs = ranges::transform_view(
*this, [](const auto &qp) { return qp.first + "=" + qp.second; });
rv.append(fmt::format(
"{}", fmt::join(query_param_strs.begin(), query_param_strs.end(), "&")));
return rv;
}
} // namespace bts::io
+13
View File
@@ -0,0 +1,13 @@
#pragma once
#include "lib/collections/FlatUnorderedMap.h"
#include <string>
namespace bts::io {
class QueryParams
: public collections::FlatUnorderedMap<std::string, std::string> {
public:
std::string to_string() const;
};
} // namespace bts::io
+153
View File
@@ -0,0 +1,153 @@
#include "URL.h"
#include "lib/api/io/URL.pb.h"
#include <fmt/format.h>
#include <iostream>
#include <range/v3/view.hpp>
#include <range/v3/view/transform.hpp>
#include <string>
namespace bts::io {
// URL:: URL(const api::io::URL &url) : protocol_(url.protocol()),
// host_(url.host()), port_(url.port()), path_(url.path()) {}
URL::URL(const bts::api::io::URL &url)
: protocol_(url.protocol()), host_(url.host()), port_(url.port()),
path_(url.path()) {
for (const auto &qp : url.query_params()) {
query_params_[qp.key()] = qp.value();
}
}
std::vector<std::pair<std::string, std::uint16_t>> URL::well_known_ports_() {
return std::vector<std::pair<std::string, std::uint16_t>>{
{"http", 80}, {"https", 443}, {"ws", 80},
{"wss", 443}, {"ssh", 22}, {"sftp", 22},
};
}
std::uint16_t URL::get_known_port_for_protocol(const std::string &protocol) {
auto wkps = well_known_ports_();
for (const auto &p : wkps) {
if (p.first == protocol) {
return p.second;
}
}
return 0;
}
std::string URL::get_known_protocol_for_port(std::uint16_t port) {
auto wkps = well_known_ports_();
for (const auto &p : wkps) {
if (p.second == port) {
return p.first;
}
}
return "";
}
std::string &URL::protocol() { return protocol_; }
const std::string &URL::protocol() const { return protocol_; }
std::string &URL::host() { return host_; }
const std::string &URL::host() const { return host_; }
std::uint16_t &URL::port() { return port_; }
std::uint16_t URL::port() const { return port_; }
std::string &URL::path() { return path_; }
const std::string &URL::path() const { return path_; }
QueryParams &URL::query_params() { return query_params_; }
const QueryParams &URL::query_params() const { return query_params_; }
std::string URL::to_string() const {
auto rv = protocol() + "://";
if (host().empty()) {
rv.append("localhost");
} else {
rv.append(host());
}
if (port_ != 0) {
rv.append(":" + std::to_string(port_));
}
if (!path_.empty()) {
rv.append("/" + path_);
}
if (!query_params_.empty()) {
rv.append("?");
auto query_param_strs =
ranges::transform_view(query_params_, [](const auto &qp) {
return qp.first + "=" + qp.second;
});
rv.append(fmt::format(
"{}",
fmt::join(query_param_strs.begin(), query_param_strs.end(), "&")));
}
return rv;
}
std::ostream &operator<<(std::ostream &out, const URL &url) noexcept {
out << url.to_string();
return out;
}
void URL::fill_protocol(const std::string &protocol) {
if (protocol_.empty()) {
protocol_ = protocol;
}
}
void URL::fill_host(const std::string &host) {
if (host_.empty()) {
host_ = host;
}
}
void URL::fill_port(std::uint16_t port) {
if (port_ == 0) {
port_ = port;
}
}
void URL::fill_path(const std::string &path) {
if (path_.empty()) {
path_ = path;
}
}
void URL::fill_query_params(
const QueryParams &query_params, bool add_missing_params) {
if (query_params_.empty()) {
query_params_ = query_params;
} else if (add_missing_params) {
for (const auto &[k, v] : query_params) {
query_params_.try_emplace(k, v);
}
}
}
void URL::fill_with(const URL &url) {
fill_path(url.path());
fill_host(url.host());
fill_protocol(url.protocol());
fill_port(url.port());
fill_query_params(url.query_params());
}
bool operator==(const URL &lhs, const URL &rhs) noexcept {
bool rv = lhs.protocol() == rhs.protocol() && lhs.host() == rhs.host() &&
lhs.path() == rhs.path() && lhs.port() == rhs.port();
if (rv) {
rv = std::equal(
lhs.query_params().begin(), lhs.query_params().end(),
rhs.query_params().begin(), rhs.query_params().end());
}
return rv;
}
bool operator!=(const URL &lhs, const URL &rhs) noexcept {
return !(lhs == rhs);
}
} // namespace bts::io
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include "QueryParams.h"
#include "lib/core/HashPhaser.h"
#include <functional>
#include <ostream>
#include <string>
#include <unordered_set>
#include <variant>
#include <vector>
namespace bts::api::io {
class URL;
}
namespace bts::io {
class URL {
public:
URL() = default;
explicit URL(const bts::api::io::URL &url);
URL(const URL &) = default;
URL(URL &&) noexcept = default;
URL &operator=(const URL &) = default;
URL &operator=(URL &&) noexcept = default;
std::string &protocol();
const std::string &protocol() const;
std::string &host();
const std::string &host() const;
std::uint16_t &port();
std::uint16_t port() const;
std::string &path();
const std::string &path() const;
QueryParams &query_params();
const QueryParams &query_params() const;
std::string to_string() const;
void fill_protocol(const std::string &protocol);
void fill_host(const std::string &host);
void fill_path(const std::string &path);
void fill_port(std::uint16_t port);
void fill_query_params(
const QueryParams &query_params, bool add_missing_params = false);
void fill_with(const URL &url);
static std::uint16_t get_known_port_for_protocol(
const std::string &protocol);
static std::string get_known_protocol_for_port(std::uint16_t port);
private:
std::string protocol_;
std::string host_;
std::uint16_t port_;
std::string path_;
QueryParams query_params_;
static std::vector<std::pair<std::string, std::uint16_t>>
well_known_ports_();
};
bool operator==(const URL &lhs, const URL &rhs) noexcept;
bool operator!=(const URL &lhs, const URL &rhs) noexcept;
std::ostream &operator<<(std::ostream &out, const URL &url) noexcept;
} // namespace bts::io
namespace std {
template <>
struct hash<bts::io::URL> {
std::size_t operator()(const bts::io::URL &url) const;
};
} // namespace std
//////////////////////////////////////////////////
// Definition
//////////////////////////////////////////////////
namespace std {
inline std::size_t hash<bts::io::URL>::operator()(
const bts::io::URL &url) const {
return bts::core::HashPhaser::auto_phase(
url.protocol(), url.host(), url.port(), url.path(),
url.query_params().size());
}
} // namespace std
+21
View File
@@ -0,0 +1,21 @@
#include "CurlHandle.h"
#include <curl/curl.h>
#include <stdexcept>
namespace bts::http {
CurlHandle::CurlHandle() {
const auto eCode = curl_global_init(CURL_GLOBAL_ALL);
if (eCode != CURLE_OK) {
throw std::runtime_error{"Error initializing libCURL"};
}
}
CurlHandle::~CurlHandle() { curl_global_cleanup(); }
CurlHandle &CurlHandle::instance() {
static CurlHandle inst{};
return inst;
}
} // namespace bts::http
+21
View File
@@ -0,0 +1,21 @@
#pragma once
namespace bts::http {
class CurlHandle {
public:
static CurlHandle &instance();
CurlHandle(CurlHandle const &) = delete;
CurlHandle(CurlHandle &&) = delete;
CurlHandle &operator=(CurlHandle const &) = delete;
CurlHandle &operator=(CurlHandle &&) = delete;
~CurlHandle();
private:
CurlHandle();
};
} // namespace bts::http
+55
View File
@@ -0,0 +1,55 @@
#include "HTTPClient.h"
#include "HTTPRequest.h"
#include "HTTPResponse.h"
#include "lib/io/URL.h"
#include "lib/logging/logging.h"
#include <curl/curl.h>
#include <fmt/format.h>
namespace bts::io::http {
static size_t write_data_(
void *ptr, size_t size, size_t nmemb, std::string *data) {
data->append((char *)ptr, size * nmemb);
return size * nmemb;
}
HTTPResponse HTTPClient::get(const HTTPRequest &request) {
auto *curl = curl_easy_init();
auto url_str = request.url().to_string();
// LOG(md, bts::Info, "do GET: {}", url_str);
curl_easy_setopt(curl, CURLOPT_URL, url_str.c_str());
struct curl_slist *request_headers = NULL;
for (const auto &[k, v] : request.headers()) {
request_headers = curl_slist_append(
request_headers, fmt::format("{}: {}", k, v).c_str());
}
std::string response_string;
std::string header_string;
std::string response_header_string;
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, write_data_);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &response_string);
curl_easy_setopt(curl, CURLOPT_HEADERDATA, &header_string);
char *url;
long response_code;
double elapsed;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &response_code);
curl_easy_getinfo(curl, CURLINFO_TOTAL_TIME, &elapsed);
curl_easy_getinfo(curl, CURLINFO_EFFECTIVE_URL, &url);
// curl_easy_getinfo(curl, CURLINFO_HEADER_OUT, &response_header_string);
curl_easy_perform(curl);
curl_easy_cleanup(curl);
curl = NULL;
HTTPResponse response;
response.headers() = HTTPHeaders(response_header_string);
response.body() = std::move(response_string);
response.code() = response_code;
// LOG(md, bts::Info, "do GET: {}. Received response:\n{}", url_str, response);
return response;
}
} // namespace bts::io::http
+35
View File
@@ -0,0 +1,35 @@
#include <algorithm>
#include <atomic>
#include <cstddef> // std::size_t
#include <cstdio> // snprintf
#include <cstdlib>
#include <cstring> // strerror, strlen, memcpy, strcpy
#include <ctime>
#include <curl/curl.h>
#include <fstream>
#include <functional>
#include <iostream>
#include <memory> // std::unique_ptr
#include <mutex>
#include <sstream>
#include <stdarg.h> // va_start, etc.
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <sys/stat.h>
#include <sys/types.h>
#include <unordered_map>
#include <vector>
namespace bts::io::http {
class HTTPRequest;
class HTTPResponse;
class HTTPClient {
public:
// HTTPClient(const std::string &url);
HTTPResponse get(const HTTPRequest &request);
};
} // namespace bts::io::http
+46
View File
@@ -0,0 +1,46 @@
#include "HTTPHeaders.h"
#include "lib/utils/StringSplitter.h"
#include <fmt/format.h>
#include <range/v3/view.hpp>
#include <string>
#include <unordered_map>
#include <vector>
namespace bts::io::http {
HTTPHeaders::HTTPHeaders(const std::string &str) {
auto item_strs = utils::StringSplitter::split(str, "\n");
auto items = ranges::transform_view(
item_strs,
[](const std::string &item_str) -> std::pair<std::string, std::string> {
auto kv = utils::StringSplitter::split(item_str, ":");
if (kv.empty()) {
return std::make_pair("", "");
}
if (kv.size() == 1) {
return std::make_pair(kv[0], std::string(""));
}
return std::make_pair(kv[0], kv[1]);
});
for (auto p : items) {
try_emplace(p.first, p.second);
}
}
std::string HTTPHeaders::to_string() const {
std::string rv;
auto query_param_strs = ranges::transform_view(
*this, [](const auto &qp) { return qp.first + ": " + qp.second; });
rv.append(fmt::format(
"{}",
fmt::join(query_param_strs.begin(), query_param_strs.end(), "\n")));
return rv;
}
std::ostream &operator<<(
std::ostream &out, const HTTPHeaders &headers) noexcept {
out << headers.to_string();
return out;
}
} // namespace bts::io::http
Loaded 100 of 302 files, more files were not shown because too many files have changed in this diff. Show more