Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
048515fb6d | ||
|
|
ebad120040 |
No files matched your search
@@ -7,24 +7,6 @@
|
||||
"commands": [
|
||||
"dotnet-format"
|
||||
]
|
||||
},
|
||||
"fable": {
|
||||
"version": "4.0.0-theta-018",
|
||||
"commands": [
|
||||
"fable"
|
||||
]
|
||||
},
|
||||
"fantomas": {
|
||||
"version": "5.2.2",
|
||||
"commands": [
|
||||
"fantomas"
|
||||
]
|
||||
},
|
||||
"fake-cli": {
|
||||
"version": "6.0.0",
|
||||
"commands": [
|
||||
"fake"
|
||||
]
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,4 +50,3 @@ trace_data/
|
||||
*.tmp/*
|
||||
/.venv*/*
|
||||
.cache/
|
||||
src/web/api/tsconfig.*.g.json
|
||||
@@ -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
|
||||
+2
-9
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
project(spark)
|
||||
|
||||
if(WIN32)
|
||||
@@ -7,12 +7,7 @@ else()
|
||||
set(platform "linux")
|
||||
endif()
|
||||
|
||||
set(
|
||||
EXTERNALS_ROOT
|
||||
"${CMAKE_SOURCE_DIR}/externals/${platform}"
|
||||
CACHE
|
||||
STRING
|
||||
"External dependencies root folder (should contain folders: lib, bin, include")
|
||||
set(EXTERNALS_ROOT "${CMAKE_SOURCE_DIR}/externals/${platform}")
|
||||
set(SPARK_PYTHON "${EXTERNALS_ROOT}/python")
|
||||
set(SPARK_BIN "${EXTERNALS_ROOT}/bin")
|
||||
set(SPARK_INCLUDE "${EXTERNALS_ROOT}/include")
|
||||
@@ -57,7 +52,6 @@ else()
|
||||
add_compile_definitions(SPARK_ENABLE_CCAPI)
|
||||
add_compile_definitions(CCAPI_ENABLE_SERVICE_MARKET_DATA)
|
||||
add_compile_definitions(CCAPI_ENABLE_EXCHANGE_FTX)
|
||||
add_compile_definitions(CCAPI_ENABLE_EXCHANGE_BINANCE)
|
||||
add_compile_definitions(CCAPI_ENABLE_LOG_WARN)
|
||||
|
||||
# flags
|
||||
@@ -106,7 +100,6 @@ else()
|
||||
|
||||
add_custom_target(server_layout ALL DEPENDS ${CMAKE_BINARY_DIR}/server)
|
||||
|
||||
install(DIRECTORY "${CMAKE_BINARY_DIR}/server/plugins" DESTINATION bin)
|
||||
install(FILES "${CMAKE_SOURCE_DIR}/externals/linux/lib/${CMAKE_BUILD_TYPE}/libACE-5.7.5.so" DESTINATION bin)
|
||||
install(FILES "${CMAKE_SOURCE_DIR}/externals/linux/lib/${CMAKE_BUILD_TYPE}/libOnixS.IceImpactMulticastPriceFeedHandlerCpp.so.3.16.0.0" DESTINATION bin)
|
||||
install(FILES "${CMAKE_SOURCE_DIR}/externals/src/emumba/sparkd.lic" DESTINATION bin)
|
||||
|
||||
@@ -106,9 +106,8 @@ function(Service_Compiler_Generate_Cpp SRCS HDRS)
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.client.pb.h"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.server.pb.cc"
|
||||
"${CMAKE_CURRENT_BINARY_DIR}/${FIL_WE}.server.pb.h"
|
||||
COMMAND ${CMAKE_SOURCE_DIR}/tools/venv_exec.sh
|
||||
ARGS
|
||||
${Protobuf_PROTOC_EXECUTABLE}
|
||||
COMMAND
|
||||
"PYTHONPATH=${SPARK_PYTHON}" ${Protobuf_PROTOC_EXECUTABLE} ARGS
|
||||
--cpp_out=${CMAKE_BINARY_DIR}/src
|
||||
--plugin=protoc-gen-service=${CMAKE_SOURCE_DIR}/src/lib/api/service_compiler/plugin.py
|
||||
--service_out=lang=cpp,make_file_name=${ABS_FIL}:${CMAKE_BINARY_DIR}/src
|
||||
|
||||
@@ -46,7 +46,6 @@ function setup_build
|
||||
assert_dir $repo_root
|
||||
assert_dir $build_root
|
||||
set compiler "$argv[1]"
|
||||
set c_compiler (which cc)
|
||||
set build_type "$argv[2]"
|
||||
|
||||
if test \( -z "$build_type" \) -o \( \( "$build_type" != debug \) -a \( "$build_type" != release \) \)
|
||||
@@ -60,7 +59,6 @@ function setup_build
|
||||
else
|
||||
# set compiler_arg "/usr/lib/ccache/clang++"
|
||||
set compiler_arg "clang++"
|
||||
set c_compiler (which clang)
|
||||
end
|
||||
else if test "$build_type" = release
|
||||
set build_type_arg Release
|
||||
@@ -87,7 +85,7 @@ function setup_build
|
||||
rm -rf "$build_dest"
|
||||
mkdir -p "$build_dest"
|
||||
cd "$build_dest"
|
||||
cmake -G Ninja -DCMAKE_BUILD_TYPE=$build_type_arg -DCMAKE_EXPORT_COMPILE_COMMANDS=1 -DCMAKE_C_COMPILER=$c_compiler -DCMAKE_CXX_COMPILER=$compiler_arg $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.
|
||||
|
||||
+1
-1
Submodule docker/linux updated: 6537812262...05967d0f18.
@@ -1,135 +0,0 @@
|
||||
FROM ubuntu:latest
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
ENV TZ=America/New_York
|
||||
|
||||
# light deps (should be quick to download/install)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
ca-certificates \
|
||||
curl \
|
||||
gnupg \
|
||||
liblttng-ust-dev \
|
||||
libpcap0.8-dev \
|
||||
locales \
|
||||
ninja-build \
|
||||
software-properties-common \
|
||||
sqlite3 \
|
||||
tzdata
|
||||
|
||||
# clang
|
||||
RUN apt-get update && apt-get install -y \
|
||||
clang-13 \
|
||||
clang-format-13 \
|
||||
clangd-13 \
|
||||
clang-15 \
|
||||
clang-format-15 \
|
||||
clangd-15
|
||||
|
||||
# g++
|
||||
RUN apt-get update && apt-get install -y \
|
||||
g++-11 \
|
||||
g++-12
|
||||
|
||||
# python
|
||||
RUN apt-get update && apt-get install -y \
|
||||
python3-pip \
|
||||
python3-venv \
|
||||
&& python3 -m pip install --upgrade pip
|
||||
|
||||
# dotnet
|
||||
RUN apt-get update && apt-get install -y \
|
||||
dotnet7
|
||||
|
||||
# ssh
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libssh2-1-dev \
|
||||
openssh-server
|
||||
|
||||
# cmake
|
||||
RUN \
|
||||
curl -fsSL https://apt.kitware.com/keys/kitware-archive-latest.asc 2> /dev/null \
|
||||
| gpg --dearmor - | tee /etc/apt/trusted.gpg.d/kitware.gpg > /dev/null \
|
||||
&& apt-add-repository "deb https://apt.kitware.com/ubuntu/ $(lsb_release -cs) main" \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y cmake
|
||||
|
||||
# node
|
||||
ARG node_major=18
|
||||
RUN mkdir -p /etc/apt/keyrings \
|
||||
&& curl -fsSL https://deb.nodesource.com/gpgkey/nodesource-repo.gpg.key \
|
||||
| gpg --dearmor -o /etc/apt/keyrings/nodesource.gpg \
|
||||
&& echo "deb [signed-by=/etc/apt/keyrings/nodesource.gpg] https://deb.nodesource.com/node_$node_major.x nodistro main" \
|
||||
| tee /etc/apt/sources.list.d/nodesource.list \
|
||||
&& apt-get update \
|
||||
&& apt-get install -y nodejs
|
||||
|
||||
# ccache is done here so that ccache sees clang++ installed, not clang-10
|
||||
RUN apt-get update && apt-get install -y \
|
||||
ccache
|
||||
|
||||
# emumba (light deps)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
build-essential \
|
||||
doxygen \
|
||||
python3-sphinx \
|
||||
graphviz \
|
||||
libgtest-dev \
|
||||
libssl-dev \
|
||||
rapidjson-dev \
|
||||
zlib1g-dev \
|
||||
pkg-config
|
||||
|
||||
# emumba (boost)
|
||||
RUN apt-get update && apt-get install -y \
|
||||
libboost-filesystem-dev \
|
||||
libboost-program-options-dev \
|
||||
libboost-test-dev \
|
||||
libboost-date-time-dev
|
||||
|
||||
# dev utils
|
||||
RUN apt-get update && apt-get install -y \
|
||||
fish \
|
||||
git-all \
|
||||
sudo \
|
||||
vim \
|
||||
wget
|
||||
|
||||
# set up default executables (update-alternatives)
|
||||
RUN \
|
||||
update-alternatives --install /usr/bin/clang++ clang++ /usr/bin/clang++-13 100; \
|
||||
update-alternatives --install /usr/bin/clang clang /usr/bin/clang-13 100; \
|
||||
update-alternatives --install /usr/bin/clang-format clang-format /usr/bin/clang-format-13 100; \
|
||||
update-alternatives --install /usr/bin/clangd clangd /usr/bin/clangd-13 100; \
|
||||
update-alternatives --install /usr/bin/g++ g++ /usr/bin/g++-11 100; \
|
||||
update-alternatives --install /usr/bin/gcc gcc /usr/bin/gcc-11 100
|
||||
|
||||
# Add compiler symlinks for ccache
|
||||
RUN \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang++; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang-13; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang++-13; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang-15; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/clang++-15; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/gcc; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/g++; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/gcc-11; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/g++-11; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/gcc-12; \
|
||||
ln -s /usr/bin/ccache /usr/local/bin/g++-12
|
||||
|
||||
RUN locale-gen en_US.UTF-8
|
||||
|
||||
ARG docker_user="bts"
|
||||
ARG docker_uid="1000"
|
||||
ARG docker_pass="bts"
|
||||
|
||||
RUN \
|
||||
groupadd -g "$docker_uid" "$docker_user" \
|
||||
&& useradd \
|
||||
-m \
|
||||
-u "$docker_uid" \
|
||||
-g "$docker_uid" \
|
||||
-G sudo \
|
||||
--password "$(openssl passwd -1 "$docker_pass")" \
|
||||
"$docker_user"
|
||||
@@ -1,64 +0,0 @@
|
||||
[dev containers]: https://code.visualstudio.com/docs/devcontainers/containers
|
||||
[dev containers ext]: https://marketplace.visualstudio.com/items?itemName=ms-vscode-remote.remote-containers
|
||||
[docker repo sparkd-dev]: https://hub.docker.com/repository/docker/bluetradingsystems/sparkd-dev/general
|
||||
# Sparkd Dev Container
|
||||
## How to create a VS Code [Dev Container][dev containers]
|
||||
|
||||
1. Make sure the **[Dev Containers][dev containers ext]** extension is installed
|
||||
1. Make sure your Docker image is up to date
|
||||
```
|
||||
docker pull bluetradingsystems/sparkd-dev:latest
|
||||
```
|
||||
1. Copy **devcontainer.json** from this folder to **$workspaceFolder/.devcontainer/**.
|
||||
|
||||
1. In the VS Code Command Palette, run **Dev Containers: Reopen in Container**
|
||||
|
||||
---
|
||||
## How to create a Sparkd Container in the terminal (without VS Code)
|
||||
|
||||
1. Make sure your Docker image is up to date
|
||||
```
|
||||
docker pull bluetradingsystems/sparkd-dev:latest
|
||||
```
|
||||
2. Start the container
|
||||
```
|
||||
# Replace <cont_name> with a name for the container. The container's
|
||||
# "$HOME" dir will be mounted to "$HOME/.sparkd-dev/mounts/<cont_name> on
|
||||
# the host
|
||||
|
||||
./start_docker.sh --container <cont_name> --mount-existing
|
||||
```
|
||||
* *Replace <cont_name> with a name for the container*
|
||||
* *The container's `$HOME` dir will be mounted to
|
||||
`$HOME/.sparkd-dev/mounts<cont_name>` on the host*<br>
|
||||
* *Run: `./start_docker.sh --help` to see additional options*
|
||||
3. *(Optional) Attach VS Code to the running container.*<br>
|
||||
Run **Dev Containers: Attach to Running Container** from the command palette,
|
||||
then select your container in the dropdown
|
||||
|
||||
---
|
||||
## How to update the Docker image
|
||||
|
||||
1. Change the image by modifying the Dockerfile (don't tag arbitrary
|
||||
images on your machine and push them to our repo on Docker Hub)
|
||||
|
||||
1. After modifying the Dockerfile, (re)build the image
|
||||
```
|
||||
# Run in this dir
|
||||
docker build -t bluetradingsystems/sparkd-dev:latest .
|
||||
```
|
||||
***Note:** Your docker login must have write permissions to push to the
|
||||
[sparkd-dev][docker repo sparkd-dev] repository*
|
||||
|
||||
2. Commit the changes to Dockerfile in git
|
||||
|
||||
3. Push the new image to Docker Hub
|
||||
|
||||
```
|
||||
docker push bluetradingsystems/sparkd-dev:latest
|
||||
```
|
||||
***Note:** The image doesn't have to be on Docker Hub, we can simply build
|
||||
it from scratch on our local machines (with the Dockerfile). However, this
|
||||
takes time. It is significantly quicker to download a prebuilt image, so we
|
||||
store it on a remote repository to save time when setting up a new dev
|
||||
machine.*
|
||||
@@ -1,123 +0,0 @@
|
||||
# ~/.bashrc: executed by bash(1) for non-login shells.
|
||||
# see /usr/share/doc/bash/examples/startup-files (in the package bash-doc)
|
||||
# for examples
|
||||
|
||||
# If not running interactively, don't do anything
|
||||
case $- in
|
||||
*i*) ;;
|
||||
*) return;;
|
||||
esac
|
||||
|
||||
# don't put duplicate lines or lines starting with space in the history.
|
||||
# See bash(1) for more options
|
||||
HISTCONTROL=ignoreboth
|
||||
|
||||
# append to the history file, don't overwrite it
|
||||
shopt -s histappend
|
||||
|
||||
# for setting history length see HISTSIZE and HISTFILESIZE in bash(1)
|
||||
HISTSIZE=1000
|
||||
HISTFILESIZE=2000
|
||||
|
||||
# check the window size after each command and, if necessary,
|
||||
# update the values of LINES and COLUMNS.
|
||||
shopt -s checkwinsize
|
||||
|
||||
# If set, the pattern "**" used in a pathname expansion context will
|
||||
# match all files and zero or more directories and subdirectories.
|
||||
#shopt -s globstar
|
||||
|
||||
# make less more friendly for non-text input files, see lesspipe(1)
|
||||
[ -x /usr/bin/lesspipe ] && eval "$(SHELL=/bin/sh lesspipe)"
|
||||
|
||||
# set variable identifying the chroot you work in (used in the prompt below)
|
||||
if [ -z "${debian_chroot:-}" ] && [ -r /etc/debian_chroot ]; then
|
||||
debian_chroot=$(cat /etc/debian_chroot)
|
||||
fi
|
||||
|
||||
# set a fancy prompt (non-color, unless we know we "want" color)
|
||||
case "$TERM" in
|
||||
xterm-color|*-256color) color_prompt=yes;;
|
||||
esac
|
||||
|
||||
# uncomment for a colored prompt, if the terminal has the capability; turned
|
||||
# off by default to not distract the user: the focus in a terminal window
|
||||
# should be on the output of commands, not on the prompt
|
||||
#force_color_prompt=yes
|
||||
|
||||
if [ -n "$force_color_prompt" ]; then
|
||||
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
|
||||
# We have color support; assume it's compliant with Ecma-48
|
||||
# (ISO/IEC-6429). (Lack of such support is extremely rare, and such
|
||||
# a case would tend to support setf rather than setaf.)
|
||||
color_prompt=yes
|
||||
else
|
||||
color_prompt=
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$color_prompt" = yes ]; then
|
||||
PS1='${debian_chroot:+($debian_chroot)}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ '
|
||||
else
|
||||
PS1='${debian_chroot:+($debian_chroot)}\u@\h:\w\$ '
|
||||
fi
|
||||
unset color_prompt force_color_prompt
|
||||
|
||||
# If this is an xterm set the title to user@host:dir
|
||||
case "$TERM" in
|
||||
xterm*|rxvt*)
|
||||
PS1="\[\e]0;${debian_chroot:+($debian_chroot)}\u@\h: \w\a\]$PS1"
|
||||
;;
|
||||
*)
|
||||
;;
|
||||
esac
|
||||
|
||||
# enable color support of ls and also add handy aliases
|
||||
if [ -x /usr/bin/dircolors ]; then
|
||||
test -r ~/.dircolors && eval "$(dircolors -b ~/.dircolors)" || eval "$(dircolors -b)"
|
||||
alias ls='ls --color=auto'
|
||||
#alias dir='dir --color=auto'
|
||||
#alias vdir='vdir --color=auto'
|
||||
|
||||
alias grep='grep --color=auto'
|
||||
alias fgrep='fgrep --color=auto'
|
||||
alias egrep='egrep --color=auto'
|
||||
fi
|
||||
|
||||
# colored GCC warnings and errors
|
||||
#export GCC_COLORS='error=01;31:warning=01;35:note=01;36:caret=01;32:locus=01:quote=01'
|
||||
|
||||
# some more ls aliases
|
||||
alias ll='ls -alF'
|
||||
alias la='ls -A'
|
||||
alias l='ls -CF'
|
||||
|
||||
# Add an "alert" alias for long running commands. Use like so:
|
||||
# sleep 10; alert
|
||||
alias alert='notify-send --urgency=low -i "$([ $? = 0 ] && echo terminal || echo error)" "$(history|tail -n1|sed -e '\''s/^\s*[0-9]\+\s*//;s/[;&|]\s*alert$//'\'')"'
|
||||
|
||||
# Alias definitions.
|
||||
# You may want to put all your additions into a separate file like
|
||||
# ~/.bash_aliases, instead of adding them here directly.
|
||||
# See /usr/share/doc/bash-doc/examples in the bash-doc package.
|
||||
|
||||
if [ -f ~/.bash_aliases ]; then
|
||||
. ~/.bash_aliases
|
||||
fi
|
||||
|
||||
# enable programmable completion features (you don't need to enable
|
||||
# this, if it's already enabled in /etc/bash.bashrc and /etc/profile
|
||||
# sources /etc/bash.bashrc).
|
||||
if ! shopt -oq posix; then
|
||||
if [ -f /usr/share/bash-completion/bash_completion ]; then
|
||||
. /usr/share/bash-completion/bash_completion
|
||||
elif [ -f /etc/bash_completion ]; then
|
||||
. /etc/bash_completion
|
||||
fi
|
||||
fi
|
||||
|
||||
if [[ ! -v XDG_CONFIG_HOME ]]; then
|
||||
export XDG_CONFIG_HOME="$HOME/.config"
|
||||
fi
|
||||
|
||||
export PATH="$HOME/.local/bin:$PATH"
|
||||
@@ -1,25 +0,0 @@
|
||||
if ! set -q XDG_CONFIG_HOME
|
||||
set -g XDG_CONFIG_HOME "$HOME/.config"
|
||||
end
|
||||
set fish_config_home $XDG_CONFIG_HOME/fish
|
||||
if test -f "$fish_config_home/aliases.fish"
|
||||
source "$fish_config_home/aliases.fish"
|
||||
end
|
||||
# enable general colors and case insensitive search in 'less'
|
||||
set -x LESS "$LESS -R -Q -I"
|
||||
set -x LC_ALL en_US.UTF-8
|
||||
# enable syntax highlighting in 'less'
|
||||
# set highlight color scheme in 'less' (fg)(bg)
|
||||
set -g LESS_TERMCAP_md (tput bold)(tput setaf 36)
|
||||
set -g LESS_TERMCAP_me (tput sgr0)
|
||||
set -g LESS_TERMCAP_so (tput setaf 232)(tput setab 49)
|
||||
|
||||
set -q TERM
|
||||
if test $status != 0; or test $TERM = 'xterm'
|
||||
set -g TERM 'xterm-256color'
|
||||
end
|
||||
|
||||
# Fix impossible-to-see navy blue command text color
|
||||
set fish_color_command F8F8F2
|
||||
|
||||
set -g PATH "$HOME/.local/bin" "$PATH"
|
||||
@@ -1,32 +0,0 @@
|
||||
{
|
||||
"image": "bluetradingsystems/sparkd-dev:latest",
|
||||
"initializeCommand": "${localWorkspaceFolder}/docker/sparkd/dev/devcontainer_initialize.sh",
|
||||
"hostRequirements": {
|
||||
"memory": "4gb",
|
||||
"storage": "6gb"
|
||||
},
|
||||
"postCreateCommand": "/home/bts/spark/docker/sparkd/dev/devcontainer_post_create.sh",
|
||||
"containerUser": "bts",
|
||||
"workspaceMount": "source=${localWorkspaceFolder},target=/home/bts/spark,type=bind",
|
||||
"workspaceFolder": "/home/bts/spark",
|
||||
"updateRemoteUserUID": true,
|
||||
"shutdownAction": "none",
|
||||
// Note: If running multiple containers on the same host, each must use a
|
||||
// unique set of ports. Usually we just add 1000 to each port as needed. For
|
||||
// example, if 8000-8003 is taken, go with 9000-9003, then 10000-10003, etc.
|
||||
"runArgs": [
|
||||
"--shm-size",
|
||||
"2gb",
|
||||
"-p",
|
||||
"8000:8000",
|
||||
"-p",
|
||||
"8001:8001",
|
||||
"-p",
|
||||
"8002:8002",
|
||||
"-p",
|
||||
"8003:8003"
|
||||
],
|
||||
"mounts": [
|
||||
"source=${localEnv:HOME}/.sparkd-dev/mounts/sparkd-dev,target=/home/bts,type=bind"
|
||||
]
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
mkdir -p "$HOME/.sparkd-dev/mounts/sparkd-dev"
|
||||
@@ -1,33 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
this_dir="$(realpath "$(dirname "${BASH_SOURCE[0]}")")"
|
||||
repo_dir="$(cd "$this_dir" && git rev-parse --show-toplevel)"
|
||||
tools_dir="$repo_dir/tools"
|
||||
gen_tag="GENERATED BY $(basename "${BASH_SOURCE[0]}")"
|
||||
|
||||
function copy_if_not_exist() {
|
||||
src="$1"
|
||||
dest="$2"
|
||||
if [[ ! -e "$src" ]]; then
|
||||
echo "Unable to copy $src to $dest. Source file doesn't exist"
|
||||
exit 1
|
||||
fi
|
||||
if [[ ! -e "$dest" ]]; then
|
||||
cp "$src" "$dest"
|
||||
fi
|
||||
}
|
||||
|
||||
# Init bashrc
|
||||
echo "Initializing bashrc"
|
||||
copy_if_not_exist "$this_dir/bashrc" "$HOME/.bashrc"
|
||||
|
||||
# Init fish config
|
||||
echo "Initializing fish config"
|
||||
fish_cfg_dir="$HOME/.config/fish/"
|
||||
mkdir -p "$fish_cfg_dir"
|
||||
exec "$tools_dir/write_tag_block.sh" \
|
||||
--tag "$gen_tag" \
|
||||
--replace \
|
||||
--in-place \
|
||||
--file "$fish_cfg_dir/config.fish" \
|
||||
--text "$(cat "$this_dir/config.fish")"
|
||||
@@ -1,250 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function _exit() {
|
||||
if [[ "$#" -gt 1 ]]; then
|
||||
# When there are multiple args, the last arg is the exit code.
|
||||
echo "${@:1:($# - 1)}"
|
||||
exit "${@: -1}"
|
||||
fi
|
||||
echo "$1"
|
||||
exit 0
|
||||
}
|
||||
|
||||
help_text="\
|
||||
Add or update a user's uid
|
||||
|
||||
This script is intended to be run in a Docker container as a means to obtain
|
||||
file permissions in mounted directories owned by the specified UID.
|
||||
|
||||
Usage: set_user.sh [OPTIONS] USER UID
|
||||
|
||||
Positionals:
|
||||
USER The name of the user
|
||||
|
||||
Options:
|
||||
--user USER The name of the user (defaults to 'bts')
|
||||
--uid UID The new uid to give USER (defaults to '1000')
|
||||
--group GROUP The primary group to give USER (defaults to USER)
|
||||
--gid GID The primary gid to give USER (defaults to UID)
|
||||
--pass PASSWORD The password to give USER (defaults to USER, only applies
|
||||
if USER hasn't been created yet)
|
||||
--modify-existing Update UID/GID even if USER already exists
|
||||
-h,--help Print this help message and exit
|
||||
|
||||
"
|
||||
|
||||
function _add_group() {
|
||||
if [[ "$#" -ne 2 ]]; then
|
||||
_exit "'_add_group' requires exactly 2 args (group, gid). Received $#." 1
|
||||
fi
|
||||
local group="$1"
|
||||
local gid="$2"
|
||||
# Check if gid already exists
|
||||
local existing_group=""
|
||||
existing_group="$(getent group "$gid" | cut -d : -f 1)"
|
||||
if [[ -n "$existing_group" ]]; then
|
||||
if [[ "$existing_group" != "$group" ]]; then
|
||||
echo "\
|
||||
The gid '$gid' is already in use by group '$existing_group' (will not rename \
|
||||
the group)"
|
||||
fi
|
||||
return
|
||||
fi
|
||||
|
||||
# Check if group with same name already exists
|
||||
local existing_gid=""
|
||||
existing_gid="$(getent group "$group" | cut -d : -f 3)"
|
||||
if [[ -n "$existing_gid" ]]; then
|
||||
# The group already exists. Only modify if --modify-existing was specified.
|
||||
if [[ "$modify_existing" -eq 0 ]]; then
|
||||
_exit "\
|
||||
The group '$group' already exists with gid '$existing_gid'.
|
||||
Specify --modify-existing to change the gid anyways." 1
|
||||
fi
|
||||
echo "Changing gid for group '$group' from '$existing_gid' to '$gid'"
|
||||
groupmod -g "$gid" "$group"
|
||||
else
|
||||
# The group doesn't exist. Add it
|
||||
echo "Adding group '$group:$gid'"
|
||||
groupadd -g "$gid" "$group"
|
||||
fi
|
||||
}
|
||||
|
||||
function _add_user() {
|
||||
local user="$1"
|
||||
local uid="$2"
|
||||
local group="$3"
|
||||
local gid="$4"
|
||||
local pass="$5"
|
||||
if [[ "$#" -ne 5 ]]; then
|
||||
_exit "'_add_user' requires exactly 5 args (user, uid, group, gid, pass). \
|
||||
Received $#." 1
|
||||
fi
|
||||
|
||||
# Check if uid is being used by another user
|
||||
local existing_user=""
|
||||
existing_user="$(getent passwd "$uid" | cut -d : -f 1)"
|
||||
if [[ -n "$existing_user" ]]; then
|
||||
if [[ "$existing_user" != "$user" ]]; then
|
||||
_exit "The uid '$uid' is already in use by user '$existing_user'." 1
|
||||
fi
|
||||
|
||||
echo "The user '$user' already has the specified uid '$uid'."
|
||||
# Modify gid if necessary
|
||||
local existing_gid=""
|
||||
existing_gid="$(id -g "$user" 2> /dev/null)"
|
||||
if [[ "$existing_gid" = "$gid" ]]; then
|
||||
echo "The user '$user' already has the specified gid '$gid'."
|
||||
return
|
||||
fi
|
||||
|
||||
if [[ "$modify_existing" -eq 0 ]]; then
|
||||
_exit "\
|
||||
The user '$user' is associated with the primary group '$existing_gid'.
|
||||
Specify --modify-existing to change the gid anyways." 1
|
||||
fi
|
||||
|
||||
echo "Changing primary group for '$user' from '$existing_gid' to '$gid'."
|
||||
usermod -g "$gid" "$user"
|
||||
return
|
||||
fi
|
||||
|
||||
# Check if user with same name already exists
|
||||
local existing_uid=""
|
||||
existing_uid="$(id -u "$user" 2> /dev/null)"
|
||||
if [[ -n "$existing_uid" ]]; then
|
||||
if [[ "$existing_uid" = "$uid" ]]; then
|
||||
_exit "The user '$user' already has the specified uid '$uid'" 0
|
||||
fi
|
||||
|
||||
if [[ "$modify_existing" -eq 0 ]]; then
|
||||
_exit "\
|
||||
User '$user' already exists with uid '$existing_uid'.
|
||||
Specify --modify-existing to change the uid anyways." 1
|
||||
fi
|
||||
|
||||
echo "Changing uid for user '$user' from '$existing_uid' to '$uid'"
|
||||
if ! usermod -u "$uid" -g "$gid" "$user"; then
|
||||
_exit "usermod exited with code $?" 1
|
||||
fi
|
||||
return
|
||||
fi
|
||||
|
||||
# The user doesn't exist. Add it
|
||||
echo "Adding user '$user:$uid' (group='$group:$gid', password='$pass')"
|
||||
useradd -m -u "$uid" -g "$gid" -G sudo --password "$(openssl passwd -1 "$pass")" "$user"
|
||||
}
|
||||
|
||||
function _update_fish_dir_perms() {
|
||||
local user="$1"
|
||||
local uid="$2"
|
||||
local gid="$3"
|
||||
# When a fish shell session starts, a temp dir named '/tmp/fish.<user>' is
|
||||
# created with the user's current uid/gid. If such a dir exists for the
|
||||
# specified USER, make sure the uid/gid match the new values.
|
||||
fish_dir="/tmp/fish.$user"
|
||||
if [[ -d "$fish_dir" ]]; then
|
||||
perms="$uid:$gid"
|
||||
existing_perms="$(stat -c %u:%g "$fish_dir")"
|
||||
if [[ "$existing_perms" != "$perms" ]]; then
|
||||
echo "Changing uid:gid for dir '$fish_dir' from '$existing_perms' to '$perms'"
|
||||
chown -R "$perms" "$fish_dir"
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
user=""
|
||||
group=""
|
||||
pass=""
|
||||
declare -i uid=0
|
||||
declare -i gid=0
|
||||
declare -i modify_existing=0
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
--user)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "USER (--user) must be non-empty" 1
|
||||
elif [[ "$2" = "root" ]]; then
|
||||
_exit "USER (--user) cannot be 'root'" 1
|
||||
fi
|
||||
user="$2"
|
||||
shift 2
|
||||
;;
|
||||
--group)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "GROUP (--group) must be non-empty" 1
|
||||
elif [[ "$2" = "root" ]]; then
|
||||
_exit "GROUP (--group) cannot be 'root'" 1
|
||||
fi
|
||||
group="$2"
|
||||
shift 2
|
||||
;;
|
||||
--uid)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "UID (--uid) must be non-empty" 1
|
||||
fi
|
||||
uid="$2"
|
||||
shift 2
|
||||
;;
|
||||
--gid)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "GID (--gid) must be non-empty" 1
|
||||
fi
|
||||
gid="$2"
|
||||
shift 2
|
||||
;;
|
||||
--pass)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "PASS (--pass) must be non-empty" 1
|
||||
fi
|
||||
pass="$2"
|
||||
shift 2
|
||||
;;
|
||||
--modify-existing)
|
||||
modify_existing=1
|
||||
shift 1
|
||||
;;
|
||||
-h)
|
||||
;&
|
||||
--help)
|
||||
_exit "$help_text" 0
|
||||
;;
|
||||
*)
|
||||
if [[ -z "$1" ]]; then
|
||||
_exit "Invalid positional argument '$1'" 1
|
||||
elif [[ -z "$user" ]]; then
|
||||
user="$1"
|
||||
elif [[ -z "$uid" ]]; then
|
||||
uid="$1"
|
||||
else
|
||||
_exit "Unexpected argument '$1'" 1
|
||||
fi
|
||||
shift 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
if [[ -z "$user" ]]; then
|
||||
user="bts"
|
||||
fi
|
||||
|
||||
if [[ $uid -eq 0 ]]; then
|
||||
uid=1000
|
||||
fi
|
||||
|
||||
# In general, a user's primary group/gid matches the user's name/uid.
|
||||
# If group/gid args weren't specified, set them to name/uid.
|
||||
if [[ -z "$group" ]]; then
|
||||
group="$user"
|
||||
fi
|
||||
if [[ $gid -eq 0 ]]; then
|
||||
gid=$uid
|
||||
fi
|
||||
if [[ -z "$pass" ]]; then
|
||||
pass="$user"
|
||||
fi
|
||||
|
||||
_add_group "$group" "$gid"
|
||||
_add_user "$user" "$uid" "$group" "$gid" "$pass"
|
||||
_update_fish_dir_perms "$user" "$uid" "$gid"
|
||||
@@ -1,230 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function _exit() {
|
||||
if [[ "$#" -gt 1 ]]; then
|
||||
# When there are multiple args, the last arg is the exit code.
|
||||
echo "${@:1:($# - 1)}"
|
||||
exit "${@: -1}"
|
||||
fi
|
||||
echo "$1"
|
||||
exit 0
|
||||
}
|
||||
|
||||
help_text="\
|
||||
Start a docker dev container
|
||||
Usage: start_docker.sh [OPTIONS] image container
|
||||
|
||||
Positionals:
|
||||
image The image to instantiate
|
||||
container The name for the container
|
||||
|
||||
Options:
|
||||
-u,--user USER The user to add in the container (defaults to 'bts')
|
||||
-p,--pass PASS The password for USER in the container (defaults to USER)
|
||||
-i,--image IMAGE The image to instantiate (defaults to 'bluetradingsystems/sparkd-dev:latest')
|
||||
-c,--container CONT The name for the container
|
||||
-m,--mount MOUNT The name for the folder (outside the container) to create/mount to the home
|
||||
directory in the container. Mount folders are added here: $mount_prefix
|
||||
--mount-existing Mount the specified dir even if it already exists
|
||||
--port <cont_port>:<host_port> OR [<cont_port>:<host_port>,...] Port mapping(s). May be
|
||||
specified multiple times.
|
||||
-h,--help Print this help message and exit
|
||||
|
||||
"
|
||||
|
||||
mount_prefix="$HOME/.sparkd-dev/mounts"
|
||||
declare docker_user=""
|
||||
declare docker_pass=""
|
||||
declare image_name=""
|
||||
declare cont_name=""
|
||||
declare mount_name=""
|
||||
declare -i mount_existing=0
|
||||
declare -a port_mappings=()
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-u)
|
||||
;&
|
||||
--user)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "User (-u,--user) must be non-empty" 1
|
||||
fi
|
||||
docker_user="$2"
|
||||
shift 2
|
||||
;;
|
||||
-p)
|
||||
;&
|
||||
--pass)
|
||||
if [[ -z "$2" ]]; then
|
||||
_exit "Password (-p,--pass) must be non-empty" 1
|
||||
fi
|
||||
docker_pass="$2"
|
||||
shift 2
|
||||
;;
|
||||
-i)
|
||||
;&
|
||||
--image)
|
||||
if [[ -n "$image_name" ]]; then
|
||||
_exit "Unexpected argument '$1'" 1
|
||||
elif [[ -z "$2" ]]; then
|
||||
_exit "Image (-i,--image) must be non-empty" 1
|
||||
fi
|
||||
image_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
-c)
|
||||
;&
|
||||
--container)
|
||||
if [[ -n "$cont_name" ]]; then
|
||||
_exit "Unexpected argument '$1'" 1
|
||||
elif [[ -z "$2" ]]; then
|
||||
_exit "Container (-c,--container) must be non-empty" 1
|
||||
fi
|
||||
cont_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
--port)
|
||||
# Parse port(s) arg, and append the result to 'port_mappings'
|
||||
# Note: port(s) may be specified in bracketed notation:
|
||||
# [a:b,c:d,...,y:z]
|
||||
next_ports="$(echo "$2" | sed -e 's/\[//g' -e 's/\]//g' -e 's/,/ /g')"
|
||||
if [[ "${#port_mappings[@]}" -gt 0 ]]; then
|
||||
next_ports=" $next_ports"
|
||||
fi
|
||||
port_mappings+=("$next_ports")
|
||||
shift 2
|
||||
;;
|
||||
-m)
|
||||
;&
|
||||
--mount)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Mount (-m,--mount) must be non-empty"
|
||||
fi
|
||||
mount_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
--mount-existing)
|
||||
mount_existing=1
|
||||
shift 1
|
||||
;;
|
||||
-h)
|
||||
;&
|
||||
--help)
|
||||
_exit "$help_text" 0
|
||||
;;
|
||||
*)
|
||||
if [[ -z "$1" ]]; then
|
||||
_exit "Invalid positional argument '$1'" "$help_text" 1
|
||||
elif [[ -z "$image_name" ]]; then
|
||||
image_name="$1"
|
||||
elif [[ -z "$cont_name" ]]; then
|
||||
cont_name="$1"
|
||||
else
|
||||
_exit "Unexpected argument '$1'" "$help_text" 1
|
||||
fi
|
||||
shift 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
|
||||
if [[ -z "$image_name" ]]; then
|
||||
image_name="bluetradingsystems/sparkd-dev:latest"
|
||||
fi
|
||||
|
||||
host_name="$(hostname)"
|
||||
if [[ -n "$cont_name" ]]; then
|
||||
host_name="$host_name.$cont_name"
|
||||
fi
|
||||
|
||||
if [[ -z "$mount_name" ]]; then
|
||||
mount_name="$cont_name"
|
||||
fi
|
||||
|
||||
if [[ -z "$mount_name" && -z "$cont_name" ]]; then
|
||||
_exit "Please specify mount (-m,--mount) and/or container (-c,--container)" 1
|
||||
fi
|
||||
|
||||
if [[ -z "$docker_user" ]]; then
|
||||
docker_user="bts"
|
||||
fi
|
||||
|
||||
if [[ "$docker_user" = "root" ]]; then
|
||||
_exit "USER (--user) cannot be 'root'" 1
|
||||
fi
|
||||
|
||||
cont_home="/home/$docker_user"
|
||||
home_src="$mount_prefix/$mount_name"
|
||||
home_tgt="$cont_home"
|
||||
this_dir="$(dirname "$(realpath "${BASH_SOURCE[0]}")")"
|
||||
repo_src="$(cd "$this_dir" && git rev-parse --show-toplevel)"
|
||||
repo_tgt="$cont_home/spark"
|
||||
working_dir="$cont_home"
|
||||
|
||||
if [[ $mount_existing -eq 0 && -e "$home_src" ]]; then
|
||||
# Don't overwrite existing dir (might be mounted in another container)
|
||||
_exit "Mount dir '$home_src' already exists (use --mount-existing to mount \
|
||||
an existing directory)" 1
|
||||
fi
|
||||
|
||||
mkdir -p "$home_src"
|
||||
|
||||
if [[ "${#port_mappings[@]}" -eq 0 ]]; then
|
||||
port_mappings=("8000:8000" "8001:8001" "8002:8002" "8003:8003")
|
||||
fi
|
||||
|
||||
# Adapt port_mappings into args for `docker run` by prepending "-p " to each
|
||||
# item
|
||||
declare -a docker_port_args=()
|
||||
for port_mapping in "${port_mappings[@]}"; do
|
||||
docker_port_args+=("-p $port_mapping")
|
||||
done
|
||||
|
||||
echo "Starting container '$cont_name'
|
||||
image_name : $image_name
|
||||
cont_name : $cont_name
|
||||
home_src : $home_src
|
||||
home_tgt : $home_tgt
|
||||
repo_src : $repo_src
|
||||
repo_tgt : $repo_tgt
|
||||
working dir : $working_dir
|
||||
ports : ${port_mappings[*]}
|
||||
"
|
||||
|
||||
# DON'T wrap $docker_port_args in quotes. We want bash to split args by
|
||||
# whitespace
|
||||
docker run \
|
||||
--net bridge \
|
||||
-h "$host_name" \
|
||||
-e "TZ=America/New_York" \
|
||||
--cap-add=SYS_PTRACE \
|
||||
--security-opt seccomp=unconfined \
|
||||
--name "$cont_name" \
|
||||
-v "$home_src:$home_tgt" \
|
||||
-v "$repo_src:$repo_tgt" \
|
||||
-w "$working_dir" \
|
||||
${docker_port_args[*]} \
|
||||
--shm-size=4024m \
|
||||
-t \
|
||||
-i \
|
||||
-d \
|
||||
-e DISPLAY="$DISPLAY" \
|
||||
"$image_name"
|
||||
|
||||
# Add user w/ same uid and gid as the current user outside of docker, so the
|
||||
# user inside the docker has file permissions in the mounted dir.
|
||||
docker_group="$docker_user"
|
||||
docker_uid="$(id -u "$USER")"
|
||||
docker_gid="$(id -g "$USER")"
|
||||
if [[ -z "$docker_pass" ]]; then
|
||||
docker_pass="$docker_user"
|
||||
fi
|
||||
docker exec -u root -it "$cont_name" "$repo_tgt/docker/sparkd/dev/set_user.sh" \
|
||||
--user "$docker_user" \
|
||||
--uid "$docker_uid" \
|
||||
--group "$docker_group" \
|
||||
--gid "$docker_gid" \
|
||||
--pass "$docker_pass"
|
||||
|
||||
# Run same script VS Code runs to initialize the container
|
||||
docker exec -u "$docker_user" -it "$cont_name" "$repo_tgt/docker/sparkd/dev/devcontainer_post_create.sh"
|
||||
@@ -1,64 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
function print_help_and_exit() {
|
||||
cat <<EOF
|
||||
Open a shell inside the docker container
|
||||
Usage: docker_shell.sh [OPTIONS] [CONTAINER]
|
||||
|
||||
Options:
|
||||
-u,--user The user to login with in the container (defaults to the current user)
|
||||
-c,--container The container name (may also be specified as positional arg)
|
||||
-h,--help Print this help message and exit
|
||||
|
||||
EOF
|
||||
exit "$1"
|
||||
}
|
||||
|
||||
|
||||
declare docker_user=""
|
||||
declare cont_name=""
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-u)
|
||||
;&
|
||||
--user)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "User (-u,--user) must be non-empty"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
docker_user="$2"
|
||||
shift 2
|
||||
;;
|
||||
-h)
|
||||
;&
|
||||
--help)
|
||||
print_help_and_exit 0
|
||||
;;
|
||||
-c)
|
||||
;&
|
||||
--container)
|
||||
shift 1
|
||||
;&
|
||||
*)
|
||||
if [[ ! -z "$cont_name" ]]; then
|
||||
echo "Unexpected argument '$1'"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
cont_name="$1"
|
||||
shift 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
|
||||
if [[ -z "$cont_name" ]]; then
|
||||
echo "Please specify the container ([-c,--container])"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "$docker_user" ]]; then
|
||||
docker_user="$USER"
|
||||
fi
|
||||
|
||||
docker exec -u "$docker_user" -it "$cont_name" bash
|
||||
@@ -1,233 +0,0 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
mount_prefix="$HOME/.spark-dev/mounts"
|
||||
|
||||
function print_help_and_exit() {
|
||||
cat <<EOF
|
||||
Start a docker dev container
|
||||
Usage: start_docker.sh [OPTIONS] image container
|
||||
|
||||
Positionals:
|
||||
image The image to instantiate
|
||||
container The name for the container
|
||||
|
||||
Options:
|
||||
-u,--user USER The user to add in the container (defaults to the current user)
|
||||
-p,--pass PASS The password for USER in the container (defaults to USER)
|
||||
-i,--image IMAGE The image to instantiate
|
||||
-c,--container CONT The name for the container
|
||||
-m,--mount MOUNT The name for the folder (outside the container) to create/mount to the home
|
||||
directory in the container. Mount folders are added here: $mount_prefix
|
||||
--mount-existing Mount the specified dir even if it already exists
|
||||
--port <cont_port>:<host_port> OR [<cont_port>:<host_port>,...] Port mapping(s). May be
|
||||
specified multiple times.
|
||||
-h,--help Print this help message and exit
|
||||
|
||||
EOF
|
||||
exit "$1"
|
||||
}
|
||||
|
||||
|
||||
declare docker_user=""
|
||||
declare docker_pass=""
|
||||
declare image_name=""
|
||||
declare cont_name=""
|
||||
declare mount_name=""
|
||||
declare -i mount_existing=0
|
||||
declare -a port_mappings=()
|
||||
|
||||
while [[ $# -gt 0 ]]; do
|
||||
case "$1" in
|
||||
-u)
|
||||
;&
|
||||
--user)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "User (-u,--user) must be non-empty"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
docker_user="$2"
|
||||
shift 2
|
||||
;;
|
||||
-p)
|
||||
;&
|
||||
--pass)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Password (-p,--pass) must be non-empty"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
docker_pass="$2"
|
||||
shift 2
|
||||
;;
|
||||
-i)
|
||||
;&
|
||||
--image)
|
||||
if [[ -n "$image_name" ]]; then
|
||||
echo "Unexpected argument '$1'"
|
||||
print_help_and_exit 1
|
||||
elif [[ -z "$2" ]]; then
|
||||
echo "Image (-i,--image) must be non-empty"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
image_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
-c)
|
||||
;&
|
||||
--container)
|
||||
if [[ -n "$cont_name" ]]; then
|
||||
echo "Unexpected argument '$1'"
|
||||
print_help_and_exit 1
|
||||
elif [[ -z "$2" ]]; then
|
||||
echo "Container (-c,--container) must be non-empty"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
cont_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
--port)
|
||||
# Parse port(s) arg, and append the result to 'port_mappings'
|
||||
# Note: port(s) may be specified in bracketed notation:
|
||||
# [a:b,c:d,...,y:z]
|
||||
next_ports="$(echo "$2" | sed -e 's/\[//g' -e 's/\]//g' -e 's/,/ /g')"
|
||||
if [[ "${#port_mappings[@]}" -gt 0 ]]; then
|
||||
next_ports=" $next_ports"
|
||||
fi
|
||||
port_mappings+=("$next_ports")
|
||||
shift 2
|
||||
;;
|
||||
-m)
|
||||
;&
|
||||
--mount)
|
||||
if [[ -z "$2" ]]; then
|
||||
echo "Mount (-m,--mount) must be non-empty"
|
||||
fi
|
||||
mount_name="$2"
|
||||
shift 2
|
||||
;;
|
||||
--mount-existing)
|
||||
mount_existing=1
|
||||
shift 1
|
||||
;;
|
||||
-h)
|
||||
;&
|
||||
--help)
|
||||
print_help_and_exit 0
|
||||
;;
|
||||
*)
|
||||
if [[ -z "$1" ]]; then
|
||||
echo "Invalid positional argument '$1'"
|
||||
print_help_and_exit 1
|
||||
elif [[ -z "$image_name" ]]; then
|
||||
image_name="$1"
|
||||
elif [[ -z "$cont_name" ]]; then
|
||||
cont_name="$1"
|
||||
else
|
||||
echo "Unexpected argument '$1'"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
shift 1
|
||||
;;
|
||||
esac
|
||||
done
|
||||
|
||||
|
||||
if [[ -z "$image_name" ]]; then
|
||||
image_name="bluetradingsystems/spark-crypto-dev"
|
||||
fi
|
||||
|
||||
host_name="$(hostname)"
|
||||
if [[ -n "$cont_name" ]]; then
|
||||
host_name="$host_name.$cont_name"
|
||||
fi
|
||||
|
||||
if [[ -z "$mount_name" ]]; then
|
||||
mount_name="$cont_name"
|
||||
fi
|
||||
|
||||
if [[ -z "$mount_name" && -z "$cont_name" ]]; then
|
||||
echo "Please specify mount (-m,--mount) and/or container (-c,--container)"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
|
||||
if [[ -z "$docker_user" ]]; then
|
||||
docker_user="$USER"
|
||||
fi
|
||||
|
||||
home_src=$mount_prefix/$mount_name
|
||||
home_tgt=$HOME
|
||||
repo_src=$(git rev-parse --show-superproject-working-tree)
|
||||
repo_tgt=$HOME/$(basename "$repo_src")
|
||||
working_dir=$HOME
|
||||
|
||||
if [[ $mount_existing -eq 0 && -e "$home_src" ]]; then
|
||||
# Don't overwrite existing dir (might be mounted in another container)
|
||||
echo "Mount dir '$home_src' already exists (use --mount-existing to mount an existing directory)"
|
||||
print_help_and_exit 1
|
||||
fi
|
||||
|
||||
mkdir -p "$home_src"
|
||||
|
||||
if [[ "${#port_mappings[@]}" -eq 0 ]]; then
|
||||
port_mappings=("8000:8000" "8001:8001" "8002:8002" "8003:8003")
|
||||
fi
|
||||
|
||||
# Adapt port_mappings into args for `docker run` by prepending "-p " to each
|
||||
# item
|
||||
declare -a docker_port_args=()
|
||||
for port_mapping in "${port_mappings[@]}"; do
|
||||
docker_port_args+=("-p $port_mapping")
|
||||
done
|
||||
|
||||
echo "Starting container '$cont_name'
|
||||
image_name : $image_name
|
||||
cont_name : $cont_name
|
||||
home_src : $home_src
|
||||
home_tgt : $home_tgt
|
||||
repo_src : $repo_src
|
||||
repo_tgt : $repo_tgt
|
||||
working dir : $working_dir
|
||||
ports : ${port_mappings[*]}
|
||||
"
|
||||
|
||||
# DON'T wrap $docker_port_args in quotes. We want bash to split args by
|
||||
# whitespace
|
||||
docker run \
|
||||
--net bridge \
|
||||
-h "$host_name" \
|
||||
-e "TZ=America/New_York" \
|
||||
--cap-add=SYS_PTRACE \
|
||||
--security-opt seccomp=unconfined \
|
||||
--name "$cont_name" \
|
||||
-v "$home_src:$home_tgt" \
|
||||
-v "$repo_src:$repo_tgt" \
|
||||
-w "$working_dir" \
|
||||
${docker_port_args[*]} \
|
||||
--shm-size=4024m \
|
||||
-t \
|
||||
-i \
|
||||
-d \
|
||||
-e DISPLAY="$DISPLAY" \
|
||||
"$image_name" \
|
||||
bash
|
||||
|
||||
# Add user w/ same uid and gid as the current user outside of docker, so the
|
||||
# user inside the docker has file permissions in the mounted dir.
|
||||
docker_group="$docker_user"
|
||||
docker_user_uid="$(id -u "$USER")"
|
||||
docker_user_gid="$(id -g "$USER")"
|
||||
|
||||
echo "Adding user in container '$cont_name'
|
||||
name : $docker_user
|
||||
uid : $docker_user_uid
|
||||
gid : $docker_user_gid"
|
||||
|
||||
if [[ -z "$docker_pass" ]]; then
|
||||
docker_pass="$docker_user"
|
||||
echo "Giving user '$docker_user' a secure password: $docker_pass"
|
||||
fi
|
||||
|
||||
docker exec -u root -it "$cont_name" groupadd -g "$docker_user_gid" "$docker_group"
|
||||
docker exec -u root -it "$cont_name" useradd -u "$docker_user_uid" -g "$docker_user_gid" "$docker_user"
|
||||
docker exec -u root -it "$cont_name" usermod --password "$(openssl passwd -1 "$docker_pass")" "$docker_user"
|
||||
docker exec -u root -it "$cont_name" usermod -aG sudo "$docker_user"
|
||||
docker exec -u root -it "$cont_name" "$repo_tgt/externals/src/emumba/install_emumba-deribit-connector.sh"
|
||||
+1
-1
Submodule externals updated: 101e97a20c...99c440f568.
@@ -12,7 +12,6 @@ pycodestyle==2.7.0
|
||||
pycparser==2.20
|
||||
pylint==2.10.2
|
||||
PyMeta3==0.5.1
|
||||
termcolor==1.1.0
|
||||
toml==0.10.2
|
||||
wrapt==1.12.1
|
||||
yapf==0.31.0
|
||||
+22
-32
@@ -1,10 +1,10 @@
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio Version 17
|
||||
VisualStudioVersion = 17.3.32922.545
|
||||
# Visual Studio Version 16
|
||||
VisualStudioVersion = 16.0.30114.105
|
||||
MinimumVisualStudioVersion = 15.0.26124.0
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_api", "src\client\spark_api\spark_api.csproj", "{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}"
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spark", "src\client\spark\Spark.csproj", "{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}"
|
||||
EndProject
|
||||
@@ -12,17 +12,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sparkcmd", "src\client\spar
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_core", "src\client\spark_core\spark_core.csproj", "{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}"
|
||||
EndProject
|
||||
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZERO_CHECK", "build\ZERO_CHECK.vcxproj", "{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_sdk", "src\client\spark_sdk\spark_sdk.csproj", "{6963C314-83C4-4667-B0D0-C2F7AE208C29}"
|
||||
ProjectSection(ProjectDependencies) = postProject
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25} = {FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40} = {9FA60215-26AF-3EB7-AB89-D4F4B126EF40}
|
||||
EndProjectSection
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_test", "src\client\spark_test\spark_test.csproj", "{ECD78CC5-138F-4809-A764-2358C2AC2E82}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_websocket", "src\client\spark_websocket\spark_websocket.csproj", "{3201359D-C071-4089-9EDE-B04D759F1508}"
|
||||
EndProject
|
||||
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_api_server", "src\client\spark_api_server\spark_api_server.csproj", "{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|x64 = Debug|x64
|
||||
@@ -39,14 +37,14 @@ Global
|
||||
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.Release|x64.Build.0 = Release|x64
|
||||
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.RelWithDebInfo|x64.ActiveCfg = Release|x64
|
||||
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.RelWithDebInfo|x64.Build.0 = Release|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Debug|x64.Build.0 = Debug|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Release|x64.ActiveCfg = Release|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Release|x64.Build.0 = Release|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
|
||||
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Debug|x64.Build.0 = Debug|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Release|x64.ActiveCfg = Release|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Release|x64.Build.0 = Release|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
|
||||
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
|
||||
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.Debug|x64.Build.0 = Debug|x64
|
||||
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.MinSizeRel|x64.ActiveCfg = Release|x64
|
||||
@@ -71,6 +69,14 @@ Global
|
||||
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.Release|x64.Build.0 = Release|x64
|
||||
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.ActiveCfg = Release|x64
|
||||
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.Build.0 = Release|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.Build.0 = Debug|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.ActiveCfg = Release|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.Build.0 = Release|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
|
||||
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
|
||||
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.Build.0 = Debug|x64
|
||||
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.MinSizeRel|x64.ActiveCfg = Release|x64
|
||||
@@ -87,22 +93,6 @@ Global
|
||||
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.Release|x64.Build.0 = Release|x64
|
||||
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.RelWithDebInfo|x64.ActiveCfg = Release|x64
|
||||
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.RelWithDebInfo|x64.Build.0 = Release|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.Debug|x64.Build.0 = Debug|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.MinSizeRel|x64.ActiveCfg = Debug|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.MinSizeRel|x64.Build.0 = Debug|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.Release|x64.ActiveCfg = Release|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.Release|x64.Build.0 = Release|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.RelWithDebInfo|x64.ActiveCfg = Release|x64
|
||||
{3201359D-C071-4089-9EDE-B04D759F1508}.RelWithDebInfo|x64.Build.0 = Release|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.Debug|x64.ActiveCfg = Debug|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.Debug|x64.Build.0 = Debug|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.MinSizeRel|x64.ActiveCfg = Debug|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.MinSizeRel|x64.Build.0 = Debug|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.Release|x64.ActiveCfg = Release|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.Release|x64.Build.0 = Release|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.RelWithDebInfo|x64.ActiveCfg = Release|x64
|
||||
{2B8C5D01-FF78-4BFA-B332-5E430586DAF9}.RelWithDebInfo|x64.Build.0 = Release|x64
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,55 +1,53 @@
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<ComputerSpecificConfig>..\..\tools\override\$(computername).props</ComputerSpecificConfig>
|
||||
<SparkRoot>$([System.IO.Path]::GetFullPath($(MSBuildThisFileDirectory)\..\..))</SparkRoot>
|
||||
<SourceRoot>$([System.IO.Path]::GetFullPath($(SparkRoot)\src))</SourceRoot>
|
||||
<Externals>$(SparkRoot)\externals\windows</Externals>
|
||||
<DepotName>$([System.IO.Path]::GetFileName($([System.IO.Path]::GetFullPath($(SparkRoot)))))</DepotName>
|
||||
<ErrorReport>None</ErrorReport>
|
||||
<Prefer32Bit>False</Prefer32Bit>
|
||||
<Deterministic>true</Deterministic>
|
||||
<EnableDefaultContentItems>False</EnableDefaultContentItems>
|
||||
<ShowMissingItemTypes>false</ShowMissingItemTypes>
|
||||
<Configuration Condition="'$(configuration)'==''">Debug</Configuration>
|
||||
<EnablePreviewFeatures>true</EnablePreviewFeatures>
|
||||
<LangVersion>11</LangVersion>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Label="Output">
|
||||
<BaseOutputPath>$(SparkRoot)\build\$(Configuration)</BaseOutputPath>
|
||||
<OutputPath>$(BaseOutputPath)\bin</OutputPath>
|
||||
<BaseIntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
|
||||
<IntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</IntermediateOutputPath>
|
||||
<ProtoOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</ProtoOutputPath>
|
||||
<GenDir>$(BaseOutputPath)\gen\$(MSBuildProjectName)</GenDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import
|
||||
Project="$(ComputerSpecificConfig)"
|
||||
Condition="Exists($(ComputerSpecificConfig))" />
|
||||
|
||||
<PropertyGroup Label="ProtoBuf">
|
||||
<ProtocPluginBase>$(SparkRoot)\src\lib\api\service_compiler</ProtocPluginBase>
|
||||
<protoc>$(Externals)\bin\protoc.exe</protoc>
|
||||
<protogen>$(Externals)\bin\protogen.exe</protogen>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemDefinitionGroup>
|
||||
<Proto2></Proto2>
|
||||
<Proto3>
|
||||
<OutBase>$(IntermediateOutputPath)\gen\%(relativedir)</OutBase>
|
||||
<OutCS>%(OutBase)%(FileName).cs</OutCS>
|
||||
<OutCSClient>%(OutBase)%(FileName).client.pb.cs</OutCSClient>
|
||||
<OutCSServer>%(OutBase)%(FileName).server.pb.cs</OutCSServer>
|
||||
<OutCSImmutable>%(OutBase)%(FileName).immutable.pb.cs</OutCSImmutable>
|
||||
<CompileOptions></CompileOptions>
|
||||
</Proto3>
|
||||
<Proto3Excel>
|
||||
<OutBase>$(IntermediateOutputPath)\gen\%(relativedir)</OutBase>
|
||||
<OutCSExcel>%(OutBase)%(FileName).excel.pb.cs</OutCSExcel>
|
||||
<CompileOptions></CompileOptions>
|
||||
</Proto3Excel>
|
||||
</ItemDefinitionGroup>
|
||||
|
||||
</Project>
|
||||
<Project>
|
||||
|
||||
<PropertyGroup>
|
||||
<ComputerSpecificConfig>..\..\tools\override\$(computername).props</ComputerSpecificConfig>
|
||||
<SparkRoot>$([System.IO.Path]::GetFullPath($(MSBuildThisFileDirectory)\..\..))</SparkRoot>
|
||||
<SourceRoot>$([System.IO.Path]::GetFullPath($(SparkRoot)\src))</SourceRoot>
|
||||
<Externals>$(SparkRoot)\externals\windows</Externals>
|
||||
<DepotName>$([System.IO.Path]::GetFileName($([System.IO.Path]::GetFullPath($(SparkRoot)))))</DepotName>
|
||||
<ErrorReport>None</ErrorReport>
|
||||
<Prefer32Bit>False</Prefer32Bit>
|
||||
<Deterministic>true</Deterministic>
|
||||
<EnableDefaultContentItems>False</EnableDefaultContentItems>
|
||||
<ShowMissingItemTypes>false</ShowMissingItemTypes>
|
||||
<Configuration Condition="'$(configuration)'==''">Debug</Configuration>
|
||||
<EnablePreviewFeatures>true</EnablePreviewFeatures>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Label="Output">
|
||||
<BaseOutputPath>$(SparkRoot)\build\$(Configuration)</BaseOutputPath>
|
||||
<OutputPath>$(BaseOutputPath)\bin</OutputPath>
|
||||
<BaseIntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</BaseIntermediateOutputPath>
|
||||
<IntermediateOutputPath>$(BaseOutputPath)\obj\$(MSBuildProjectName)</IntermediateOutputPath>
|
||||
<GenDir>$(BaseOutputPath)\gen\$(MSBuildProjectName)</GenDir>
|
||||
</PropertyGroup>
|
||||
|
||||
<Import
|
||||
Project="$(ComputerSpecificConfig)"
|
||||
Condition="Exists($(ComputerSpecificConfig))" />
|
||||
|
||||
<PropertyGroup Label="ProtoBuf">
|
||||
<ProtocPluginBase>$(SparkRoot)\src\lib\api\service_compiler</ProtocPluginBase>
|
||||
<protoc>$(Externals)\bin\protoc.exe</protoc>
|
||||
<protogen>$(Externals)\bin\protogen.exe</protogen>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemDefinitionGroup>
|
||||
<Proto2></Proto2>
|
||||
<Proto3>
|
||||
<OutBase>$(IntermediateOutputPath)\gen\%(relativedir)</OutBase>
|
||||
<OutCS>%(OutBase)%(FileName).cs</OutCS>
|
||||
<OutCSClient>%(OutBase)%(FileName).client.pb.cs</OutCSClient>
|
||||
<OutCSServer>%(OutBase)%(FileName).server.pb.cs</OutCSServer>
|
||||
<OutCSImmutable>%(OutBase)%(FileName).immutable.pb.cs</OutCSImmutable>
|
||||
<CompileOptions></CompileOptions>
|
||||
</Proto3>
|
||||
<Proto3Excel>
|
||||
<OutBase>$(IntermediateOutputPath)\gen\%(relativedir)</OutBase>
|
||||
<OutCSExcel>%(OutBase)%(FileName).excel.pb.cs</OutCSExcel>
|
||||
<CompileOptions></CompileOptions>
|
||||
</Proto3Excel>
|
||||
</ItemDefinitionGroup>
|
||||
|
||||
</Project>
|
||||
@@ -52,7 +52,8 @@
|
||||
<Exec Command="set PYTHONPATH=$(SparkRoot)\.venv\Scripts\python" />
|
||||
<Exec
|
||||
Command="
|
||||
$(protoc) %* %(Proto3.FullPath) ^
|
||||
$(SparkRoot)\tools\build_protos.cmd ^
|
||||
%(Proto3.FullPath) ^
|
||||
--error_format=msvs ^
|
||||
--proto_path=$(SourceRoot) ^
|
||||
--plugin="protoc-gen-service=$(ProtocPluginBase)\plugin.cmd" ^
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace mbts.spark {
|
||||
using bts.api;
|
||||
using bts.api.analytics;
|
||||
using bts.collections;
|
||||
using bts.reactive;
|
||||
using bts.utils;
|
||||
|
||||
using mbts;
|
||||
@@ -14,10 +15,7 @@ namespace mbts.spark {
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
@@ -35,15 +33,14 @@ namespace mbts.spark {
|
||||
class AnalyticsExpirationParametersVM : DisposableViewModelBase, IHandleRowSelection {
|
||||
readonly IBus _bus;
|
||||
readonly ObservableCollection<AnalyticsExpirationParameters> _parameters = new();
|
||||
readonly DeferrableAction _sync_visible_rows;
|
||||
readonly DeferrableActionWrapper _sync_visible_rows;
|
||||
readonly Property<AnalyticsExpirationParametersRowVM?> _copy_row_source;
|
||||
readonly Property<bool> _auto_copy_rolls_is_checked;
|
||||
readonly Property<bool> _auto_copy_rates_is_checked;
|
||||
readonly DelegateProperty<bool> _is_dirty;
|
||||
readonly ObservableHashSet<AnalyticsExpirationParametersRowVM> _selected_rows = new();
|
||||
readonly DeferrableAction _raise_selected_rows_changed;
|
||||
readonly DeferrableActionWrapper _raise_selected_rows_changed;
|
||||
readonly IRaiseCanExecuteChangedCommand _set_driver_to_nearest_exp_cmd;
|
||||
IList<string>? _pending_selected_symbols;
|
||||
|
||||
AnalyticsExpirationParametersMap? _parameter_map;
|
||||
(ICommand cmd, IDisposable can_exe_sub)? _smart_copy_roll_target_to_selection_cmd;
|
||||
@@ -66,7 +63,9 @@ namespace mbts.spark {
|
||||
_is_dirty = backing(nameof(is_dirty), () => rows.Any(r => r.is_dirty));
|
||||
|
||||
if (startup_data is not null) {
|
||||
_pending_selected_symbols = startup_data.selected_symbols;
|
||||
if (!startup_data.selected_symbols.is_null_or_empty()) {
|
||||
selected_symbols.AddRange(startup_data.selected_symbols);
|
||||
}
|
||||
auto_copy_rolls_is_checked = startup_data.auto_copy_rolls_is_checked;
|
||||
auto_copy_rates_is_checked = startup_data.auto_copy_rates_is_checked;
|
||||
}
|
||||
@@ -82,32 +81,32 @@ namespace mbts.spark {
|
||||
selected_rows_changed += _ => _set_driver_to_nearest_exp_cmd.RaiseCanExecuteChanged();
|
||||
|
||||
_dispose = Disposable.Create(
|
||||
_selected_rows.Subscribe((s, e) => _raise_selected_rows_changed.Invoke()),
|
||||
_selected_rows.Subscribe((s, e) => _raise_selected_rows_changed.execute()),
|
||||
ObservableAutoWrapper.connect(_parameters, rows, p => new(this, p), r => r.Dispose()),
|
||||
ObservableAutoWrapper.connect(
|
||||
non_options,
|
||||
explicit_drivers,
|
||||
sec => new ExpirationDriverImmutable(new() { Security = sec.to_api_sec_exp() })),
|
||||
rows.Subscribe((s, e) => _sync_visible_rows.Invoke()),
|
||||
rows.Subscribe((s, e) => _sync_visible_rows.execute()),
|
||||
_bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(
|
||||
CompositeObserver.create(
|
||||
Observer.Create<AnalyticsExpirationParametersMap>(_on_parameter_map),
|
||||
can_commit_observer.wrap<bool, AnalyticsExpirationParametersMap>(m => m is not null))),
|
||||
ObservableAutoWrapper.connect_item_hooks(selected_symbols, sym => {
|
||||
if (selected_symbol_ref_count.increment_adds_key(sym)) {
|
||||
_sync_visible_rows.Invoke();
|
||||
_sync_visible_rows.execute();
|
||||
}
|
||||
return Disposable.Create(() => {
|
||||
if (selected_symbol_ref_count.decrement_removes_key(sym)) {
|
||||
_sync_visible_rows.Invoke();
|
||||
_sync_visible_rows.execute();
|
||||
}
|
||||
});
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_hooks(
|
||||
rows, r => r.observe_is_dirty().Subscribe(_ => _is_dirty.refresh())),
|
||||
_is_dirty.observe_current(true).OnDispatcher().Subscribe(can_revert_observer),
|
||||
Disposable.wrap_collection(rows),
|
||||
Disposable.Create(() => {
|
||||
rows.DisposeAll();
|
||||
_smart_copy_roll_target_to_selection_cmd?.can_exe_sub?.Dispose();
|
||||
_smart_copy_riskless_rate_to_selection_cmd?.can_exe_sub?.Dispose();
|
||||
}));
|
||||
@@ -196,18 +195,10 @@ namespace mbts.spark {
|
||||
};
|
||||
|
||||
void _set_driver_to_nearest_exp(IEnumerable<AnalyticsExpirationParametersRowVM> rows) {
|
||||
Func<ExpirationDriverImmutable, bool> is_unexpired = (d) => {
|
||||
var st = d.Security.to_sec_exp().security_tuple.to_api_sec_tuple();
|
||||
var exp = d.Security.Expiration.date_time();
|
||||
return SecurityExpirationHelper.is_unexpired(st, exp);
|
||||
};
|
||||
foreach (var r in rows) {
|
||||
if (drivers
|
||||
.Where(d => d.HasSecurity && d.Security.Symbol == r.security.symbol)
|
||||
.Where(d => is_unexpired(d))
|
||||
.TryGetMinElement(
|
||||
d => (r.security.expiration - d.Security.Expiration.date_time()).Ticks.abs(),
|
||||
out var nearest_exp)) {
|
||||
if (drivers.Where(d => d.HasSecurity).TryGetMinElement(
|
||||
d => (r.security.expiration - d.Security.Expiration.date_time()).Ticks.abs(),
|
||||
out var nearest_exp)) {
|
||||
r.driver = nearest_exp;
|
||||
}
|
||||
}
|
||||
@@ -294,10 +285,10 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
symbols.sync_with(_parameters.Select(p => p.security.symbol).Distinct().Ordered());
|
||||
using var _ = _sync_visible_rows.defer();
|
||||
using var _ = _sync_visible_rows.defer_execution();
|
||||
if (is_first_update) {
|
||||
selected_symbols.sync_with(_pending_selected_symbols?.Intersect(symbols) ?? symbols);
|
||||
_pending_selected_symbols = null;
|
||||
// select all symbols on first update
|
||||
selected_symbols.sync_with(symbols);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
xmlns:u="clr-namespace:mbts.ui"
|
||||
xmlns:cv="clr-namespace:mbts.ui.converters"
|
||||
xmlns:shell="clr-namespace:mbts.ui.shell"
|
||||
Background="{u:BTSBrush UI.common_background}">
|
||||
Background="{StaticResource CommonBackground}">
|
||||
<UserControl.Resources>
|
||||
<cv:DoubleTextConverter x:Key="DoubleTextConverter" />
|
||||
<cv:DoubleTextConverter
|
||||
@@ -30,6 +30,9 @@
|
||||
<Setter
|
||||
Property="FontStyle"
|
||||
Value="Italic" />
|
||||
<Setter
|
||||
Property="Foreground"
|
||||
Value="Gray" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -48,6 +51,9 @@
|
||||
<Setter
|
||||
Property="FontStyle"
|
||||
Value="Italic" />
|
||||
<Setter
|
||||
Property="Foreground"
|
||||
Value="Gray" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -117,20 +123,6 @@
|
||||
CommandParameter="{Binding}"
|
||||
/>
|
||||
</ContextMenu>
|
||||
|
||||
<Style x:Key="TextBlockCellElement" TargetType="TextBlock">
|
||||
<Setter
|
||||
Property="Foreground"
|
||||
Value="{Binding Foreground, RelativeSource={RelativeSource AncestorType=DataGridCell}}" />
|
||||
</Style>
|
||||
|
||||
<Style x:Key="ComboBoxCellElement" TargetType="ComboBox" BasedOn="{StaticResource {x:Type ComboBox}}">
|
||||
<Setter
|
||||
Property="Foreground"
|
||||
Value="{Binding Foreground, RelativeSource={RelativeSource AncestorType=DataGridCell}}" />
|
||||
<Setter Property="Margin" Value="2" />
|
||||
<Setter Property="IsSynchronizedWithCurrentItem" Value="False" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
<Grid>
|
||||
<Grid.Resources>
|
||||
@@ -153,23 +145,17 @@
|
||||
SelectedItems="{Binding selected_symbols}"
|
||||
HorizontalAlignment="Left"
|
||||
Margin="5,2,2,2"
|
||||
TextBlock.Foreground="Black"
|
||||
HeaderContent="Symbols"
|
||||
ShowSelectAll="True">
|
||||
<c:ComboCheckBox.HeaderContentTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding}" Foreground="{u:BTSColor UI.default_text}" />
|
||||
</DataTemplate>
|
||||
</c:ComboCheckBox.HeaderContentTemplate>
|
||||
</c:ComboCheckBox>
|
||||
ShowSelectAll="True"
|
||||
/>
|
||||
|
||||
<WrapPanel>
|
||||
<TextBlock
|
||||
Margin="5,5,0,0" Foreground="{u:BTSBrush UI.default_text}" Text="Auto copy rolls:" />
|
||||
<TextBlock Margin="5,5,0,0" Text="Auto copy rolls:" />
|
||||
<CheckBox Margin="5,5,10,0" IsChecked="{Binding auto_copy_rolls_is_checked}" />
|
||||
</WrapPanel>
|
||||
<WrapPanel>
|
||||
<TextBlock
|
||||
Margin='0,5,0,0' Foreground="{u:BTSBrush UI.default_text}" Text="Auto copy rates:" />
|
||||
<TextBlock Margin='0,5,0,0' Text="Auto copy rates:" />
|
||||
<CheckBox Margin="5,5,0,0" IsChecked="{Binding auto_copy_rates_is_checked}" />
|
||||
</WrapPanel>
|
||||
</StackPanel>
|
||||
@@ -177,8 +163,8 @@
|
||||
x:Name="_grid"
|
||||
Grid.Row="1"
|
||||
ItemsSource="{Binding visible_rows}"
|
||||
Background="Transparent"
|
||||
VerticalGridLinesBrush="{u:BTSColor Grid.grid_line}"
|
||||
AlternatingRowBackground="{u:BTSColor MarketData.driver_background}"
|
||||
VerticalGridLinesBrush="Gray"
|
||||
EnableRowVirtualization="True"
|
||||
EnableColumnVirtualization="True"
|
||||
CanUserAddRows="False"
|
||||
@@ -191,10 +177,35 @@
|
||||
SelectionUnit="FullRow"
|
||||
SelectedUnits="{Binding selected_rows}"
|
||||
PreviewMouseRightButtonUp="_grid_PreviewMouseRightButtonUp">
|
||||
<c:DataGridEx.RowStyle>
|
||||
<Style TargetType="DataGridRow" BasedOn="{StaticResource {x:Type DataGridRow}}">
|
||||
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}"/>
|
||||
<DataGrid.Resources>
|
||||
<Style TargetType="{x:Type DataGridCell}" BasedOn="{StaticResource {x:Type DataGridCell}}">
|
||||
<Setter Property="BorderThickness" Value="1" />
|
||||
<Style.Triggers>
|
||||
<Trigger
|
||||
Property="IsSelected"
|
||||
Value="True">
|
||||
<Setter
|
||||
Property="Background"
|
||||
Value="{u:BTSColor Grid.grid_selection_background}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="{u:BTSColor Grid.grid_selection_background}" />
|
||||
</Trigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGrid.Resources>
|
||||
<DataGrid.RowStyle>
|
||||
<Style TargetType="DataGridRow">
|
||||
<Setter Property="IsSelected" Value="{Binding is_selected, Mode=TwoWay}"/>
|
||||
<Setter Property="Background" Value="Transparent"/>
|
||||
<Style.Triggers>
|
||||
<Trigger
|
||||
Property="IsSelected"
|
||||
Value="true">
|
||||
<Setter
|
||||
Property="Background"
|
||||
Value="{u:BTSColor Grid.grid_selection_background}" />
|
||||
</Trigger>
|
||||
<DataTrigger
|
||||
Binding="{Binding is_last_row_of_month_group}"
|
||||
Value="True">
|
||||
@@ -207,7 +218,7 @@
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</c:DataGridEx.RowStyle>
|
||||
</DataGrid.RowStyle>
|
||||
<DataGrid.ColumnHeaderStyle>
|
||||
<Style TargetType="DataGridColumnHeader">
|
||||
<Setter
|
||||
@@ -219,6 +230,9 @@
|
||||
<Setter
|
||||
Property="HorizontalContentAlignment"
|
||||
Value="Center" />
|
||||
<Setter
|
||||
Property="BorderThickness"
|
||||
Value="0,0,1,0" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Black" />
|
||||
@@ -245,6 +259,9 @@
|
||||
<Setter
|
||||
Property="Foreground"
|
||||
Value="{u:BTSColor Name=header_text}" />
|
||||
<Setter
|
||||
Property="BorderThickness"
|
||||
Value="0" />
|
||||
<Setter
|
||||
Property="VerticalContentAlignment"
|
||||
Value="Center" />
|
||||
@@ -291,7 +308,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_driver_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="{u:BTSColor UI.input_dirty_border}" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -299,10 +318,11 @@
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<ComboBox
|
||||
IsSynchronizedWithCurrentItem="False"
|
||||
ItemsSource="{Binding Source={StaticResource Drivers}}"
|
||||
ItemTemplate="{StaticResource DriverTemplate}"
|
||||
SelectedItem="{Binding driver, UpdateSourceTrigger=PropertyChanged}"
|
||||
Style="{StaticResource ComboBoxCellElement}" />
|
||||
Margin="2" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -320,28 +340,21 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_deliverable_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding is_deliverable_dirty}" Value="False" />
|
||||
<Condition Binding="{Binding
|
||||
deliverable,
|
||||
Converter={x:Static shell:AnalyticsExpirationParametersView.expiration_is_defined_converter}}"
|
||||
Value="False" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.default_foreground_dark}" />
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGridTemplateColumn.CellStyle>
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<ComboBox
|
||||
IsSynchronizedWithCurrentItem="False"
|
||||
ItemsSource="{Binding Source={StaticResource NonOptionsWithEmpty}}"
|
||||
ItemTemplate="{StaticResource ExpirationTemplate}"
|
||||
SelectedItem="{Binding deliverable, UpdateSourceTrigger=PropertyChanged}"
|
||||
Style="{StaticResource ComboBoxCellElement}" />
|
||||
Margin="2" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -359,28 +372,21 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_roll_schedule_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
<MultiDataTrigger>
|
||||
<MultiDataTrigger.Conditions>
|
||||
<Condition Binding="{Binding is_roll_schedule_dirty}" Value="False" />
|
||||
<Condition Binding="{Binding
|
||||
roll_schedule,
|
||||
Converter={x:Static shell:AnalyticsExpirationParametersView.expiration_is_defined_converter}}"
|
||||
Value="False" />
|
||||
</MultiDataTrigger.Conditions>
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.default_foreground_dark}" />
|
||||
</MultiDataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</DataGridTemplateColumn.CellStyle>
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<ComboBox
|
||||
IsSynchronizedWithCurrentItem="False"
|
||||
ItemsSource="{Binding Source={StaticResource NonOptionsWithEmpty}}"
|
||||
ItemTemplate="{StaticResource ExpirationTemplate}"
|
||||
SelectedItem="{Binding roll_schedule, UpdateSourceTrigger=PropertyChanged}"
|
||||
Style="{StaticResource ComboBoxCellElement}" />
|
||||
Margin="2" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -396,7 +402,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_roll_target_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -407,15 +415,14 @@
|
||||
Text="{Binding roll_target, Converter={StaticResource DoubleTextConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource RollTargetContextMenu}"
|
||||
Style="{StaticResource TextBlockCellElement}" />
|
||||
ContextMenu="{StaticResource RollTargetContextMenu}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate>
|
||||
<DataTemplate>
|
||||
<TextBox
|
||||
Text="{Binding roll_target, Converter={StaticResource DoubleTextConverter}}"
|
||||
Margin="2" />
|
||||
Text="{Binding roll_target, Converter={StaticResource DoubleTextConverter}}"
|
||||
Margin="2" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -431,7 +438,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_riskless_rate_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -442,14 +451,12 @@
|
||||
Text="{Binding riskless_rate, Converter={StaticResource RisklessRateConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource RisklessRateContextMenu}"
|
||||
Style="{StaticResource TextBlockCellElement}" />
|
||||
ContextMenu="{StaticResource RisklessRateContextMenu}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate>
|
||||
<DataTemplate>
|
||||
<TextBox
|
||||
Text="{Binding riskless_rate, Converter={StaticResource RisklessRateConverter}}" />
|
||||
<TextBox Text="{Binding riskless_rate, Converter={StaticResource RisklessRateConverter}}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -465,7 +472,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_settlement_price_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -476,14 +485,12 @@
|
||||
Text="{Binding settlement_price, Converter={StaticResource DoubleTextConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource SettlementPriceContextMenu}"
|
||||
Style="{StaticResource TextBlockCellElement}" />
|
||||
ContextMenu="{StaticResource SettlementPriceContextMenu}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate>
|
||||
<DataTemplate>
|
||||
<TextBox
|
||||
Text="{Binding settlement_price, Converter={StaticResource DoubleTextConverter}}" />
|
||||
<TextBox Text="{Binding settlement_price, Converter={StaticResource DoubleTextConverter}}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -500,7 +507,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_delta_beta_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -511,14 +520,12 @@
|
||||
Text="{Binding delta_beta, Converter={StaticResource DoubleTextConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource DeltaBetaContextMenu}"
|
||||
Style="{StaticResource TextBlockCellElement}" />
|
||||
ContextMenu="{StaticResource DeltaBetaContextMenu}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate>
|
||||
<DataTemplate>
|
||||
<TextBox
|
||||
Text="{Binding delta_beta, Converter={StaticResource DoubleTextConverter}}" />
|
||||
<TextBox Text="{Binding delta_beta, Converter={StaticResource DoubleTextConverter}}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellEditingTemplate>
|
||||
</DataGridTemplateColumn>
|
||||
@@ -535,7 +542,9 @@
|
||||
<DataTrigger
|
||||
Binding="{Binding is_vega_beta_dirty}"
|
||||
Value="True">
|
||||
<Setter Property="Foreground" Value="{u:BTSColor UI.input_dirty_foreground}" />
|
||||
<Setter
|
||||
Property="BorderBrush"
|
||||
Value="Red" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
@@ -543,11 +552,10 @@
|
||||
<DataGridTemplateColumn.CellTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock
|
||||
Text="{Binding vega_beta, Converter={StaticResource DoubleTextConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource VegaBetaContextMenu}"
|
||||
Style="{StaticResource TextBlockCellElement}" />
|
||||
Text="{Binding vega_beta, Converter={StaticResource DoubleTextConverter}}"
|
||||
VerticalAlignment="Center"
|
||||
Margin="2,0,2,0"
|
||||
ContextMenu="{StaticResource VegaBetaContextMenu}" />
|
||||
</DataTemplate>
|
||||
</DataGridTemplateColumn.CellTemplate>
|
||||
<DataGridTemplateColumn.CellEditingTemplate>
|
||||
|
||||
@@ -7,8 +7,6 @@ namespace mbts.ui.shell {
|
||||
using mbts.ui.converters;
|
||||
using mbts.ui.extensions;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Windows;
|
||||
using System.Windows.Controls;
|
||||
@@ -53,10 +51,6 @@ namespace mbts.ui.shell {
|
||||
} :
|
||||
null);
|
||||
|
||||
public static IValueConverter expiration_is_defined_converter =>
|
||||
ValueConverter.create<SecurityExpiration?, bool>(exp =>
|
||||
exp is not null && exp.expiration != default);
|
||||
|
||||
void _grid_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e) {
|
||||
Disposable.dispose(ref _context_menu_op);
|
||||
if (e.OriginalSource is not FrameworkElement el || DataContext is not AnalyticsExpirationParametersVM vm) {
|
||||
|
||||
@@ -5,8 +5,6 @@ namespace mbts.spark {
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
|
||||
@@ -6,8 +6,6 @@ namespace mbts.spark {
|
||||
|
||||
using mbts.analytics;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -42,12 +40,6 @@ namespace mbts.spark {
|
||||
exp_params_out_src.Subscribe(save_exp_params));
|
||||
|
||||
void save_exp_params(IEnumerable<AnalyticsExpirationParameters> exp_params) {
|
||||
Func<AnalyticsExpirationParameters, bool> is_unexpired = (p) => {
|
||||
var st = p.driver_security.security_tuple.to_api_sec_tuple();
|
||||
var exp = p.security.expiration;
|
||||
return SecurityExpirationHelper.is_unexpired(st, exp);
|
||||
};
|
||||
exp_params = exp_params.Where(t => is_unexpired(t));
|
||||
// listens to the commit tag and saves it
|
||||
Log.Gen.info($"AnalyticsParametersManager received commit req. count:{exp_params.Count()}");
|
||||
var to_save = new ExpirationParameterEntryList();
|
||||
|
||||
@@ -1,120 +0,0 @@
|
||||
namespace mbts.spark {
|
||||
using bts;
|
||||
using bts.api;
|
||||
|
||||
using mbts;
|
||||
using mbts.analytics;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Collections;
|
||||
|
||||
// For each vs, it sends the vol surface calc request (_do_periodic_auto_fit)
|
||||
// and then commits the response
|
||||
public class SingleVolSurfaceAutoFitSource : IDisposable {
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private readonly int _vs_id;
|
||||
private readonly ITag<VolSurfaceInput> _vs_input_tag;
|
||||
private readonly ITag<VolSurfaceCalculationResponse> _vs_calc_response_tag;
|
||||
private DateTime _last_req_time = DateTime.MinValue;
|
||||
private TimeSpan _req_period = TimeSpan.MaxValue;
|
||||
private int _req_id = 0;
|
||||
public SingleVolSurfaceAutoFitSource(int vs_id, ThreadedBlackboard bb) {
|
||||
_bb = bb;
|
||||
_vs_id = vs_id;
|
||||
_vs_input_tag = SparkTags.VolSurfaceCommittedInputTag(vs_id);
|
||||
_vs_calc_response_tag = SparkTags.VolSurfaceAutoCalculationResponseTag(vs_id);
|
||||
_bb.subscribe(_vs_input_tag);
|
||||
_bb.subscribe(_vs_calc_response_tag);
|
||||
_bb.subscribe(SparkTags.CurrentUser);
|
||||
_bb.data_callback += _on_bb_data;
|
||||
_bb.timer_callback += _on_bb_timer;
|
||||
}
|
||||
|
||||
private void _on_bb_data(object tag, object data) {
|
||||
if (tag.Equals(_vs_input_tag))
|
||||
_possibly_autofit();
|
||||
else if (tag.Equals(_vs_calc_response_tag)) {
|
||||
VolSurfaceCalculationResponse calc_resp = data as VolSurfaceCalculationResponse;
|
||||
bts.Log.Gen.info($"SingleVolSurfaceAutoFitSource._on_bb_data vs_id: {_vs_id} " +
|
||||
$"received calculation response");
|
||||
_bb.post(SparkTags.VolSurfaceCommitTag(_vs_id),
|
||||
calc_resp.volsurface_calculation_output.volsurface_input);
|
||||
}
|
||||
}
|
||||
|
||||
private bool _user_has_vs_control() {
|
||||
VolSurfaceInput vs_input = _bb.read_state(_vs_input_tag);
|
||||
string current_user = _bb.read_state(SparkTags.CurrentUser).name;
|
||||
return vs_input != null &&
|
||||
vs_input.surface_settings.core_settings.vs_manager == current_user;
|
||||
}
|
||||
|
||||
private void _on_bb_timer() {
|
||||
_possibly_autofit();
|
||||
}
|
||||
|
||||
private void _possibly_autofit() {
|
||||
var auto_fit_period = _get_auto_fit_periodic();
|
||||
if (!auto_fit_period.HasValue)
|
||||
return;
|
||||
if (DateTime.Now - _last_req_time <= auto_fit_period)
|
||||
return;
|
||||
if (!_user_has_vs_control())
|
||||
return;
|
||||
// auto fit here
|
||||
bts.Log.Gen.info($"SingleVolSurfaceAutoFitSource vs_id: {_vs_id} requesting fit " +
|
||||
$"last_req_time: {_last_req_time} period: {auto_fit_period.Value}");
|
||||
_send_request();
|
||||
}
|
||||
|
||||
private Nullable<TimeSpan> _get_auto_fit_periodic() {
|
||||
VolSurfaceInput vs_input = _bb.read_state(_vs_input_tag);
|
||||
if (vs_input == null)
|
||||
return null;
|
||||
var fit_settings =
|
||||
VolSurfaceDataFunctions.get_market_fit_settings(vs_input.surface_settings);
|
||||
if (fit_settings == null)
|
||||
return null;
|
||||
var auto_fit_setting = fit_settings.vs_auto_fit_settings;
|
||||
if (auto_fit_setting == null)
|
||||
return null;
|
||||
if (auto_fit_setting.auto_fit_region == VolSurfaceEnums.VolCurveFitRegion.None)
|
||||
return null;
|
||||
var time_based_fit_setting = auto_fit_setting.time_based_settings;
|
||||
if (time_based_fit_setting == null)
|
||||
return null;
|
||||
if (!time_based_fit_setting.period_seconds.HasValue)
|
||||
return null;
|
||||
return TimeSpan.FromSeconds(time_based_fit_setting.period_seconds.Value);
|
||||
}
|
||||
|
||||
private void _send_request() {
|
||||
VolSurfaceInput vs_input = _bb.read_state(_vs_input_tag);
|
||||
if (vs_input == null)
|
||||
return;
|
||||
VolCurveMarketFitAction mf_action = new VolCurveMarketFitAction(
|
||||
VolCurveMarketFitAction.ActionType.FitWholeCurve, null, false);
|
||||
VolCurveAction vc_action = new VolCurveAction(mf_action);
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map =
|
||||
vs_input.surface_parameters.curve_parameters_map.ToDictionary(
|
||||
i => i.Item1,
|
||||
i => vc_action
|
||||
);
|
||||
VolSurfaceCalculationRequest req = new VolSurfaceCalculationRequest(vs_input,
|
||||
_req_id++, action_map, true, true);
|
||||
_last_req_time = DateTime.Now;
|
||||
_bb.post(SparkTags.VolSurfaceAutoCalculationRequestTag(_vs_id), req);
|
||||
}
|
||||
|
||||
|
||||
#region IDisposable
|
||||
public void Dispose() {
|
||||
_bb.data_callback -= _on_bb_data;
|
||||
_bb.timer_callback -= _on_bb_timer;
|
||||
}
|
||||
#endregion
|
||||
|
||||
}
|
||||
}
|
||||
@@ -63,9 +63,9 @@ namespace mbts.spark {
|
||||
vs_input, vs_nonvol_data.contracts, aux_data_map);
|
||||
_timer.stop();
|
||||
var tag_str = tag == null ? "Null" : tag.ToString();
|
||||
// bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish " +
|
||||
// $"vs_id: {_vs_id} time:{_timer.lastIntervalTime} ms tag:{tag_str} " +
|
||||
// $"tid:{_tid()}"); //output: {vs_output.log_string()}*/");
|
||||
bts.Log.Gen.info($"SingleVolSurfaceCommittedOutputRetriever._recompute_and_publish " +
|
||||
$"vs_id: {_vs_id} time:{_timer.lastIntervalTime} ms tag:{tag_str} " +
|
||||
$"tid:{_tid()}"); //output: {vs_output.log_string()}*/");
|
||||
_logger.log(_log_id, _log_id, _timer.lastIntervalTime);
|
||||
_bb.post(_out_bb_computed_vol_tag, vs_output);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,6 @@
|
||||
using bts.api.analytics;
|
||||
|
||||
using mbts.analytics;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
@@ -14,7 +13,6 @@
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Threading;
|
||||
using System.Windows;
|
||||
|
||||
// For a single VolSurface this class
|
||||
// 1. Listents to commmits and calls the service to persist data
|
||||
@@ -26,6 +24,7 @@
|
||||
private readonly ITag<VolSurfaceInput> _in_bb_committ_tag;
|
||||
private readonly AnalyticsService _analytics_service;
|
||||
private readonly HighPerformanceTimer _timer = new HighPerformanceTimer();
|
||||
private readonly string _user;
|
||||
private readonly List<IDisposable> _disposables = new List<IDisposable>();
|
||||
private IDictionary<UInt64, VolSurfaceInputSnapshot> _snp_shot_map = new
|
||||
Dictionary<UInt64, VolSurfaceInputSnapshot>();
|
||||
@@ -36,10 +35,10 @@
|
||||
volsurface_id));
|
||||
_volsurface_id = volsurface_id;
|
||||
_bb = threaded_bb;
|
||||
_user = "TEST_USER"; // TODO
|
||||
_in_bb_committ_tag = SparkTags.VolSurfaceCommitTag(volsurface_id);
|
||||
_analytics_service = analytics_service;
|
||||
_bb.subscribe(_in_bb_committ_tag);
|
||||
_bb.subscribe(SparkTags.CurrentUser);
|
||||
_bb.data_callback += _on_bb_data;
|
||||
var vs_sub = _analytics_service.subscribei_volsurfaces()
|
||||
.ObserveOn(SynchronizationContext.Current)
|
||||
@@ -55,10 +54,8 @@
|
||||
private void _on_vss(bts.api.core.Update<VolSurfaceEntryImmutable, UInt64> update) {
|
||||
IEnumerable<VolSurfaceEntryImmutable> all_vss = update.all;
|
||||
var this_vs_vss = all_vss.Where(vs => vs.VsId == _volsurface_id);
|
||||
bts.Log.Gen.info(
|
||||
$"SingleVolSurfaceGateway._on_vss vs_count: {this_vs_vss.Count()} " +
|
||||
$"all: {update.all.Count()} added: {update.added.Count()} " +
|
||||
$"updated: {update.changed.Count()} removed: {update.removed.Count()}");
|
||||
bts.Log.Gen.info(String.Format("SingleVolSurfaceGateway._on_vss count:{0} vs_count:{1}",
|
||||
all_vss.Count(), this_vs_vss.Count()));
|
||||
if (this_vs_vss.Count() == 0) {
|
||||
return;
|
||||
}
|
||||
@@ -86,39 +83,22 @@
|
||||
static VolSurfaceInput _to_vs_input(VolSurfaceEntryImmutable vs) =>
|
||||
ProtobufSerializationHelper.deserialize<VolSurfaceInput>(vs.Volsurface.ToByteArray());
|
||||
|
||||
// private void _show_save_error(string message) {
|
||||
// BTSMessageBox.Show(message, "Vol Save Error", BTSMessageBoxButtons.OK);
|
||||
// }
|
||||
|
||||
private void _on_bb_data(object tag, object data) {
|
||||
if (_in_bb_committ_tag.Equals(tag)) {
|
||||
try {
|
||||
_timer.start();
|
||||
VolSurfaceInput vs_input = data as VolSurfaceInput;
|
||||
var user_tup = _bb.read_state(SparkTags.CurrentUser);
|
||||
string current_user = user_tup.name;
|
||||
string vs_manager = vs_input.surface_settings.core_settings.vs_manager;
|
||||
if (current_user != vs_manager) {
|
||||
string msg = $"User {current_user} does not have the permission to save vols. " +
|
||||
$"Permission can be obtained via the grid context menu item 'Acquire ownership from {vs_manager}'";
|
||||
BTSMessageBox.Show(msg, "Vol Save Error", BTSMessageBoxButtons.OK);
|
||||
return;
|
||||
}
|
||||
_sanitize_input(ref vs_input);
|
||||
vs_input = VolSurfaceDataFunctions.unset_driver_overrides(vs_input);
|
||||
VolSurfaceUtilityFunctions.save_volsurface(vs_input, _analytics_service, current_user);
|
||||
vs_input.saver_login = _user;
|
||||
VolSurfaceUtilityFunctions.save_volsurface(vs_input, _analytics_service, _user);
|
||||
_timer.stop();
|
||||
Log.Gen.info(String.Format(
|
||||
"SingleVolSurfaceGateway._on_bb_data Time to commit volsurface {0} {1} msecs",
|
||||
_volsurface_id, _timer.lastIntervalTime));
|
||||
var archived_theos = _get_theos();
|
||||
if (archived_theos != null) {
|
||||
_timer.start();
|
||||
if (archived_theos != null)
|
||||
_analytics_service.archive_theos(archived_theos);
|
||||
_timer.stop();
|
||||
Log.Gen.info($"SingleVolSurfaceGateway._on_bb_data archiving theos vs_id: {_volsurface_id} size: " +
|
||||
$"{archived_theos.SecTheo.Count} time: {_timer.lastIntervalTime} msecs");
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.Gen.warn(ex.ToString());
|
||||
_bb.post(SparkTags.MessageDisplayTag,
|
||||
|
||||
@@ -36,11 +36,7 @@ namespace mbts.spark {
|
||||
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb,
|
||||
a_syms => new SingleVolSurfaceCommittedOutputRetriever(_vs_id, _bb, a_syms)),
|
||||
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb,
|
||||
a_syms => new SingleVolSurfaceRequestCalculator(
|
||||
SingleVolSurfaceRequestCalculator.RequestType.UI, _vs_id, a_syms, _bb)),
|
||||
new SingleVolSurfaceDataSource(SingleVolSurfaceDataSource.SymbolListType.Combined, _vs_id, _bb,
|
||||
a_syms => new SingleVolSurfaceRequestCalculator(
|
||||
SingleVolSurfaceRequestCalculator.RequestType.AUTO, _vs_id, a_syms, _bb)),
|
||||
a_syms => new SingleVolSurfaceRequestCalculator(_vs_id, a_syms, _bb)),
|
||||
new SingleVolSurfaceMarketImpliedVolSource(_vs_id, _bb),
|
||||
// new SingleVolSurfaceTheoSource(_vs_id, _bb),
|
||||
// TODO: suspending heatmaps for now (12/24/21)
|
||||
@@ -48,7 +44,6 @@ namespace mbts.spark {
|
||||
// server work that can optionally be done on the client
|
||||
new SingleVolSurfaceDataSource (SingleVolSurfaceDataSource.SymbolListType.Committed, _vs_id, _bb,
|
||||
a_syms => new SingleVolSurfaceInterpGreeksPublisher (_vs_id, _bb, a_syms)),
|
||||
new SingleVolSurfaceAutoFitSource(_vs_id, _bb),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ namespace mbts.spark {
|
||||
var exp_price_map = OptionDriverPriceMap.get_vs_price_map(
|
||||
all_sym_price_map, (s) => _option_symbols.Contains(s));
|
||||
if (sc_data != null && vs_nonvol_input != null && exp_price_map != null) {
|
||||
bts.Log.Gen.diag($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} " +
|
||||
bts.Log.Gen.info($"SingleVolSurfaceNonVolDataSource vs_id:{_vs_id} " +
|
||||
"publishing VolSurfaceNonVolData");
|
||||
_bb.post(_out_bb_vs_nonvol_data_tag,
|
||||
new VolSurfaceNonVolData(
|
||||
|
||||
@@ -18,16 +18,10 @@ namespace mbts.spark {
|
||||
// Pubs :
|
||||
// 1. Calc Resp
|
||||
public class SingleVolSurfaceRequestCalculator : IDisposable {
|
||||
public enum RequestType {
|
||||
UI = 0,
|
||||
AUTO
|
||||
}
|
||||
private readonly RequestType _request_type = RequestType.UI;
|
||||
private readonly int _vs_id;
|
||||
private readonly HashSet<string> _symbols;
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private readonly ITag<VolSurfaceCalculationRequest> _in_bb_request_tag;
|
||||
private readonly ITag<VolSurfaceCalculationRequest> _in_bb_auto_request_tag;
|
||||
private readonly ITag<VolSurfaceNonVolData> _in_bb_nonvol_data_tag;
|
||||
private readonly ITag<VolSurfaceStandardTime> _in_bb_vs_standard_time_tag;
|
||||
private readonly ITag<VolSurfaceEnums.MarketSide> _in_bb_market_impliedvol_side_tag;
|
||||
@@ -36,22 +30,18 @@ namespace mbts.spark {
|
||||
/// data
|
||||
private VolSurfaceOutput _last_output;
|
||||
|
||||
public SingleVolSurfaceRequestCalculator(RequestType request_type,
|
||||
int vs_id, IEnumerable<string> symbols,
|
||||
public SingleVolSurfaceRequestCalculator(int vs_id, IEnumerable<string> symbols,
|
||||
ThreadedBlackboard threaded_bb) {
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id: {vs_id} request_type: {request_type}");
|
||||
_request_type = request_type;
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator cons vs_id:{vs_id}");
|
||||
_vs_id = vs_id;
|
||||
_symbols = new HashSet<string>(symbols);
|
||||
_bb = threaded_bb;
|
||||
_in_bb_request_tag = SparkTags.VolSurfaceCalculationRequestTag(vs_id);
|
||||
_in_bb_auto_request_tag = SparkTags.VolSurfaceAutoCalculationRequestTag(vs_id);
|
||||
_in_bb_nonvol_data_tag = SparkTags.VolSurfaceNonVolDataTag(vs_id);
|
||||
_in_bb_vs_standard_time_tag = SparkTags.VolSurfaceStandardTimeTag(vs_id);
|
||||
_in_bb_market_impliedvol_side_tag = SparkTags.VolSurfaceMarketImpliedVolSide(vs_id);
|
||||
_in_bb_dirty_tag = SparkTags.VolSurfaceDirtyStateTag(vs_id);
|
||||
_bb.subscribe(_in_bb_request_tag);
|
||||
_bb.subscribe(_in_bb_auto_request_tag);
|
||||
_bb.subscribe(_in_bb_nonvol_data_tag);
|
||||
_bb.subscribe(_in_bb_vs_standard_time_tag);
|
||||
_bb.subscribe(_in_bb_vs_standard_time_tag);
|
||||
@@ -61,21 +51,11 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
private void _on_bb_data(object tag, object data) {
|
||||
switch (_request_type) {
|
||||
case RequestType.UI: {
|
||||
if (_in_bb_request_tag.Equals(tag) || _in_bb_dirty_tag.Equals(tag))
|
||||
_recompute_and_publish(true);
|
||||
else if (_in_bb_nonvol_data_tag.Equals(tag) || _in_bb_vs_standard_time_tag.Equals(tag))
|
||||
_recompute_and_publish(false);
|
||||
break;
|
||||
}
|
||||
case RequestType.AUTO: {
|
||||
if (tag.Equals(_in_bb_auto_request_tag)) {
|
||||
_serve_auto_request();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (_in_bb_request_tag.Equals(tag) || _in_bb_dirty_tag.Equals(tag))
|
||||
_recompute_and_publish(true);
|
||||
else if (_in_bb_nonvol_data_tag.Equals(tag) || _in_bb_vs_standard_time_tag.Equals(tag))
|
||||
_recompute_and_publish(false);
|
||||
|
||||
}
|
||||
|
||||
private void _recompute_and_publish(bool is_new_request) {
|
||||
@@ -100,7 +80,7 @@ namespace mbts.spark {
|
||||
nonvol_data.driver_price_map,
|
||||
vs_standard_time, true);
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map =
|
||||
_post_process_action(_bb, _vs_id, effective_req, aux_data_map);
|
||||
_post_process_action(effective_req, aux_data_map);
|
||||
_last_output = GeneralVolSurfaceCalculator.compute(effective_req.volsurface_input,
|
||||
nonvol_data.contracts,
|
||||
aux_data_map,
|
||||
@@ -109,49 +89,16 @@ namespace mbts.spark {
|
||||
effective_req.cascade_up,
|
||||
effective_req.cascade_down);
|
||||
_timer.stop();
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish vs_id: {_vs_id} " +
|
||||
$"time: {_timer.lastIntervalTime}");
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._recompute_and_publish time:" +
|
||||
$"{_timer.lastIntervalTime} vs_output:{_last_output.log_string()}");
|
||||
_bb.post(SparkTags.VolSurfaceCalculationResponseTag(_vs_id),
|
||||
new VolSurfaceCalculationResponse(_last_output, effective_req.request_id));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void _serve_auto_request() {
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._serve_auto_request " +
|
||||
$"vs_id: {_vs_id} auto request received");
|
||||
bool is_dirty = _bb.read_state(_in_bb_dirty_tag, false);
|
||||
VolSurfaceNonVolData nonvol_data = _bb.read_state(_in_bb_nonvol_data_tag);
|
||||
VolSurfaceStandardTime vs_standard_time = _bb.read_state(_in_bb_vs_standard_time_tag);
|
||||
VolSurfaceCalculationRequest auto_req = _bb.read_state(_in_bb_auto_request_tag);
|
||||
if (is_dirty || nonvol_data == null || vs_standard_time == null || auto_req == null) {
|
||||
return;
|
||||
}
|
||||
_timer.start();
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map =
|
||||
VolSurfaceUtilityFunctions.compute_aux_data(auto_req.volsurface_input,
|
||||
nonvol_data.input,
|
||||
nonvol_data.driver_price_map,
|
||||
vs_standard_time, true);
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map =
|
||||
_post_process_action(_bb, _vs_id, auto_req, aux_data_map);
|
||||
var vs_output = GeneralVolSurfaceCalculator.compute(auto_req.volsurface_input,
|
||||
nonvol_data.contracts,
|
||||
aux_data_map,
|
||||
action_map,
|
||||
null,
|
||||
auto_req.cascade_up,
|
||||
auto_req.cascade_down);
|
||||
_timer.stop();
|
||||
bts.Log.Gen.info($"SingleVolSurfaceRequestCalculator._serve_auto_request vs_id: {_vs_id} " +
|
||||
$"time: {_timer.lastIntervalTime}");
|
||||
_bb.post(SparkTags.VolSurfaceAutoCalculationResponseTag(_vs_id),
|
||||
new VolSurfaceCalculationResponse(vs_output, auto_req.request_id));
|
||||
}
|
||||
|
||||
/// Computes the impl vol if the action is fit to market
|
||||
private static IDictionary<VolSurfaceExpiration, VolCurveAction> _post_process_action(
|
||||
ThreadedBlackboard bb, int vs_id,
|
||||
private IDictionary<VolSurfaceExpiration, VolCurveAction> _post_process_action(
|
||||
VolSurfaceCalculationRequest req,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map) {
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> rv = req.action_map;
|
||||
@@ -162,7 +109,7 @@ namespace mbts.spark {
|
||||
VolCurveAction rep_action = rv.ElementAt(0).Value;
|
||||
if (rep_action.action_type == VolCurveAction.ActionType.FitToMarket) {
|
||||
IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> impl_vol_map =
|
||||
_fill_in_implied_vols(bb, vs_id, req.volsurface_input, req.action_map, aux_data_map,
|
||||
_fill_in_implied_vols(req.volsurface_input, req.action_map, aux_data_map,
|
||||
req.cascade_up, req.cascade_down);
|
||||
rv = impl_vol_map.ToDictionary(kv => kv.Key, kv => new VolCurveAction(
|
||||
new VolCurveMarketFitAction(rep_action.market_fit_action.fit_action, kv.Value,
|
||||
@@ -172,8 +119,7 @@ namespace mbts.spark {
|
||||
return rv;
|
||||
}
|
||||
|
||||
private static IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> _fill_in_implied_vols(
|
||||
ThreadedBlackboard bb, int vs_id,
|
||||
private IDictionary<VolSurfaceExpiration, VolCurveMarketImpliedVolData> _fill_in_implied_vols(
|
||||
VolSurfaceInput vs_inp,
|
||||
IDictionary<VolSurfaceExpiration, VolCurveAction> action_map,
|
||||
IDictionary<VolSurfaceExpiration, VolSurfaceExpirationAuxiliaryData> aux_data_map,
|
||||
@@ -194,15 +140,15 @@ namespace mbts.spark {
|
||||
applicable_exps = applicable_exps.Where(vs_exp => master_exps.Contains(vs_exp));
|
||||
|
||||
VolSurfaceEnums.MarketSide impliedvol_side =
|
||||
SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(bb, vs_id);
|
||||
SingleVolSurfaceMarketImpliedVolSource._get_market_impliedvol_side(_bb, _vs_id);
|
||||
foreach (VolSurfaceExpiration vs_exp in applicable_exps) {
|
||||
VolSurfaceExpiration md_exp;
|
||||
VolCurveMarketImpliedVolData exp_impl_data =
|
||||
VolSurfaceCoreFunctions.compute_implied_vols(vs_inp, vs_exp, aux_data_map,
|
||||
arg_vs_exp => SingleVolSurfaceMarketImpliedVolSource.get_option_bbo(bb, arg_vs_exp),
|
||||
arg_vs_exp => SingleVolSurfaceMarketImpliedVolSource.get_option_bbo(_bb, arg_vs_exp),
|
||||
impliedvol_side,
|
||||
SingleVolSurfaceMarketImpliedVolSource._ignore_market_implied_vol_source_settings(
|
||||
bb, vs_id),
|
||||
_bb, _vs_id),
|
||||
out md_exp);
|
||||
rv[vs_exp] = exp_impl_data;
|
||||
}
|
||||
|
||||
@@ -160,8 +160,8 @@ namespace mbts.spark {
|
||||
|
||||
public static IEnumerable<bts.api.SecurityTuple> get_vs_sectups(
|
||||
int vs_id, ThreadedBlackboard bb) {
|
||||
var vs_usage_list = bb.read_state(SparkTags.VolSurfaceUsageTag);
|
||||
return (vs_usage_list?.get_sectups(vs_id)).empty_if_null();
|
||||
VolSurfaceUsageListImmutable vs_usage_list = bb.read_state(SparkTags.VolSurfaceUsageTag);
|
||||
return vs_usage_list.get_sectups(vs_id);
|
||||
}
|
||||
|
||||
|
||||
@@ -242,4 +242,4 @@ namespace mbts.spark {
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -13,21 +13,28 @@ namespace mbts.spark {
|
||||
bts.Log.Gen.info($"SingleVolSurfaceTimeSource cons vs_id:{vs_id}");
|
||||
_vs_id = vs_id;
|
||||
_bb = bb;
|
||||
_bb.timer_callback += _on_timer;
|
||||
_bb.subscribe(SparkTags.VolSurfaceStandardServerTimeTag);
|
||||
_bb.data_callback += _on_data;
|
||||
_read_and_publish();
|
||||
}
|
||||
|
||||
private void _on_timer() {
|
||||
if (DateTime.Now - _last_publish_time >= _publish_period) {
|
||||
_last_publish_time = DateTime.Now;
|
||||
VolSurfaceStandardTime time = VolSurfaceStandardTime.get_local_default();
|
||||
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{time.ToString()}");
|
||||
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), time);
|
||||
private void _on_data(object tag, object data) {
|
||||
if (tag.Equals(SparkTags.VolSurfaceStandardServerTimeTag)) {
|
||||
_read_and_publish();
|
||||
}
|
||||
}
|
||||
|
||||
private void _read_and_publish() {
|
||||
VolSurfaceStandardTime vs_time = _bb.read_state(SparkTags.VolSurfaceStandardServerTimeTag);
|
||||
if (vs_time != null) {
|
||||
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{vs_time.ToString()}");
|
||||
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), vs_time);
|
||||
}
|
||||
}
|
||||
|
||||
#region IDisposable
|
||||
public void Dispose() {
|
||||
_bb.timer_callback -= _on_timer;
|
||||
_bb.data_callback -= _on_data;
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
|
||||
@@ -11,22 +11,18 @@ namespace mbts.analytics {
|
||||
// tags, into IReadOnlyDictionary of symbol vs data publsihed under one tag
|
||||
public class SymbolAggregationPublisher<TData> : IDisposable {
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private readonly SecurityType _sec_type;
|
||||
Func<string, ITag<TData>> _get_tag;
|
||||
// the tag on which the output will be published
|
||||
ITag<IReadOnlyDictionary<string, TData>> _out_tag;
|
||||
private readonly ITag<SystemContractData> _sc_data_tag;
|
||||
Func<string, ITag<TData>> _get_tag;
|
||||
ITag<IReadOnlyDictionary<string, TData>> _out_tag;
|
||||
private Dictionary<string, ITag<TData>> _tag_map =
|
||||
new Dictionary<string, ITag<TData>>();
|
||||
private HashSet<object> _obj_tags = new HashSet<object>();
|
||||
private bool _dirty = true;
|
||||
public SymbolAggregationPublisher(
|
||||
ThreadedBlackboard bb,
|
||||
SecurityType sec_type,
|
||||
Func<string, ITag<TData>> get_tag,
|
||||
ITag<IReadOnlyDictionary<string, TData>> out_tag) {
|
||||
_bb = bb;
|
||||
_sec_type = sec_type;
|
||||
_get_tag = get_tag;
|
||||
_out_tag = out_tag;
|
||||
_sc_data_tag = SparkTags.SystemContractsTag;
|
||||
@@ -52,20 +48,15 @@ namespace mbts.analytics {
|
||||
return;
|
||||
}
|
||||
foreach (var st in sc_data.sectup_map) {
|
||||
if (st.security_type != _sec_type) {
|
||||
continue;
|
||||
}
|
||||
// this is not correct since it is assuming symbol/name is
|
||||
// unique across securty_tuples
|
||||
string symbol = st.security_name;
|
||||
if (!_tag_map.ContainsKey(symbol)) {
|
||||
var tag = _get_tag(symbol);
|
||||
if (tag != null) {
|
||||
_tag_map.Add(symbol, tag);
|
||||
_obj_tags.Add(tag);
|
||||
_bb.subscribe(tag);
|
||||
_dirty = true;
|
||||
}
|
||||
var symbol_tag = _get_tag(symbol);
|
||||
_tag_map.Add(symbol, symbol_tag);
|
||||
_obj_tags.Add(symbol_tag);
|
||||
_bb.subscribe(symbol_tag);
|
||||
_dirty = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -81,7 +72,7 @@ namespace mbts.analytics {
|
||||
output.Add(symbol, symbol_data);
|
||||
}
|
||||
IReadOnlyDictionary<string, TData> ro_output = output;
|
||||
bts.Log.Gen.diag($"SymbolAggregationPublisher._on_timer publishing " +
|
||||
bts.Log.Gen.info($"SymbolAggregationPublisher._on_timer publishing " +
|
||||
$"tag: {_out_tag} sz: {ro_output.Count}");
|
||||
_bb.post(_out_tag, ro_output);
|
||||
}
|
||||
|
||||
@@ -16,7 +16,6 @@ using System.Collections;
|
||||
using mbts.spark;
|
||||
using System.DirectoryServices.ActiveDirectory;
|
||||
using Spark.Core.Protobuf;
|
||||
using mbts.ui;
|
||||
// using mbts.bb;
|
||||
|
||||
namespace mbts.spark {
|
||||
@@ -77,8 +76,7 @@ namespace mbts.spark {
|
||||
private HighPerformanceTimer _timer = new HighPerformanceTimer();
|
||||
|
||||
public VolSurfaceBusManager(bts.api.IBus bus,
|
||||
bts.api.analytics.AnalyticsService analytics_service,
|
||||
bts.api.orderman.OrderService order_service) {
|
||||
bts.api.analytics.AnalyticsService analytics_service) {
|
||||
bts.Log.Ui.info("VSBusManager cons tid:{VolSurfaceTroubleshootingFunctions.tid()}");
|
||||
_bus = bus;
|
||||
_bb = new ThreadedBlackboard("AW2", bus);
|
||||
@@ -98,21 +96,21 @@ namespace mbts.spark {
|
||||
var vs_usage_sub = _analytics_service.subscribei_volsurface_usage()
|
||||
.ObserveOn(SynchronizationContext.Current)
|
||||
.Subscribe(_on_vs_usage_update);
|
||||
var vs_time_sub = _analytics_service.subscribei_volsurface_time()
|
||||
.ObserveOn(SynchronizationContext.Current)
|
||||
.Subscribe(_on_vs_time);
|
||||
_subs.Add(vs_time_sub);
|
||||
_subs.Add(vs_sub);
|
||||
_subs.Add(vs_usage_sub);
|
||||
_subs.Add(new AnalyticsParametersManager(bus, _analytics_service));
|
||||
_subs.Add(new ResourceAllocator(bus, _bb));
|
||||
_subs.Add(new SymbolAggregationPublisher<OptionDriverPriceMap>(
|
||||
_bb, SecurityType.Option, sym => SparkTags.OptionDriverBBOTag(sym),
|
||||
_bb, (sym) => SparkTags.OptionDriverBBOTag(sym),
|
||||
SparkTags.AllOptionDriverBBOTag));
|
||||
_subs.Add(new SymbolAggregationPublisher<OptionTheoInterpolationData>(
|
||||
_bb, SecurityType.Option, sym => SparkTags.SymbolInterpGreeksTag(sym),
|
||||
_bb, (sym) => SparkTags.SymbolInterpGreeksTag(sym),
|
||||
SparkTags.AllInterpGreeks));
|
||||
_subs.Add(new SymbolAggregationPublisher<ExpStrikeKeyedData<TheoPoint>>(
|
||||
_bb, SecurityType.Option, sym => SparkTags.TC2Tags.LiveTheosTag(sym),
|
||||
SparkTags.TC2Tags.AllLiveTheosTag));
|
||||
_subs.Add(new LiveTheoPublisher(_bb));
|
||||
_subs.Add(new InterpTheosServerPublisher(_bb, order_service));
|
||||
_subs.Add(new VolSurfaceInterpGreeksMultiplexer(_bb));
|
||||
// usage
|
||||
var list_sub = _bus.subscribe(SparkTags.VolSurfaceListTag).OnDispatcher().Subscribe(t => {
|
||||
@@ -144,74 +142,14 @@ namespace mbts.spark {
|
||||
var list_imm = new VolSurfaceUsageListImmutable(ulist);
|
||||
Log.Ui.info(list_imm.log_string());
|
||||
_bb.post(SparkTags.VolSurfaceUsageTag, list_imm);
|
||||
_spin_vss(list_imm);
|
||||
});
|
||||
_disps.Add(list_sub);
|
||||
// f(contract keyed theos, securities) -> id keyed theos
|
||||
// (so the newer UI controls can access theos vis sec keys)
|
||||
var theo_sub =
|
||||
_bus.subscribe(SparkTags.TC2Tags.AllLiveTheosTag)
|
||||
.CombineLatest(bus.subscribe(SparkTags.SystemContractsTag),
|
||||
(theos, sc_data) => (theos, sc_data)).Subscribe(
|
||||
tup => {
|
||||
var keyed_theos = _assemble_keyed_theos(tup.sc_data, tup.theos);
|
||||
_bus.post(SparkTags.KeyedTheos, keyed_theos);
|
||||
}
|
||||
);
|
||||
_disps.Add(theo_sub);
|
||||
}
|
||||
|
||||
static IReadOnlyDictionary<uint, VolSurfaceTheoPoint> _assemble_keyed_theos(
|
||||
SystemContractData sc_data,
|
||||
IReadOnlyDictionary<string, ExpStrikeKeyedData<TheoPoint>> theos) {
|
||||
if (sc_data is null || theos is null) {
|
||||
return new Dictionary<uint, VolSurfaceTheoPoint>(0);
|
||||
}
|
||||
|
||||
HighPerformanceTimer timer = new HighPerformanceTimer();
|
||||
timer.start();
|
||||
Dictionary<uint, VolSurfaceTheoPoint> rv = new Dictionary<uint, VolSurfaceTheoPoint>();
|
||||
foreach (var kv in theos) {
|
||||
var symbol = kv.Key;
|
||||
ExpStrikeKeyedData<TheoPoint> sym_theos = kv.Value;
|
||||
if (sym_theos == null)
|
||||
continue;
|
||||
foreach (var s_kv in sym_theos.get_data_linearly()) {
|
||||
DateTime exp = s_kv.first;
|
||||
double strike = s_kv.second;
|
||||
TheoPoint tp = s_kv.third;
|
||||
// TODO: fix exchange later
|
||||
Tuple<uint?, uint?> keys =
|
||||
sc_data.get_option_sec_id(Venue.Deribit, symbol, exp, strike);
|
||||
if (keys != null) {
|
||||
var c_key = keys.Item1;
|
||||
var p_key = keys.Item2;
|
||||
if (c_key.HasValue) {
|
||||
rv[c_key.Value] = new VolSurfaceTheoPoint(tp, true);
|
||||
}
|
||||
if (p_key.HasValue) {
|
||||
rv[p_key.Value] = new VolSurfaceTheoPoint(tp, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
timer.stop();
|
||||
Log.Gen.info($"VolSurfaceBusManager keyed theos count: {rv.Count} " +
|
||||
$"time: {timer.lastIntervalTime}");
|
||||
return rv;
|
||||
}
|
||||
|
||||
public ThreadedBlackboard bb() {
|
||||
return _bb;
|
||||
}
|
||||
|
||||
void _spin_vss(VolSurfaceUsageListImmutable ulist) {
|
||||
foreach (var u in ulist.UsageList) {
|
||||
var vs_id = u.VsId;
|
||||
_bb.post(SparkTags.VolSurfaceActiveUITag(vs_id), true);
|
||||
}
|
||||
}
|
||||
|
||||
void _on_vs_usage_update(Update<VolSurfaceUsageListImmutable, int> update) {
|
||||
// TODO
|
||||
return;
|
||||
@@ -229,6 +167,17 @@ namespace mbts.spark {
|
||||
_init_vss(to_publish.Keys);
|
||||
}
|
||||
|
||||
void _on_vs_time(bts.api.core.Update<VolSurfaceServerTimeImmutable, int> update) {
|
||||
if (update.all.Count() != 1) {
|
||||
return;
|
||||
}
|
||||
VolSurfaceStandardTime vs_time =
|
||||
new VolSurfaceStandardTime(update.all.ElementAt(0).UtcTime.Seconds);
|
||||
bts.Log.Gen.info(String.Format("VSBusManager._on_vs_time vs_time: {0}",
|
||||
vs_time.ToString()));
|
||||
_bb.post(SparkTags.VolSurfaceStandardServerTimeTag, vs_time);
|
||||
}
|
||||
|
||||
private void _init_vss(IEnumerable<int> vs_ids) {
|
||||
// we consider every vs in the db as "activated" which might prove to be expensive
|
||||
// (will take care of it later)
|
||||
@@ -270,7 +219,6 @@ namespace mbts.spark {
|
||||
new mbts.analytics.VolSurfaceNonVolInput(exp_param_map.exp_map.ToDictionary()));
|
||||
} else if (_in_bb_req_vol.Equals(tag)) {
|
||||
ClientArchivedVolRequest client_req = _bb.read_state(_in_bb_req_vol);
|
||||
bts.Log.Ui.info($"VolSurfaceBusManager._on_bb_update ClientArchivedVolRequest: {client_req.ToString()}");
|
||||
ArchivedTheoRetrieval ret = client_req.ret;
|
||||
if (ret == null || ret.SecTup == null) {
|
||||
bts.Log.Ui.warn($"VolSurfaceBusManager malformed ArchivedTheoRetrieval");
|
||||
|
||||
@@ -1,20 +0,0 @@
|
||||
|
||||
|
||||
namespace mbts.analytics {
|
||||
using mbts.spark;
|
||||
|
||||
// TheoPoint (from edge) has both calls and puts in the same structure.
|
||||
// This shoudl dis-entangle that
|
||||
public class VolSurfaceTheoPoint {
|
||||
public readonly double theo = double.NaN;
|
||||
public readonly double delta = double.NaN;
|
||||
public readonly double driver = double.NaN;
|
||||
public VolSurfaceTheoPoint(TheoPoint tp, bool is_call) {
|
||||
if (tp != null) {
|
||||
theo = is_call ? tp.fwd_normalized_call : tp.fwd_normalized_put;
|
||||
delta = is_call ? tp.cdelta : tp.pdelta;
|
||||
driver = tp.driver;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -6,7 +6,6 @@
|
||||
using mbts.user.settings;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
public class VolSurfaceDisplayGridColumn : IEquatable<VolSurfaceDisplayGridColumn> {
|
||||
public readonly Func<object, string> format;
|
||||
@@ -19,19 +18,16 @@
|
||||
VolSurfaceColumnSettings settings,
|
||||
Func<object, string> format = null,
|
||||
Func<string, object> parse = null,
|
||||
Func<object, bool, object> tick_move = null,
|
||||
IEqualityComparer<object> comparer = null) {
|
||||
Func<object, bool, object> tick_move = null) {
|
||||
this.settings = settings;
|
||||
this.format = format ?? (v => v?.ToString() ?? string.Empty);
|
||||
this.parse = parse ?? (v => v);
|
||||
this.tick_move = tick_move ?? ((v, is_up) => v);
|
||||
this.comparer = comparer ?? EqualityComparer<object>.Default;
|
||||
}
|
||||
|
||||
public string unique_col_name => settings.id;
|
||||
public string display_name => settings.display_name;
|
||||
public string group => settings.group;
|
||||
public IEqualityComparer<object> comparer { get; }
|
||||
|
||||
internal VolSurfaceColumnType type => settings.type;
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@
|
||||
using mbts.user.settings;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
class VolSurfaceDisplayUtilities {
|
||||
public static TickDisplaySettings default_tick_display =>
|
||||
@@ -19,10 +18,6 @@
|
||||
default_tick_display.with(display_multiplier: 100);
|
||||
|
||||
public static double parse_double(object obj) {
|
||||
if (obj is null) {
|
||||
Log.Gen.warn("parse_double received null input (will return nan and continue)");
|
||||
return double.NaN;
|
||||
}
|
||||
Log.assert(obj is double);
|
||||
obj = obj ?? Double.NaN;
|
||||
double rv = obj is Double ? (double)obj : (Double.TryParse(obj.ToString(), out rv) ? rv : Double.NaN);
|
||||
@@ -54,31 +49,9 @@
|
||||
}
|
||||
|
||||
public static Func<object, bool, object> get_double_tickmove(TickFactors tick_factors, int tick_move) =>
|
||||
(data, is_up) => {
|
||||
if (data is not double dbl) {
|
||||
return data;
|
||||
}
|
||||
if (dbl.is_nan()) {
|
||||
return 0D;
|
||||
}
|
||||
return tick_factors.tick(dbl, is_up ? tick_move : -tick_move);
|
||||
};
|
||||
|
||||
public static IEqualityComparer<double> get_double_comparer(
|
||||
TickFactors tick_factors = null, double display_mult = double.NaN) {
|
||||
if (tick_factors is null) {
|
||||
return new TickFactors(10^7, 1).tick_equality_comparer();
|
||||
}
|
||||
// This equality comparer is used to compare actual values (not multiplied by
|
||||
// 'display_mult'), while the TickFactors are used to format the display value (multiplied
|
||||
// by 'display_mult'). Multiply the tick base by 'display_mult' so the equality comparison
|
||||
// is done with the correct number of decimal places.
|
||||
if (display_mult > 0 && Math.Log10(display_mult).is_int()) {
|
||||
tick_factors = tick_factors.with(
|
||||
tick_base: tick_factors.tick_base * display_mult);
|
||||
}
|
||||
return tick_factors.tick_equality_comparer();
|
||||
}
|
||||
(data, is_up) => data is double d_data ?
|
||||
tick_factors.tick(d_data, is_up ? tick_move : -tick_move) :
|
||||
data;
|
||||
|
||||
public static VolSurfaceDisplayGridColumn get_double_output_col(
|
||||
string group,
|
||||
@@ -140,10 +113,7 @@
|
||||
col_config,
|
||||
format: get_double_tostring(col_config.tick_factors, col_config.tick_display),
|
||||
parse: get_parse_double(col_config.tick_factors, col_config.tick_display),
|
||||
tick_move: get_double_tickmove(col_config.tick_factors, col_config.tick_move),
|
||||
comparer: get_double_comparer(
|
||||
col_config.tick_factors, col_config.tick_display.display_multiplier)
|
||||
.cast<double, object>());
|
||||
tick_move: get_double_tickmove(col_config.tick_factors, col_config.tick_move));
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,138 +0,0 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using mbts.analytics;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using System.Linq;
|
||||
using bts.api.orderman;
|
||||
using bts.api.analytics;
|
||||
using bts;
|
||||
|
||||
namespace mbts.spark {
|
||||
// Listens to the interp theos, decorates the data
|
||||
// and sends them over to the sparkd server
|
||||
public class InterpTheosServerPublisher : IDisposable {
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private readonly bts.api.orderman.OrderService _order_service;
|
||||
private HighPerformanceTimer _timer = new HighPerformanceTimer();
|
||||
|
||||
public InterpTheosServerPublisher(ThreadedBlackboard bb,
|
||||
bts.api.orderman.OrderService order_service) {
|
||||
bts.Log.Ui.info(
|
||||
$"InterpTheosServerPublisher cons tid:{VolSurfaceTroubleshootingFunctions.tid()}");
|
||||
_bb = bb;
|
||||
_order_service = order_service;
|
||||
_bb.subscribe(SparkTags.AllInterpGreeks);
|
||||
_bb.subscribe(SparkTags.SystemContractsTag);
|
||||
_bb.subscribe(SparkTags.CurrentUser);
|
||||
_bb.subscribe(SparkTags.VolSurfaceUsageTag);
|
||||
_bb.data_callback += _on_data;
|
||||
}
|
||||
|
||||
private void _on_data(object tag, object data) {
|
||||
if (tag.Equals(SparkTags.SystemContractsTag) ||
|
||||
tag.Equals(SparkTags.AllInterpGreeks)) {
|
||||
_publish_data();
|
||||
}
|
||||
}
|
||||
|
||||
private static IDictionary<UInt32, DriverMD> _get_drivers(
|
||||
IReadOnlyDictionary<string, OptionDriverPriceMap> driver_map,
|
||||
SystemContractData sc_data) {
|
||||
var rv = new Dictionary<UInt32, DriverMD>();
|
||||
foreach (var kv in driver_map) {
|
||||
rv.AddRange(
|
||||
SecurityNormalizer.normalize_drivers(kv.Value, sc_data).ToArray());
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
private static IEnumerable<Tuple<SecurityImmutable, TheoPoint>> _get_theos(
|
||||
IReadOnlyDictionary<string, OptionTheoInterpolationData> theo_data,
|
||||
SystemContractData sc_data) {
|
||||
var rv = new List<Tuple<SecurityImmutable, TheoPoint>>();
|
||||
foreach (var kv in theo_data) {
|
||||
rv.AddRange(
|
||||
SecurityNormalizer.normalize_interp_theos(kv.Value, sc_data));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
private IReadOnlyDictionary<string, OptionTheoInterpolationData>
|
||||
_filter_for_publish(IReadOnlyDictionary<string, OptionTheoInterpolationData> all_theos) {
|
||||
// find the symbol vs vs_id, get the committed vs, see if it is
|
||||
// owned by the current user, and only then publish it
|
||||
HashSet<string> syms = new HashSet<string>();
|
||||
var usage = _bb.read_state(SparkTags.VolSurfaceUsageTag);
|
||||
string current_user = _bb.read_state(SparkTags.CurrentUser).name;
|
||||
foreach (var u in (usage?.UsageList).empty_if_null()) {
|
||||
VolSurfaceInput vs_input =
|
||||
_bb.read_state(SparkTags.VolSurfaceCommittedInputTag(u.VsId));
|
||||
if (vs_input != null) {
|
||||
if (vs_input.surface_settings.core_settings.vs_manager ==
|
||||
current_user) {
|
||||
syms.Add(u.SecTup.Symbol);
|
||||
}
|
||||
}
|
||||
}
|
||||
return
|
||||
all_theos.Where(kv => syms.Contains(kv.Key)).ToDictionary(kv => kv.Key, kv => kv.Value);
|
||||
}
|
||||
|
||||
private void _publish_data() {
|
||||
SystemContractData sc_data = _bb.read_state(SparkTags.SystemContractsTag, null);
|
||||
IReadOnlyDictionary<string, OptionTheoInterpolationData> all_theos =
|
||||
_bb.read_state(SparkTags.AllInterpGreeks, null);
|
||||
IReadOnlyDictionary<string, OptionDriverPriceMap> all_drivers =
|
||||
_bb.read_state(SparkTags.AllOptionDriverBBOTag, null);
|
||||
if (sc_data == null || all_theos == null || all_drivers == null)
|
||||
return;
|
||||
_timer.start();
|
||||
all_theos = _filter_for_publish(all_theos);
|
||||
if (all_theos.Count == 0) {
|
||||
bts.Log.Gen.info($"InterpTheosServerPublisher._publish_data all_theos.Count == 0");
|
||||
return;
|
||||
}
|
||||
IDictionary<UInt32, DriverMD> driver_map = _get_drivers(all_drivers, sc_data);
|
||||
IEnumerable<Tuple<SecurityImmutable, TheoPoint>> theo_map = _get_theos(all_theos, sc_data);
|
||||
// assemble it together and send it to the server
|
||||
var ptp_list = new List<bts.api.orderman.PrecomputedTheoPoint>();
|
||||
foreach (var tup in theo_map) {
|
||||
SecurityImmutable sec = tup.Item1;
|
||||
TheoPoint tp = tup.Item2;
|
||||
bool is_call = sec.Option.CallPut == PutOrCall.Call;
|
||||
var sec_id = sec.Id;
|
||||
DriverMD dmd = null;
|
||||
driver_map.TryGetValue(sec_id, out dmd);
|
||||
PrecomputedTheoPoint ptp = new PrecomputedTheoPoint();
|
||||
ptp.SecId = sec_id;
|
||||
ptp.Driver = tp.driver;
|
||||
ptp.DriverSecId = dmd != null && dmd.driver_security.HasValue ?
|
||||
dmd.driver_security.Value.Id : 0;
|
||||
ptp.Theo = is_call ? tp.call : tp.put;
|
||||
ptp.Delta = is_call ? tp.cdelta : tp.pdelta;
|
||||
ptp.Gamma = is_call ? tp.cgamma : tp.pgamma;
|
||||
ptp.Vega = is_call ? tp.cvega : tp.pvega;
|
||||
ptp.Theta = is_call ? tp.c_theta : tp.p_theta;
|
||||
ptp.Rho = Double.NaN;
|
||||
ptp.Vol = tp.vol;
|
||||
ptp_list.Add(ptp);
|
||||
}
|
||||
bts.api.orderman.PrecomputedTheos server_theos = new PrecomputedTheos();
|
||||
server_theos.Theos.AddRange(ptp_list);
|
||||
_timer.stop();
|
||||
var comp_time = _timer.lastIntervalTime;
|
||||
_timer.start();
|
||||
_order_service.set_precomputed_theos(server_theos);
|
||||
_timer.stop();
|
||||
var pub_time = _timer.lastIntervalTime;
|
||||
bts.Log.Gen.info($"InterpTheosServerPublisher._publish_data symbols: {all_theos.Count} " +
|
||||
$"size: {server_theos.Theos.Count} comp_time: {comp_time} msecs " +
|
||||
$"pub_time: {pub_time}");
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
_bb.data_callback -= _on_data;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,8 +5,6 @@ using bts.api;
|
||||
using mbts.ui;
|
||||
using MathNet.Numerics.Providers.FourierTransform;
|
||||
using BCG;
|
||||
using System.Windows.Automation;
|
||||
using bts.collections;
|
||||
|
||||
namespace mbts.spark {
|
||||
// Publishes theos for all options (on the side, also publishes the theos for TC2)
|
||||
@@ -70,14 +68,19 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
private void _log_theos(SystemContractData sc_data,
|
||||
IReadOnlyDictionary<uint, GreeksTuple> greeks_map) {
|
||||
IReadOnlyDictionary<uint, GreeksTuple> greeks_map,
|
||||
DateTime? exp_filt = null) {
|
||||
string rv = "LiveTheosPublisher data: ";
|
||||
foreach (var kv in greeks_map) {
|
||||
var id = kv.Key;
|
||||
var g_tup = kv.Value;
|
||||
if (sc_data.sec_md_map.TryGetValue(id, out var smd)) {
|
||||
string sec_str = smd.ToString();
|
||||
rv += "\n" + $"id: {id} sec: {sec_str} greeks: {g_tup}";
|
||||
if (exp_filt == null ||
|
||||
(smd.security.security_type() == SecurityType.Option &&
|
||||
smd.security.Option.expiration_date().Equals(exp_filt.Value))) {
|
||||
string sec_str = smd.ToString();
|
||||
rv += "\n" + $"id: {id} sec: {sec_str} greeks: {g_tup}";
|
||||
}
|
||||
}
|
||||
}
|
||||
bts.Log.Gen.info(rv);
|
||||
@@ -131,7 +134,6 @@ namespace mbts.spark {
|
||||
return;
|
||||
}
|
||||
var k_theos = new Dictionary<SecurityStrike, TheoPoint>();
|
||||
// option spreads
|
||||
foreach (var kv in sc_data.strike_map) {
|
||||
foreach (SecurityStrike k in kv.Value) {
|
||||
var (call_id, put_id) = k.call_put_id;
|
||||
@@ -140,59 +142,26 @@ namespace mbts.spark {
|
||||
k_theos[k] = tp;
|
||||
// put it in the output map
|
||||
if (call_id.HasValue) {
|
||||
var normalized_theo = VolSurfaceCoreFunctions.normalize_theo(tp.call, tp.driver);
|
||||
res.Add(call_id.Value,
|
||||
new GreeksTuple(tp.vol, tp.driver, tp.call, tp.cdelta, tp.cgamma,
|
||||
tp.cvega, tp.c_theta, Double.NaN, normalized_theo));
|
||||
tp.cvega, tp.c_theta, Double.NaN));
|
||||
}
|
||||
if (put_id.HasValue) {
|
||||
var normalized_theo = VolSurfaceCoreFunctions.normalize_theo(tp.put, tp.driver);
|
||||
res.Add(put_id.Value,
|
||||
new GreeksTuple(tp.vol, tp.driver, tp.put, tp.pdelta, tp.pgamma,
|
||||
tp.pvega, tp.p_theta, Double.NaN, normalized_theo));
|
||||
tp.pvega, tp.p_theta, Double.NaN));
|
||||
}
|
||||
}
|
||||
}
|
||||
// futures
|
||||
var future_theos = _get_future_theos();
|
||||
res.AddRange(future_theos);
|
||||
// spreads, all option and future non tied spreads
|
||||
foreach (var spr in sc_data.spreads) {
|
||||
GreeksTuple gtup = StatelessSpreadCalculator.compute_non_tied_spread(spr.security, res);
|
||||
res.Add(spr.security.Id, gtup);
|
||||
}
|
||||
// copy and publish
|
||||
IReadOnlyDictionary<uint, GreeksTuple> res_ro = res;
|
||||
bts.Log.Gen.info($"LiveTheoPublisher._interp_and_publish posting " +
|
||||
$"count: {res_ro.Count}");
|
||||
$"count: {res_ro.Count}");
|
||||
_timer.stop();
|
||||
_logger.log(_log_id, _log_id, _timer.lastIntervalTime);
|
||||
_bb.post(SparkTags.Greeks, res_ro);
|
||||
// oh and those TC2 theos for comptability
|
||||
_publish_tc2_theos(k_theos);
|
||||
}
|
||||
|
||||
// If we do any rolls like SP for futures, it will be here
|
||||
IDictionary<UInt32, GreeksTuple> _get_future_theos() {
|
||||
var rv = new Dictionary<UInt32, GreeksTuple>();
|
||||
SystemContractData sc_data = _bb.read_state(SparkTags.SystemContractsTag);
|
||||
if (sc_data == null)
|
||||
return rv;
|
||||
foreach (var kv in sc_data.exp_map) {
|
||||
var id = kv.Value;
|
||||
SecurityMD sec_md;
|
||||
if (sc_data.sec_md_map.TryGetValue(id, out sec_md)) {
|
||||
if (sec_md.security.HasFuture) {
|
||||
SecurityExpiration exp = kv.Key;
|
||||
double pr = sec_md.md.fixing_price;
|
||||
rv.Add(sec_md.security.Id,
|
||||
new GreeksTuple(0, pr, pr, 1, 0, 0, 0, 0, pr));
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
// recomputes and publishes them periodicially
|
||||
void _publish_future_theos() {
|
||||
if (DateTime.Now - _last_future_theos_published < _futures_theos_publish_period)
|
||||
|
||||
@@ -1,7 +1,5 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts.api;
|
||||
|
||||
using mbts.analytics;
|
||||
|
||||
using System;
|
||||
@@ -41,10 +39,5 @@ namespace mbts.spark {
|
||||
.SelectMany(kv => kv.Value.exp_price_map)
|
||||
.ToDictionaryCrushed(kv => kv.Key.to_vs_exp(), kv => kv.Value);
|
||||
}
|
||||
|
||||
public IReadOnlyDictionary<SecurityExpiration, DriverMD> get_price_map() {
|
||||
return new Dictionary<SecurityExpiration, DriverMD>(exp_price_map);
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -1,70 +0,0 @@
|
||||
namespace mbts.spark {
|
||||
using bts.api;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
|
||||
// A lot of options data (migrated from edge) is not normalized
|
||||
// on the sec_id, but rather on a combination of symbol, exp, strike.
|
||||
// Additionally the exchange is missing. This class serves as that
|
||||
// one since point to resolve that.
|
||||
// (Over time we will normalize all the data and this wont be needed)
|
||||
public static class SecurityNormalizer {
|
||||
// f(option_exp:driver_md) -> (sec_id:driver_md)
|
||||
|
||||
public static IDictionary<UInt32, DriverMD> normalize_drivers(
|
||||
OptionDriverPriceMap driver_map, SystemContractData sc_data) {
|
||||
if (driver_map is null) {
|
||||
return new Dictionary<uint, DriverMD>(0);
|
||||
}
|
||||
Dictionary<UInt32, DriverMD> rv = new Dictionary<uint, DriverMD>();
|
||||
foreach (var kv in driver_map.get_price_map()) {
|
||||
var exp = kv.Key;
|
||||
var dmd = kv.Value;
|
||||
IEnumerable<SecurityMD> exp_secs = sc_data.get_securities(
|
||||
(sec_md) => {
|
||||
var s = sec_md.security;
|
||||
return s.security_type() == SecurityType.Option &&
|
||||
s.Symbol == driver_map.option_symbol &&
|
||||
s.earliest_expiration() == exp.expiration;
|
||||
}
|
||||
);
|
||||
foreach (var sec_md in exp_secs) {
|
||||
rv.Add(sec_md.security.Id, kv.Value);
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
public static IEnumerable<Tuple<SecurityImmutable, TheoPoint>> normalize_interp_theos(
|
||||
OptionTheoInterpolationData symbol_theos, SystemContractData sc_data) {
|
||||
if (symbol_theos is null) {
|
||||
return Enumerable.Empty<Tuple<SecurityImmutable, TheoPoint>>();
|
||||
}
|
||||
var rv = new List<Tuple<SecurityImmutable, TheoPoint>>();
|
||||
foreach (DateTime exp in symbol_theos.get_expirations()) {
|
||||
Dictionary<double, Dictionary<double, TheoPoint>> exp_data =
|
||||
symbol_theos.get_expiration_data(exp);
|
||||
// exp_data is driver vs strike vs TP
|
||||
foreach (var exp_kv in exp_data) {
|
||||
foreach (var k_kv in exp_kv.Value) {
|
||||
double strike = k_kv.Key;
|
||||
TheoPoint tp = k_kv.Value;
|
||||
IEnumerable<SecurityMD> calls = sc_data.get_options(
|
||||
null, symbol_theos.symbol, exp, strike, PutOrCall.Call);
|
||||
IEnumerable<SecurityMD> puts = sc_data.get_options(
|
||||
null, symbol_theos.symbol, exp, strike, PutOrCall.Put);
|
||||
foreach (SecurityMD sec_md in calls) {
|
||||
rv.Add(Tuple.Create(sec_md.security, tp));
|
||||
}
|
||||
foreach (SecurityMD sec_md in puts) {
|
||||
rv.Add(Tuple.Create(sec_md.security, tp));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,4 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -108,22 +107,6 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
|
||||
public SecurityImmutable? get_option_contract(
|
||||
Venue venue, string symbol, DateTime exp, double strike, PutOrCall cp) {
|
||||
var k_tup = get_option_sec_id(venue, symbol, exp, strike);
|
||||
if (k_tup != null) {
|
||||
var id = cp == PutOrCall.Call ? k_tup.Item1 : k_tup.Item2;
|
||||
if (id.HasValue) {
|
||||
var id_val = id.Value;
|
||||
SecurityMD sec_md;
|
||||
if (sec_md_map.TryGetValue(id_val, out sec_md)) {
|
||||
return sec_md.security;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public Tuple<uint?, uint?> get_option_sec_id(
|
||||
Venue venue, string symbol, DateTime exp, double strike) {
|
||||
var s_exp = new SecurityExpiration(venue, SecurityType.Option, symbol, exp);
|
||||
@@ -259,28 +242,5 @@ namespace mbts.spark {
|
||||
kv.Value.Count > 0).Select(kv => kv.Key.expiration);
|
||||
}
|
||||
|
||||
public IEnumerable<SecurityMD> spreads {
|
||||
get {
|
||||
return sec_md_map.Where(kv => kv.Value.security.HasSpread)
|
||||
.Select(kv => kv.Value);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<SecurityMD> get_securities(Func<SecurityMD, bool> criteria) {
|
||||
return sec_md_map.Values.Where(sec_md => criteria(sec_md));
|
||||
}
|
||||
|
||||
public IEnumerable<SecurityMD> get_options(
|
||||
Venue? exchange, string option_name, DateTime? exp, double? strike, PutOrCall? cp) {
|
||||
return get_securities(sc => {
|
||||
var s = sc.security;
|
||||
return s.security_type() == SecurityType.Option &&
|
||||
(exchange == null || s.Exchange == exchange) &&
|
||||
(exp == null || s.earliest_expiration() == exp) &&
|
||||
(strike == null || s.strike() == strike) &&
|
||||
(cp == null || s.Option.CallPut == cp);
|
||||
});
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -63,27 +63,6 @@ namespace mbts.spark {
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static string log_string(this VolSurfaceCalculationRequest vs_req) {
|
||||
if (vs_req == null) {
|
||||
return "Null";
|
||||
}
|
||||
string action_str = String.Empty;
|
||||
foreach (var kv in vs_req.action_map) {
|
||||
action_str += $"exp: {kv.Key.ToString()} action: {kv.Value.ToString()}, ";
|
||||
}
|
||||
action_str = action_str.TrimEnd(',', ' ');
|
||||
return $"vs_inp: {vs_req.volsurface_input.log_string()}\nreq_id: {vs_req.request_id}\n" +
|
||||
$"action_map: {action_str}\nup: {vs_req.cascade_up} down: {vs_req.cascade_down}";
|
||||
}
|
||||
|
||||
public static string log_string(this VolSurfaceCalculationResponse resp) {
|
||||
if (resp == null) {
|
||||
return "Null";
|
||||
}
|
||||
return $"req_id: {resp.request_id} vs_output: " +
|
||||
$"{resp.volsurface_calculation_output.volsurface_input.log_string()}";
|
||||
}
|
||||
|
||||
private static string _trim_leading_char(string s, char c) {
|
||||
if (!s.is_null_or_empty() && s.EndsWith(c)) {
|
||||
return s.Remove(s.Length - 1, 1);
|
||||
@@ -92,12 +71,11 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
internal static string log_string(this VolSurfaceDisplayModel.DisplayModelData dm_data) {
|
||||
var vs_output = dm_data.vs_output;
|
||||
var exp_grid = dm_data.exp_grid;
|
||||
var vs_output_str = vs_output == null ? "NULL" : vs_output.volsurface_input.log_string();
|
||||
var exp_grid_str = exp_grid == null ? "NULL" : exp_grid.log_string();
|
||||
var rv = $"DisplayModelData\nvs_output:\n{vs_output_str}\n" +
|
||||
$"exp_grid\n{exp_grid_str}\n";
|
||||
string rv = String.Empty;
|
||||
string global_grid_str = dm_data.global_grid == null ? "Null" : dm_data.global_grid.log_string();
|
||||
rv += $"global_grid: {global_grid_str} \n";
|
||||
string exp_grid_str = dm_data.exp_grid == null ? "Null" : dm_data.exp_grid.log_string();
|
||||
rv += $"exp_grid: {exp_grid_str} \n";
|
||||
return rv;
|
||||
}
|
||||
|
||||
@@ -113,19 +91,19 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
internal static string log_string(this VolSurfaceDisplayGrid dgrid) {
|
||||
Func<IDictionary<string, object>, string> log_exp = (col_val_map) => {
|
||||
Func<IDictionary<string, object>, string> log_exp = (map) => {
|
||||
string rv = String.Empty;
|
||||
foreach (var kv in col_val_map) {
|
||||
foreach (var kv in map) {
|
||||
string val_string = kv.Value == null ? "Null" : kv.Value.ToString();
|
||||
rv += $"{kv.Key}: {val_string}, ";
|
||||
rv += $"{kv.Key}:{val_string},";
|
||||
}
|
||||
return _trim_leading_char(rv, ',');
|
||||
};
|
||||
string rv = String.Empty;
|
||||
foreach (var kv in dgrid.data_map) {
|
||||
rv += $"Exp: {kv.Key.expiration.ToShortDateString()} Data: {log_exp(kv.Value)}\n";
|
||||
rv += $"Exp:{kv.Key.expiration.ToShortDateString()} Data:{log_exp(kv.Value)},";
|
||||
}
|
||||
return rv;
|
||||
return _trim_leading_char(rv, ',');
|
||||
}
|
||||
|
||||
internal static string log_string(this OptionDriverPriceMap map) {
|
||||
@@ -260,15 +238,6 @@ namespace mbts.spark {
|
||||
return rv;
|
||||
}
|
||||
|
||||
internal static string log_string(this IPNLUnit p) {
|
||||
string rv = "IPNLUnit:";
|
||||
rv += $" account: {p.account} sec: {p.security.security_desc()} driver: {p.driver} theo: {p.theo} settle: {p.settle_price}" +
|
||||
$" start_pos: {p.start_long_pos - p.start_short_pos} day_pos: {p.day_long_pos - p.day_short_pos}" +
|
||||
$" start_pnl: {p.start_pnl} start_delta: {p.start_delta} start_vega: {p.start_vega}" +
|
||||
$" day_pnl: {p.day_pnl} day_delta: {p.day_delta} day_vega: {p.day_vega}";
|
||||
return rv;
|
||||
}
|
||||
|
||||
internal static int tid() {
|
||||
return System.Threading.Thread.CurrentThread.ManagedThreadId;
|
||||
}
|
||||
|
||||
@@ -12,7 +12,7 @@ namespace mbts.spark {
|
||||
using System.Collections.Generic;
|
||||
|
||||
[ProtoContract]
|
||||
class VolSurfaceGraphSettings : IProtobuf<VolSurfaceGraphSettings> {
|
||||
class VolSurfaceGraphSettings : IEquatable<VolSurfaceGraphSettings>, ICloneable {
|
||||
public static VolSurfaceGraphSettings get_default() {
|
||||
return new VolSurfaceGraphSettings {
|
||||
put_control_points = new ScatterSeriesSettings {
|
||||
@@ -110,7 +110,7 @@ namespace mbts.spark {
|
||||
// }
|
||||
//}
|
||||
|
||||
public VolSurfaceGraphSettings Clone() =>
|
||||
public object Clone() =>
|
||||
ProtobufSerializationHelper.clone(this);
|
||||
|
||||
public bool Equals(VolSurfaceGraphSettings other) =>
|
||||
|
||||
@@ -6,10 +6,6 @@ using mbts.analytics;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -55,7 +51,7 @@ namespace mbts.spark {
|
||||
var vs_removes = removed.Select(exp => exp.ToVSExp());
|
||||
|
||||
var true_removed = removed.Where(rmv => !vs_adds.Contains(rmv.ToVSExp()));
|
||||
var true_added = added.Except(vs_removes.Concat(_hidden_exps), v => v.ToVSExp());
|
||||
var true_added = added.Where(add => !vs_removes.Contains(add.ToVSExp()));
|
||||
var changed_calc_modes = added.Where(add => vs_removes.Contains(add.ToVSExp()));
|
||||
|
||||
foreach (var tr in true_removed) {
|
||||
@@ -65,10 +61,16 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
|
||||
var comp = ComparerWrapper<object>.wrap_cast(
|
||||
NullCheckComparer.create<IExpirationBasedRow>(
|
||||
(r1, r2) => r1.expiration.CompareTo(r2.expiration)));
|
||||
visible_rows.InsertSorted(true_added, comp);
|
||||
foreach (var ta in true_added) {
|
||||
if (_hidden_exps.Contains(ta.ToVSExp()) ||
|
||||
!rows.TryGetFirst(r => r.expiration.expiration == ta.expiration, out var row)) {
|
||||
continue;
|
||||
}
|
||||
visible_rows.InsertSorted(row,
|
||||
Comparer<IExpirationBasedRow>.Create(
|
||||
(r1, r2) => r1.expiration.CompareTo(r2.expiration))
|
||||
.wrap<IExpirationBasedRow, object>());
|
||||
}
|
||||
|
||||
foreach (var ccm in changed_calc_modes) {
|
||||
int index = visible_rows
|
||||
|
||||
@@ -10,10 +10,6 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Analytics.View;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
@@ -31,13 +27,13 @@ namespace mbts.spark {
|
||||
readonly LinearAxisVM _x_axis = new() { position = AxisPosition.BottomLeftToRight };
|
||||
readonly LinearAxisVM _y_axis = new() { position = AxisPosition.LeftBottomToTop };
|
||||
readonly Dictionary<SecurityExpiration, ExpGraphBounds> _expiration_graph_bounds;
|
||||
readonly VolSurfaceGraphSettings _settings;
|
||||
readonly ObservableCollection<VolSurfaceDisplayGridExpiration> _expirations = new();
|
||||
readonly Dictionary<VolSurfaceDisplayGridExpiration, SeriesSetVM> _expiration_series_cache = new();
|
||||
|
||||
VolSurfaceExpiration _md_exp;
|
||||
VolSurfaceDisplayGridExpiration _expiration;
|
||||
VolSurfaceDisplayGridExpiration _earliest_selected_expiration;
|
||||
VolSurfaceGraphSettings _settings;
|
||||
object _implied_vol_market_side = ImpliedVolHelper.None;
|
||||
bool _show_vol_path;
|
||||
|
||||
@@ -50,9 +46,7 @@ namespace mbts.spark {
|
||||
if (startup_data.vol_curve_x_axis == null) {
|
||||
var x_axis = BTSOxyGraphAxisDouble.Default;
|
||||
x_axis.name = "Strike";
|
||||
x_axis.axis_line_color = BTSColors.Graph.axis_line;
|
||||
x_axis.major_grid_line_color = BTSColors.Graph.grid_line;
|
||||
x_axis.tick_line_color = BTSColors.Graph.tick_line;
|
||||
x_axis.position = AxisPosition.BottomLeftToRight;
|
||||
x_axis.minimum = 0;
|
||||
x_axis.maximum = 2000;
|
||||
@@ -64,9 +58,7 @@ namespace mbts.spark {
|
||||
if (startup_data.vol_curve_y_axis == null) {
|
||||
var y_axis = BTSOxyGraphAxisDouble.Default;
|
||||
y_axis.name = "Volatility";
|
||||
y_axis.axis_line_color = BTSColors.Graph.axis_line;
|
||||
y_axis.major_grid_line_color = BTSColors.Graph.grid_line;
|
||||
y_axis.tick_line_color = BTSColors.Graph.tick_line;
|
||||
y_axis.position = AxisPosition.LeftBottomToTop;
|
||||
y_axis.minimum = 0;
|
||||
y_axis.maximum = 1;
|
||||
@@ -86,17 +78,13 @@ namespace mbts.spark {
|
||||
if (_model.get_active_settings() is not VolSurfaceSettings vss) {
|
||||
return null;
|
||||
}
|
||||
var vm = new VolSurfaceGraphSettingsVM(vss.core_settings.vol_surface_name);
|
||||
vm.load_from(_settings.Clone());
|
||||
vm.request_commit += commit;
|
||||
return new VolSurfaceGraphSettingsWindow {
|
||||
DataContext = vm
|
||||
};
|
||||
|
||||
void commit(VolSurfaceGraphSettings settings) {
|
||||
_settings = settings;
|
||||
_recreate_series();
|
||||
}
|
||||
// return new VolSurfaceGraphSettingsEditor {
|
||||
// DataContext = new VolSurfaceGraphSettingsEditorVM(vss.core_settings.vol_surface_name, ProtoBufSerializationHelper.clone_protobuf(_settings), settings => {
|
||||
// _settings = settings;
|
||||
// _recreate_series();
|
||||
// })
|
||||
// };
|
||||
return null;
|
||||
});
|
||||
graph_vm = new BTSGraphVM {
|
||||
plot_area_background = Colors.Transparent,
|
||||
@@ -125,7 +113,7 @@ namespace mbts.spark {
|
||||
})
|
||||
.BufferLatest(TimeSpan.FromSeconds(0.1))
|
||||
.OnDispatcher()
|
||||
.SelectSeries(series => Observable.Create<SeriesVM>(o => {
|
||||
.SelectManyInSeries(series => Observable.Create<SeriesVM>(o => {
|
||||
o.OnNext(null);
|
||||
return Disposable.Create(series
|
||||
.Select(svm => svm.points.Subscribe((s, e) => o.OnNext(svm)))
|
||||
@@ -193,20 +181,6 @@ namespace mbts.spark {
|
||||
static (double call_wing_start, double put_wing_start) _get_actual_wing_starts(VolCurveDisplayGraph disp_graph) =>
|
||||
disp_graph.all_points.Select(p => p.Item1).MinMax() ?? (double.NaN, double.NaN);
|
||||
|
||||
void _recreate_series() {
|
||||
/// 'graph_vm.series_set' is bound to '_expirations', so clearing and re-adding expirations
|
||||
/// in turn regenerates the series. '_expiration_series_cache' must
|
||||
/// be cleared as well, otherwise cached series vms would just be back to the collection
|
||||
/// ('graph_vm.series_set').
|
||||
var visible_exp = _earliest_selected_expiration;
|
||||
_expiration_series_cache.Clear();
|
||||
_expirations.SetItems(_model.get_ordered_expirations());
|
||||
foreach (var svm in graph_vm.series.OfType<SeriesSetVM>()) {
|
||||
svm.is_visible = svm.args.Equals(visible_exp);
|
||||
}
|
||||
_update();
|
||||
}
|
||||
|
||||
void _expirations_changed(IEnumerable<VolSurfaceDisplayGridExpiration> added, IEnumerable<VolSurfaceDisplayGridExpiration> removed) {
|
||||
_expirations.sync_with(_model.get_ordered_expirations());
|
||||
_update();
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
namespace mbts.spark {
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using System;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Input;
|
||||
|
||||
class VolGridCellVM : DisposableViewModelBase {
|
||||
readonly Property<object> _candidate_value;
|
||||
readonly Property<object> _committed_value;
|
||||
readonly Property<bool> _is_dirty;
|
||||
|
||||
public VolGridCellVM(string column_id) {
|
||||
this.column_id = column_id ?? throw new ArgumentNullException(nameof(column_id));
|
||||
_committed_value = backing<object>(nameof(committed_value));
|
||||
_candidate_value = backing<object>(nameof(candidate_value));
|
||||
_is_dirty = backing(nameof(is_dirty),
|
||||
_committed_value.observe_current(true)
|
||||
.CombineLatest(_candidate_value.observe_current(true))
|
||||
.Select(tup => !Equals(tup.First, tup.Second))
|
||||
.OnDispatcher());
|
||||
}
|
||||
|
||||
public string column_id { get; }
|
||||
|
||||
public object committed_value {
|
||||
get => _committed_value.Value;
|
||||
set => _committed_value.set(value);
|
||||
}
|
||||
|
||||
public object candidate_value {
|
||||
get => _candidate_value.Value;
|
||||
set => _candidate_value.set(value);
|
||||
}
|
||||
|
||||
public bool is_dirty => _is_dirty.Value;
|
||||
|
||||
public IObservable<object> observe_candidate(bool start_immediately = false) =>
|
||||
_candidate_value.observe_current(start_immediately);
|
||||
|
||||
public void revert() =>
|
||||
candidate_value = committed_value;
|
||||
|
||||
public override string ToString() =>
|
||||
$"column_id: {column_id}, committed: {committed_value}, candidate: {candidate_value}";
|
||||
}
|
||||
|
||||
class VolGridCellVM<T> : VolGridCellVM {
|
||||
public VolGridCellVM(string column_id) : base(column_id) { }
|
||||
|
||||
public VolGridCellVM(string column_id, T committed_value, T candidate_value) : base(column_id) {
|
||||
this.committed_value = committed_value;
|
||||
this.candidate_value = candidate_value;
|
||||
}
|
||||
|
||||
public new T committed_value {
|
||||
get => base.committed_value is T v ? v : default;
|
||||
set => base.committed_value = value;
|
||||
}
|
||||
|
||||
public new T candidate_value {
|
||||
get => base.candidate_value is T v ? v : default;
|
||||
set => base.candidate_value = value;
|
||||
}
|
||||
}
|
||||
|
||||
class VolGridTickCellVM : VolGridCellVM {
|
||||
ICommand _tick_up_cmd;
|
||||
ICommand _tick_down_cmd;
|
||||
|
||||
public VolGridTickCellVM(string column_id) : base(column_id) { }
|
||||
|
||||
public event Action<bool> request_tick;
|
||||
|
||||
public ICommand tick_up_cmd =>
|
||||
_tick_up_cmd ??= new DelegateCommand(() =>
|
||||
request_tick?.Invoke(true));
|
||||
|
||||
public ICommand tick_down_cmd =>
|
||||
_tick_down_cmd ??= new DelegateCommand(() =>
|
||||
request_tick?.Invoke(false));
|
||||
}
|
||||
}
|
||||
@@ -1,11 +0,0 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark.VolSurface {
|
||||
using System.Windows.Media;
|
||||
|
||||
readonly struct VolSurfaceCellState {
|
||||
public bool is_dirty => committed_text is not null;
|
||||
|
||||
public FormattedText? text { get; init; }
|
||||
public FormattedText? committed_text { get; init; }
|
||||
}
|
||||
}
|
||||
@@ -1,80 +0,0 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts;
|
||||
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core;
|
||||
|
||||
using System;
|
||||
|
||||
class VolSurfaceCellVM : DisposableViewModelBase {
|
||||
readonly Property<object?> _candidate_value;
|
||||
readonly Property<object?> _committed_value;
|
||||
readonly DelegateProperty<bool> _is_dirty;
|
||||
readonly DeferrableAction _refresh;
|
||||
|
||||
public VolSurfaceCellVM(
|
||||
VolSurfaceDisplayGridExpiration expiration, VolSurfaceDisplayGridColumn column) {
|
||||
this.column = column ?? throw new ArgumentNullException(nameof(column));
|
||||
this.expiration = expiration ?? throw new ArgumentNullException(nameof(expiration));
|
||||
_committed_value = backing<object?>(nameof(committed_value), column.comparer);
|
||||
_candidate_value = backing<object?>(nameof(candidate_value), column.comparer);
|
||||
_is_dirty = backing(
|
||||
nameof(is_dirty), () => !column.comparer.Equals(candidate_value, committed_value));
|
||||
_refresh = new(_is_dirty.refresh);
|
||||
_committed_value.Changed += on_committed_changed;
|
||||
_candidate_value.Changed += on_candidate_changed;
|
||||
if (column.type.is_editable()) {
|
||||
_is_dirty.Changed += (o, n) => {
|
||||
Log.Ui.info(
|
||||
$"VolSurface '{expiration}.{column}' is_dirty changed to {n}. " +
|
||||
$"commited: {committed_value}; candidate: {candidate_value}");
|
||||
};
|
||||
}
|
||||
|
||||
void on_committed_changed(object? oldval, object? newval) =>
|
||||
_is_dirty.refresh();
|
||||
|
||||
void on_candidate_changed(object? oldval, object? newval) =>
|
||||
_is_dirty.refresh();
|
||||
}
|
||||
|
||||
public event PropertyChange<object?>? candidate_value_changed {
|
||||
add => _candidate_value.Changed += value;
|
||||
remove => _candidate_value.Changed -= value;
|
||||
}
|
||||
|
||||
public VolSurfaceDisplayGridColumn column { get; }
|
||||
public string column_id => column.unique_col_name;
|
||||
public VolSurfaceDisplayGridExpiration expiration { get; }
|
||||
|
||||
public object? committed_value {
|
||||
get => _committed_value.Value;
|
||||
set => _committed_value.set(value);
|
||||
}
|
||||
|
||||
public object? candidate_value {
|
||||
get => _candidate_value.Value;
|
||||
set => _candidate_value.set(value);
|
||||
}
|
||||
|
||||
public bool is_dirty => _is_dirty.Value;
|
||||
|
||||
public IObservable<object?> observe_candidate(bool start_immediately = false) =>
|
||||
_candidate_value.observe_current(start_immediately);
|
||||
|
||||
public void reset(object? committed_value, object? candidate_value) {
|
||||
using var _ = _refresh.defer();
|
||||
this.committed_value = committed_value;
|
||||
this.candidate_value = candidate_value;
|
||||
}
|
||||
|
||||
public void revert() =>
|
||||
candidate_value = committed_value;
|
||||
|
||||
public override string ToString() =>
|
||||
$"column: {column}, committed: {committed_value}, candidate: {candidate_value}";
|
||||
}
|
||||
}
|
||||
@@ -73,12 +73,12 @@ namespace mbts.spark.VolSurface {
|
||||
var view = new TextBlock {
|
||||
HorizontalAlignment = HorizontalAlignment.Right,
|
||||
Margin = _cell_padding,
|
||||
Foreground = BTSColors.VolSurfaceGrid.readonly_column_foreground
|
||||
Foreground = Brushes.Blue,
|
||||
};
|
||||
view.SetBinding(FrameworkElement.DataContextProperty, new Binding() {
|
||||
Converter = _data_context_converter
|
||||
});
|
||||
view.SetBinding(TextBlock.TextProperty, new Binding(nameof(VolSurfaceCellVM.candidate_value)) {
|
||||
view.SetBinding(TextBlock.TextProperty, new Binding(nameof(VolGridCellVM.candidate_value)) {
|
||||
Converter = ValueConverter.create(obj => model.format(obj))
|
||||
});
|
||||
return view;
|
||||
@@ -101,16 +101,16 @@ namespace mbts.spark.VolSurface {
|
||||
view.SetBinding(FrameworkElement.DataContextProperty, new Binding() {
|
||||
Converter = _data_context_converter
|
||||
});
|
||||
view.SetBinding(VolSurfaceCellView.CommittedValueProperty, new Binding(nameof(VolSurfaceCellVM.committed_value)) {
|
||||
view.SetBinding(VolSurfaceCellView.CommittedValueProperty, new Binding(nameof(VolGridCellVM.committed_value)) {
|
||||
Mode = BindingMode.OneWay,
|
||||
Converter = ValueConverter.create(obj => model.format(obj))
|
||||
});
|
||||
view.SetBinding(VolSurfaceCellView.CandidateValueProperty, new Binding(nameof(VolSurfaceCellVM.candidate_value)) {
|
||||
view.SetBinding(VolSurfaceCellView.CandidateValueProperty, new Binding(nameof(VolGridCellVM.candidate_value)) {
|
||||
Mode = BindingMode.TwoWay,
|
||||
Converter = ValueConverter.create<object, string>(obj => model.format(obj), obj => model.parse(obj))
|
||||
});
|
||||
view.SetBinding(VolSurfaceCellView.TickDownCommandProperty, new Binding(nameof(VolSurfaceTickCellVM.tick_down_cmd)));
|
||||
view.SetBinding(VolSurfaceCellView.TickUpCommandProperty, new Binding(nameof(VolSurfaceTickCellVM.tick_up_cmd)));
|
||||
view.SetBinding(VolSurfaceCellView.TickDownCommandProperty, new Binding(nameof(VolGridTickCellVM.tick_down_cmd)));
|
||||
view.SetBinding(VolSurfaceCellView.TickUpCommandProperty, new Binding(nameof(VolGridTickCellVM.tick_up_cmd)));
|
||||
var bd = new Border {
|
||||
HorizontalAlignment = HorizontalAlignment.Stretch,
|
||||
VerticalAlignment = VerticalAlignment.Stretch,
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark.VolSurface {
|
||||
using bts;
|
||||
using bts.collections;
|
||||
@@ -12,10 +11,6 @@ namespace mbts.spark.VolSurface {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -29,25 +24,19 @@ namespace mbts.spark.VolSurface {
|
||||
|
||||
class VolSurfaceGridVM : DisposableViewModelBase {
|
||||
readonly VolSurfaceVM _parent;
|
||||
readonly UserTuple _user;
|
||||
readonly ObservableCollection<VolSurfaceDisplayGridExpiration> _expirations = new();
|
||||
readonly DeferrableAction _invalidate_rows;
|
||||
readonly DeferrableActionWrapper _invalidate_rows;
|
||||
readonly ColumnsModel _columns_model;
|
||||
|
||||
ISet<string> _hidden_columns;
|
||||
ISet<VolSurfaceExpiration>? _hidden_expirations;
|
||||
IDisposable? _shift_editor;
|
||||
ISet<VolSurfaceExpiration> _hidden_expirations;
|
||||
IDisposable _shift_editor;
|
||||
|
||||
public VolSurfaceGridVM(
|
||||
VolSurfaceVM vm,
|
||||
VolSurfaceDisplayModel model,
|
||||
ISet<string> hidden_columns,
|
||||
ISet<VolSurfaceExpiration> hidden_expirations,
|
||||
UserTuple user) {
|
||||
Log.notnull(hidden_columns);
|
||||
Log.notnull(hidden_expirations);
|
||||
public VolSurfaceGridVM(VolSurfaceVM vm, VolSurfaceDisplayModel model,
|
||||
ISet<string> hidden_columns, ISet<VolSurfaceExpiration> hidden_expirations) {
|
||||
Log.assert(hidden_columns != null);
|
||||
Log.assert(hidden_expirations != null);
|
||||
_parent = vm;
|
||||
_user = user;
|
||||
this.model = model;
|
||||
_columns_model = new(create_exp_column_view());
|
||||
_hidden_columns = hidden_columns;
|
||||
@@ -74,31 +63,16 @@ namespace mbts.spark.VolSurface {
|
||||
};
|
||||
|
||||
_dispose = Disposable.Create(
|
||||
ObservableAutoWrapper.connect(_expirations, rows, row_factory),
|
||||
ObservableAutoWrapper.connect_item_hooks(rows, connect_row),
|
||||
ObservableAutoWrapper.connect(_expirations, rows, exp => new VolSurfaceRowVM(this, exp), row => row.Dispose()),
|
||||
sorted_visible_rows.bind(visible_rows),
|
||||
Disposable.Create(() => {
|
||||
this.model.on_candidate_grid_change -= _on_grid_updated;
|
||||
this.model.on_committed_grid_change -= _on_grid_updated;
|
||||
rows.DisposeAll(true);
|
||||
Disposable.dispose(rows);
|
||||
Disposable.dispose(ref _shift_editor);
|
||||
}),
|
||||
_columns_model);
|
||||
|
||||
VolSurfaceRowVM row_factory(VolSurfaceDisplayGridExpiration exp) =>
|
||||
new(this, exp, _user);
|
||||
|
||||
IDisposable connect_row(VolSurfaceRowVM row) {
|
||||
row.request_calculate += request_recalc;
|
||||
return Disposable.Create(() => {
|
||||
row.request_calculate -= request_recalc;
|
||||
row.Dispose();
|
||||
});
|
||||
|
||||
void request_recalc() =>
|
||||
model.set_candidate_grid(current_grid);
|
||||
}
|
||||
|
||||
VolSurfaceColumn create_exp_column_view() {
|
||||
var filter = new ComboCheckBox();
|
||||
filter.SetResourceReference(FrameworkElement.StyleProperty, "ExpirationFilterDropDown");
|
||||
@@ -118,7 +92,7 @@ namespace mbts.spark.VolSurface {
|
||||
}
|
||||
}
|
||||
|
||||
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>>? on_selection_changed;
|
||||
public event Action<IEnumerable<VolSurfaceDisplayGridExpiration>> on_selection_changed;
|
||||
|
||||
public VolSurfaceDisplayGrid current_grid { get; private set; }
|
||||
public VolSurfaceDisplayGrid committed_grid { get; private set; }
|
||||
@@ -144,7 +118,6 @@ namespace mbts.spark.VolSurface {
|
||||
.Select(group => new DIYGridSuperHeaderVM(group.Key, group.Count(), collapsed_content: _short_header(group.Key)))
|
||||
.ToList();
|
||||
|
||||
public ICommand populate_empty_exps_cmd => _parent.populate_empty_exps_cmd;
|
||||
public ICommand main_settings_cmd => _parent.main_settings_cmd;
|
||||
public ICommand advanced_settings_cmd => _parent.advanced_settings_cmd;
|
||||
public ICommand graph_settings_cmd => _parent.vol_curve_vm.settings_command;
|
||||
@@ -168,14 +141,13 @@ namespace mbts.spark.VolSurface {
|
||||
rows.select_exp().Except(visible_rows.select_exp());
|
||||
|
||||
public void invalidate_rows() =>
|
||||
_invalidate_rows.Invoke();
|
||||
_invalidate_rows.execute();
|
||||
|
||||
public IDisposable defer_invalidate_rows() =>
|
||||
_invalidate_rows.defer();
|
||||
_invalidate_rows.defer_execution();
|
||||
|
||||
public VolSurfaceColumn get_column(string id) =>
|
||||
columns.FirstOrDefault(c => c.id == id) as VolSurfaceColumn ??
|
||||
throw new InvalidOperationException($"Failed to find column '{id}'");
|
||||
columns.FirstOrDefault(c => c.id == id) as VolSurfaceColumn;
|
||||
|
||||
internal void signal_selection_changed() {
|
||||
var e = on_selection_changed;
|
||||
@@ -246,7 +218,7 @@ namespace mbts.spark.VolSurface {
|
||||
!_hidden_columns.Contains(column.unique_col_name);
|
||||
|
||||
void _on_grid_updated() {
|
||||
using var _ = _invalidate_rows.defer();
|
||||
using var _ = _invalidate_rows.defer_execution();
|
||||
var grid_new = model.get_active_grid();
|
||||
// add/remove columns
|
||||
var cols_new = grid_new.get_ordered_columns()
|
||||
@@ -271,7 +243,7 @@ namespace mbts.spark.VolSurface {
|
||||
}
|
||||
current_grid = grid_new;
|
||||
committed_grid = is_dirty ? model.get_committed_grid() : current_grid;
|
||||
_invalidate_rows.Invoke();
|
||||
_invalidate_rows.execute();
|
||||
}
|
||||
|
||||
void _launch_shift_editor(VolSurfaceDisplayGridColumn column, Action<double> commit_shift) {
|
||||
@@ -352,7 +324,7 @@ namespace mbts.spark.VolSurface {
|
||||
model.set_candidate_grid(current_grid);
|
||||
|
||||
class ColumnsModel : IDisposable {
|
||||
IDisposable? _dispose;
|
||||
IDisposable _dispose;
|
||||
|
||||
public ColumnsModel(VolSurfaceColumn row_header_col) {
|
||||
views_with_header_ro = ObservableAutoWrapper.create_read_only_wrapper(views_with_header);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts;
|
||||
using bts.collections;
|
||||
|
||||
using mbts.spark.VolSurface;
|
||||
@@ -9,9 +8,6 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -24,10 +20,6 @@ namespace mbts.spark {
|
||||
readonly VolSurfaceGridVM _parent;
|
||||
readonly Property<VolSurfaceColumn?> _column;
|
||||
readonly Property<DIYGridSuperHeaderVM?> _super_header;
|
||||
readonly UserTuple _user;
|
||||
readonly Property<bool> _is_open;
|
||||
readonly DelegateProperty<string> _vs_manager;
|
||||
readonly List<IDisposable> _resources = new();
|
||||
|
||||
ICommand? _revert_cmd;
|
||||
ICommand? _shift_selection_cmd;
|
||||
@@ -40,29 +32,21 @@ namespace mbts.spark {
|
||||
ICommand? _copy_all_to_clipboard_cmd;
|
||||
ICommand? _smart_copy_rolls_rates_cmd;
|
||||
ICommand? _import_csv_cmd;
|
||||
ObservantCommand? _acquire_ownership_cmd;
|
||||
|
||||
public VolSurfaceRowContextMenuVM(VolSurfaceGridVM parent, VolSurfaceRowVM row, UserTuple user) {
|
||||
public VolSurfaceRowContextMenuVM(VolSurfaceGridVM parent, VolSurfaceRowVM row) {
|
||||
_parent = parent;
|
||||
_row = row;
|
||||
_user = user;
|
||||
_column = backing<VolSurfaceColumn?>(nameof(column));
|
||||
_super_header = backing<DIYGridSuperHeaderVM?>(nameof(super_header));
|
||||
_vs_manager = backing(
|
||||
nameof(vs_manager),
|
||||
() => _parent.model.get_active_settings()?.core_settings?.vs_manager ?? string.Empty);
|
||||
_is_open = backing(nameof(is_open), false);
|
||||
|
||||
_resources.AddRange(
|
||||
_dispose = Disposable.Create(
|
||||
_column.invalidate_others_on_change(nameof(column_name)),
|
||||
_super_header.invalidate_others_on_change(nameof(group_name)),
|
||||
_is_open.Subscribe(_ => _vs_manager.refresh()),
|
||||
_parent.visible_rows.ObserveSelf()
|
||||
.BufferLatest(TimeSpan.FromSeconds(1))
|
||||
.OnDispatcher()
|
||||
.Subscribe(_ => sync_symbols()));
|
||||
|
||||
_dispose = Disposable.Create(() => _resources.DisposeAll(true));
|
||||
void sync_symbols() {
|
||||
var visible_exps = _parent.visible_rows.Map(r => r.expiration.symbol);
|
||||
symbols.sync_with_models(
|
||||
@@ -95,7 +79,6 @@ namespace mbts.spark {
|
||||
|
||||
public bool is_input_cell => column?.type == VolSurfaceColumnType.ReadWriteTick;
|
||||
|
||||
public ICommand populate_empty_exps_cmd => _parent.populate_empty_exps_cmd;
|
||||
public ICommand main_settings_cmd => _parent.main_settings_cmd;
|
||||
public ICommand advanced_settings_cmd => _parent.advanced_settings_cmd;
|
||||
public ICommand grid_settings_cmd => _parent.grid_settings_cmd;
|
||||
@@ -178,34 +161,6 @@ namespace mbts.spark {
|
||||
_parent.model.csv_importing_enabled,
|
||||
null);
|
||||
|
||||
public ICommand acquire_ownership_cmd {
|
||||
get {
|
||||
if (_acquire_ownership_cmd is null) {
|
||||
_acquire_ownership_cmd = new(
|
||||
() => {
|
||||
var settings = _parent.model.get_active_settings();
|
||||
if (settings is null) {
|
||||
Log.Ui.error("Unable to acquire volsurface ownership: settings are null.");
|
||||
return;
|
||||
}
|
||||
settings.core_settings.vs_manager = _user.name;
|
||||
_parent.model.set_candidate_settings(settings);
|
||||
});
|
||||
_resources.Add(_vs_manager.observe_current(true)
|
||||
.Subscribe(SelectorObserver.builder(_acquire_ownership_cmd).wrap<string>(
|
||||
curr => curr != _user.name)));
|
||||
}
|
||||
return _acquire_ownership_cmd;
|
||||
}
|
||||
}
|
||||
|
||||
public bool is_open {
|
||||
get => _is_open.Value;
|
||||
set => _is_open.set(value);
|
||||
}
|
||||
|
||||
public string vs_manager => _vs_manager.Value;
|
||||
|
||||
VolSurfaceDisplayGridColumn _assert_model() =>
|
||||
column?.model ?? throw new InvalidOperationException();
|
||||
|
||||
|
||||
@@ -1,34 +1,32 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark.VolSurface {
|
||||
using bts;
|
||||
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Media;
|
||||
|
||||
public struct VolSurfaceCellState {
|
||||
public bool is_dirty => committed_text is not null;
|
||||
public FormattedText? text;
|
||||
public FormattedText? committed_text;
|
||||
}
|
||||
|
||||
class VolSurfaceRowVM : DisposableViewModelBase, ISelectable, IFormatCellsToClipboard, DIYGrid.IRowVM {
|
||||
readonly VolSurfaceGridVM _parent;
|
||||
readonly VolSurfaceDisplayGridExpiration _exp;
|
||||
readonly Dictionary<string, CellData> _cells = new();
|
||||
readonly UserTuple _user;
|
||||
readonly DeferrableAction _request_calculate;
|
||||
|
||||
VolSurfaceRowContextMenuVM? _context_menu;
|
||||
bool _is_selected;
|
||||
|
||||
public VolSurfaceRowVM(VolSurfaceGridVM parent, VolSurfaceDisplayGridExpiration exp, UserTuple user) {
|
||||
public VolSurfaceRowVM(VolSurfaceGridVM parent, VolSurfaceDisplayGridExpiration exp) {
|
||||
_parent = parent;
|
||||
_exp = exp;
|
||||
_user = user;
|
||||
_request_calculate = new(() => request_calculate?.Invoke());
|
||||
_dispose = Disposable.Create(() => {
|
||||
_cells.Values.DisposeAll();
|
||||
_cells.Clear();
|
||||
@@ -38,7 +36,6 @@ namespace mbts.spark.VolSurface {
|
||||
|
||||
public event Action<bool>? is_selected_changed;
|
||||
public event Action? invalidated;
|
||||
public event Action? request_calculate;
|
||||
|
||||
public VolSurfaceDisplayGridExpiration expiration => _exp;
|
||||
|
||||
@@ -53,16 +50,14 @@ namespace mbts.spark.VolSurface {
|
||||
}
|
||||
|
||||
public VolSurfaceRowContextMenuVM context_menu =>
|
||||
_context_menu ??= new(_parent, this, _user);
|
||||
_context_menu ??= new(_parent, this);
|
||||
|
||||
public VolSurfaceCellVM get_cell(VolSurfaceDisplayGridColumn column) =>
|
||||
public VolGridCellVM get_cell(VolSurfaceDisplayGridColumn column) =>
|
||||
_cells.GetOrAdd(column.unique_col_name, _ => _create_cell(column)).vm;
|
||||
|
||||
public void invalidate() {
|
||||
using (_request_calculate.supress()) {
|
||||
foreach (var cell in _cells.Values) {
|
||||
_sync_cell(cell.vm);
|
||||
}
|
||||
foreach (var cell in _cells.Values) {
|
||||
_sync_cell(cell.vm);
|
||||
}
|
||||
invalidated?.Invoke();
|
||||
}
|
||||
@@ -84,15 +79,29 @@ namespace mbts.spark.VolSurface {
|
||||
CellData _create_cell(VolSurfaceDisplayGridColumn column) {
|
||||
var cell = column.type switch {
|
||||
VolSurfaceColumnType.ReadWriteTick => create_tick_cell(),
|
||||
_ => new VolSurfaceCellVM(_exp, column)
|
||||
_ => new VolGridCellVM(column.unique_col_name),
|
||||
};
|
||||
_sync_cell(cell);
|
||||
return new(cell, _connect_cell(cell));
|
||||
var dispose = cell.observe_candidate().DistinctUntilChanged().OnDispatcher()
|
||||
.Subscribe(value => {
|
||||
var curr = _parent.current_grid.read(expiration, column);
|
||||
if (Equals(value, curr)) {
|
||||
return;
|
||||
}
|
||||
var grid = _parent.current_grid;
|
||||
grid.write(expiration, column, value);
|
||||
_parent.model.set_candidate_grid(grid);
|
||||
});
|
||||
return new(cell, dispose);
|
||||
|
||||
VolSurfaceCellVM create_tick_cell() {
|
||||
var cell = new VolSurfaceTickCellVM(_exp, column);
|
||||
VolGridTickCellVM create_tick_cell() {
|
||||
var cell = new VolGridTickCellVM(column.unique_col_name);
|
||||
cell.request_tick += is_up => {
|
||||
var col = _parent.get_column(column.unique_col_name);
|
||||
if (col is null) {
|
||||
throw new InvalidOperationException(
|
||||
$"Failed to find column with id {column.unique_col_name}");
|
||||
}
|
||||
if (col.model?.tick_move is var tm) {
|
||||
cell.candidate_value = tm?.Invoke(cell.candidate_value, is_up);
|
||||
return;
|
||||
@@ -103,48 +112,23 @@ namespace mbts.spark.VolSurface {
|
||||
}
|
||||
}
|
||||
|
||||
void _sync_cell(VolSurfaceCellVM cell) {
|
||||
void _sync_cell(VolGridCellVM cell) {
|
||||
if (cell is null) {
|
||||
return;
|
||||
}
|
||||
using var _ = _request_calculate.supress();
|
||||
cell.reset(
|
||||
committed_value: _parent.committed_grid.read(_exp, cell.column_id),
|
||||
candidate_value: _parent.current_grid.read(_exp, cell.column_id));
|
||||
}
|
||||
|
||||
IDisposable? _connect_cell(VolSurfaceCellVM cell) {
|
||||
return cell.column.type switch {
|
||||
VolSurfaceColumnType.ReadWriteTick => connect_input(),
|
||||
_ => null
|
||||
};
|
||||
|
||||
IDisposable connect_input() {
|
||||
cell.candidate_value_changed += on_candidate_value_changed;
|
||||
return Disposable.Create(() =>
|
||||
cell.candidate_value_changed -= on_candidate_value_changed);
|
||||
|
||||
void on_candidate_value_changed(object? oldval, object? newval) {
|
||||
var curr = _parent.current_grid.read(expiration, cell.column);
|
||||
if (cell.column.comparer.Equals(newval, curr)) {
|
||||
return;
|
||||
}
|
||||
var grid = _parent.current_grid;
|
||||
grid.write(expiration, cell.column, newval);
|
||||
_request_calculate.Invoke();
|
||||
}
|
||||
}
|
||||
cell.committed_value = _parent.committed_grid.read(_exp, cell.column_id);
|
||||
cell.candidate_value = _parent.current_grid.read(_exp, cell.column_id);
|
||||
}
|
||||
|
||||
class CellData : IDisposable {
|
||||
IDisposable? _dispose;
|
||||
IDisposable _dispose;
|
||||
|
||||
public CellData(VolSurfaceCellVM vm, IDisposable? dispose) {
|
||||
public CellData(VolGridCellVM vm, IDisposable dispose) {
|
||||
this.vm = vm;
|
||||
_dispose = Disposable.Create(vm, dispose);
|
||||
}
|
||||
|
||||
public VolSurfaceCellVM vm { get; }
|
||||
public VolGridCellVM vm { get; }
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(ref _dispose);
|
||||
|
||||
@@ -1,27 +0,0 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
|
||||
using System;
|
||||
using System.Windows.Input;
|
||||
|
||||
class VolSurfaceTickCellVM : VolSurfaceCellVM {
|
||||
ICommand? _tick_up_cmd;
|
||||
ICommand? _tick_down_cmd;
|
||||
|
||||
public VolSurfaceTickCellVM(
|
||||
VolSurfaceDisplayGridExpiration expiration, VolSurfaceDisplayGridColumn column)
|
||||
: base(expiration, column) { }
|
||||
|
||||
public event Action<bool>? request_tick;
|
||||
|
||||
public ICommand tick_up_cmd =>
|
||||
_tick_up_cmd ??= new DelegateCommand(() =>
|
||||
request_tick?.Invoke(true));
|
||||
|
||||
public ICommand tick_down_cmd =>
|
||||
_tick_down_cmd ??= new DelegateCommand(() =>
|
||||
request_tick?.Invoke(false));
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -14,7 +14,7 @@ namespace mbts.spark {
|
||||
class VolSurfaceAdvancedSettingsEditorVM : ViewModelBase {
|
||||
readonly VolSurfaceAdvancedSettings _settings;
|
||||
|
||||
public VolSurfaceAdvancedSettingsEditorVM(VolSurfaceAdvancedSettings settings, string vs_name) {
|
||||
public VolSurfaceAdvancedSettingsEditorVM(VolSurfaceAdvancedSettings settings, string vs_name, Action<VolSurfaceAdvancedSettings> commit) {
|
||||
_settings = settings;
|
||||
_settings.theo_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Absolute;
|
||||
_settings.slide_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Percentage;
|
||||
@@ -23,7 +23,7 @@ namespace mbts.spark {
|
||||
if (_settings.precomputed_theo_handles == null)
|
||||
_settings.precomputed_theo_handles = new List<double>();
|
||||
vol_surface_name = vs_name;
|
||||
commit = new DelegateCommand(() => request_commit?.Invoke(ProtobufSerializationHelper.clone(_settings)));
|
||||
this.commit = new DelegateCommand(() => request_commit?.Invoke(ProtobufSerializationHelper.clone(_settings)));
|
||||
}
|
||||
|
||||
public event Action<VolSurfaceAdvancedSettings> request_commit;
|
||||
|
||||
@@ -1,89 +0,0 @@
|
||||
#nullable enable
|
||||
|
||||
namespace mbts.spark {
|
||||
using bts.api.domain;
|
||||
|
||||
using mbts.analytics;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
using VolCurveFitRegion = analytics.VolSurfaceEnums.VolCurveFitRegion;
|
||||
|
||||
public class VolSurfaceAutoFitSettingsVM : DisposableViewModelBase {
|
||||
readonly Property<VolCurveFitRegion> _fit_region;
|
||||
readonly Property<uint?> _period_secs;
|
||||
readonly Property<double?> _driver_points_moved;
|
||||
readonly Property<double?> _atm_points_moved;
|
||||
readonly Property<bool> _is_auto_fit_enabled;
|
||||
|
||||
public VolSurfaceAutoFitSettingsVM() {
|
||||
_fit_region = backing(nameof(fit_region), VolCurveFitRegion.None);
|
||||
_is_auto_fit_enabled = backing(
|
||||
nameof(is_auto_fit_enabled),
|
||||
_fit_region.observe_current(true),
|
||||
r => r != VolCurveFitRegion.None);
|
||||
_period_secs = backing<uint?>(nameof(period_secs), 10);
|
||||
_driver_points_moved = backing<double?>(nameof(driver_points_moved));
|
||||
_atm_points_moved = backing<double?>(nameof(atm_points_moved));
|
||||
_fit_region.Changed += (o, n) => RaisePropertyChanged(nameof(is_auto_fit_enabled));
|
||||
}
|
||||
|
||||
public IEnumerable<VolCurveFitRegion> fit_regions =>
|
||||
EnumHelper.get_values<VolCurveFitRegion>();
|
||||
|
||||
public VolCurveFitRegion fit_region {
|
||||
get => _fit_region.Value;
|
||||
set => _fit_region.set(value);
|
||||
}
|
||||
|
||||
public bool is_auto_fit_enabled => _is_auto_fit_enabled.Value;
|
||||
|
||||
public uint? period_secs {
|
||||
get => _period_secs.Value;
|
||||
set => _period_secs.set(value);
|
||||
}
|
||||
|
||||
public double? driver_points_moved {
|
||||
get => _driver_points_moved.Value;
|
||||
set => _driver_points_moved.set(value);
|
||||
}
|
||||
|
||||
public TickDisplaySettingsImmutable? driver_points_display =>
|
||||
user.settings.TickFactors.pennies.to_api_tick_display_settingsi();
|
||||
|
||||
public double? atm_points_moved {
|
||||
get => _atm_points_moved.Value;
|
||||
set => _atm_points_moved.set(value);
|
||||
}
|
||||
|
||||
public TickDisplaySettingsImmutable? atm_points_display =>
|
||||
user.settings.TickFactors.pennies.to_api_tick_display_settingsi();
|
||||
|
||||
public void load_from(VolSurfaceAutoFitSettings value) {
|
||||
fit_region = value?.auto_fit_region ?? VolCurveFitRegion.None;
|
||||
period_secs = value?.time_based_settings?.period_seconds;
|
||||
driver_points_moved = value?.driver_move_based_settings?.points_moved;
|
||||
atm_points_moved = value?.atm_implied_vol_based_settings?.points_moved;
|
||||
}
|
||||
|
||||
public void assign_to(VolSurfaceAutoFitSettings value) {
|
||||
if (value is null) {
|
||||
throw new ArgumentNullException(nameof(value));
|
||||
}
|
||||
|
||||
value.auto_fit_region = fit_region;
|
||||
value.time_based_settings = new() {
|
||||
period_seconds = period_secs
|
||||
};
|
||||
value.driver_move_based_settings = new() {
|
||||
points_moved = driver_points_moved
|
||||
};
|
||||
value.atm_implied_vol_based_settings = new() {
|
||||
points_moved = atm_points_moved
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -96,7 +96,7 @@ namespace mbts.spark {
|
||||
get => _core_settings.font_weight_override;
|
||||
set {
|
||||
using var _ = detect_property_change();
|
||||
_core_settings.with(font_weight_override: value.HasValue ? new(value) : null);
|
||||
_core_settings.with(font_weight_override: value.HasValue ? new NullableFontWeightProto(value) : null);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls.graph;
|
||||
using System;
|
||||
using System.Windows.Input;
|
||||
using System.Windows.Media;
|
||||
|
||||
namespace mbts.spark
|
||||
{
|
||||
class VolSurfaceGraphSettingsEditorVM
|
||||
{
|
||||
public VolSurfaceGraphSettingsEditorVM(string vol_surface_name, VolSurfaceGraphSettings settings, Action<VolSurfaceGraphSettings> commit) {
|
||||
this.vol_surface_name = vol_surface_name;
|
||||
_settings = settings;
|
||||
this.commit = new DelegateCommand(() => commit(_settings));
|
||||
}
|
||||
|
||||
private readonly VolSurfaceGraphSettings _settings;
|
||||
|
||||
public string vol_surface_name { get; private set; }
|
||||
|
||||
public VolSurfaceScatterSeriesSettingsVM implied_puts { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_puts); } }
|
||||
public VolSurfaceScatterSeriesSettingsVM implied_atm { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_atm); } }
|
||||
public VolSurfaceScatterSeriesSettingsVM implied_calls { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.implied_calls); } }
|
||||
|
||||
public VolSurfaceScatterSeriesSettingsVM put_control_points { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.put_control_points); } }
|
||||
public VolSurfaceScatterSeriesSettingsVM atm { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.atm); } }
|
||||
public VolSurfaceScatterSeriesSettingsVM call_control_points { get { return new VolSurfaceScatterSeriesSettingsVM(_settings.call_control_points); } }
|
||||
|
||||
public VolSurfaceLineSeriesSettingsVM put_wing { get { return new VolSurfaceLineSeriesSettingsVM(_settings.put_wing); } }
|
||||
public VolSurfaceLineSeriesSettingsVM inner_curve { get { return new VolSurfaceLineSeriesSettingsVM(_settings.inner_curve); } }
|
||||
public VolSurfaceLineSeriesSettingsVM call_wing { get { return new VolSurfaceLineSeriesSettingsVM(_settings.call_wing); } }
|
||||
|
||||
public VolSurfaceLineSeriesSettingsVM vol_path { get { return new VolSurfaceLineSeriesSettingsVM(_settings.vol_path); } }
|
||||
|
||||
public ICommand commit { get; private set; }
|
||||
}
|
||||
|
||||
|
||||
class VolSurfaceScatterSeriesSettingsVM
|
||||
{
|
||||
public VolSurfaceScatterSeriesSettingsVM(ScatterSeriesSettings settings) {
|
||||
_settings = settings;
|
||||
}
|
||||
|
||||
private readonly ScatterSeriesSettings _settings;
|
||||
|
||||
public MarkerShape shape { get { return _settings.shape; } set { _settings.shape = value; } }
|
||||
public double size { get { return _settings.size; } set { _settings.size = value; } }
|
||||
public Color fill {
|
||||
get => _settings.fill;
|
||||
set => _settings.fill = value;
|
||||
}
|
||||
public Color stroke {
|
||||
get => _settings.stroke;
|
||||
set => _settings.stroke = value;
|
||||
}
|
||||
|
||||
public Array shapes { get { return Enum.GetValues(typeof(MarkerShape)); } }
|
||||
}
|
||||
|
||||
class VolSurfaceLineSeriesSettingsVM
|
||||
{
|
||||
public VolSurfaceLineSeriesSettingsVM(LineSeriesSettings settings) {
|
||||
_settings = settings;
|
||||
}
|
||||
|
||||
private readonly LineSeriesSettings _settings;
|
||||
|
||||
public Color color { get { return (Color)_settings.color; } set { _settings.color = (BTSColor)value; } }
|
||||
public double thickness { get { return _settings.stroke_thickness; } set { _settings.stroke_thickness = value; } }
|
||||
}
|
||||
}
|
||||
@@ -9,7 +9,6 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
using System;
|
||||
@@ -40,7 +39,6 @@ namespace mbts.spark {
|
||||
vol_model_cubic_spline_vm.load_from(settings.spline_model_settings);
|
||||
vol_model_dual_quadratic_vm.load_from(settings.dualquadratic_model_settings);
|
||||
vol_path_parabolic_vm.load_from(settings.core_settings.volpath_settings.parabolic_vol_path_settings);
|
||||
auto_fit_vm.load_from(settings.core_settings.market_fit_settings.vs_auto_fit_settings);
|
||||
|
||||
init_rotation_vms(call_rotations, _core_settings.call_rotation.strike_vol_movement_pairs);
|
||||
init_rotation_vms(put_rotations, _core_settings.put_rotation.strike_vol_movement_pairs);
|
||||
@@ -106,7 +104,6 @@ namespace mbts.spark {
|
||||
}).ToList();
|
||||
_core_settings.strangle.strike_vol_movement_pairs = strangles.SelectMany(r => new[] { Tuple.Create(r.target_put_strike, r.put_move), Tuple.Create(r.target_call_strike, r.call_move) }).ToList();
|
||||
_core_settings.atm_shift.atm_strike_vol_movement = atm_shifts.Count == 1 ? atm_shifts[0].move : 0;
|
||||
auto_fit_vm.assign_to(_core_settings.market_fit_settings.vs_auto_fit_settings);
|
||||
commit(_settings);
|
||||
}
|
||||
|
||||
@@ -235,7 +232,23 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
|
||||
public VolSurfaceAutoFitSettingsVM auto_fit_vm { get; } = new();
|
||||
public bool enable_auto_fit {
|
||||
get => _core_settings.market_fit_settings.enable_auto_fit;
|
||||
set {
|
||||
using var _ = detect_property_change();
|
||||
_core_settings.market_fit_settings.enable_auto_fit = value;
|
||||
}
|
||||
}
|
||||
|
||||
public VolSurfaceEnums.VolCurveFitRegion auto_fit_region {
|
||||
get => _core_settings.market_fit_settings.auto_fit_region;
|
||||
set { _core_settings.market_fit_settings.auto_fit_region = value; }
|
||||
}
|
||||
|
||||
public double auto_fit_time_ms {
|
||||
get => _core_settings.market_fit_settings.auto_fit_time_ms;
|
||||
set { _core_settings.market_fit_settings.auto_fit_time_ms = value; }
|
||||
}
|
||||
|
||||
public bool auto_decay_vol_time {
|
||||
get => _core_settings.time_settings.time_mode == VolSurfaceEnums.VolSurfaceTimeMode.AutoDecay;
|
||||
@@ -526,7 +539,7 @@ namespace mbts.spark {
|
||||
public ObservableCollection<VSSymbol> symbols { get; private set; }
|
||||
|
||||
public void Dispose() =>
|
||||
symbols.DisposeAll(true);
|
||||
Disposable.dispose(symbols);
|
||||
}
|
||||
|
||||
public class VSSymbolStructureVM : DisposableViewModelBase {
|
||||
@@ -537,11 +550,11 @@ namespace mbts.spark {
|
||||
_selected_driver_grid = backing<VSSymbolGridVM>(nameof(selected_driver_grid));
|
||||
settings.core_settings.master_slave_relationships ??= new List<VolSurfaceSymbolRelationship>();
|
||||
settings.core_settings.implied_vol_marketdata_relationships ??= new List<VolSurfaceSymbolRelationship>();
|
||||
_dispose = Disposable.Create(
|
||||
_dispose = new DisposableCombo(
|
||||
driver_grids.Subscribe((s, e) =>
|
||||
selected_driver_grid ??= driver_grids.FirstOrDefault()),
|
||||
bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(on_exp_params_input),
|
||||
Disposable.Create(() => driver_grids.DisposeAll(true)));
|
||||
bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(on_exp_params_input)) +
|
||||
new Action(() => Disposable.dispose(driver_grids));
|
||||
|
||||
void on_exp_params_input(AnalyticsExpirationParametersMap data) {
|
||||
var driver_map = data.get_option_driver_map();
|
||||
|
||||
@@ -77,8 +77,8 @@
|
||||
public IRaiseCanExecuteChangedCommand vol_shift { get; }
|
||||
|
||||
IEnumerable<IRaiseCanExecuteChangedCommand> _commands =>
|
||||
ReflectionHelper.property_getters<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
|
||||
.Select(pg => pg.get(this));
|
||||
ReflectionHelper.property_delegates_of_type<VolSurfaceMacroActionsVM, IRaiseCanExecuteChangedCommand>()
|
||||
.Select(g => g(this));
|
||||
|
||||
public void selection_changed(IEnumerable<VolSurfaceDisplayGridExpiration> selected) {
|
||||
_selected_exps = selected.ToList();
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
|
||||
@@ -11,7 +10,6 @@ namespace mbts.spark {
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
@@ -28,7 +26,6 @@ namespace mbts.spark {
|
||||
readonly IBus _bus;
|
||||
readonly string _request_id = Guid.NewGuid().ToString();
|
||||
readonly VolSurfaceDisplayModel _model;
|
||||
readonly UserTuple _user;
|
||||
readonly IRaiseCanExecuteChangedCommand _revert_cmd;
|
||||
readonly IRaiseCanExecuteChangedCommand _commit_cmd;
|
||||
readonly IDialogCommand _main_settings_cmd;
|
||||
@@ -40,16 +37,10 @@ namespace mbts.spark {
|
||||
bool _ignore_implied_vol_settings;
|
||||
|
||||
public VolSurfaceVM(
|
||||
VolSurfaceDisplayModel model,
|
||||
int id,
|
||||
IBus bus,
|
||||
VolSurfaceWindowSettings startup_data,
|
||||
UserTuple user
|
||||
) {
|
||||
VolSurfaceDisplayModel model, int id, IBus bus, VolSurfaceWindowSettings startup_data) {
|
||||
_model = model;
|
||||
_vs_id = id;
|
||||
_bus = bus;
|
||||
_user = user;
|
||||
macro_actions = new VolSurfaceMacroActionsVM(_model);
|
||||
globals = new VolSurfaceGlobalParameterVM(_model);
|
||||
|
||||
@@ -57,7 +48,7 @@ namespace mbts.spark {
|
||||
_grid_settings = startup_data.macro_grid_settings ?? new VolSurfaceMacroGridSettings();
|
||||
var hidden_exps_set = startup_data.hidden_exps.empty_if_null().ToHashSet();
|
||||
grid = new VolSurfaceGridVM(
|
||||
this, _model, _grid_settings.hidden_cols(), hidden_exps_set, _user);
|
||||
this, _model, _grid_settings.hidden_cols(), hidden_exps_set);
|
||||
grid.on_selection_changed += _on_grid_selection_changed;
|
||||
_model.publish_grid_settings(_grid_settings);
|
||||
|
||||
@@ -69,7 +60,6 @@ namespace mbts.spark {
|
||||
vol_terms_vm = new VolTermsGraphVM(_model, demux);
|
||||
|
||||
// command
|
||||
populate_empty_exps_cmd = new Command(() => { _model.populate_empty_expirations(); });
|
||||
_revert_cmd = new Command(o => _model.revert(), o => _model.is_dirty);
|
||||
_commit_cmd = new Command(o => _model.commit(), o => _model.is_dirty);
|
||||
load_previous_cmd = new Command(
|
||||
@@ -121,24 +111,21 @@ namespace mbts.spark {
|
||||
if (settings == null) {
|
||||
return null;
|
||||
}
|
||||
var vm = new VolSurfaceAdvancedSettingsEditorVM(
|
||||
VolSurfaceUtilityFunctions.clone_proto(settings.advanced_settings),
|
||||
settings.core_settings.vol_surface_name);
|
||||
vm.request_commit += commit_advanced_settings;
|
||||
return new VolSurfaceAdvancedSettingsEditor {
|
||||
DataContext = vm
|
||||
};
|
||||
|
||||
async void commit_advanced_settings(VolSurfaceAdvancedSettings value) {
|
||||
var current_settings = await _get_volsurface_settings();
|
||||
if (current_settings == null) {
|
||||
BTSMessageBox.Show("Error changing settings", "VS Settings");
|
||||
}
|
||||
else {
|
||||
current_settings.advanced_settings = value;
|
||||
_model.set_candidate_settings(current_settings);
|
||||
}
|
||||
}
|
||||
// return new VolSurfaceAdvancedSettingsEditor {
|
||||
// DataContext = new VolSurfaceAdvancedSettingsEditorVM(
|
||||
// VolSurfaceUtilityFunctions.clone_proto(settings.advanced_settings),
|
||||
// settings.core_settings.vol_surface_name,
|
||||
// advanced_settings => {
|
||||
// var current_settings = _get_volsurface_settings();
|
||||
// if (current_settings == null) BTSMessageBox.Show("Error changing settings", "VS Settings", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error, true, true, true);
|
||||
// else {
|
||||
// current_settings.advanced_settings = advanced_settings;
|
||||
// _model.set_candidate_settings(current_settings);
|
||||
// }
|
||||
// }
|
||||
// )
|
||||
// };
|
||||
return null;
|
||||
}
|
||||
|
||||
Window? mk_grid_settings_win() {
|
||||
@@ -198,7 +185,6 @@ namespace mbts.spark {
|
||||
|
||||
public ICommand revert_cmd => _revert_cmd;
|
||||
public ICommand commit_cmd => _commit_cmd;
|
||||
public ICommand populate_empty_exps_cmd { get; }
|
||||
public ICommand main_settings_cmd => _main_settings_cmd;
|
||||
public ICommand advanced_settings_cmd => _advanced_settings_cmd;
|
||||
public ICommand grid_settings_cmd => _grid_settings_cmd;
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
using mbts.analytics;
|
||||
using mbts.ui.controls;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
using System;
|
||||
@@ -127,20 +126,6 @@
|
||||
_log_bad_transition(_state, "set candidate grid");
|
||||
}
|
||||
|
||||
public void populate_empty_expirations() {
|
||||
bts.Log.Ui.info(String.Format("VolSurfaceDisplayModel.populate_expirations called with state: {0}",
|
||||
_state.ToString()));
|
||||
if (_state == DisplayModelState.Idle || _state == DisplayModelState.ResponseReady) {
|
||||
DisplayModelData curr_data = _get_current_data();
|
||||
VolSurfaceInput vs_inp =
|
||||
VolSurfaceDataFunctions.populate_empty_expirations(curr_data.vs_output.volsurface_input);
|
||||
_change_state(DisplayModelState.WaitingForCalcResponse);
|
||||
_bus.post(SparkTags.VolSurfaceCalculationRequestTag(_vs_id),
|
||||
new VolSurfaceCalculationRequest(vs_inp, _request_version_no++));
|
||||
} else
|
||||
_log_bad_transition(_state, "populate_expirations");
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Globals
|
||||
@@ -160,7 +145,6 @@
|
||||
return (_committed_data != null && _committed_data.vs_output != null) ? _committed_data.vs_output.volsurface_input.surface_parameters.vol_time : DateTime.MinValue;
|
||||
}
|
||||
public void set_candidate_vol_time(DateTime vol_time) {
|
||||
bts.Log.Ui.info($"VolSurfaceDisplayModel.set_candidate_vol_time vs_id: {_vs_id} state: {_state.ToString()} vol_time: {vol_time}");
|
||||
if (_state == DisplayModelState.Idle || _state == DisplayModelState.ResponseReady) {
|
||||
DisplayModelData curr_data = _get_current_data();
|
||||
if (curr_data != null) {
|
||||
@@ -584,7 +568,9 @@
|
||||
private void _change_state(DisplayModelState new_state) {
|
||||
bool dirty_before = _translate_to_dirty(_state),
|
||||
dirty_after = _translate_to_dirty(new_state);
|
||||
bts.Log.Ui.info($"VolSurfaceDisplayModel._change_state vs_id: {_vs_id} {_state.ToString()}->{new_state.ToString()}");
|
||||
// mbts.Logger.log(bts.log.Level.Info, bts.log.Subsystem.ui,
|
||||
// String.Format("State change {0}->{1}", _state.ToString(), new_state.ToString()));
|
||||
bts.Log.Ui.info(String.Format("State change {0}->{1}", _state.ToString(), new_state.ToString()));
|
||||
_state = new_state;
|
||||
if (dirty_before != dirty_after && on_dirty_change != null) {
|
||||
_bus.post(SparkTags.VolSurfaceDirtyStateTag(_vs_id), dirty_after);
|
||||
@@ -627,8 +613,9 @@
|
||||
}
|
||||
}
|
||||
|
||||
private void _log_bad_transition(DisplayModelState state, string action) {
|
||||
bts.Log.Ui.error($"VoLSurfaceDisplayModel bad_transaction vs_id: {_vs_id} {state}:{action}");
|
||||
private static void _log_bad_transition(DisplayModelState state, string action) {
|
||||
//mbts.Logger.log(bts.log.Level.Error, bts.log.Subsystem.ui, String.Format("{0}:{1}", state, action));
|
||||
bts.Log.Ui.error(String.Format("{0}:{1}", state, action));
|
||||
}
|
||||
|
||||
private static bool _translate_to_dirty(DisplayModelState state) {
|
||||
|
||||
@@ -172,18 +172,6 @@ namespace mbts.spark {
|
||||
return new(sec.Exchange, sec.ContractCase, sec.Symbol, exp_date, sec.Id);
|
||||
}
|
||||
|
||||
public static SecurityTuple security_tuple(this Security sec) {
|
||||
return security_tuple(new SecurityImmutable(sec));
|
||||
}
|
||||
|
||||
public static SecurityTuple security_tuple(this SecurityImmutable sec) {
|
||||
bts.api.SecurityTuple rv = new SecurityTuple();
|
||||
rv.Symbol = sec.Symbol;
|
||||
rv.Type = sec.security_type();
|
||||
rv.Venue = sec.Exchange;
|
||||
return rv;
|
||||
}
|
||||
|
||||
public static ExpirationDriver to_exp_driver(this SecurityExpiration sec_exp) =>
|
||||
new() {
|
||||
Security = new() {
|
||||
|
||||
@@ -22,7 +22,7 @@ namespace mbts.spark {
|
||||
// ii. IntepGreeks for each vs
|
||||
public class VolSurfaceInterpGreeksMultiplexer : IDisposable {
|
||||
private readonly ThreadedBlackboard _bb;
|
||||
private readonly ITag<VolSurfaceUsageListImmutable?> _in_bb_vs_usage_tag;
|
||||
private readonly ITag<VolSurfaceUsageListImmutable> _in_bb_vs_usage_tag;
|
||||
private IDictionary<int, ITag<VSTheos>> _vs_theo_tags =
|
||||
new Dictionary<int, ITag<VSTheos>>();
|
||||
private VolSurfaceUsageListImmutable _vs_usage_map =
|
||||
@@ -48,8 +48,8 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
private void _analyze_usages() {
|
||||
_vs_usage_map = _bb.read_state(_in_bb_vs_usage_tag) ??
|
||||
new VolSurfaceUsageList().immutable();
|
||||
_vs_usage_map = _bb.read_state(_in_bb_vs_usage_tag,
|
||||
new VolSurfaceUsageListImmutable(new VolSurfaceUsageList()));
|
||||
bts.Log.Gen.info($"VolSurfaceInterpGreeksMultiplexer._analyze_usages " +
|
||||
$"count: {_vs_usage_map.UsageList.Count()}");
|
||||
foreach (int vs_id in _vs_usage_map.vss()) {
|
||||
|
||||
@@ -5,8 +5,6 @@ using bts.api.core;
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
@@ -43,7 +41,7 @@ namespace mbts.spark {
|
||||
on_users = Observable.Return(DictionaryHelper.wrap_value(user.id, user.name));
|
||||
all_user_tuples = user.permissions == UserTuple.Permissions.Admin ?
|
||||
service.subscribei_admin_data()
|
||||
.Select(u => u.all.FirstOrNull())
|
||||
.Select(u => u.all.TryFirst())
|
||||
.Where(ad => ad.HasValue)
|
||||
.Select(ad => ad.Value.Users
|
||||
.Where(u => user.can_access_user_data(u.Id))
|
||||
@@ -52,14 +50,11 @@ namespace mbts.spark {
|
||||
.Table(UserTuple.key_fn)
|
||||
.Cache() :
|
||||
Observable.Return(TableUpdate<UserTuple, uint>.mk_empty(UserTuple.key_fn).with_added(new[] { user }));
|
||||
_dispose = Disposable.Create(
|
||||
all_user_tuples.Subscribe(t => bus.post(SparkTags.Users, t.state)),
|
||||
on_accounts.Subscribe(map => {
|
||||
_account_map = map;
|
||||
var account_tuple_map = MappedDictionary.create(map, (id, name) => new AccountTuple(id, name));
|
||||
bus.post(SparkTags.AccountsTag, account_tuple_map);
|
||||
}));
|
||||
bus.post(SparkTags.CurrentUser, user);
|
||||
_dispose = on_accounts.Subscribe(map => {
|
||||
_account_map = map;
|
||||
var account_tuple_map = MappedDictionary.create(map, (id, name) => new AccountTuple(id, name));
|
||||
bus.post(SparkTags.AccountsTag, account_tuple_map);
|
||||
});
|
||||
}
|
||||
|
||||
public IObservable<IReadOnlyDictionary<uint, string>> on_users { get; }
|
||||
@@ -81,7 +76,7 @@ namespace mbts.spark {
|
||||
}));
|
||||
|
||||
public AccountTuple? get_default_account() =>
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).FirstOrNull();
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst();
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(ref _dispose);
|
||||
|
||||
@@ -10,8 +10,7 @@ namespace mbts.analytics {
|
||||
double gamma = double.NaN,
|
||||
double vega = double.NaN,
|
||||
double theta = double.NaN,
|
||||
double rho = double.NaN,
|
||||
double normalized_theo = double.NaN) {
|
||||
double rho = double.NaN) {
|
||||
this.vol = vol;
|
||||
this.driver = driver;
|
||||
this.theo = theo;
|
||||
@@ -20,7 +19,6 @@ namespace mbts.analytics {
|
||||
this.vega = vega;
|
||||
this.theta = theta;
|
||||
this.rho = rho;
|
||||
this.normalized_theo = normalized_theo;
|
||||
}
|
||||
|
||||
public static GreeksTuple empty => new();
|
||||
@@ -33,7 +31,6 @@ namespace mbts.analytics {
|
||||
public double vega { get; }
|
||||
public double theta { get; }
|
||||
public double rho { get; }
|
||||
public double normalized_theo { get; }
|
||||
|
||||
public bool Equals(GreeksTuple other) =>
|
||||
vol.Equals(other.vol) &&
|
||||
@@ -68,8 +65,7 @@ namespace mbts.analytics {
|
||||
double? gamma = null,
|
||||
double? vega = null,
|
||||
double? theta = null,
|
||||
double? rho = null,
|
||||
double? normalized_theo = null) =>
|
||||
double? rho = null) =>
|
||||
new(
|
||||
vol ?? greeks_tuple.vol,
|
||||
driver ?? greeks_tuple.driver,
|
||||
@@ -78,7 +74,12 @@ namespace mbts.analytics {
|
||||
gamma ?? greeks_tuple.gamma,
|
||||
vega ?? greeks_tuple.vega,
|
||||
theta ?? greeks_tuple.theta,
|
||||
rho ?? greeks_tuple.rho,
|
||||
normalized_theo ?? greeks_tuple.normalized_theo);
|
||||
rho ?? greeks_tuple.rho);
|
||||
|
||||
public static double normalized_theo(this in GreeksTuple greeks_tuple) =>
|
||||
greeks_tuple.theo / greeks_tuple.driver;
|
||||
|
||||
public static double normalized_delta(this in GreeksTuple greeks_tuple) =>
|
||||
greeks_tuple.delta / greeks_tuple.driver;
|
||||
}
|
||||
}
|
||||
@@ -8,7 +8,6 @@ namespace mbts {
|
||||
|
||||
using ProtoBuf;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
@@ -101,13 +100,17 @@ namespace mbts {
|
||||
|
||||
public static IComparer<SecurityExpiration> get_comparer(Properties prop) {
|
||||
return prop switch {
|
||||
Properties.Type => ComparerWrapper<SecurityExpiration>.wrap(s => s.security_type),
|
||||
Properties.Symbol => ComparerWrapper<SecurityExpiration>.wrap(s => s.symbol),
|
||||
Properties.Expiration => ComparerWrapper<SecurityExpiration>.wrap(s => s.expiration),
|
||||
Properties.Venue => ComparerWrapper<SecurityExpiration>.wrap(s => s.exchange),
|
||||
Properties.Id => ComparerWrapper<SecurityExpiration>.wrap(s => s.id),
|
||||
Properties.Type => wrap(s => s.security_type),
|
||||
Properties.Symbol => wrap(s => s.symbol),
|
||||
Properties.Expiration => wrap(s => s.expiration),
|
||||
Properties.Venue => wrap(s => s.exchange),
|
||||
Properties.Id => wrap(s => s.id).to_safe(),
|
||||
_ => throw new NotImplementedException()
|
||||
};
|
||||
|
||||
static IComparer<SecurityExpiration> wrap<T>(
|
||||
Func<SecurityExpiration, T> selector, IComparer<T>? comparer = null) =>
|
||||
(comparer ?? Comparer<T>.Default).wrap(selector);
|
||||
}
|
||||
|
||||
public static IComparer<SecurityExpiration> get_comparer(params Properties[] hierarchy) =>
|
||||
@@ -145,7 +148,7 @@ namespace mbts {
|
||||
!(x == y);
|
||||
|
||||
public override string ToString() =>
|
||||
$"{security_tuple} {SecurityFormatter.format_expiration(expiration)}";
|
||||
$"{security_tuple} {expiration.ToShortDateString()}";
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
@@ -186,6 +189,6 @@ namespace mbts {
|
||||
exchange ?? sec_exp.exchange, security_type ?? sec_exp.security_type,
|
||||
symbol ?? sec_exp.symbol,
|
||||
expiration ?? sec_exp.expiration,
|
||||
id.has_value ? id : sec_exp.id);
|
||||
id.has_value ? id.value : sec_exp.id);
|
||||
}
|
||||
}
|
||||
@@ -9,34 +9,26 @@ namespace mbts.analytics
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceAdvancedSettings")]
|
||||
public class VolSurfaceAdvancedSettings
|
||||
{
|
||||
public static VolSurfaceAdvancedSettings Default =>
|
||||
new() {
|
||||
number_of_cashed_saved_days = double.NaN,
|
||||
precomputed_theo_handles = new(0),
|
||||
theo_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Absolute,
|
||||
precomputed_slide_handles = new(0),
|
||||
slide_handle_measure = VolSurfaceEnums.GeneralChangeMeasure.Percentage,
|
||||
publish_from_client = false,
|
||||
publish_from_client_user = string.Empty,
|
||||
strike_normalization_axis = VolSurfaceEnums.VolCurveStrikeAxis.RawStrike,
|
||||
};
|
||||
|
||||
[ProtoBuf.ProtoMember(1)]
|
||||
[System.ComponentModel.DefaultValue(Double.NaN)]
|
||||
public double number_of_cashed_saved_days;
|
||||
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public List<double> precomputed_theo_handles;
|
||||
|
||||
[ProtoBuf.ProtoMember(15)]
|
||||
[System.ComponentModel.DefaultValue(VolSurfaceEnums.GeneralChangeMeasure.Absolute)]
|
||||
public VolSurfaceEnums.GeneralChangeMeasure theo_handle_measure;
|
||||
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public List<double> precomputed_slide_handles;
|
||||
|
||||
[ProtoBuf.ProtoMember(25)]
|
||||
[System.ComponentModel.DefaultValue(VolSurfaceEnums.GeneralChangeMeasure.Percentage)]
|
||||
public VolSurfaceEnums.GeneralChangeMeasure slide_handle_measure;
|
||||
|
||||
[ProtoBuf.ProtoMember(30)]
|
||||
//[System.ComponentModel.DefaultValue(false)]
|
||||
public bool publish_from_client;
|
||||
|
||||
[ProtoBuf.ProtoMember(40)]
|
||||
@@ -46,11 +38,5 @@ namespace mbts.analytics
|
||||
[ProtoBuf.ProtoMember(50)]
|
||||
[System.ComponentModel.DefaultValue(VolSurfaceEnums.VolCurveStrikeAxis.RawStrike)]
|
||||
public VolSurfaceEnums.VolCurveStrikeAxis strike_normalization_axis;
|
||||
|
||||
public void ensure_no_nulls() {
|
||||
precomputed_theo_handles ??= new(0);
|
||||
precomputed_slide_handles ??= new(0);
|
||||
publish_from_client_user ??= string.Empty;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -4,11 +4,13 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.analytics {
|
||||
namespace mbts.analytics
|
||||
{
|
||||
/// These are the VolSurface settings that are common
|
||||
/// to any Vol Model
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceCoreSettings")]
|
||||
public class VolSurfaceCoreSettings {
|
||||
public class VolSurfaceCoreSettings
|
||||
{
|
||||
[ProtoBuf.ProtoMember(1)]
|
||||
public string vol_surface_name;
|
||||
[ProtoBuf.ProtoMember(2)]
|
||||
@@ -85,7 +87,5 @@ namespace mbts.analytics {
|
||||
get => _time_settings ??= new();
|
||||
set => _time_settings = value;
|
||||
}
|
||||
[ProtoBuf.ProtoMember(240)]
|
||||
public string vs_manager { get; set; } = string.Empty;
|
||||
}
|
||||
}
|
||||
@@ -25,8 +25,7 @@ namespace mbts.analytics {
|
||||
volpath_settings = new(),
|
||||
safety_limits = new(),
|
||||
},
|
||||
polynomial_model_settings = new(),
|
||||
advanced_settings = VolSurfaceAdvancedSettings.Default
|
||||
polynomial_model_settings = new()
|
||||
};
|
||||
|
||||
[ProtoMember(10)]
|
||||
@@ -76,12 +75,9 @@ namespace mbts.analytics {
|
||||
if (core_settings.market_fit_settings == null) {
|
||||
core_settings.market_fit_settings = new VolSurfaceMarketFitSettings();
|
||||
}
|
||||
core_settings.market_fit_settings.vs_auto_fit_settings ??= new();
|
||||
if (core_settings.time_settings == null) {
|
||||
core_settings.time_settings = new VolSurfaceTimeSettings();
|
||||
}
|
||||
advanced_settings ??= VolSurfaceAdvancedSettings.Default;
|
||||
advanced_settings.ensure_no_nulls();
|
||||
return this;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -141,7 +141,6 @@ namespace mbts.analytics
|
||||
|
||||
public enum VolCurveFitRegion
|
||||
{
|
||||
None,
|
||||
ATM,
|
||||
All
|
||||
}
|
||||
@@ -231,4 +230,4 @@ namespace mbts.analytics
|
||||
USE_CALENDAR_FOR_BUSINESS
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,7 +65,7 @@ namespace mbts.analytics {
|
||||
}
|
||||
|
||||
public override string ToString() {
|
||||
return String.Format("{0} {1} {2}",
|
||||
return String.Format("{0} {1} {2}",
|
||||
security_type.ToString().ToUpper().First(), symbol, expiration.ToShortDateString());
|
||||
}
|
||||
|
||||
@@ -74,11 +74,6 @@ namespace mbts.analytics {
|
||||
int rv = expiration.CompareTo(other.expiration);
|
||||
return rv != 0 ? rv : symbol.CompareTo(other.symbol);
|
||||
}
|
||||
|
||||
public double diff_days(VolSurfaceExpiration exp_other) {
|
||||
TimeSpan ts = expiration - exp_other.expiration;
|
||||
return ts.TotalDays;
|
||||
}
|
||||
}
|
||||
|
||||
public static class VolSurfaceExpirationExtensions {
|
||||
|
||||
@@ -17,6 +17,13 @@ namespace mbts.analytics {
|
||||
this.server_time_utc = server_time_utc;
|
||||
}
|
||||
|
||||
public VolSurfaceStandardTime(long seconds_from_epoch) {
|
||||
timezone = TimeZoneInfo.Local;
|
||||
server_time_utc =
|
||||
DateTimeOffset.FromUnixTimeSeconds(seconds_from_epoch).DateTime;
|
||||
server_time = server_time_utc.ToLocalTime();
|
||||
}
|
||||
|
||||
public static VolSurfaceStandardTime get_local_default() {
|
||||
DateTime local_rounded = VolSurfaceUtilityFunctions.round_time_mins(
|
||||
DateTime.Now, VolSurfaceConstants.vol_time_sample_mins);
|
||||
|
||||
@@ -4,9 +4,11 @@ using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.analytics {
|
||||
namespace mbts.analytics
|
||||
{
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceMarketFitSettings")]
|
||||
public class VolSurfaceMarketFitSettings {
|
||||
public class VolSurfaceMarketFitSettings
|
||||
{
|
||||
/// use one sided market or not
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public bool ignore_one_sided_markets;
|
||||
@@ -20,44 +22,19 @@ namespace mbts.analytics {
|
||||
public double graph_update_period_ms = 2500;
|
||||
/// If this is set to true a regression curve is drawn
|
||||
/// and the vol model adheres to that
|
||||
[ProtoBuf.ProtoMember(50)]
|
||||
[ProtoBuf.ProtoMember(50)]
|
||||
public bool use_weighted_regression_fit = false;
|
||||
[ProtoBuf.ProtoMember(55)]
|
||||
public uint regression_order = 4;
|
||||
|
||||
[ProtoBuf.ProtoMember(90)]
|
||||
public VolSurfaceAutoFitSettings vs_auto_fit_settings { get; set; }
|
||||
}
|
||||
|
||||
[ProtoBuf.ProtoContract(Name = "VolSurfaceAutoFitSettings")]
|
||||
public class VolSurfaceAutoFitSettings {
|
||||
// each of these settings can be enabled independently. if they are enabled
|
||||
// then any of them being true will result in an autmatic fit
|
||||
[ProtoBuf.ProtoContract(Name = "TimeBasedSettings")]
|
||||
public class TimeBasedSettings {
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public uint? period_seconds { get; set; }
|
||||
}
|
||||
|
||||
[ProtoBuf.ProtoContract(Name = "DriverMoveBasedSettings")]
|
||||
public class DriverMoveBasedSettings {
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public double? points_moved { get; set; }
|
||||
}
|
||||
|
||||
[ProtoBuf.ProtoContract(Name = "ATMImpliedVolBasedSettings")]
|
||||
public class ATMImpliedVolBasedSettings {
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public double? points_moved { get; set; }
|
||||
// we can do price terms moved as well
|
||||
}
|
||||
[ProtoBuf.ProtoMember(5)]
|
||||
public VolSurfaceEnums.VolCurveFitRegion auto_fit_region;
|
||||
[ProtoBuf.ProtoMember(10)]
|
||||
public TimeBasedSettings time_based_settings = null;
|
||||
[ProtoBuf.ProtoMember(20)]
|
||||
public DriverMoveBasedSettings driver_move_based_settings = null;
|
||||
[ProtoBuf.ProtoMember(30)]
|
||||
public ATMImpliedVolBasedSettings atm_implied_vol_based_settings = null;
|
||||
/// The system auto fits and saves vols if this is
|
||||
/// set to true
|
||||
[ProtoBuf.ProtoMember(60)]
|
||||
public bool enable_auto_fit = false;
|
||||
/// If enable_auto_fit = true, this governs
|
||||
/// how often the system auto-fits
|
||||
[ProtoBuf.ProtoMember(70)]
|
||||
public double auto_fit_time_ms = 30000;
|
||||
[ProtoBuf.ProtoMember(80)]
|
||||
public VolSurfaceEnums.VolCurveFitRegion auto_fit_region = VolSurfaceEnums.VolCurveFitRegion.ATM;
|
||||
}
|
||||
}
|
||||
@@ -943,15 +943,7 @@ namespace mbts.analytics {
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region inverse contracts
|
||||
// Bitcoin contracts, for example, where the strike is in USD, and the theo
|
||||
// needs to be in terms of the underlying contract
|
||||
public static double normalize_theo(double theo, double fwd) {
|
||||
return fwd == 0 ? Double.NaN : (theo / fwd);
|
||||
}
|
||||
#endregion
|
||||
#endregion
|
||||
|
||||
#region Other Pricing Utilities
|
||||
|
||||
|
||||
@@ -680,60 +680,5 @@ namespace mbts.analytics
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Data copying
|
||||
|
||||
public static bool exp_has_input(VolSurfaceSettings vs_settings, VolCurveParameters exp_params) {
|
||||
if (exp_params == null || vs_settings == null)
|
||||
return false;
|
||||
double atm_vol = get_atm_vol(vs_settings, exp_params);
|
||||
double ref_fwd = exp_params.core_parameters.ref_forward;
|
||||
return !Double.IsNaN(atm_vol) && !Double.IsNaN(ref_fwd);
|
||||
}
|
||||
|
||||
public static VolSurfaceExpiration find_nearest_populated_exp(
|
||||
VolSurfaceInput vs_input, VolSurfaceExpiration vs_exp) {
|
||||
VolCurveParameters exp_params = get_curve_parameters(vs_input, vs_exp);
|
||||
if (exp_has_input(vs_input.surface_settings, exp_params))
|
||||
return vs_exp;
|
||||
VolSurfaceExpiration rv = null;
|
||||
double rv_diff_days = Double.MaxValue;
|
||||
foreach (var kv in vs_input.surface_parameters.curve_parameters_map) {
|
||||
var this_exp = kv.Item1;
|
||||
var this_exp_params = kv.Item2;
|
||||
if (exp_has_input(vs_input.surface_settings, this_exp_params)) {
|
||||
double this_exp_diff_days = Math.Abs(vs_exp.diff_days(this_exp));
|
||||
if (this_exp_diff_days < rv_diff_days) {
|
||||
rv = this_exp;
|
||||
rv_diff_days = this_exp_diff_days;
|
||||
}
|
||||
}
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
// Copies the empty exps from closest neighbor
|
||||
public static VolSurfaceInput populate_empty_expirations(VolSurfaceInput vs_input) {
|
||||
VolSurfaceInput rv = Spark.Core.Protobuf.ProtobufSerializationHelper.clone(vs_input);
|
||||
rv.surface_parameters.curve_parameters_map.Clear();
|
||||
foreach (var kv in vs_input.surface_parameters.curve_parameters_map) {
|
||||
var vs_exp = kv.Item1;
|
||||
var exp_params = kv.Item2;
|
||||
if (!exp_has_input(vs_input.surface_settings, exp_params)) {
|
||||
VolSurfaceExpiration np_exp = find_nearest_populated_exp(vs_input, vs_exp);
|
||||
if (np_exp != null) {
|
||||
var np_exp_params = get_curve_parameters(vs_input, np_exp);
|
||||
if (np_exp_params != null) {
|
||||
exp_params = Spark.Core.Protobuf.ProtobufSerializationHelper.clone(np_exp_params);
|
||||
}
|
||||
}
|
||||
}
|
||||
rv.surface_parameters.curve_parameters_map.Add(
|
||||
new Tuple<VolSurfaceExpiration, VolCurveParameters>(vs_exp, exp_params));
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
@@ -475,7 +475,6 @@ namespace mbts.analytics {
|
||||
public static ResultMessage save_volsurface(
|
||||
VolSurfaceInput vs_input, AnalyticsService service, string user = "") {
|
||||
vs_input.saver_login = user;
|
||||
vs_input.surface_settings.core_settings.vs_manager = user;
|
||||
// convert to VolSurfaceEntry
|
||||
var to_save = new VolSurfaceEntry();
|
||||
var serialized_vs = ProtobufSerializationHelper.serialize(vs_input);
|
||||
@@ -596,7 +595,7 @@ namespace mbts.analytics {
|
||||
_greek_getter(g)(t, is_call);
|
||||
|
||||
public static IDictionary<double, IEnumerable<Theos>> hash_strikes(IEnumerable<Theos> theos) =>
|
||||
theos.Map(t => t.strike);
|
||||
theos.Map(t => t.strike);
|
||||
|
||||
static Func<Theos, bool, double> _greek_getter(VolSurfaceGreeks g) =>
|
||||
g switch {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
using System;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
@@ -40,8 +40,10 @@ namespace mbts.analytics {
|
||||
/// last computed min/max driver for each exp
|
||||
private IDictionary<VolSurfaceExpiration, Tuple<double, double>>
|
||||
_computed_driver_range_map = new Dictionary<VolSurfaceExpiration, Tuple<double, double>>();
|
||||
private readonly IEnumerable<double> _default_abs_moves = config.Configuration.get<bts.config.VolSurface>().default_abs_moves;
|
||||
private readonly IEnumerable<double> _default_abs_moves =
|
||||
new double[] { 300, -200, -125, -100, -75, -50, -25, 0, 25, 50, 75, 100, 125, 200, 300 };
|
||||
private readonly double _cushion_percentage = 25.0;
|
||||
|
||||
public event
|
||||
Action<IDictionary<VolSurfaceExpiration, IEnumerable<Theos>>, double, double> on_theos =
|
||||
(o, vt, tt) => { };
|
||||
@@ -50,7 +52,7 @@ namespace mbts.analytics {
|
||||
(o, vt, tt) => { };
|
||||
|
||||
public VolSurfaceInterpGreeksProducer(int vs_id) {
|
||||
Log.Gen.info($"VolSurfaceInterpGreeksProducer.cons vs_id: {vs_id}, _default_abs_moves: {string.Join(", ", _default_abs_moves)}");
|
||||
Log.Gen.info($"VolSurfaceInterpGreeksProducer.cons vs_id: {vs_id}");
|
||||
_vs_id = vs_id;
|
||||
}
|
||||
|
||||
@@ -70,7 +72,7 @@ namespace mbts.analytics {
|
||||
}
|
||||
|
||||
public void set_vol_data(VolSurfaceInput vs_input) {
|
||||
Log.Gen.info($"VolSurfaceInterpGreeksProducer.set_vol_data vs_id: {_vs_id} precomputed_theo_handles?: {string.Join(", ", (vs_input?.surface_settings?.advanced_settings?.precomputed_theo_handles).empty_if_null())}");
|
||||
Log.Gen.info($"VolSurfaceInterpGreeksProducer.set_vol_data vs_id: {_vs_id}");
|
||||
_vs_input = vs_input != null ? VolSurfaceUtilityFunctions.clone_proto(vs_input) : null;
|
||||
_compute_and_fire(InputType.Vol);
|
||||
}
|
||||
@@ -86,8 +88,8 @@ namespace mbts.analytics {
|
||||
|
||||
public void set_driver_price(
|
||||
IDictionary<VolSurfaceExpiration, double> driver_price_map) {
|
||||
// Log.Gen.info($"VolSurfaceInterpGreeksProducer.set_driver_price " +
|
||||
// $"vs_id: {_vs_id} exp_count: {driver_price_map.Count}");
|
||||
Log.Gen.info($"VolSurfaceInterpGreeksProducer.set_driver_price " +
|
||||
$"vs_id: {_vs_id} exp_count: {driver_price_map.Count}");
|
||||
_driver_price_map = new Dictionary<VolSurfaceExpiration, double>(driver_price_map);
|
||||
_compute_and_fire(InputType.DriverPrice);
|
||||
}
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
namespace Spark {
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
static class ConsoleInterop {
|
||||
[DllImport("kernel32.dll")]
|
||||
static extern IntPtr GetConsoleWindow();
|
||||
|
||||
[DllImport("user32.dll")]
|
||||
static extern bool ShowWindow(IntPtr h_wnd, int n_cmd_show);
|
||||
|
||||
[DllImport("kernel32.dll", SetLastError = true)]
|
||||
internal static extern int FreeConsole();
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,10 @@
|
||||
using bts.api;
|
||||
|
||||
using mbts;
|
||||
using mbts.config;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Diagnostics;
|
||||
|
||||
@@ -8,22 +8,22 @@ using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utilities;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
using bts.api.analytics;
|
||||
using BCG;
|
||||
|
||||
using Disposable = mbts.Disposable;
|
||||
|
||||
namespace bts {
|
||||
[Export(typeof(IShellDaemon))]
|
||||
class AnalyticsDaemon : IShellDaemon, IDisposable {
|
||||
private readonly IBus _bus;
|
||||
private readonly AnalyticsService _analytics_service;
|
||||
private readonly bts.api.orderman.OrderService _order_service;
|
||||
private readonly VolSurfaceBusManager _vs_manager;
|
||||
private readonly SpreadManager _spread_manager;
|
||||
private readonly SpreadCalculationSynchronizer _spread_calc;
|
||||
@@ -31,13 +31,11 @@ namespace bts {
|
||||
IDisposable _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
public AnalyticsDaemon(IBus bus, AnalyticsService analytics_service,
|
||||
bts.api.orderman.OrderService order_service) {
|
||||
public AnalyticsDaemon(IBus bus, AnalyticsService analytics_service) {
|
||||
bts.Log.Gen.info("AnalyticsDaemon started");
|
||||
_bus = bus;
|
||||
_analytics_service = analytics_service;
|
||||
_order_service = order_service;
|
||||
_vs_manager = new VolSurfaceBusManager(_bus, _analytics_service, _order_service);
|
||||
_vs_manager = new VolSurfaceBusManager(_bus, _analytics_service);
|
||||
_spread_manager = new SpreadManager(_vs_manager.bb(), "xxx");
|
||||
_spread_calc = new SpreadCalculationSynchronizer(_vs_manager.bb());
|
||||
}
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
using bts.api;
|
||||
using bts.spark;
|
||||
|
||||
using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
@@ -7,8 +7,6 @@ using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -11,7 +11,6 @@ using System.Reactive.Linq;
|
||||
|
||||
using SecurityKey = System.UInt32;
|
||||
using MDHandle = mbts.co2.FakeMDConsumerHandle;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
namespace bts {
|
||||
//[Export(typeof(IShellDaemon))]
|
||||
|
||||
@@ -7,8 +7,6 @@ namespace bts.daemons {
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
@@ -19,7 +17,7 @@ namespace bts.daemons {
|
||||
|
||||
[Export(typeof(IShellDaemon))]
|
||||
public sealed class FakeSymbolDriverDaemon : IShellDaemon, IDisposable {
|
||||
IDisposable? _dispose;
|
||||
IDisposable _dispose;
|
||||
|
||||
public FakeSymbolDriverDaemon(IBus bus) {
|
||||
int tid_counter = 1;
|
||||
@@ -70,7 +68,6 @@ namespace bts.daemons {
|
||||
double price,
|
||||
int size = 1,
|
||||
string account = "ACC A",
|
||||
uint account_id = 1,
|
||||
double? strike = null,
|
||||
PutOrCall? cp = null,
|
||||
double? theo = null
|
||||
@@ -84,11 +81,9 @@ namespace bts.daemons {
|
||||
price,
|
||||
theo ?? price + 10 * new Random().NextDouble(),
|
||||
account,
|
||||
account_id,
|
||||
true,
|
||||
DateTime.Now,
|
||||
"FakeTrader",
|
||||
1);
|
||||
"FakeTrader");
|
||||
return t1;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,14 +8,15 @@ using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utilities;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
|
||||
using Disposable = mbts.Disposable;
|
||||
|
||||
namespace bts {
|
||||
[Export(typeof(IShellDaemon))]
|
||||
class GlobalAlertsDaemon : IShellDaemon, IDisposable {
|
||||
@@ -38,14 +39,13 @@ namespace bts {
|
||||
_notification_service = notification_service;
|
||||
_launcher = new ThreadedWindowLauncher(_window_name);
|
||||
_dispose = Disposable.Create(
|
||||
bus.subscribe(SparkTags.ShowGlobalAlertsTag).Subscribe(_ =>
|
||||
_launcher.show(_view_factory)),
|
||||
_hub.subscribe_default_settings().SubscribeEach(s =>
|
||||
Disposable.Create(s.alerts.trade_alerts
|
||||
.Where(t => t.is_enabled)
|
||||
.Select(a => _notification_service.link_to_trades(
|
||||
a.predicate.security_criteria, a.predicate.create(), a.sound))
|
||||
.ToList())));
|
||||
bus.subscribe(SparkTags.ShowGlobalAlertsTag)
|
||||
.Subscribe(_ => _launcher.show(_view_factory)),
|
||||
_hub.subscribe_default_settings()
|
||||
.SubscribeEach(s => new CompositeDisposable(
|
||||
s.alerts.trade_alerts.Where(t => t.is_enabled).Select(
|
||||
a => _notification_service.link_to_trades(
|
||||
a.predicate.security_criteria, a.predicate.create(), a.sound)))));
|
||||
}
|
||||
|
||||
Window _view_factory() {
|
||||
|
||||
@@ -14,7 +14,6 @@ namespace bts {
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
@@ -135,10 +134,7 @@ namespace bts {
|
||||
var meta = _security_metadata.get(smd.security);
|
||||
if (meta.HasValue) {
|
||||
exch_secs[smd.id] = new(
|
||||
smd.security,
|
||||
smd.md,
|
||||
meta.Value.HasPriceDisplay ? meta.Value.PriceDisplay : null,
|
||||
meta.Value.HasQuantityDisplay ? meta.Value.QuantityDisplay : null);
|
||||
smd.security, smd.md, meta.Value.PriceDisplay, meta.Value.QuantityDisplay);
|
||||
}
|
||||
}
|
||||
_bus.post(SparkTags.ServerSecuritiesTag, exch_secs);
|
||||
@@ -146,6 +142,6 @@ namespace bts {
|
||||
}
|
||||
|
||||
public void Dispose() =>
|
||||
_resources.DisposeAll(true);
|
||||
Disposable.dispose(_resources);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,6 @@ using BCG;
|
||||
|
||||
using bts.api;
|
||||
using bts.api.synthetic;
|
||||
using bts.collections;
|
||||
using bts.md;
|
||||
using bts.utils;
|
||||
|
||||
@@ -11,8 +10,6 @@ using mbts.co2;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -30,22 +27,16 @@ namespace bts {
|
||||
IDisposable _dispose;
|
||||
Dictionary<uint, SecurityMD> _server_sec_map = new Dictionary<uint, SecurityMD>();
|
||||
Dictionary<uint, SecurityMD> _fake_sec_map = new Dictionary<uint, SecurityMD>();
|
||||
private readonly IList<IDisposable> _subs = new List<IDisposable>();
|
||||
|
||||
[ImportingConstructor]
|
||||
public MergedMDDaemon(IBus bus) {
|
||||
//TempTester.test_analytics();
|
||||
bts.Log.Gen.info("MergedMDDaemon started");
|
||||
_bus = bus;
|
||||
_subs.Add(_bus.subscribe(SparkTags.ServerSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_server_sec_map(d)));
|
||||
_subs.Add(_bus.subscribe(SparkTags.FakeSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_fake_sec_map(d)));
|
||||
// This is done periodically to remove expired contracts
|
||||
// (disabling it right now because we are not sure if deleting securities
|
||||
// works with the various UI windows)
|
||||
// _subs.Add(_bus.subscribe(SparkTags.SparkTimer).BufferLatest(TimeSpan.FromMinutes(1))
|
||||
// .Subscribe(t => _merge_and_post()));
|
||||
_bus.subscribe(SparkTags.ServerSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_server_sec_map(d));
|
||||
_bus.subscribe(SparkTags.FakeSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_fake_sec_map(d));
|
||||
}
|
||||
|
||||
private void _log_options(IReadOnlyDictionary<uint, SecurityMD> sec_map) {
|
||||
@@ -62,28 +53,34 @@ namespace bts {
|
||||
}
|
||||
|
||||
private void _on_server_sec_map(IReadOnlyDictionary<uint, SecurityMD> sec_map) {
|
||||
//_log_options(sec_map);
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._on_server_sec_map sz: {0}", sec_map.Count()));
|
||||
_log_options(sec_map);
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._on_server_sec_map sz:{0}", sec_map.Count()));
|
||||
_server_sec_map = new Dictionary<uint, SecurityMD>(sec_map);
|
||||
_merge_and_post();
|
||||
}
|
||||
|
||||
private void _on_fake_sec_map(IReadOnlyDictionary<uint, SecurityMD> sec_map) {
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._on_fake_sec_map sz: {0}", sec_map.Count()));
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._on_fake_sec_map sz:{0}", sec_map.Count()));
|
||||
_fake_sec_map = new Dictionary<uint, SecurityMD>(sec_map);
|
||||
_merge_and_post();
|
||||
}
|
||||
|
||||
private void _merge_and_post() {
|
||||
Func<SecurityMD, bool> is_active = (sec_md) => {
|
||||
var sec = sec_md.security;
|
||||
return SecurityExpirationHelper.is_unexpired(sec);
|
||||
if (sec_md.security.HasFuture || sec_md.security.HasOption) {
|
||||
var exp = sec_md.security.security_expiration();
|
||||
if (exp.HasValue) {
|
||||
return exp.Value.Date >= DateTime.Now.Date.AddDays(-1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
var to_pub = _server_sec_map.Where(kv => is_active(kv.Value)).ToDictionary(kv => kv.Key, kv => kv.Value);
|
||||
foreach (var kv in _fake_sec_map) {
|
||||
to_pub[kv.Key] = kv.Value;
|
||||
}
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._merge_and_post sz: {0}", to_pub.Count()));
|
||||
bts.Log.Gen.info(String.Format("MergedMDDaemon._merge_and_post sz:{0}", to_pub.Count()));
|
||||
_bus.post(SparkTags.SecuritiesTag, to_pub);
|
||||
SystemContractData sc_data = new SystemContractData(to_pub);
|
||||
_bus.post(SparkTags.SystemContractsTag, sc_data);
|
||||
|
||||
@@ -2,11 +2,10 @@
|
||||
using bts.api.orderman;
|
||||
using bts.spark;
|
||||
|
||||
using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -10,8 +10,6 @@ using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
using bts.api;
|
||||
using mbts.ui;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Reactive.Linq;
|
||||
using System.Collections.Generic;
|
||||
using mbts.spark;
|
||||
using bts.api.orderman;
|
||||
using bts.collections;
|
||||
using System.Linq;
|
||||
using Microsoft.Scripting.Utils;
|
||||
|
||||
namespace bts {
|
||||
[Export(typeof(IShellDaemon))]
|
||||
class RFQDaemon : IShellDaemon, IDisposable {
|
||||
private readonly IBus _bus;
|
||||
private readonly bts.api.orderman.OrderService _order_service;
|
||||
private List<IDisposable> _subs = new List<IDisposable>();
|
||||
|
||||
[ImportingConstructor]
|
||||
public RFQDaemon(IBus bus, bts.api.orderman.OrderService order_service) {
|
||||
bts.Log.Gen.info("RFQDaemon started");
|
||||
_bus = bus;
|
||||
_order_service = order_service;
|
||||
var d = bus.subscribe(SparkTags.RFQSend)
|
||||
.Subscribe(_handle_rfq);
|
||||
}
|
||||
|
||||
private void _handle_rfq(RFQRequestImmutable rfq) {
|
||||
bts.Log.Gen.info($"RFQDaemon._handle_rfq");
|
||||
_order_service.send_rfq(rfq);
|
||||
}
|
||||
|
||||
public void Dispose() {
|
||||
foreach (var d in _subs) {
|
||||
d.Dispose();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,8 +2,6 @@
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -13,7 +13,6 @@ namespace bts.daemons {
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -30,11 +29,10 @@ namespace bts.daemons {
|
||||
readonly OrderService _order_service;
|
||||
readonly ErrorReporter _error_reporter;
|
||||
readonly IBus _bus;
|
||||
readonly mbts.analytics.PNLReportCalculator _pnl_calc;
|
||||
|
||||
IReadOnlyDictionary<int, ReportImmutable> _report_parameters_map =
|
||||
new Dictionary<int, ReportImmutable>();
|
||||
IDisposable? _dispose;
|
||||
IDisposable _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
public ReportDaemon(
|
||||
@@ -50,7 +48,6 @@ namespace bts.daemons {
|
||||
_error_reporter = error_reporter;
|
||||
_order_service = order_service;
|
||||
_report_calculators = new(mk_report_calculator);
|
||||
_pnl_calc = new PNLReportCalculator(bus);
|
||||
|
||||
_dispose = Disposable.Create(
|
||||
bus.subscribe(SparkTags.ReportBlackboardTags.Create).Subscribe(rp => _create_report(rp).ignore()),
|
||||
@@ -62,8 +59,7 @@ namespace bts.daemons {
|
||||
_bus.subscribe(SparkTags.SystemContractsTag).CombineLatest(
|
||||
_order_service.subscribe_fills(), _position_service.subscribe_manual_fills())
|
||||
.Subscribe(tup => _on_all_trade_data(tup.First, tup.Second, tup.Third)),
|
||||
_report_calculators,
|
||||
_pnl_calc);
|
||||
_report_calculators);
|
||||
|
||||
IDisposable mk_report_calculator(int id) {
|
||||
if (!_report_parameters_map.TryGetValue(id, out var r)) {
|
||||
@@ -160,8 +156,8 @@ namespace bts.daemons {
|
||||
|
||||
var fills_tl = fills_filtered.Select(
|
||||
f => new TradeLogRow(f, sc_data.sec_md_map[f.SecurityKey].security));
|
||||
var m_fills_tl = man_fills_filtered.Select(m => new TradeLogRow(
|
||||
m, sc_data.sec_md_map[m.SecurityKey].security, Fill.Types.FillKind.Standard));
|
||||
var m_fills_tl = man_fills_filtered.Select(
|
||||
m => new TradeLogRow(m, sc_data.sec_md_map[m.SecurityKey].security));
|
||||
var merged_fills = fills_tl.Concat(m_fills_tl).ToList();
|
||||
Log.Ui.info($"ReportDaemon posting {merged_fills.Count} trades");
|
||||
_bus.post(SparkTags.TradeLogTag, merged_fills);
|
||||
|
||||
@@ -5,8 +5,6 @@ using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
using bts.api.core;
|
||||
using bts.metrics;
|
||||
|
||||
using mbts;
|
||||
using mbts.config;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Linq;
|
||||
|
||||
Loaded 100 of 1292 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user