Compare commits
208
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
2c4bb25f5f | ||
|
|
56005accdc | ||
|
|
0bac9236b4 | ||
|
|
54c382dac9 | ||
|
|
9916fafedb | ||
|
|
8ffdc2f9ee | ||
|
|
7cbc0e44f6 | ||
|
|
9adc002c9b | ||
|
|
819fa629de | ||
|
|
d0b38fa172 | ||
|
|
07329061b1 | ||
|
|
5dc1b53267 | ||
|
|
0291b2a8b2 | ||
|
|
1ee4915fcd | ||
|
|
723e2d2268 | ||
|
|
5e296f76eb | ||
|
|
8e39b0b7ff | ||
|
|
1beb9460ba | ||
|
|
e00eae1129 | ||
|
|
95595c4cbf | ||
|
|
aad36a4972 | ||
|
|
cc03f47d70 | ||
|
|
5c5e5c23ef | ||
|
|
4b531a2a1a | ||
|
|
35530bec0b | ||
|
|
5853bb2436 | ||
|
|
bfdf45d30d | ||
|
|
a330bc5020 | ||
|
|
66f68ef3ec | ||
|
|
d6e651129b | ||
|
|
d4a59b8253 | ||
|
|
569f1460a4 | ||
|
|
2f369dbd57 | ||
|
|
444e486862 | ||
|
|
b42504d827 | ||
|
|
18ac85a454 | ||
|
|
788a1a06c5 | ||
|
|
787b485bce | ||
|
|
788df0e888 | ||
|
|
916532f7c5 | ||
|
|
3c511bb177 | ||
|
|
49f13755c6 | ||
|
|
dcb4b1ae7e | ||
|
|
2152b48fe2 | ||
|
|
b6f2f99f21 | ||
|
|
c44df8ec06 | ||
|
|
493f082d6d | ||
|
|
bbe76b2709 | ||
|
|
ce8eda24fc | ||
|
|
9f9113bf9a | ||
|
|
a199595938 | ||
|
|
83de5fac75 | ||
|
|
c688657d53 | ||
|
|
a5c62c66b1 | ||
|
|
6d595d18ee | ||
|
|
946e8f1c47 | ||
|
|
b765c3756d | ||
|
|
54dc7bf6c3 | ||
|
|
6142a08db6 | ||
|
|
ca59976e00 | ||
|
|
7f7a160916 | ||
|
|
c8eb51c303 | ||
|
|
4160233a58 | ||
|
|
c5f79f754b | ||
|
|
5f568d681a | ||
|
|
83a2147428 | ||
|
|
9dd2cee6d9 | ||
|
|
57365013bd | ||
|
|
3d55ef075b | ||
|
|
14da6461b1 | ||
|
|
e84d3df024 | ||
|
|
ed38fe0ce9 | ||
|
|
b5daee3bcf | ||
|
|
f5c8c29f5a | ||
|
|
89fa2eae50 | ||
|
|
41b8c9238c | ||
|
|
28b66306da | ||
|
|
0bdbc1897a | ||
|
|
c3d9443a89 | ||
|
|
400db13a78 | ||
|
|
1d7d5858d5 | ||
|
|
8792f24c5d | ||
|
|
76d35b16eb | ||
|
|
81f7fe72ab | ||
|
|
649ba11edb | ||
|
|
2fc6d7c262 | ||
|
|
45421eedce | ||
|
|
8ecb3118e4 | ||
|
|
3fdb10890d | ||
|
|
2a6224c88d | ||
|
|
8d6ddc8250 | ||
|
|
6cc8590a1c | ||
|
|
063d908775 | ||
|
|
93565f0ebf | ||
|
|
1d7fcf5d18 | ||
|
|
897d20f12f | ||
|
|
a928925252 | ||
|
|
4088affa15 | ||
|
|
7def6aacd2 | ||
|
|
94ae1780cd | ||
|
|
2c65c4376b | ||
|
|
68bb3dbfa1 | ||
|
|
82a73693a6 | ||
|
|
612cd4a4c8 | ||
|
|
b3828dfc53 | ||
|
|
01f26567ed | ||
|
|
90d21c9c15 | ||
|
|
6351c1340e | ||
|
|
18cdddf76d | ||
|
|
b14c8bb1ac | ||
|
|
ceff286120 | ||
|
|
59aa4677e8 | ||
|
|
996cd4c856 | ||
|
|
9287149c26 | ||
|
|
306b56a999 | ||
|
|
812cf0a43f | ||
|
|
2c539fd833 | ||
|
|
334295ed67 | ||
|
|
c157b9cdfd | ||
|
|
8280b7a815 | ||
|
|
fb7f982c65 | ||
|
|
75b50d93e8 | ||
|
|
865bdac9df | ||
|
|
ebe5f468d7 | ||
|
|
1bc8d886f4 | ||
|
|
38e352e0d3 | ||
|
|
f6079e7031 | ||
|
|
8c51488190 | ||
|
|
9aad08ada6 | ||
|
|
2d3d11ba59 | ||
|
|
6087953185 | ||
|
|
851654c8a5 | ||
|
|
57a4745e29 | ||
|
|
32cd00895e | ||
|
|
dee5f2684f | ||
|
|
f639a526cf | ||
|
|
d168d8712e | ||
|
|
78a9605383 | ||
|
|
a713b1018e | ||
|
|
9f626dd10c | ||
|
|
8ec7fdd60a | ||
|
|
ffb2245ae6 | ||
|
|
21051c9a0b | ||
|
|
1c8bd34144 | ||
|
|
f614fb7e7d | ||
|
|
b222cd3e55 | ||
|
|
4f2be64813 | ||
|
|
bfb73ffc5a | ||
|
|
9bb7025752 | ||
|
|
bbfbd0b691 | ||
|
|
5628e96a90 | ||
|
|
ef517b7554 | ||
|
|
ba06af327d | ||
|
|
b8b03172bc | ||
|
|
fb5c3c1e6e | ||
|
|
faaa7b11d4 | ||
|
|
92a0467e1e | ||
|
|
3bb2025ea2 | ||
|
|
f2730ff0d7 | ||
|
|
7fcff9e5b4 | ||
|
|
51f83f4880 | ||
|
|
88cb510aea | ||
|
|
452c642af0 | ||
|
|
3fafc5004e | ||
|
|
fd8e502140 | ||
|
|
b499a5c38b | ||
|
|
2320383b16 | ||
|
|
59b3e73330 | ||
|
|
9d9a1b86c4 | ||
|
|
21cc2cefbf | ||
|
|
904df4260d | ||
|
|
af785d5d0b | ||
|
|
1d796856ca | ||
|
|
35f0d5a53f | ||
|
|
2b2fdd2b94 | ||
|
|
9e4539a902 | ||
|
|
a76c8ffd98 | ||
|
|
d7474cb8da | ||
|
|
890a23a537 | ||
|
|
ab17eee260 | ||
|
|
8701fb7132 | ||
|
|
89fcb3092b | ||
|
|
c9856b96ae | ||
|
|
04477a4b7c | ||
|
|
99371a2ead | ||
|
|
70487a8ef7 | ||
|
|
44c419fdaf | ||
|
|
5eb151f9a0 | ||
|
|
855a939c51 | ||
|
|
7071d9b961 | ||
|
|
adf14491bc | ||
|
|
7e0e8f2801 | ||
|
|
4a37e2d6a6 | ||
|
|
12b2371a69 | ||
|
|
c19d173983 | ||
|
|
203164f372 | ||
|
|
6f69f1c2e2 | ||
|
|
ad1a585b5c | ||
|
|
f29e367ec7 | ||
|
|
18127383f0 | ||
|
|
b450c757c9 | ||
|
|
836683bcbe | ||
|
|
c271af30d8 | ||
|
|
31fab94208 | ||
|
|
a9b5067d7a | ||
|
|
7a31b025a2 | ||
|
|
31897a1b2e | ||
|
|
f93bc592cb |
No files matched your search
@@ -50,3 +50,5 @@ trace_data/
|
||||
*.tmp/*
|
||||
/.venv*/*
|
||||
.cache/
|
||||
src/web/api/tsconfig.*.g.json
|
||||
/.cpm_cache/**
|
||||
@@ -7,6 +7,3 @@
|
||||
[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
|
||||
+53
-49
@@ -1,4 +1,4 @@
|
||||
cmake_minimum_required(VERSION 3.5)
|
||||
cmake_minimum_required(VERSION 3.12)
|
||||
project(spark)
|
||||
|
||||
if(WIN32)
|
||||
@@ -7,7 +7,12 @@ else()
|
||||
set(platform "linux")
|
||||
endif()
|
||||
|
||||
set(EXTERNALS_ROOT "${CMAKE_SOURCE_DIR}/externals/${platform}")
|
||||
set(
|
||||
EXTERNALS_ROOT
|
||||
"${CMAKE_SOURCE_DIR}/externals/${platform}"
|
||||
CACHE
|
||||
STRING
|
||||
"External dependencies root folder (should contain folders: lib, bin, include")
|
||||
set(SPARK_PYTHON "${EXTERNALS_ROOT}/python")
|
||||
set(SPARK_BIN "${EXTERNALS_ROOT}/bin")
|
||||
set(SPARK_INCLUDE "${EXTERNALS_ROOT}/include")
|
||||
@@ -18,62 +23,61 @@ set(BUILD_WEB ON CACHE BOOL "Build the web server")
|
||||
include_directories(BEFORE SYSTEM ${SPARK_INCLUDE} ${EXTERNALS_ROOT}/include/zlib)
|
||||
link_directories(${SPARK_LIB})
|
||||
|
||||
if(WIN32)
|
||||
# flags
|
||||
set(
|
||||
CMAKE_CXX_FLAGS
|
||||
"${CMAKE_CXX_FLAGS} \
|
||||
/MP \
|
||||
/WX /wd4251 /wd4250 /wd4251 /wd4244 /wd4267 /wd4355 /wd4275 /wd4345 \
|
||||
/bigobj \
|
||||
/DCURL_STATICLIB \
|
||||
/D_WINSOCK_DEPRECATED_NO_WARNINGS \
|
||||
/D__TBB_NO_IMPLICIT_LINKAGE \
|
||||
/DBOOST_ALL_NO_LIB \
|
||||
/std:c++17 \
|
||||
/D_SCL_SECURE_NO_WARNINGS /D_CRT_SECURE_NO_WARNINGS /D_WIN32_WINNT=0x0600")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} /MTd")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} /MT")
|
||||
set(
|
||||
CMAKE_SHARED_LINKER_FLAGS_RELEASE
|
||||
"${CMAKE_SHARED_LINKER_FLAGS_RELEASE} \
|
||||
/DEBUG \
|
||||
/OPT:REF \
|
||||
/OPT:ICF \
|
||||
/LTCG")
|
||||
include(${CMAKE_SOURCE_DIR}/cmake/CPM.cmake)
|
||||
|
||||
# CPM packages
|
||||
CPMAddPackage("gh:nlohmann/json@3.11.2")
|
||||
CPMAddPackage("gh:fmtlib/fmt#8.1.1")
|
||||
CPMAddPackage("gh:ericniebler/range-v3#0.12.0")
|
||||
CPMAddPackage("gh:ReactiveX/RxCpp@4.1.1")
|
||||
CPMAddPackage("gh:google/double-conversion@3.2.1")
|
||||
CPMAddPackage("gh:cameron314/concurrentqueue@1.0.3")
|
||||
CPMAddPackage("gh:cameron314/readerwriterqueue@1.0.6")
|
||||
CPMAddPackage("gh:HowardHinnant/date@3.0.1")
|
||||
|
||||
# websocketpp
|
||||
CPMAddPackage("gh:zaphoyd/websocketpp#0.8.2")
|
||||
add_library(websocketpp INTERFACE)
|
||||
set_target_properties(websocketpp PROPERTIES CMAKE_CXX_FLAGS "-Wno-null-pointer-subtraction")
|
||||
|
||||
# abseil
|
||||
CPMAddPackage(
|
||||
NAME absl
|
||||
GITHUB_REPOSITORY abseil/abseil-cpp
|
||||
GIT_TAG 20220623.1
|
||||
DOWNLOAD_ONLY True
|
||||
)
|
||||
add_library(absl INTERFACE)
|
||||
|
||||
string(TOUPPER ${CMAKE_BUILD_TYPE} _build_type_u)
|
||||
# benchmark
|
||||
CPMAddPackage(
|
||||
NAME benchmark
|
||||
GITHUB_REPOSITORY google/benchmark
|
||||
VERSION 1.5.0
|
||||
OPTIONS
|
||||
"BENCHMARK_ENABLE_TESTING OFF"
|
||||
"CMAKE_CXX_FLAGS_${_build_type_u} -Wno-unused-but-set-variable -Wno-deprecated-declarations"
|
||||
"BENCHMARK_DOWNLOAD_DEPENDENCIES ON"
|
||||
"CMAKE_CXX_STANDARD 17"
|
||||
)
|
||||
|
||||
if(WIN32)
|
||||
# subdirs
|
||||
add_subdirectory(src/lib)
|
||||
else()
|
||||
# make sparkd look for libspark.so in its directory
|
||||
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
|
||||
set(CMAKE_INSTALL_RPATH ".")
|
||||
set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/install/${CMAKE_BUILD_TYPE}/sparkd")
|
||||
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
|
||||
set(
|
||||
CMAKE_CXX_FLAGS_DEBUG
|
||||
"${CMAKE_CXX_FLAGS_DEBUG} \
|
||||
-fPIC \
|
||||
-Wall \
|
||||
-pedantic \
|
||||
-Wextra \
|
||||
-Werror \
|
||||
-Wno-missing-braces \
|
||||
-Wno-ignored-qualifiers \
|
||||
--std=c++17 -fdiagnostics-color")
|
||||
set(CMAKE_CXX_FLAGS_RELEASE "${CMAKE_CXX_FLAGS_DEBUG} -fno-omit-frame-pointer -DNDEBUG -O3")
|
||||
set(CMAKE_CXX_FLAGS_DEBUG "${CMAKE_CXX_FLAGS_DEBUG} -DDEBUG")
|
||||
set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -Wno-undef")
|
||||
|
||||
# subdirs
|
||||
add_subdirectory(src/server/sparkd)
|
||||
add_dependencies(sparkd benchmark)
|
||||
add_subdirectory(src/lib)
|
||||
if (BUILD_WEB)
|
||||
add_dependencies(libspark benchmark)
|
||||
if(BUILD_WEB)
|
||||
add_subdirectory(src/web)
|
||||
endif()
|
||||
add_subdirectory(doc/user)
|
||||
@@ -90,9 +94,9 @@ else()
|
||||
COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/data_files ${CMAKE_BINARY_DIR}/server
|
||||
COMMAND ln ARGS -sf ${CMAKE_BINARY_DIR}/src/lib/libspark.so ${CMAKE_BINARY_DIR}/server
|
||||
COMMAND
|
||||
ln ARGS -sf
|
||||
${EXTERNALS_ROOT}/lib/Release/libOnixS.IceImpactMulticastPriceFeedHandlerCpp.so.3.16.0.0
|
||||
${CMAKE_BINARY_DIR}/server
|
||||
ln ARGS -sf
|
||||
${EXTERNALS_ROOT}/lib/Release/libOnixS.IceImpactMulticastPriceFeedHandlerCpp.so.3.16.0.0
|
||||
${CMAKE_BINARY_DIR}/server
|
||||
COMMAND ln ARGS -sf ${EXTERNALS_ROOT}/lib/Release/libACE-5.7.5.so ${CMAKE_BINARY_DIR}/server
|
||||
COMMAND mkdir ARGS -p ${CMAKE_BINARY_DIR}/server/plugins
|
||||
COMMENT "Creating server runtime layout"
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
{
|
||||
"version": 4,
|
||||
"cmakeMinimumRequired": {
|
||||
"major": 3,
|
||||
"minor": 23,
|
||||
"patch": 0
|
||||
},
|
||||
|
||||
"configurePresets": [
|
||||
{
|
||||
"name": "spark",
|
||||
"condition": {
|
||||
"type": "equals",
|
||||
"lhs": "${hostSystemName}",
|
||||
"rhs": "Windows"
|
||||
},
|
||||
"generator": "Visual Studio 17 2022",
|
||||
"binaryDir": "${sourceDir}/build",
|
||||
"cacheVariables": {
|
||||
"CMAKE_CXX_FLAGS": "/MP /WX /wd4250 /wd4251 /wd4244 /wd4267 /wd4355 /wd4275 /wd4345 /bigobj /EHsc /DCURL_STATICLIB /D_WINSOCK_DEPRECATED_NO_WARNINGS /D__TBB_NO_IMPLICIT_LINKAGE /DBOOST_ALL_NO_LIB /std:c++17 /D_SCL_SECURE_NO_WARNINGS /D_CRT_SECURE_NO_WARNINGS /D_WIN32_WINNT=0x0600",
|
||||
"CMAKE_CXX_FLAGS_DEBUG": "/MTd",
|
||||
"CMAKE_CXX_FLAGS_RELEASE": "/MT",
|
||||
"CMAKE_SHARED_LINKER_FLAGS_RELEASE": "/DEBUG /OPT:REF /OPT:ICF /LTCG",
|
||||
"EXTERNALS_ROOT": "${sourceDir}/externals/windows"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd",
|
||||
"condition": {
|
||||
"type": "equals",
|
||||
"lhs": "${hostSystemName}",
|
||||
"rhs": "Linux"
|
||||
},
|
||||
"hidden": true,
|
||||
"generator": "Ninja",
|
||||
"binaryDir": "${sourceDir}/build/${presetName}",
|
||||
"cacheVariables": {
|
||||
"platform": "",
|
||||
"CMAKE_BUILD_WITH_INSTALL_RPATH": {
|
||||
"type": "BOOL",
|
||||
"value": "ON"
|
||||
},
|
||||
"CMAKE_INSTALL_RPATH": ".",
|
||||
"CMAKE_INSTALL_PREFIX": "${sourceDir}/install/${presetName}/sparkd",
|
||||
"CMAKE_EXE_LINKER_FLAGS": "-Wno-undef",
|
||||
"CPM_SOURCE_CACHE": "${sourceDir}/.cpm_cache/",
|
||||
"EXTERNALS_ROOT": "${sourceDir}/externals/linux",
|
||||
"CMAKE_CXX_STANDARD": "17",
|
||||
"WEB_TSCONFIG_NAME": "${presetName}",
|
||||
"BUILD_SDK": {
|
||||
"type": "BOOL",
|
||||
"value": "OFF"
|
||||
},
|
||||
"BUILD_WEB": {
|
||||
"type": "BOOL",
|
||||
"value": "ON"
|
||||
}
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-dev-clang",
|
||||
"inherits": "sparkd",
|
||||
"displayName": "Development (clang)",
|
||||
"description": "Debug build compiled w/ clang",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": {
|
||||
"type": "BOOL",
|
||||
"value": "ON"
|
||||
},
|
||||
"CMAKE_C_COMPILER": "clang",
|
||||
"CMAKE_CXX_COMPILER": "clang++",
|
||||
"CMAKE_CXX_FLAGS_DEBUG": "-fPIC -Wall -pedantic -Wextra -Werror -Wno-missing-braces -Wno-deprecated-builtins -Wno-array-parameter -Wno-ignored-qualifiers --std=c++17 -fdiagnostics-color"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-dev-gcc",
|
||||
"inherits": "sparkd",
|
||||
"displayName": "Development (gcc)",
|
||||
"description": "Debug build compiled w/ gcc",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Debug",
|
||||
"CMAKE_EXPORT_COMPILE_COMMANDS": {
|
||||
"type": "BOOL",
|
||||
"value": "ON"
|
||||
},
|
||||
"CMAKE_C_COMPILER": "gcc",
|
||||
"CMAKE_CXX_COMPILER": "g++",
|
||||
"CMAKE_CXX_FLAGS_DEBUG": "-fPIC -Wall -pedantic -Wextra -Werror -Wno-missing-braces -Wno-ignored-qualifiers --std=c++17 -fdiagnostics-color -Wno-stringop-overread -DDEBUG"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-prod-clang",
|
||||
"inherits": "sparkd",
|
||||
"displayName": "Production (clang)",
|
||||
"description": "Release build compiled w/ clang",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"CMAKE_C_COMPILER": "clang",
|
||||
"CMAKE_CXX_COMPILER": "clang++",
|
||||
"CMAKE_CXX_FLAGS_RELEASE": "-fPIC -Wall -pedantic -Wextra -Werror -Wno-missing-braces -Wno-ignored-qualifiers --std=c++17 -fdiagnostics-color -fno-omit-frame-pointer -DNDEBUG -O3"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-prod-gcc",
|
||||
"inherits": "sparkd",
|
||||
"displayName": "Production (gcc)",
|
||||
"description": "Release build compiled w/ gcc",
|
||||
"cacheVariables": {
|
||||
"CMAKE_BUILD_TYPE": "Release",
|
||||
"CMAKE_C_COMPILER": "gcc",
|
||||
"CMAKE_CXX_COMPILER": "g++",
|
||||
"CMAKE_CXX_FLAGS_RELEASE": "-fPIC -Wall -pedantic -Wextra -Werror -Wno-missing-braces -Wno-ignored-qualifiers --std=c++17 -fdiagnostics-color -Wno-stringop-overread -fno-omit-frame-pointer -DNDEBUG -O3"
|
||||
}
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-publish",
|
||||
"inherits": "sparkd",
|
||||
"displayName": "Publish",
|
||||
"description": "Publish build compiled w/ gcc and ready to ship",
|
||||
"cacheVariables": {
|
||||
"CMAKE_CXX_COMPILER": "g++"
|
||||
}
|
||||
}
|
||||
],
|
||||
|
||||
"buildPresets": [
|
||||
{
|
||||
"name": "spark",
|
||||
"condition": {
|
||||
"type": "equals",
|
||||
"lhs": "${hostSystemName}",
|
||||
"rhs": "Windows"
|
||||
},
|
||||
"hidden": true,
|
||||
"jobs": 4
|
||||
},
|
||||
|
||||
{
|
||||
"name": "spark-dev",
|
||||
"displayName": "Development",
|
||||
"inherits": "spark",
|
||||
"configurePreset": "spark",
|
||||
"configuration": "Debug"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "spark-prod",
|
||||
"displayName": "Production",
|
||||
"inherits": "spark",
|
||||
"configurePreset": "spark",
|
||||
"configuration": "Release"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd",
|
||||
"condition": {
|
||||
"type": "equals",
|
||||
"lhs": "${hostSystemName}",
|
||||
"rhs": "Linux"
|
||||
},
|
||||
"hidden": true,
|
||||
"jobs": 4,
|
||||
"targets": [
|
||||
"data_files_dir",
|
||||
"doc_manual_bundle",
|
||||
"install",
|
||||
"libspark",
|
||||
"rapidjson_project",
|
||||
"server_layout",
|
||||
"sparkd",
|
||||
"web_ui_bundle"
|
||||
]
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-dev-clang",
|
||||
"configurePreset": "sparkd-dev-clang",
|
||||
"displayName": "Development (clang)",
|
||||
"inherits": "sparkd"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-dev-gcc",
|
||||
"configurePreset": "sparkd-dev-gcc",
|
||||
"displayName": "Development (gcc)",
|
||||
"inherits": "sparkd"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-prod-clang",
|
||||
"configurePreset": "sparkd-prod-clang",
|
||||
"displayName": "Production (clang)",
|
||||
"inherits": "sparkd"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-prod-gcc",
|
||||
"configurePreset": "sparkd-prod-gcc",
|
||||
"displayName": "Production (gcc)",
|
||||
"inherits": "sparkd"
|
||||
},
|
||||
|
||||
{
|
||||
"name": "sparkd-publish",
|
||||
"configurePreset": "sparkd-publish",
|
||||
"displayName": "Publish",
|
||||
"inherits": "sparkd",
|
||||
"targets": "install"
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
# CPM Code (https://github.com/cpm-cmake/CPM.cmake/releases/latest/download/get_cpm.cmake)
|
||||
set(CPM_DOWNLOAD_VERSION 0.36.0)
|
||||
|
||||
if(CPM_SOURCE_CACHE)
|
||||
set(CPM_DOWNLOAD_LOCATION "${CPM_SOURCE_CACHE}/cpm/CPM_${CPM_DOWNLOAD_VERSION}.cmake")
|
||||
elseif(DEFINED ENV{CPM_SOURCE_CACHE})
|
||||
set(CPM_DOWNLOAD_LOCATION "$ENV{CPM_SOURCE_CACHE}/cpm/CPM_${CPM_DOWNLOAD_VERSION}.cmake")
|
||||
else()
|
||||
set(CPM_DOWNLOAD_LOCATION "${CMAKE_BINARY_DIR}/cmake/CPM_${CPM_DOWNLOAD_VERSION}.cmake")
|
||||
endif()
|
||||
|
||||
# Expand relative path. This is important if the provided path contains a tilde (~)
|
||||
get_filename_component(CPM_DOWNLOAD_LOCATION ${CPM_DOWNLOAD_LOCATION} ABSOLUTE)
|
||||
|
||||
if(NOT(EXISTS ${CPM_DOWNLOAD_LOCATION}))
|
||||
message(STATUS "Downloading CPM.cmake to ${CPM_DOWNLOAD_LOCATION}")
|
||||
file(DOWNLOAD
|
||||
https://github.com/cpm-cmake/CPM.cmake/releases/download/v${CPM_DOWNLOAD_VERSION}/CPM.cmake
|
||||
${CPM_DOWNLOAD_LOCATION}
|
||||
)
|
||||
endif()
|
||||
|
||||
include(${CPM_DOWNLOAD_LOCATION})
|
||||
@@ -106,8 +106,9 @@ 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
|
||||
"PYTHONPATH=${SPARK_PYTHON}" ${Protobuf_PROTOC_EXECUTABLE} ARGS
|
||||
COMMAND ${CMAKE_SOURCE_DIR}/tools/venv_exec.sh
|
||||
ARGS
|
||||
${Protobuf_PROTOC_EXECUTABLE}
|
||||
--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,6 +46,7 @@ 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 \) \)
|
||||
@@ -59,6 +60,7 @@ 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
|
||||
@@ -85,7 +87,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_CXX_COMPILER=$compiler_arg $repo_root
|
||||
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
|
||||
end
|
||||
|
||||
# The while loop below removes arguments (via shift) as it parses them.
|
||||
|
||||
+1
-1
Submodule docker/linux updated: 05967d0f18...56c61231f3.
+1
-1
Submodule externals updated: 99c440f568...38322377cf.
@@ -12,6 +12,7 @@ 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
|
||||
@@ -52,8 +52,7 @@
|
||||
<Exec Command="set PYTHONPATH=$(SparkRoot)\.venv\Scripts\python" />
|
||||
<Exec
|
||||
Command="
|
||||
$(SparkRoot)\tools\build_protos.cmd ^
|
||||
%(Proto3.FullPath) ^
|
||||
$(protoc) %* %(Proto3.FullPath) ^
|
||||
--error_format=msvs ^
|
||||
--proto_path=$(SourceRoot) ^
|
||||
--plugin="protoc-gen-service=$(ProtocPluginBase)\plugin.cmd" ^
|
||||
|
||||
@@ -17,6 +17,7 @@ namespace mbts.spark {
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
@@ -106,8 +107,8 @@ namespace mbts.spark {
|
||||
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,9 +197,15 @@ 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)) {
|
||||
|
||||
@@ -7,6 +7,8 @@ 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;
|
||||
|
||||
@@ -5,6 +5,8 @@ namespace mbts.spark {
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows;
|
||||
|
||||
@@ -6,6 +6,8 @@ namespace mbts.spark {
|
||||
|
||||
using mbts.analytics;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -40,6 +42,12 @@ 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();
|
||||
|
||||
@@ -145,6 +145,58 @@ namespace mbts.spark {
|
||||
_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() {
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@ 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)
|
||||
@@ -68,19 +70,14 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
private void _log_theos(SystemContractData sc_data,
|
||||
IReadOnlyDictionary<uint, GreeksTuple> greeks_map,
|
||||
DateTime? exp_filt = null) {
|
||||
IReadOnlyDictionary<uint, GreeksTuple> greeks_map) {
|
||||
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)) {
|
||||
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}";
|
||||
}
|
||||
string sec_str = smd.ToString();
|
||||
rv += "\n" + $"id: {id} sec: {sec_str} greeks: {g_tup}";
|
||||
}
|
||||
}
|
||||
bts.Log.Gen.info(rv);
|
||||
@@ -134,6 +131,7 @@ 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;
|
||||
@@ -142,26 +140,59 @@ 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));
|
||||
tp.cvega, tp.c_theta, Double.NaN, normalized_theo));
|
||||
}
|
||||
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));
|
||||
tp.pvega, tp.p_theta, Double.NaN, normalized_theo));
|
||||
}
|
||||
}
|
||||
}
|
||||
// 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)
|
||||
|
||||
@@ -107,6 +107,22 @@ 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);
|
||||
@@ -242,5 +258,12 @@ 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);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,10 @@ 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;
|
||||
@@ -51,7 +55,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.Where(add => !vs_removes.Contains(add.ToVSExp()));
|
||||
var true_added = added.Except(vs_removes.Concat(_hidden_exps), v => v.ToVSExp());
|
||||
var changed_calc_modes = added.Where(add => vs_removes.Contains(add.ToVSExp()));
|
||||
|
||||
foreach (var tr in true_removed) {
|
||||
@@ -61,16 +65,10 @@ namespace mbts.spark {
|
||||
}
|
||||
}
|
||||
|
||||
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>());
|
||||
}
|
||||
var comp = ComparerWrapper<object>.wrap_cast(
|
||||
NullCheckComparer.create<IExpirationBasedRow>(
|
||||
(r1, r2) => r1.expiration.CompareTo(r2.expiration)));
|
||||
visible_rows.InsertSorted(true_added, comp);
|
||||
|
||||
foreach (var ccm in changed_calc_modes) {
|
||||
int index = visible_rows
|
||||
|
||||
@@ -10,6 +10,8 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
@@ -115,7 +117,7 @@ namespace mbts.spark {
|
||||
})
|
||||
.BufferLatest(TimeSpan.FromSeconds(0.1))
|
||||
.OnDispatcher()
|
||||
.SelectManyInSeries(series => Observable.Create<SeriesVM>(o => {
|
||||
.SelectSeries(series => Observable.Create<SeriesVM>(o => {
|
||||
o.OnNext(null);
|
||||
return Disposable.Create(series
|
||||
.Select(svm => svm.points.Subscribe((s, e) => o.OnNext(svm)))
|
||||
|
||||
@@ -13,6 +13,8 @@ namespace mbts.spark.VolSurface {
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -75,7 +77,7 @@ namespace mbts.spark.VolSurface {
|
||||
Disposable.Create(() => {
|
||||
this.model.on_candidate_grid_change -= _on_grid_updated;
|
||||
this.model.on_committed_grid_change -= _on_grid_updated;
|
||||
Disposable.dispose(rows);
|
||||
rows.DisposeAll(true);
|
||||
Disposable.dispose(ref _shift_editor);
|
||||
}),
|
||||
_columns_model);
|
||||
@@ -347,7 +349,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);
|
||||
|
||||
@@ -8,6 +8,8 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace mbts.spark.VolSurface {
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -9,6 +9,7 @@ namespace mbts.spark {
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
using System;
|
||||
@@ -539,7 +540,7 @@ namespace mbts.spark {
|
||||
public ObservableCollection<VSSymbol> symbols { get; private set; }
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(symbols);
|
||||
symbols.DisposeAll(true);
|
||||
}
|
||||
|
||||
public class VSSymbolStructureVM : DisposableViewModelBase {
|
||||
@@ -550,11 +551,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 = new DisposableCombo(
|
||||
_dispose = Disposable.Create(
|
||||
driver_grids.Subscribe((s, e) =>
|
||||
selected_driver_grid ??= driver_grids.FirstOrDefault()),
|
||||
bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(on_exp_params_input)) +
|
||||
new Action(() => Disposable.dispose(driver_grids));
|
||||
bus.subscribe(SparkTags.ExpirationParametersInputTag).OnDispatcher().Subscribe(on_exp_params_input),
|
||||
Disposable.Create(() => driver_grids.DisposeAll(true)));
|
||||
|
||||
void on_exp_params_input(AnalyticsExpirationParametersMap data) {
|
||||
var driver_map = data.get_option_driver_map();
|
||||
|
||||
@@ -10,6 +10,7 @@ namespace mbts.spark {
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
|
||||
@@ -8,6 +8,7 @@
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -5,6 +5,7 @@
|
||||
using mbts.analytics;
|
||||
using mbts.ui.controls;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
using System;
|
||||
|
||||
@@ -172,6 +172,18 @@ 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() {
|
||||
|
||||
@@ -5,6 +5,8 @@ using bts.api.core;
|
||||
using bts.collections;
|
||||
using bts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
@@ -41,7 +43,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.TryFirst())
|
||||
.Select(u => u.all.FirstOrNull())
|
||||
.Where(ad => ad.HasValue)
|
||||
.Select(ad => ad.Value.Users
|
||||
.Where(u => user.can_access_user_data(u.Id))
|
||||
@@ -78,7 +80,7 @@ namespace mbts.spark {
|
||||
}));
|
||||
|
||||
public AccountTuple? get_default_account() =>
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).TryFirst();
|
||||
_account_map.Select(kv => new AccountTuple(kv.Key, kv.Value)).FirstOrNull();
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(ref _dispose);
|
||||
|
||||
@@ -10,7 +10,8 @@ namespace mbts.analytics {
|
||||
double gamma = double.NaN,
|
||||
double vega = double.NaN,
|
||||
double theta = double.NaN,
|
||||
double rho = double.NaN) {
|
||||
double rho = double.NaN,
|
||||
double normalized_theo = double.NaN) {
|
||||
this.vol = vol;
|
||||
this.driver = driver;
|
||||
this.theo = theo;
|
||||
@@ -19,6 +20,7 @@ namespace mbts.analytics {
|
||||
this.vega = vega;
|
||||
this.theta = theta;
|
||||
this.rho = rho;
|
||||
this.normalized_theo = normalized_theo;
|
||||
}
|
||||
|
||||
public static GreeksTuple empty => new();
|
||||
@@ -31,6 +33,7 @@ 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) &&
|
||||
@@ -65,7 +68,8 @@ namespace mbts.analytics {
|
||||
double? gamma = null,
|
||||
double? vega = null,
|
||||
double? theta = null,
|
||||
double? rho = null) =>
|
||||
double? rho = null,
|
||||
double? normalized_theo = null) =>
|
||||
new(
|
||||
vol ?? greeks_tuple.vol,
|
||||
driver ?? greeks_tuple.driver,
|
||||
@@ -74,12 +78,7 @@ namespace mbts.analytics {
|
||||
gamma ?? greeks_tuple.gamma,
|
||||
vega ?? greeks_tuple.vega,
|
||||
theta ?? greeks_tuple.theta,
|
||||
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;
|
||||
rho ?? greeks_tuple.rho,
|
||||
normalized_theo ?? greeks_tuple.normalized_theo);
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,7 @@ namespace mbts {
|
||||
|
||||
using ProtoBuf;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Protobuf;
|
||||
|
||||
@@ -100,17 +101,13 @@ namespace mbts {
|
||||
|
||||
public static IComparer<SecurityExpiration> get_comparer(Properties prop) {
|
||||
return prop switch {
|
||||
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(),
|
||||
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),
|
||||
_ => 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) =>
|
||||
|
||||
@@ -943,7 +943,15 @@ namespace mbts.analytics {
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
#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
|
||||
|
||||
#region Other Pricing Utilities
|
||||
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
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,17 +8,16 @@ 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 {
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
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,6 +7,8 @@ using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -11,6 +11,7 @@ using System.Reactive.Linq;
|
||||
|
||||
using SecurityKey = System.UInt32;
|
||||
using MDHandle = mbts.co2.FakeMDConsumerHandle;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
namespace bts {
|
||||
//[Export(typeof(IShellDaemon))]
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace bts.daemons {
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
@@ -17,7 +19,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;
|
||||
|
||||
@@ -8,15 +8,14 @@ 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 {
|
||||
@@ -39,13 +38,14 @@ 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 => 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)))));
|
||||
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())));
|
||||
}
|
||||
|
||||
Window _view_factory() {
|
||||
|
||||
@@ -14,6 +14,7 @@ namespace bts {
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
@@ -142,6 +143,6 @@ namespace bts {
|
||||
}
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(_resources);
|
||||
_resources.DisposeAll(true);
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ using BCG;
|
||||
|
||||
using bts.api;
|
||||
using bts.api.synthetic;
|
||||
using bts.collections;
|
||||
using bts.md;
|
||||
using bts.utils;
|
||||
|
||||
@@ -10,6 +11,8 @@ using mbts.co2;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
@@ -27,16 +30,22 @@ 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;
|
||||
_bus.subscribe(SparkTags.ServerSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_server_sec_map(d));
|
||||
_bus.subscribe(SparkTags.FakeSecuritiesTag).OnDispatcher().Subscribe(
|
||||
d => _on_fake_sec_map(d));
|
||||
_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()));
|
||||
}
|
||||
|
||||
private void _log_options(IReadOnlyDictionary<uint, SecurityMD> sec_map) {
|
||||
@@ -54,33 +63,27 @@ 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()));
|
||||
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) => {
|
||||
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 sec = sec_md.security;
|
||||
return SecurityExpirationHelper.is_unexpired(sec);
|
||||
};
|
||||
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,10 +2,11 @@
|
||||
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,6 +10,8 @@ using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
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,6 +2,8 @@
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -13,6 +13,7 @@ namespace bts.daemons {
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
@@ -33,7 +34,7 @@ namespace bts.daemons {
|
||||
|
||||
IReadOnlyDictionary<int, ReportImmutable> _report_parameters_map =
|
||||
new Dictionary<int, ReportImmutable>();
|
||||
IDisposable _dispose;
|
||||
IDisposable? _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
public ReportDaemon(
|
||||
|
||||
@@ -5,6 +5,8 @@ using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Composition;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
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;
|
||||
|
||||
@@ -60,6 +60,7 @@ namespace mbts.ui {
|
||||
LetterDKey = nameof(LetterDKey),
|
||||
MenuOrientationGeometryKey = nameof(MenuOrientationGeometryKey),
|
||||
OrdersGeometryKey = nameof(OrdersGeometryKey),
|
||||
PaperPlaneGeometryKey = nameof(PaperPlaneGeometryKey),
|
||||
PauseGeometryKey = nameof(PauseGeometryKey),
|
||||
PaymentGeometryKey = nameof(PaymentGeometryKey),
|
||||
PencilGeometryKey = nameof(PencilGeometryKey),
|
||||
@@ -230,8 +231,12 @@ namespace mbts.ui {
|
||||
public static ImageSource Import => load_resource_and_freeze("Import");
|
||||
public static ImageSource Key => create_icon(KeyGeometryKey);
|
||||
public static ImageSource Knight { get { return load_resource_and_freeze("Knight"); } }
|
||||
public static ImageSource manual_fills => create_icon(DataEditGeometryKey);
|
||||
public static ImageSource MenuOrientation => create_icon(MenuOrientationGeometryKey);
|
||||
public static ImageSource open_orders => Book;
|
||||
public static ImageSource options_view => Sheets;
|
||||
public static ImageSource paper_plane => create_icon(
|
||||
PaperPlaneGeometryKey, null, new(Brushes.Black, 2));
|
||||
public static ImageSource Pause => create_icon(PauseGeometryKey);
|
||||
public static ImageSource Payment => create_icon(PaymentGeometryKey);
|
||||
public static ImageSource Pencil => create_icon(PencilGeometryKey);
|
||||
@@ -242,6 +247,7 @@ namespace mbts.ui {
|
||||
public static ImageSource RecurringScheduleGray => create_icon(RecurringScheduleGeometryKey, Brushes.Gray);
|
||||
public static ImageSource RubberStamp => create_icon(RubberStampGeometryKey);
|
||||
public static ImageSource RedoCircular => create_icon(UndoCircularGeometryKey, Brushes.Black, null, new ScaleTransform(-1, 1));
|
||||
public static ImageSource rfq => paper_plane;
|
||||
public static ImageSource Spawn { get { return load_resource_and_freeze("Spawn"); } }
|
||||
public static ImageSource Speaker => create_icon(SpeakerGeometryKey);
|
||||
public static ImageSource Star => create_icon(StarGeometryKey);
|
||||
|
||||
@@ -325,6 +325,18 @@
|
||||
M50.14375,33.389126C50.416863,33.394688,50.653496,33.587773,50.705998,33.864617L50.015995,45.114388C49.810295,46.291462,49.130394,45.097489,49.130394,45.097489L47.65659,42.640538C42.747776,49.635197 34.633152,54.221001 25.433924,54.221001 14.884193,54.221001 5.7437552,48.204125 1.2449617,39.419205 0.80087067,38.552021 0.21358696,37.705738 0.052086769,36.736958 -0.49735315,33.490925 3.4507786,32.901036 4.8049124,34.432404 5.3674143,35.067692 6.034036,36.16407 6.5079177,37.026051 10.106778,43.799416 17.2321,48.413819 25.433924,48.413819 32.656544,48.413819 39.026364,44.826695 42.903977,39.351506L40.229367,38.854115C40.229367,38.854115,38.677464,38.647118,39.742466,37.996033L50.024895,33.398526C50.064972,33.391365,50.104733,33.388333,50.14375,33.389126z M23.030291,9.0310004L27.889918,9.0310004 27.889918,13.028299C30.539786,13.205498,32.324932,13.958096,33.464161,14.528294L33.964176,14.775793 32.417435,20.038878 31.706417,19.68068C30.579987,19.11958 28.839241,18.244583 26.149073,18.244583 24.006916,18.244583 22.723183,19.122181 22.723183,20.590876 22.723183,21.894272 23.943314,22.804369 27.551308,24.187165 32.706444,26.124659 34.911,28.702853 34.911,32.817341 34.911,36.892929 32.090527,40.05172 27.673611,40.989117L27.673611,45.540001 22.767485,45.540001 22.767485,41.330414C20.252919,41.155815,17.695551,40.424118,16.101811,39.404721L15.683999,39.137619 17.221739,33.731438 17.969059,34.180634C19.088988,34.851235 21.402748,35.97873 24.340325,35.97873 26.734886,35.97873 28.276728,34.921635 28.276728,33.291336 28.276728,31.986641 27.547409,30.853846 23.986016,29.57255 20.083815,28.144253 16.095511,26.04406 16.095511,21.239174 16.095511,17.280985 18.737379,14.291395 23.030291,13.329098z M25.268765,0C35.819447,2.7347414E-07 44.961449,6.0155495 49.458798,14.804573 49.902695,15.669173 50.490094,16.516972 50.651287,17.48427 51.198281,20.734265 47.255726,21.318962 45.901341,19.789065 45.336346,19.153567 44.669552,18.051968 44.19566,17.19517 40.5957,10.421881 33.473275,5.8072398 25.268765,5.8072393 18.047545,5.8072398 11.678013,9.3918336 7.8003562,14.867073L10.474627,15.367072C10.474627,15.367072,12.026909,15.574172,10.962921,16.223872L0.67933281,20.826762C0.36037083,20.880062,0.057029126,20.669165,0.00099972012,20.354063L0.69093342,9.1118043C0.89552094,7.9296158,1.5738537,9.124924,1.5738539,9.124924L3.0452772,11.583379C7.9566038,4.584462,16.073666,2.7347414E-07,25.268765,0z
|
||||
</sys:String>
|
||||
|
||||
<!-- Paper Plane (the icon is free to use if we include this information in our credit section)
|
||||
Icon by <a href="https://freeicons.io/profile/2257">www.wishforge.games</a> on <a href="https://freeicons.io">freeicons.io</a>
|
||||
-->
|
||||
<x:Array x:Key="{x:Static mbts:Icons.PaperPlaneGeometryKey}" Type="sys:String">
|
||||
<sys:String>
|
||||
M26.4,2.9L3.8,15c-0.7,0.4-0.7,1.5,0.1,1.8l20.8,8.7c0.6,0.3,1.3-0.2,1.4-0.8l1.7-20.8 C27.9,3,27.1,2.5,26.4,2.9z
|
||||
</sys:String>
|
||||
<sys:String>
|
||||
M26,4L13,20v7.3c0,0.9,1.2,1.4,1.8,0.7L19,23
|
||||
</sys:String>
|
||||
</x:Array>
|
||||
|
||||
<sys:String x:Key="{x:Static mbts:Icons.PauseGeometryKey}">
|
||||
M17.94,0L29.150001,0 29.150001,32 17.94,32z M0,0L11.210002,0 11.210002,32 0,32z
|
||||
</sys:String>
|
||||
|
||||
@@ -4,6 +4,7 @@
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
using System;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
#nullable enable
|
||||
namespace Spark.Model {
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.co2;
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Core;
|
||||
|
||||
using System.Composition;
|
||||
|
||||
class SecurityResolverExporter : VirtualSingleton<SecurityResolverExporter> {
|
||||
readonly LazyOnce<SecurityResolver>? _resolver;
|
||||
|
||||
[ImportingConstructor]
|
||||
public SecurityResolverExporter(IBus bus, MarketDataRelay md_relay) =>
|
||||
_resolver = new(() => new(md_relay, bus.subscribe(SparkTags.SecuritiesTag)));
|
||||
|
||||
[Export]
|
||||
public SecurityResolver resolver =>
|
||||
Log.notnull(_resolver);
|
||||
}
|
||||
}
|
||||
@@ -22,6 +22,7 @@ namespace bts.settings {
|
||||
interface ISyntheticManagementMigrationRule : ISettingsMigrationRule<GridSettings> { }
|
||||
interface IReconcileReportMigrationRule : ISettingsMigrationRule<GridSettings> { }
|
||||
interface IDayFillsGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
|
||||
interface IOpenOrdersGridSettingsMigrationRule : ISettingsMigrationRule<GridSettings> { }
|
||||
|
||||
static class SettingsMigrationHelper {
|
||||
public static bool apply<T>(T settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, out T new_settings) {
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
using mbts.spark;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
@@ -87,7 +89,8 @@ namespace mbts.persist {
|
||||
public IWindowSettingsManagerNonShared<T> as_non_shared() =>
|
||||
new NonSharedWrapper(_wsm);
|
||||
|
||||
public void Dispose() => Disposable.dispose(ref _dispose);
|
||||
public void Dispose() =>
|
||||
Disposable.dispose(ref _dispose);
|
||||
}
|
||||
|
||||
public class DisconnectedImpl : IWindowSettingsManager<T> {
|
||||
|
||||
@@ -1,239 +1,248 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts.shell;
|
||||
using bts.shell.fills;
|
||||
using bts.shell.market_view;
|
||||
using bts.shell.orderbook;
|
||||
using bts.shell.pnl;
|
||||
using bts.shell.time_and_sales;
|
||||
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
|
||||
using mbts.ui.settings;
|
||||
|
||||
using ProtoBuf;
|
||||
|
||||
using Spark.Trading;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
interface IDefaultableSettings {
|
||||
bool use_defaults { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings Mothership. All window - and any other future user based - settings should have a corresponding default member here.
|
||||
/// </summary>
|
||||
[ProtoContract]
|
||||
class UserSettings {
|
||||
public static UserSettings factory_defaults =>
|
||||
new() {
|
||||
_ladder = LadderSettings.Default,
|
||||
_notification = NotificationSettings.Default,
|
||||
_market_view_grid = MarketViewSettings.DefaultGridSettings,
|
||||
_fills_grid = FillsSettings.DefaultGridSettings,
|
||||
_time_and_sales_grid = TimeAndSalesSettings.DefaultGridSettings,
|
||||
_synthetic_management = SyntheticManagementSettings.default_grid_settings,
|
||||
_reconcile_report = ReconcileReportSettings.Default().grid,
|
||||
_order_book = OrderBookStartupData.DefaultGrid
|
||||
};
|
||||
|
||||
[ProtoMember(1)]
|
||||
LadderSettings? _ladder;
|
||||
[ProtoMember(11)]
|
||||
LadderSettingsProfile[]? _ladder_profiles;
|
||||
/// When Profiles Are Deleted, ladders that were using that profile shall copy the profile's settings to a local profile.
|
||||
/// Therefor:
|
||||
/// Deleted profile ids must never be reused.
|
||||
/// If they were reused, consider an unloaded workspace with ladders that were using the deleted profile.
|
||||
/// If such a workspace was reloaded after a new profile was saved with the deleted one's id, the ladders using that deleted profile would suddenly be using the new profile.
|
||||
/// To Prevent IDs From Being Recycled:
|
||||
/// The last profile id is stored in the protobuf (<see cref="_last_ladder_profile_id"/>).
|
||||
/// Anytime a profile is added, it shall use <see cref="next_ladder_profile_id"/>.
|
||||
[ProtoMember(12)]
|
||||
uint _last_ladder_profile_id;
|
||||
// removing NotificationSettings these from proto-serialization, since they are disabled by default for now.
|
||||
// This way, when they are enabled, there won't be any backwards compatability issues to worry about, as no clients will have persisted them yet.
|
||||
NotificationSettings? _notification;
|
||||
|
||||
[ProtoMember(5)]
|
||||
GridSettings? _market_view_grid;
|
||||
[ProtoMember(6)]
|
||||
GridSettings? _time_and_sales_grid;
|
||||
[ProtoMember(7)]
|
||||
GridSettings? _fills_grid;
|
||||
[ProtoMember(15)]
|
||||
GridSettings? _day_fills_grid;
|
||||
[ProtoMember(8)]
|
||||
GridSettings? _synthetic_management;
|
||||
[ProtoMember(14)]
|
||||
GridSettings? _reconcile_report;
|
||||
[ProtoMember(9)]
|
||||
OrderBookGridSettings? _order_book;
|
||||
[ProtoMember(10)]
|
||||
PNLSettings? _pnl;
|
||||
[ProtoMember(13)]
|
||||
GlobalAlertSettings? _alerts;
|
||||
|
||||
public UserSettings() { }
|
||||
|
||||
public LadderSettings ladder =>
|
||||
_ladder ??= LadderSettings.Default;
|
||||
|
||||
public IReadOnlyList<LadderSettingsProfile> ladder_profiles =>
|
||||
_ladder_profiles ?? Array.Empty<LadderSettingsProfile>();
|
||||
|
||||
public uint next_ladder_profile_id =>
|
||||
_last_ladder_profile_id + 1;
|
||||
|
||||
public NotificationSettings notification =>
|
||||
_notification ??= NotificationSettings.Default;
|
||||
|
||||
public GridSettings market_view_grid =>
|
||||
_market_view_grid ??= MarketViewSettings.DefaultGridSettings;
|
||||
|
||||
public GridSettings time_and_sales_grid =>
|
||||
_time_and_sales_grid ??= GridSettings.Default.with(
|
||||
TimeAndSalesSettings.DefaultColumns.all);
|
||||
|
||||
public GridSettings fills_grid =>
|
||||
_fills_grid ??= FillsSettings.DefaultGridSettings;
|
||||
|
||||
public GridSettings day_fills_grid =>
|
||||
_day_fills_grid ??= DayFillsSettings.default_grid();
|
||||
|
||||
public GridSettings synthetic_management_grid =>
|
||||
_synthetic_management ??=
|
||||
SyntheticManagementSettings.default_grid_settings;
|
||||
|
||||
public GridSettings reconcile_report_grid =>
|
||||
_reconcile_report ??= ReconcileReportSettings.Default().grid ??
|
||||
throw new InvalidOperationException();
|
||||
|
||||
public PNLSettings pnl =>
|
||||
_pnl ??= PNLSettings.Default;
|
||||
|
||||
public OrderBookGridSettings order_book_grid =>
|
||||
_order_book ??= OrderBookStartupData.Default.grid_settings_wrapper();
|
||||
|
||||
public GlobalAlertSettings alerts =>
|
||||
_alerts ??= new GlobalAlertSettings();
|
||||
|
||||
public UserSettings with(
|
||||
LadderSettings? ladder = null,
|
||||
LadderSettingsProfile[]? ladder_profiles = null,
|
||||
NotificationSettings? notification = null,
|
||||
GridSettings? market_view = null,
|
||||
GridSettings? time_and_sales = null,
|
||||
GridSettings? fills = null,
|
||||
GridSettings? day_fills = null,
|
||||
GridSettings? synthetic_management = null,
|
||||
GridSettings? reconcile_report = null,
|
||||
PNLSettings? pnl = null,
|
||||
OrderBookGridSettings? order_book_grid = null,
|
||||
GlobalAlertSettings? alerts = null) {
|
||||
var us = new UserSettings() {
|
||||
_ladder_profiles = ladder_profiles ?? _ladder_profiles,
|
||||
_ladder = ladder ?? _ladder,
|
||||
_notification = notification ?? _notification,
|
||||
_market_view_grid = market_view ?? _market_view_grid,
|
||||
_time_and_sales_grid = time_and_sales ?? _time_and_sales_grid,
|
||||
_fills_grid = fills ?? _fills_grid,
|
||||
_day_fills_grid = day_fills ?? _day_fills_grid,
|
||||
_synthetic_management = synthetic_management ?? _synthetic_management,
|
||||
_reconcile_report = reconcile_report ?? _reconcile_report,
|
||||
_pnl = pnl ?? _pnl,
|
||||
_order_book = order_book_grid ?? _order_book,
|
||||
_alerts = alerts ?? _alerts
|
||||
};
|
||||
us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault());
|
||||
return us;
|
||||
}
|
||||
|
||||
public static class FileExtensions {
|
||||
public const string
|
||||
GRID = "grid",
|
||||
LADDER = "ladder",
|
||||
PNL = "pnl";
|
||||
}
|
||||
}
|
||||
|
||||
// - currently all notification-triggers are in GridSettings
|
||||
// - the SoundNotificationSettings below are used to disable/enable SoundNotifications
|
||||
// - the ToastNotificationSettings below are used to disable/enable ToastNotifications, and adjust the flash-duration (if enabled).
|
||||
// - since this is a new feature, the ability to quickly enable/disable both types of notifications may save us the trouble of having to redeploy,
|
||||
// in the unfortunate event that a bug slipped through the cracks, or the performance impact is more significant than expected.
|
||||
// TODO: maybe globalize notification settings?
|
||||
[ProtoContract]
|
||||
class NotificationSettings {
|
||||
[ProtoMember(1)]
|
||||
readonly SoundNotificationSettings? _sound_notification;
|
||||
[ProtoMember(2)]
|
||||
readonly ToastNotificationSettings? _toast_notification;
|
||||
|
||||
public NotificationSettings() { }
|
||||
public NotificationSettings(SoundNotificationSettings sound_notification, ToastNotificationSettings toast_notification) {
|
||||
_sound_notification = sound_notification;
|
||||
_toast_notification = toast_notification;
|
||||
}
|
||||
|
||||
public static NotificationSettings Default => new NotificationSettings(SoundNotificationSettings.Default, ToastNotificationSettings.Default);
|
||||
|
||||
public SoundNotificationSettings? sound_notification => _sound_notification;
|
||||
public ToastNotificationSettings? toast_notification => _toast_notification;
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
class SoundNotificationSettings {
|
||||
[ProtoMember(1)]
|
||||
readonly bool _enabled;
|
||||
|
||||
public SoundNotificationSettings() { }
|
||||
public SoundNotificationSettings(bool enabled) =>
|
||||
_enabled = enabled;
|
||||
|
||||
public static SoundNotificationSettings Default => new(true);
|
||||
|
||||
public bool enabled => _enabled;
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
class ToastNotificationSettings {
|
||||
// though it is possible to infer such Modes from Duration values (null = Disabled, max = ManualClose, otherwise Flash)
|
||||
// this Mode enum makes the behavior very clear, and less likely to be misinterpretted down the road.
|
||||
// (without this enum, the meaning of "duration = null," and "duration = 0 seconds," is debatable)
|
||||
public enum Mode {
|
||||
Disabled,
|
||||
ManualClose,
|
||||
Flash
|
||||
}
|
||||
|
||||
public static ToastNotificationSettings Default =>
|
||||
new(Mode.Flash, new Duration { Seconds = 5 }, 320);
|
||||
|
||||
[ProtoMember(1)]
|
||||
readonly Mode _mode;
|
||||
[ProtoMember(2)]
|
||||
readonly Duration? _duration;
|
||||
[ProtoMember(3)]
|
||||
readonly double _max_height;
|
||||
|
||||
public ToastNotificationSettings() { }
|
||||
|
||||
public ToastNotificationSettings(Mode mode, Duration duration, double max_height) {
|
||||
_mode = mode;
|
||||
_duration = duration;
|
||||
_max_height = max_height;
|
||||
}
|
||||
|
||||
public Mode mode => _mode;
|
||||
public TimeSpan duration =>
|
||||
_mode switch {
|
||||
Mode.Flash => _duration?.ToTimeSpan() ?? TimeSpan.FromSeconds(5),
|
||||
_ => new()
|
||||
};
|
||||
public double max_height => _max_height;
|
||||
}
|
||||
}
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using bts.shell;
|
||||
using bts.shell.fills;
|
||||
using bts.shell.market_view;
|
||||
using bts.shell.orderbook;
|
||||
using bts.shell.pnl;
|
||||
using bts.shell.time_and_sales;
|
||||
|
||||
using Google.Protobuf.WellKnownTypes;
|
||||
|
||||
using mbts.ui.settings;
|
||||
|
||||
using ProtoBuf;
|
||||
|
||||
using Spark.Trading;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
interface IDefaultableSettings {
|
||||
bool use_defaults { get; set; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The settings Mothership. All window - and any other future user based - settings should have a corresponding default member here.
|
||||
/// </summary>
|
||||
[ProtoContract]
|
||||
class UserSettings {
|
||||
public static UserSettings factory_defaults =>
|
||||
new() {
|
||||
_ladder = LadderSettings.Default,
|
||||
_notification = NotificationSettings.Default,
|
||||
_market_view_grid = MarketViewSettings.DefaultGridSettings,
|
||||
_fills_grid = FillsSettings.DefaultGridSettings,
|
||||
_day_fills_grid = DayFillsSettings.default_grid(),
|
||||
_open_orders_grid = OpenOrdersSettings.default_grid(),
|
||||
_time_and_sales_grid = TimeAndSalesSettings.DefaultGridSettings,
|
||||
_synthetic_management = SyntheticManagementSettings.default_grid_settings,
|
||||
_reconcile_report = ReconcileReportSettings.Default().grid,
|
||||
_order_book = OrderBookStartupData.DefaultGrid
|
||||
};
|
||||
|
||||
[ProtoMember(1)]
|
||||
LadderSettings? _ladder;
|
||||
[ProtoMember(11)]
|
||||
LadderSettingsProfile[]? _ladder_profiles;
|
||||
/// When Profiles Are Deleted, ladders that were using that profile shall copy the profile's settings to a local profile.
|
||||
/// Therefor:
|
||||
/// Deleted profile ids must never be reused.
|
||||
/// If they were reused, consider an unloaded workspace with ladders that were using the deleted profile.
|
||||
/// If such a workspace was reloaded after a new profile was saved with the deleted one's id, the ladders using that deleted profile would suddenly be using the new profile.
|
||||
/// To Prevent IDs From Being Recycled:
|
||||
/// The last profile id is stored in the protobuf (<see cref="_last_ladder_profile_id"/>).
|
||||
/// Anytime a profile is added, it shall use <see cref="next_ladder_profile_id"/>.
|
||||
[ProtoMember(12)]
|
||||
uint _last_ladder_profile_id;
|
||||
// removing NotificationSettings these from proto-serialization, since they are disabled by default for now.
|
||||
// This way, when they are enabled, there won't be any backwards compatability issues to worry about, as no clients will have persisted them yet.
|
||||
NotificationSettings? _notification;
|
||||
|
||||
[ProtoMember(5)]
|
||||
GridSettings? _market_view_grid;
|
||||
[ProtoMember(6)]
|
||||
GridSettings? _time_and_sales_grid;
|
||||
[ProtoMember(7)]
|
||||
GridSettings? _fills_grid;
|
||||
[ProtoMember(15)]
|
||||
GridSettings? _day_fills_grid;
|
||||
[ProtoMember(16)]
|
||||
GridSettings? _open_orders_grid;
|
||||
[ProtoMember(8)]
|
||||
GridSettings? _synthetic_management;
|
||||
[ProtoMember(14)]
|
||||
GridSettings? _reconcile_report;
|
||||
[ProtoMember(9)]
|
||||
OrderBookGridSettings? _order_book;
|
||||
[ProtoMember(10)]
|
||||
PNLSettings? _pnl;
|
||||
[ProtoMember(13)]
|
||||
GlobalAlertSettings? _alerts;
|
||||
|
||||
public UserSettings() { }
|
||||
|
||||
public LadderSettings ladder =>
|
||||
_ladder ??= LadderSettings.Default;
|
||||
|
||||
public IReadOnlyList<LadderSettingsProfile> ladder_profiles =>
|
||||
_ladder_profiles ?? Array.Empty<LadderSettingsProfile>();
|
||||
|
||||
public uint next_ladder_profile_id =>
|
||||
_last_ladder_profile_id + 1;
|
||||
|
||||
public NotificationSettings notification =>
|
||||
_notification ??= NotificationSettings.Default;
|
||||
|
||||
public GridSettings market_view_grid =>
|
||||
_market_view_grid ??= MarketViewSettings.DefaultGridSettings;
|
||||
|
||||
public GridSettings time_and_sales_grid =>
|
||||
_time_and_sales_grid ??= GridSettings.Default.with(
|
||||
TimeAndSalesSettings.DefaultColumns.all);
|
||||
|
||||
public GridSettings fills_grid =>
|
||||
_fills_grid ??= FillsSettings.DefaultGridSettings;
|
||||
|
||||
public GridSettings day_fills_grid =>
|
||||
_day_fills_grid ??= DayFillsSettings.default_grid();
|
||||
|
||||
public GridSettings open_orders_grid =>
|
||||
_open_orders_grid ??= OpenOrdersSettings.default_grid();
|
||||
|
||||
public GridSettings synthetic_management_grid =>
|
||||
_synthetic_management ??=
|
||||
SyntheticManagementSettings.default_grid_settings;
|
||||
|
||||
public GridSettings reconcile_report_grid =>
|
||||
_reconcile_report ??= ReconcileReportSettings.Default().grid ??
|
||||
throw new InvalidOperationException();
|
||||
|
||||
public PNLSettings pnl =>
|
||||
_pnl ??= PNLSettings.Default;
|
||||
|
||||
public OrderBookGridSettings order_book_grid =>
|
||||
_order_book ??= OrderBookStartupData.Default.grid_settings_wrapper();
|
||||
|
||||
public GlobalAlertSettings alerts =>
|
||||
_alerts ??= new GlobalAlertSettings();
|
||||
|
||||
public UserSettings with(
|
||||
LadderSettings? ladder = null,
|
||||
LadderSettingsProfile[]? ladder_profiles = null,
|
||||
NotificationSettings? notification = null,
|
||||
GridSettings? market_view = null,
|
||||
GridSettings? time_and_sales = null,
|
||||
GridSettings? fills = null,
|
||||
GridSettings? day_fills = null,
|
||||
GridSettings? open_orders = null,
|
||||
GridSettings? synthetic_management = null,
|
||||
GridSettings? reconcile_report = null,
|
||||
PNLSettings? pnl = null,
|
||||
OrderBookGridSettings? order_book_grid = null,
|
||||
GlobalAlertSettings? alerts = null) {
|
||||
var us = new UserSettings() {
|
||||
_ladder_profiles = ladder_profiles ?? _ladder_profiles,
|
||||
_ladder = ladder ?? _ladder,
|
||||
_notification = notification ?? _notification,
|
||||
_market_view_grid = market_view ?? _market_view_grid,
|
||||
_time_and_sales_grid = time_and_sales ?? _time_and_sales_grid,
|
||||
_fills_grid = fills ?? _fills_grid,
|
||||
_day_fills_grid = day_fills ?? _day_fills_grid,
|
||||
_open_orders_grid = open_orders ?? _open_orders_grid,
|
||||
_synthetic_management = synthetic_management ?? _synthetic_management,
|
||||
_reconcile_report = reconcile_report ?? _reconcile_report,
|
||||
_pnl = pnl ?? _pnl,
|
||||
_order_book = order_book_grid ?? _order_book,
|
||||
_alerts = alerts ?? _alerts
|
||||
};
|
||||
us._last_ladder_profile_id = Math.Max(_last_ladder_profile_id, us.ladder_profiles.Select(p => p.id).MaxOrDefault());
|
||||
return us;
|
||||
}
|
||||
|
||||
public static class FileExtensions {
|
||||
public const string
|
||||
GRID = "grid",
|
||||
LADDER = "ladder",
|
||||
PNL = "pnl";
|
||||
}
|
||||
}
|
||||
|
||||
// - currently all notification-triggers are in GridSettings
|
||||
// - the SoundNotificationSettings below are used to disable/enable SoundNotifications
|
||||
// - the ToastNotificationSettings below are used to disable/enable ToastNotifications, and adjust the flash-duration (if enabled).
|
||||
// - since this is a new feature, the ability to quickly enable/disable both types of notifications may save us the trouble of having to redeploy,
|
||||
// in the unfortunate event that a bug slipped through the cracks, or the performance impact is more significant than expected.
|
||||
// TODO: maybe globalize notification settings?
|
||||
[ProtoContract]
|
||||
class NotificationSettings {
|
||||
[ProtoMember(1)]
|
||||
readonly SoundNotificationSettings? _sound_notification;
|
||||
[ProtoMember(2)]
|
||||
readonly ToastNotificationSettings? _toast_notification;
|
||||
|
||||
public NotificationSettings() { }
|
||||
public NotificationSettings(SoundNotificationSettings sound_notification, ToastNotificationSettings toast_notification) {
|
||||
_sound_notification = sound_notification;
|
||||
_toast_notification = toast_notification;
|
||||
}
|
||||
|
||||
public static NotificationSettings Default => new NotificationSettings(SoundNotificationSettings.Default, ToastNotificationSettings.Default);
|
||||
|
||||
public SoundNotificationSettings? sound_notification => _sound_notification;
|
||||
public ToastNotificationSettings? toast_notification => _toast_notification;
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
class SoundNotificationSettings {
|
||||
[ProtoMember(1)]
|
||||
readonly bool _enabled;
|
||||
|
||||
public SoundNotificationSettings() { }
|
||||
public SoundNotificationSettings(bool enabled) =>
|
||||
_enabled = enabled;
|
||||
|
||||
public static SoundNotificationSettings Default => new(true);
|
||||
|
||||
public bool enabled => _enabled;
|
||||
}
|
||||
|
||||
[ProtoContract]
|
||||
class ToastNotificationSettings {
|
||||
// though it is possible to infer such Modes from Duration values (null = Disabled, max = ManualClose, otherwise Flash)
|
||||
// this Mode enum makes the behavior very clear, and less likely to be misinterpretted down the road.
|
||||
// (without this enum, the meaning of "duration = null," and "duration = 0 seconds," is debatable)
|
||||
public enum Mode {
|
||||
Disabled,
|
||||
ManualClose,
|
||||
Flash
|
||||
}
|
||||
|
||||
public static ToastNotificationSettings Default =>
|
||||
new(Mode.Flash, new Duration { Seconds = 5 }, 320);
|
||||
|
||||
[ProtoMember(1)]
|
||||
readonly Mode _mode;
|
||||
[ProtoMember(2)]
|
||||
readonly Duration? _duration;
|
||||
[ProtoMember(3)]
|
||||
readonly double _max_height;
|
||||
|
||||
public ToastNotificationSettings() { }
|
||||
|
||||
public ToastNotificationSettings(Mode mode, Duration duration, double max_height) {
|
||||
_mode = mode;
|
||||
_duration = duration;
|
||||
_max_height = max_height;
|
||||
}
|
||||
|
||||
public Mode mode => _mode;
|
||||
public TimeSpan duration =>
|
||||
_mode switch {
|
||||
Mode.Flash => _duration?.ToTimeSpan() ?? TimeSpan.FromSeconds(5),
|
||||
_ => new()
|
||||
};
|
||||
public double max_height => _max_height;
|
||||
}
|
||||
}
|
||||
@@ -1,188 +1,201 @@
|
||||
using bts;
|
||||
using bts.settings;
|
||||
using bts.shell.pnl;
|
||||
using bts.utils;
|
||||
|
||||
using mbts.spark;
|
||||
using mbts.ui.settings;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.persist {
|
||||
/// <summary>
|
||||
/// Represents the top level of the persisted settings hierarchy.
|
||||
/// One UserSettings object, which contains the defaults for every SparkWindow, can be read/written on the server by UISettingsHub.
|
||||
/// </summary>
|
||||
[Export(typeof(UserSettingsHub))]
|
||||
class UserSettingsHub {
|
||||
// do NOT CHANGE these consts, they represent a file path on the server
|
||||
const string NAME_SPACE = "settings", DEFAULT_KEY = "default";
|
||||
|
||||
static readonly IImmutableProperty<UserSettings, GridSettings>
|
||||
_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(fills: gs)),
|
||||
_day_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.day_fills_grid, (us, gs) => us.with(day_fills: gs)),
|
||||
_mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(market_view: gs)),
|
||||
_synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(synthetic_management: gs)),
|
||||
_reconcile_report_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.reconcile_report_grid, (us, gs) => us.with(reconcile_report: gs));
|
||||
|
||||
static readonly IImmutableProperty<UserSettings, PNLSettings>
|
||||
_pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl));
|
||||
|
||||
readonly object _default_settings_lock = new object();
|
||||
readonly BehaviorSubject<UserSettings> _default_settings_subject = new BehaviorSubject<UserSettings>(UserSettings.factory_defaults);
|
||||
readonly IEnumerable<IFillsGridSettingsMigrationRule> _fills_migration_rules;
|
||||
readonly IEnumerable<IDayFillsGridSettingsMigrationRule> _day_fills_migration_rules;
|
||||
readonly IEnumerable<IMarketViewGridSettingsMigrationRule> _mview_migration_rules;
|
||||
readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules;
|
||||
readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules;
|
||||
readonly IEnumerable<IReconcileReportMigrationRule> _reconcile_report_migration_rules;
|
||||
readonly IUserPersist _persist;
|
||||
|
||||
UserSettings _default_settings;
|
||||
|
||||
[ImportingConstructor]
|
||||
public UserSettingsHub(
|
||||
IUserPersist persist,
|
||||
[ImportMany] IEnumerable<IFillsGridSettingsMigrationRule> fills_migration_rules,
|
||||
[ImportMany] IEnumerable<IDayFillsGridSettingsMigrationRule> day_fills_migration_rules,
|
||||
[ImportMany] IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules,
|
||||
[ImportMany] IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules,
|
||||
[ImportMany] IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules,
|
||||
[ImportMany] IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules,
|
||||
[ImportMany] IEnumerable<IReconcileReportMigrationRule> reconcile_report_migration_rules) {
|
||||
//
|
||||
_persist = persist;
|
||||
_fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>();
|
||||
_day_fills_migration_rules = day_fills_migration_rules ?? Enumerable.Empty<IDayFillsGridSettingsMigrationRule>();
|
||||
_mview_migration_rules = mview_migration_rules ?? Enumerable.Empty<IMarketViewGridSettingsMigrationRule>();
|
||||
_pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>();
|
||||
_synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>();
|
||||
_reconcile_report_migration_rules = reconcile_report_migration_rules.empty_if_null();
|
||||
init();
|
||||
async void init() {
|
||||
UserSettings s;
|
||||
try {
|
||||
s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
|
||||
if (s != null) {
|
||||
var wrapped_rules = new[] {
|
||||
_fills_migration_rules.merge().wrap(_fills_propi),
|
||||
_mview_migration_rules.merge().wrap(_mview_propi),
|
||||
_pnl_migration_rules.merge().wrap(_pnl_propi),
|
||||
_synth_migration_rules.merge().wrap(_synth_propi),
|
||||
_reconcile_report_migration_rules.merge().wrap(_reconcile_report_propi)
|
||||
};
|
||||
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
|
||||
// TODO: move ladder sanitization logic into ISettingsMigrationRule
|
||||
s.ladder.sanitize();
|
||||
// ensure valid named ladder set (w/ distinct, non-zero ids)
|
||||
var ladder_profile_map = new Dictionary<uint, LadderSettingsProfile>();
|
||||
var unidentified_lps = new List<LadderSettingsProfile>();
|
||||
foreach (var lp in s.ladder_profiles) {
|
||||
lp.value.sanitize();
|
||||
if (lp.id == 0) {
|
||||
unidentified_lps.Add(lp);
|
||||
} else ladder_profile_map[lp.id] = lp;
|
||||
}
|
||||
uint id = s.next_ladder_profile_id;
|
||||
foreach (var lp in unidentified_lps) {
|
||||
ladder_profile_map[id] = lp.with(id);
|
||||
id++;
|
||||
}
|
||||
var sorted_lps = ladder_profile_map.Values.ToArray();
|
||||
Array.Sort(sorted_lps, Comparer<uint>.Default.wrap<uint, LadderSettingsProfile>(lp => lp.id));
|
||||
if (!sorted_lps.SequenceEqual(s.ladder_profiles))
|
||||
await _persist.set(NAME_SPACE, DEFAULT_KEY, s = s.with(ladder_profiles: sorted_lps));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.Persist.warn($"Error loading {typeof(UserSettings)} from namespace '{NAME_SPACE}', will restore factory defaults and continue as usual: {ex}");
|
||||
await save_default(s = UserSettings.factory_defaults);
|
||||
}
|
||||
lock (_default_settings_lock) {
|
||||
initialized = true;
|
||||
if (s != null)
|
||||
_default_settings_subject.OnNext(_default_settings = s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
|
||||
public bool initialized { get; private set; }
|
||||
|
||||
internal UserSettings current {
|
||||
get {
|
||||
lock (_default_settings_lock)
|
||||
return _default_settings ?? UserSettings.factory_defaults;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
|
||||
/// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
|
||||
public IObservable<UserSettings> subscribe_default_settings() => _default_settings_subject.AsObservable();
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_fills_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_fills_migration_rules,
|
||||
_fills_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_mview_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_mview_migration_rules,
|
||||
_mview_propi);
|
||||
|
||||
public IWindowSettingsManager<PNLSettings> create_pnl_settings_manager(PNLSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_pnl_migration_rules,
|
||||
_pnl_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_synth_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_synth_migration_rules,
|
||||
_synth_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_reconcile_report_settings_manager(
|
||||
GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_reconcile_report_migration_rules,
|
||||
_reconcile_report_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_day_fills_settings_manager(
|
||||
GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_day_fills_migration_rules,
|
||||
_day_fills_propi);
|
||||
|
||||
public async Task save_default(UserSettings value) {
|
||||
// notify observers before persisting so the changes are reflected immediately in the ui
|
||||
lock (_default_settings_lock) {
|
||||
_default_settings_subject.OnNext(_default_settings = value);
|
||||
}
|
||||
await _persist_async();
|
||||
}
|
||||
|
||||
IWindowSettingsManager<T> _create_settings_manager<T>(T instance_settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, IImmutableProperty<UserSettings, T> propi) where T : class {
|
||||
if (instance_settings != null && migration_rules.merge().apply(instance_settings, out var new_settings))
|
||||
instance_settings = new_settings;
|
||||
return new WindowSettingsManager<T>(this, instance_settings, propi.get, propi.set);
|
||||
}
|
||||
|
||||
async Task _persist_async() {
|
||||
try {
|
||||
await _persist.set(NAME_SPACE, DEFAULT_KEY, _default_settings);
|
||||
} catch (Exception ex) {
|
||||
Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
using bts;
|
||||
using bts.settings;
|
||||
using bts.shell.pnl;
|
||||
using bts.utils;
|
||||
|
||||
using mbts.spark;
|
||||
using mbts.ui.settings;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace mbts.persist {
|
||||
/// <summary>
|
||||
/// Represents the top level of the persisted settings hierarchy.
|
||||
/// One UserSettings object, which contains the defaults for every SparkWindow, can be read/written on the server by UISettingsHub.
|
||||
/// </summary>
|
||||
[Export(typeof(UserSettingsHub))]
|
||||
class UserSettingsHub {
|
||||
// do NOT CHANGE these consts, they represent a file path on the server
|
||||
const string NAME_SPACE = "settings", DEFAULT_KEY = "default";
|
||||
|
||||
static readonly IImmutableProperty<UserSettings, GridSettings>
|
||||
_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.fills_grid, (us, gs) => us.with(fills: gs)),
|
||||
_day_fills_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.day_fills_grid, (us, gs) => us.with(day_fills: gs)),
|
||||
_open_orders_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.open_orders_grid, (us, gs) => us.with(open_orders: gs)),
|
||||
_mview_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.market_view_grid, (us, gs) => us.with(market_view: gs)),
|
||||
_synth_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.synthetic_management_grid, (us, gs) => us.with(synthetic_management: gs)),
|
||||
_reconcile_report_propi = ImmutableProperty.create<UserSettings, GridSettings>(us => us.reconcile_report_grid, (us, gs) => us.with(reconcile_report: gs));
|
||||
|
||||
static readonly IImmutableProperty<UserSettings, PNLSettings>
|
||||
_pnl_propi = ImmutableProperty.create<UserSettings, PNLSettings>(us => us.pnl, (us, pnl) => us.with(pnl: pnl));
|
||||
|
||||
readonly object _default_settings_lock = new object();
|
||||
readonly BehaviorSubject<UserSettings> _default_settings_subject = new BehaviorSubject<UserSettings>(UserSettings.factory_defaults);
|
||||
readonly IEnumerable<IFillsGridSettingsMigrationRule> _fills_migration_rules;
|
||||
readonly IEnumerable<IDayFillsGridSettingsMigrationRule> _day_fills_migration_rules;
|
||||
readonly IEnumerable<IOpenOrdersGridSettingsMigrationRule> _open_orders_migration_rules;
|
||||
readonly IEnumerable<IMarketViewGridSettingsMigrationRule> _mview_migration_rules;
|
||||
readonly IEnumerable<IPNLSettingsMigrationRule> _pnl_migration_rules;
|
||||
readonly IEnumerable<ISyntheticManagementMigrationRule> _synth_migration_rules;
|
||||
readonly IEnumerable<IReconcileReportMigrationRule> _reconcile_report_migration_rules;
|
||||
readonly IUserPersist _persist;
|
||||
|
||||
UserSettings _default_settings;
|
||||
|
||||
[ImportingConstructor]
|
||||
public UserSettingsHub(
|
||||
IUserPersist persist,
|
||||
[ImportMany] IEnumerable<IFillsGridSettingsMigrationRule> fills_migration_rules,
|
||||
[ImportMany] IEnumerable<IDayFillsGridSettingsMigrationRule> day_fills_migration_rules,
|
||||
[ImportMany] IEnumerable<IOpenOrdersGridSettingsMigrationRule> open_orders_migration_rules,
|
||||
[ImportMany] IEnumerable<IMarketViewGridSettingsMigrationRule> mview_migration_rules,
|
||||
[ImportMany] IEnumerable<IPAndLGridSettingsMigrationRule> pandl_migration_rules,
|
||||
[ImportMany] IEnumerable<IPNLSettingsMigrationRule> pnl_migration_rules,
|
||||
[ImportMany] IEnumerable<ISyntheticManagementMigrationRule> synth_migration_rules,
|
||||
[ImportMany] IEnumerable<IReconcileReportMigrationRule> reconcile_report_migration_rules) {
|
||||
//
|
||||
_persist = persist;
|
||||
_fills_migration_rules = fills_migration_rules ?? Enumerable.Empty<IFillsGridSettingsMigrationRule>();
|
||||
_day_fills_migration_rules = day_fills_migration_rules ?? Enumerable.Empty<IDayFillsGridSettingsMigrationRule>();
|
||||
_open_orders_migration_rules = open_orders_migration_rules ?? Enumerable.Empty<IOpenOrdersGridSettingsMigrationRule>();
|
||||
_mview_migration_rules = mview_migration_rules ?? Enumerable.Empty<IMarketViewGridSettingsMigrationRule>();
|
||||
_pnl_migration_rules = pnl_migration_rules ?? Enumerable.Empty<IPNLSettingsMigrationRule>();
|
||||
_synth_migration_rules = synth_migration_rules ?? Enumerable.Empty<ISyntheticManagementMigrationRule>();
|
||||
_reconcile_report_migration_rules = reconcile_report_migration_rules.empty_if_null();
|
||||
init();
|
||||
async void init() {
|
||||
UserSettings s;
|
||||
try {
|
||||
s = await _persist.get<UserSettings>(NAME_SPACE, DEFAULT_KEY);
|
||||
if (s != null) {
|
||||
var wrapped_rules = new[] {
|
||||
_fills_migration_rules.merge().wrap(_fills_propi),
|
||||
_day_fills_migration_rules.merge().wrap(_day_fills_propi),
|
||||
_open_orders_migration_rules.merge().wrap(_open_orders_propi),
|
||||
_mview_migration_rules.merge().wrap(_mview_propi),
|
||||
_pnl_migration_rules.merge().wrap(_pnl_propi),
|
||||
_synth_migration_rules.merge().wrap(_synth_propi),
|
||||
_reconcile_report_migration_rules.merge().wrap(_reconcile_report_propi)
|
||||
};
|
||||
SettingsMigrationHelper.apply_quiet(ref s, wrapped_rules);
|
||||
// TODO: move ladder sanitization logic into ISettingsMigrationRule
|
||||
s.ladder.sanitize();
|
||||
// ensure valid named ladder set (w/ distinct, non-zero ids)
|
||||
var ladder_profile_map = new Dictionary<uint, LadderSettingsProfile>();
|
||||
var unidentified_lps = new List<LadderSettingsProfile>();
|
||||
foreach (var lp in s.ladder_profiles) {
|
||||
lp.value.sanitize();
|
||||
if (lp.id == 0) {
|
||||
unidentified_lps.Add(lp);
|
||||
} else ladder_profile_map[lp.id] = lp;
|
||||
}
|
||||
uint id = s.next_ladder_profile_id;
|
||||
foreach (var lp in unidentified_lps) {
|
||||
ladder_profile_map[id] = lp.with(id);
|
||||
id++;
|
||||
}
|
||||
var sorted_lps = ladder_profile_map.Values.ToArray();
|
||||
Array.Sort(sorted_lps, Comparer<uint>.Default.wrap<uint, LadderSettingsProfile>(lp => lp.id));
|
||||
if (!sorted_lps.SequenceEqual(s.ladder_profiles))
|
||||
await _persist.set(NAME_SPACE, DEFAULT_KEY, s = s.with(ladder_profiles: sorted_lps));
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Log.Persist.warn($"Error loading {typeof(UserSettings)} from namespace '{NAME_SPACE}', will restore factory defaults and continue as usual: {ex}");
|
||||
await save_default(s = UserSettings.factory_defaults);
|
||||
}
|
||||
lock (_default_settings_lock) {
|
||||
initialized = true;
|
||||
if (s != null)
|
||||
_default_settings_subject.OnNext(_default_settings = s);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// indicates whether or not the settings have been loaded from the server (this happens once, on startup - see the constructor for details)
|
||||
public bool initialized { get; private set; }
|
||||
|
||||
internal UserSettings current {
|
||||
get {
|
||||
lock (_default_settings_lock)
|
||||
return _default_settings ?? UserSettings.factory_defaults;
|
||||
}
|
||||
}
|
||||
|
||||
/// Subscribing via _persist.subscribe may be cleaner in theory, however using a local event allows observers to be notified immediately.
|
||||
/// Assuming there aren't any rogue agents saving UserSettings by themselves, there should never be any discrepancies.
|
||||
public IObservable<UserSettings> subscribe_default_settings() => _default_settings_subject.AsObservable();
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_fills_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_fills_migration_rules,
|
||||
_fills_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_mview_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_mview_migration_rules,
|
||||
_mview_propi);
|
||||
|
||||
public IWindowSettingsManager<PNLSettings> create_pnl_settings_manager(PNLSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_pnl_migration_rules,
|
||||
_pnl_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_synth_settings_manager(GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_synth_migration_rules,
|
||||
_synth_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_reconcile_report_settings_manager(
|
||||
GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_reconcile_report_migration_rules,
|
||||
_reconcile_report_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_day_fills_settings_manager(
|
||||
GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_day_fills_migration_rules,
|
||||
_day_fills_propi);
|
||||
|
||||
public IWindowSettingsManager<GridSettings> create_open_orders_settings_manager(
|
||||
GridSettings instance_settings) =>
|
||||
_create_settings_manager(
|
||||
instance_settings,
|
||||
_day_fills_migration_rules,
|
||||
_day_fills_propi);
|
||||
|
||||
public async Task save_default(UserSettings value) {
|
||||
// notify observers before persisting so the changes are reflected immediately in the ui
|
||||
lock (_default_settings_lock) {
|
||||
_default_settings_subject.OnNext(_default_settings = value);
|
||||
}
|
||||
await _persist_async();
|
||||
}
|
||||
|
||||
IWindowSettingsManager<T> _create_settings_manager<T>(T instance_settings, IEnumerable<ISettingsMigrationRule<T>> migration_rules, IImmutableProperty<UserSettings, T> propi) where T : class {
|
||||
if (instance_settings != null && migration_rules.merge().apply(instance_settings, out var new_settings))
|
||||
instance_settings = new_settings;
|
||||
return new WindowSettingsManager<T>(this, instance_settings, propi.get, propi.set);
|
||||
}
|
||||
|
||||
async Task _persist_async() {
|
||||
try {
|
||||
await _persist.set(NAME_SPACE, DEFAULT_KEY, _default_settings);
|
||||
} catch (Exception ex) {
|
||||
Log.Persist.warn($"Error persisting {typeof(UserSettings)} in namespace '{NAME_SPACE}': {ex}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ namespace Spark.Model.Trading {
|
||||
|
||||
using mbts.spark;
|
||||
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Core.Reactive;
|
||||
|
||||
using System;
|
||||
@@ -25,7 +26,7 @@ namespace Spark.Model.Trading {
|
||||
public OrderDataSource(
|
||||
IBus bus,
|
||||
AdminModel admin_model,
|
||||
SecurityStore security_store,
|
||||
SecurityResolver sec_resolver,
|
||||
OrderService order_service,
|
||||
ISecurityAuxiliaryDataModel security_auxiliary_model,
|
||||
ErrorReporter error_reporter
|
||||
@@ -38,7 +39,7 @@ namespace Spark.Model.Trading {
|
||||
order_service.subscribei_orders()
|
||||
.Naggle(interval, scheduler),
|
||||
o => o.account_id())
|
||||
.join(security_store, o => o.security_key())
|
||||
.join(sec_resolver, o => o.security_key())
|
||||
.Table()
|
||||
.Cache();
|
||||
|
||||
|
||||
@@ -9,12 +9,13 @@ namespace Spark.Trading {
|
||||
using bts.shell.pnl;
|
||||
using bts.spark;
|
||||
|
||||
using mbts;
|
||||
using mbts.analytics;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Api.Reactive;
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
using Spark.Model.Trading;
|
||||
|
||||
@@ -32,13 +33,13 @@ namespace Spark.Trading {
|
||||
readonly ErrorReporter _error_reporter;
|
||||
readonly TableUpdateDemuxer<(SecurityImmutable?, PositionUnitImmutable), int, uint> _security_positions_demuxer;
|
||||
|
||||
IDisposable _dispose;
|
||||
ThreadSafeDisposable? _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
public PositionModel(
|
||||
IBus bus,
|
||||
AdminModel admin_model,
|
||||
SecurityStore security_store,
|
||||
SecurityResolver sec_resolver,
|
||||
PositionService position_service,
|
||||
OrderService order_service,
|
||||
OrderDataSource order_data,
|
||||
@@ -55,7 +56,7 @@ namespace Spark.Trading {
|
||||
on_exchange_positions = order_service.subscribei_exchange_positions()
|
||||
.Filter(ep => ep.SecurityKey != 0)
|
||||
.SelectKeyValue(ep => ep, ep => new AccountSecurityKey(ep.AccountId, ep.SecurityKey))
|
||||
.join(security_store, ep => ep.SecurityKey)
|
||||
.join(sec_resolver, ep => ep.SecurityKey)
|
||||
.Table()
|
||||
.Cache();
|
||||
|
||||
@@ -63,11 +64,11 @@ namespace Spark.Trading {
|
||||
.permission_filter(
|
||||
_position_service.subscribei_position_data().Naggle(interval, scheduler),
|
||||
p => p.AccountId)
|
||||
.join(security_store, pos => pos.SecurityId)
|
||||
.join(sec_resolver, pos => pos.SecurityId)
|
||||
.Table()
|
||||
.Cache();
|
||||
|
||||
day_fills = DayFillsDataSource.create(bus, security_store);
|
||||
day_fills = DayFillsDataSource.create(bus, sec_resolver);
|
||||
|
||||
pnl = bus.subscribe(SparkTags.ReportBlackboardTags.PNL.PNLData)
|
||||
.Select(d => d.position_data.ToDictionary(u => u.id(), PNLRowData.from_pnl_unit))
|
||||
@@ -101,8 +102,7 @@ namespace Spark.Trading {
|
||||
merged_positions = ReconcileReportDataSource.create(on_exchange_positions, on_positions)
|
||||
.Cache();
|
||||
|
||||
_dispose = Disposable.Create(
|
||||
on_positions.Subscribe(_security_positions_demuxer));
|
||||
_dispose = new(on_positions.Subscribe(_security_positions_demuxer));
|
||||
}
|
||||
|
||||
public IObservable<TableUpdate<(SecurityImmutable? sec, RetrievedExchangePositionImmutable exch_pos), AccountSecurityKey>> on_exchange_positions { get; }
|
||||
@@ -142,6 +142,6 @@ namespace Spark.Trading {
|
||||
"reset positions");
|
||||
|
||||
public void Dispose() =>
|
||||
Disposable.dispose_thread_safe(ref _dispose);
|
||||
Disposable.dispose(ref _dispose);
|
||||
}
|
||||
}
|
||||
@@ -15,6 +15,7 @@ namespace mbts.spark {
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reactive;
|
||||
using Spark.Trading;
|
||||
using Spark.ViewModel;
|
||||
@@ -66,7 +67,7 @@ namespace mbts.spark {
|
||||
};
|
||||
var vol_surfaces_src = _bus.subscribe(SparkTags.VolSurfaceListTag).OnDispatcher();
|
||||
var reports_src = _bus.subscribe(SparkTags.ReportBlackboardTags.ListTag).OnDispatcher();
|
||||
_dispose = new DisposableCombo(
|
||||
_dispose = Disposable.Create(
|
||||
vol_surfaces_src.Subscribe(_on_vol_surfaces),
|
||||
reports_src.Subscribe(_on_reports),
|
||||
nullable_reports_src.Subscribe(reports_demuxer),
|
||||
|
||||
@@ -98,7 +98,6 @@
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<Button
|
||||
@@ -107,36 +106,17 @@
|
||||
Style="{StaticResource LargeMenuButton}"
|
||||
/>
|
||||
|
||||
<Grid Grid.Row="1">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="*" />
|
||||
<ColumnDefinition Width="Auto" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<Rectangle
|
||||
Margin="5,1,5,0"
|
||||
Fill="{DynamicResource StartMenuMouseOverBackground}"
|
||||
HorizontalAlignment="Stretch"
|
||||
Height="1"
|
||||
/>
|
||||
|
||||
<c:HelpButton
|
||||
Grid.Column="1"
|
||||
ManPage="AW2"
|
||||
ToolTip="Click Here for help"
|
||||
/>
|
||||
</Grid>
|
||||
|
||||
<ToggleButton
|
||||
Grid.Row="2"
|
||||
Grid.Row="1"
|
||||
c:RadioButtonGroupManager.Value="vol_surfaces"
|
||||
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
|
||||
Content="Vol Surfaces"
|
||||
Margin="0,6,0,0"
|
||||
Content="Vol Surface"
|
||||
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=VolSurfacesContent, Mode=TwoWay}"
|
||||
Style="{StaticResource LargeMenuToggleButton}"
|
||||
/>
|
||||
|
||||
<ContentControl Grid.Row="3" Height="0">
|
||||
<ContentControl Grid.Row="2" Height="0">
|
||||
<ContentControl
|
||||
x:Name="VolSurfacesContent"
|
||||
Content="{Binding vol_surface_launcher_vm}"
|
||||
@@ -145,16 +125,16 @@
|
||||
</ContentControl>
|
||||
|
||||
<ToggleButton
|
||||
Grid.Row="4"
|
||||
Grid.Row="3"
|
||||
c:RadioButtonGroupManager.Value="slide_reports"
|
||||
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
|
||||
Margin="0,6,0,0"
|
||||
Content="Slide Reports"
|
||||
Content="Slide"
|
||||
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=SlideReportContent, Mode=TwoWay}"
|
||||
Style="{StaticResource LargeMenuToggleButton}"
|
||||
/>
|
||||
|
||||
<ContentControl Grid.Row="5" Height="0">
|
||||
<ContentControl Grid.Row="4" Height="0">
|
||||
<ContentControl
|
||||
x:Name="SlideReportContent"
|
||||
Content="{Binding slide_report_launcher_vm}"
|
||||
@@ -163,16 +143,16 @@
|
||||
</ContentControl>
|
||||
|
||||
<ToggleButton
|
||||
Grid.Row="6"
|
||||
Grid.Row="5"
|
||||
c:RadioButtonGroupManager.Value="combo_reports"
|
||||
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
|
||||
Margin="0,6,0,0"
|
||||
Content="Combo Report"
|
||||
Content="Combo"
|
||||
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=ComboReportContent, Mode=TwoWay}"
|
||||
Style="{StaticResource LargeMenuToggleButton}"
|
||||
/>
|
||||
|
||||
<ContentControl Grid.Row="7" Height="0">
|
||||
<ContentControl Grid.Row="6" Height="0">
|
||||
<ContentControl
|
||||
x:Name="ComboReportContent"
|
||||
Content="{Binding combo_report_launcher_vm}"
|
||||
@@ -181,27 +161,27 @@
|
||||
</ContentControl>
|
||||
|
||||
<ToggleButton
|
||||
Grid.Row="8"
|
||||
Grid.Row="7"
|
||||
c:RadioButtonGroupManager.Value="pnl"
|
||||
c:RadioButtonGroupManager.Manager="{StaticResource WindowTypeRadioButtonGroupManager}"
|
||||
Margin="0,6,0,0"
|
||||
Content="P&L Reports"
|
||||
Content="P&L"
|
||||
IsChecked="{Binding Path='(u:ExpandCollapseAnimator.IsExpanded)', ElementName=PNLContent, Mode=TwoWay}"
|
||||
Style="{StaticResource LargeMenuToggleButton}" />
|
||||
|
||||
<ContentControl Grid.Row="9" Height="0">
|
||||
<ContentControl Grid.Row="8" Height="0">
|
||||
<Grid x:Name="PNLContent">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
</Grid.RowDefinitions>
|
||||
<Button
|
||||
Content="{x:Static bshell:PNLWindow.WINDOW_TITLE}"
|
||||
Content="Summary"
|
||||
Command="{Binding launch_pnl_cmd}"
|
||||
Style="{StaticResource LaunchButton}" />
|
||||
<Button
|
||||
Grid.Row="1"
|
||||
Content="{x:Static trading:DayFillsWindow.WINDOW_TITLE}"
|
||||
Content="Day Fills"
|
||||
Command="{Binding launch_day_fills_cmd}"
|
||||
Style="{StaticResource LaunchButton}" />
|
||||
</Grid>
|
||||
|
||||
@@ -4,6 +4,8 @@ namespace mbts.ui.controls {
|
||||
using mbts.ui.converters;
|
||||
using mbts.ui.extensions;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -6,6 +6,8 @@
|
||||
using mbts.ui.converters;
|
||||
using mbts.ui.extensions;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Windows;
|
||||
|
||||
@@ -7,6 +7,8 @@
|
||||
using mbts.ui.extensions;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
@@ -41,7 +43,7 @@
|
||||
|
||||
public void thread_init() {
|
||||
_vm = new VolSurfaceVM(new VolSurfaceDisplayModel(vs_id, _bus, true), vs_id, _bus, _startup_data);
|
||||
DisposableCombo hooks = new();
|
||||
var hooks = new ImmutableDisposable();
|
||||
|
||||
var dummy_view = new Border {
|
||||
Background = BTSColors.UI.default_background.to_brush().frozen(),
|
||||
|
||||
@@ -1,142 +0,0 @@
|
||||
using mbts.ui;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Media;
|
||||
|
||||
using CellAnimation = mbts.ui.spark.CellAnimation;
|
||||
using Columns = mbts.spark.MarketViewColumnType;
|
||||
|
||||
namespace mbts.spark {
|
||||
internal partial class MarketViewVM : IDisposable {
|
||||
private class AnimationManager {
|
||||
private IDisposable _remove_position_increase, _remove_position_decrease,
|
||||
_remove_day_change_increase, _remove_day_change_decrease,
|
||||
_remove_working_bids_filled, _remove_working_asks_filled;
|
||||
private bool _position_increased, _position_decreased,
|
||||
_day_change_increased, _day_change_decreased,
|
||||
_working_bids_active, _working_bids_inside, _working_bids_filled,
|
||||
_working_asks_active, _working_asks_inside, _working_asks_filled;
|
||||
|
||||
public void animate_position(bool increased) {
|
||||
if (increased) {
|
||||
Disposable.dispose(ref _remove_position_increase);
|
||||
Disposable.dispose(ref _remove_position_decrease);
|
||||
_position_decreased = false;
|
||||
_position_increased = true;
|
||||
_remove_position_increase = TaskHelper.DelayAction(flash_duration, () => { _position_increased = false; _fire_animations_changed(); });
|
||||
} else {
|
||||
Disposable.dispose(ref _remove_position_decrease);
|
||||
Disposable.dispose(ref _remove_position_increase);
|
||||
_position_increased = false;
|
||||
_position_decreased = true;
|
||||
_remove_position_decrease = TaskHelper.DelayAction(flash_duration, () => { _position_decreased = false; _fire_animations_changed(); });
|
||||
}
|
||||
_fire_animations_changed();
|
||||
}
|
||||
public void animate_day_change(bool increased) {
|
||||
if (increased) {
|
||||
Disposable.dispose(ref _remove_day_change_increase);
|
||||
Disposable.dispose(ref _remove_day_change_decrease);
|
||||
_day_change_decreased = false;
|
||||
_day_change_increased = true;
|
||||
_remove_day_change_increase = TaskHelper.DelayAction(flash_duration, () => { _day_change_increased = false; _fire_animations_changed(); });
|
||||
} else {
|
||||
Disposable.dispose(ref _remove_day_change_decrease);
|
||||
Disposable.dispose(ref _remove_day_change_increase);
|
||||
_day_change_increased = false;
|
||||
_day_change_decreased = true;
|
||||
_remove_day_change_decrease = TaskHelper.DelayAction(flash_duration, () => { _day_change_decreased = false; _fire_animations_changed(); });
|
||||
}
|
||||
_fire_animations_changed();
|
||||
}
|
||||
public void animate_working_bids_active(bool active) {
|
||||
if (_working_bids_active != active) {
|
||||
_working_bids_active = active;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
}
|
||||
public void animate_working_bids_inside(bool inside) {
|
||||
if (_working_bids_inside != inside) {
|
||||
_working_bids_inside = inside;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
}
|
||||
public void animate_working_bids_filled() {
|
||||
Disposable.dispose(ref _remove_working_bids_filled);
|
||||
if (!_working_bids_filled) {
|
||||
_working_bids_filled = true;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
_remove_working_bids_filled = TaskHelper.DelayAction(flash_duration, () => { _working_bids_filled = false; _fire_animations_changed(); });
|
||||
}
|
||||
public void animate_working_asks_active(bool active) {
|
||||
if (_working_asks_active != active) {
|
||||
_working_asks_active = active;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
}
|
||||
public void animate_working_asks_inside(bool inside) {
|
||||
if (_working_asks_inside != inside) {
|
||||
_working_asks_inside = inside;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
}
|
||||
public void animate_working_asks_filled() {
|
||||
Disposable.dispose(ref _remove_working_asks_filled);
|
||||
if (!_working_asks_filled) {
|
||||
_working_asks_filled = true;
|
||||
_fire_animations_changed();
|
||||
}
|
||||
_remove_working_asks_filled = TaskHelper.DelayAction(flash_duration, () => { _working_asks_filled = false; _fire_animations_changed(); });
|
||||
}
|
||||
public IEnumerable<CellAnimation> get_animations() {
|
||||
if (_position_increased) yield return Bank.PositionIncrease;
|
||||
else if (_position_decreased) yield return Bank.PositionDecrease;
|
||||
if (_working_bids_filled) yield return Bank.WorkingBidsFilled;
|
||||
else if (_working_bids_inside) yield return Bank.WorkingBidsInside;
|
||||
else if (_working_bids_active) yield return Bank.WorkingBidsActive;
|
||||
if (_working_asks_filled) yield return Bank.WorkingAsksFilled;
|
||||
else if (_working_asks_inside) yield return Bank.WorkingAsksInside;
|
||||
else if (_working_asks_active) yield return Bank.WorkingAsksActive;
|
||||
if (_day_change_increased) yield return Bank.DayChangeIncrease;
|
||||
else if (_day_change_decreased) yield return Bank.DayChangeDecrease;
|
||||
}
|
||||
|
||||
private void _fire_animations_changed() { AnimationsChanged?.Invoke(); }
|
||||
public event Action AnimationsChanged;
|
||||
|
||||
private static readonly Animations Bank = new Animations(new CellAnimation(Columns.Position, CellAnimation.Type.UpArrow, Brushes.Green),
|
||||
new CellAnimation(Columns.Position, CellAnimation.Type.DownArrow, Brushes.Red),
|
||||
new CellAnimation(Columns.DayChange, CellAnimation.Type.UpArrow, Brushes.Green),
|
||||
new CellAnimation(Columns.DayChange, CellAnimation.Type.DownArrow, Brushes.Red),
|
||||
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
|
||||
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, new SolidColorBrush(BTSColors.MarketData.bid)),
|
||||
new CellAnimation(Columns.WorkingBids, CellAnimation.Type.Border, Brushes.Green),
|
||||
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
|
||||
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, new SolidColorBrush(BTSColors.MarketData.ask)),
|
||||
new CellAnimation(Columns.WorkingAsks, CellAnimation.Type.Border, Brushes.Red));
|
||||
private static readonly TimeSpan flash_duration = TimeSpan.FromSeconds(2);
|
||||
}
|
||||
|
||||
private class Animations {
|
||||
public Animations(CellAnimation positionIncrease, CellAnimation positionDecrease,
|
||||
CellAnimation dayChangeIncrease, CellAnimation dayChangeDecrease,
|
||||
CellAnimation workingBidsActive, CellAnimation workingBidsInside, CellAnimation workingBidsFilled,
|
||||
CellAnimation workingAsksActive, CellAnimation workingAsksInside, CellAnimation workingAsksFilled) {
|
||||
PositionIncrease = positionIncrease;
|
||||
PositionDecrease = positionDecrease;
|
||||
DayChangeIncrease = dayChangeIncrease;
|
||||
DayChangeDecrease = dayChangeDecrease;
|
||||
WorkingBidsActive = workingBidsActive;
|
||||
WorkingBidsInside = workingBidsInside;
|
||||
WorkingBidsFilled = workingBidsFilled;
|
||||
WorkingAsksActive = workingAsksActive;
|
||||
WorkingAsksInside = workingAsksInside;
|
||||
WorkingAsksFilled = workingAsksFilled;
|
||||
}
|
||||
public readonly CellAnimation PositionIncrease, PositionDecrease, DayChangeIncrease, DayChangeDecrease, WorkingBidsActive, WorkingBidsInside, WorkingBidsFilled, WorkingAsksActive, WorkingAsksInside, WorkingAsksFilled;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -16,6 +16,7 @@
|
||||
|
||||
using Spark.Api.Position;
|
||||
using Spark.Core;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Trading;
|
||||
|
||||
using System;
|
||||
@@ -29,10 +30,10 @@
|
||||
using TickFactors = bts.api.domain.TickFactorsImmutable;
|
||||
|
||||
partial class MarketViewVM {
|
||||
public class Row : DisposableViewModelBase, ISecurityMDRow, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
|
||||
public class Row : DisposableViewModelBase, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
|
||||
readonly IBus _bus;
|
||||
readonly OrdersModel _orders_model;
|
||||
readonly AnimationManager _animation = new();
|
||||
readonly MarketViewRowAnimationModel _animation = new();
|
||||
readonly MyOrderSummarizer _order_summarizer;
|
||||
readonly DeferrableAction _raise_invalidated;
|
||||
|
||||
@@ -85,7 +86,7 @@
|
||||
_orders_model = orders_model;
|
||||
_order_summarizer = new(
|
||||
smd.quantity_display.HasTickFactors ?
|
||||
smd.quantity_display.TickFactors : new(new() { TickBase = 1, TickUnit = 1}));
|
||||
smd.quantity_display.TickFactors : new(new() { TickBase = 1, TickUnit = 1 }));
|
||||
_raise_invalidated = new(() => invalidated?.Invoke());
|
||||
|
||||
_day_position = new CellProperty<double>(this, nameof(day_position), fmt_display_qty_double);
|
||||
@@ -112,14 +113,16 @@
|
||||
_ask_implied_size = backing(nameof(iask_qty), 0u, convert_display_qty_uint);
|
||||
_ask_merged_size = backing(nameof(ask_qty), 0u, convert_display_qty_uint);
|
||||
|
||||
_working_best_bid = new CellProperty<double>(this, nameof(working_best_bid), this.format_price, double.NaN);
|
||||
_working_best_ask = new CellProperty<double>(this, nameof(working_best_ask), this.format_price, double.NaN);
|
||||
_working_best_bid = new CellProperty<double>(
|
||||
this, nameof(working_best_bid), format_price, double.NaN);
|
||||
_working_best_ask = new CellProperty<double>(
|
||||
this, nameof(working_best_ask), format_price, double.NaN);
|
||||
|
||||
// greeks
|
||||
_greeks = backing(nameof(greeks), GreeksTuple.empty);
|
||||
_vol = backing(nameof(vol), _greeks.observe_current(true), g => g.vol);
|
||||
_driver = backing(nameof(driver), _greeks.observe_current(true), g => g.driver);
|
||||
_theo = backing(nameof(theo), _greeks.observe_current(true), g => g.theo);
|
||||
_theo = backing(nameof(theo), _greeks.observe_current(true), g => g.normalized_theo);
|
||||
_delta = backing(nameof(delta), _greeks.observe_current(true), g => g.delta);
|
||||
_gamma = backing(nameof(gamma), _greeks.observe_current(true), g => g.gamma);
|
||||
_vega = backing(nameof(vega), _greeks.observe_current(true), g => g.vega);
|
||||
@@ -138,7 +141,7 @@
|
||||
ask_implied_size_click = new DelegateCommand(() => _show_order_ticket(MarketViewColumnType.AskImpliedQty));
|
||||
working_asks_click = new DelegateCommand(() => _show_order_book(MarketViewColumnType.WorkingAsks));
|
||||
|
||||
_animation.AnimationsChanged += on_animations_changed;
|
||||
_animation.animations_changed += on_animations_changed;
|
||||
|
||||
_dispose = Disposable.Create(
|
||||
attach_prop_changed_cb(_bid_direct_size, mk_echo_prop_changed_cb<(uint, uint)>(nameof(dbid_qty_text))),
|
||||
@@ -152,7 +155,7 @@
|
||||
_inside_bids.OnDispatcher().Subscribe(v => _animation.animate_working_bids_inside(v.newval)),
|
||||
_inside_asks.OnDispatcher().Subscribe(v => _animation.animate_working_asks_inside(v.newval)),
|
||||
_day_change.OnDispatcher().Subscribe(v => _animation.animate_day_change(v.newval > v.oldval)),
|
||||
Disposable.Create(() => _animation.AnimationsChanged -= on_animations_changed));
|
||||
Disposable.Create(() => _animation.animations_changed -= on_animations_changed));
|
||||
|
||||
void on_animations_changed() => RaisePropertyChanged(nameof(animations));
|
||||
|
||||
@@ -210,7 +213,6 @@
|
||||
public SecurityMD security_md { get; }
|
||||
public SecurityImmutable security => security_md.security;
|
||||
public uint security_key => security_md.security.Id;
|
||||
SecurityMD ISecurityMDRow.md => security_md;
|
||||
|
||||
public bool inside_bids => _inside_bids.value;
|
||||
public bool inside_asks => _inside_asks.value;
|
||||
@@ -293,8 +295,7 @@
|
||||
public double rho => _rho.Value;
|
||||
|
||||
// animations
|
||||
public IList<ui.spark.CellAnimation> animations => _animation.get_animations().ToList();
|
||||
public ObservableCollection<RowAnimation> row_animations { get; } = new();
|
||||
public IList<ui.spark.CellAnimation> animations => _animation.animations.ToList();
|
||||
|
||||
public bool is_visible {
|
||||
get => _is_visible;
|
||||
@@ -318,6 +319,9 @@
|
||||
(_display_qty_divisor_backing = _orders_model.security_auxiliary_model.get_display_quantity_divisor(security)).Value;
|
||||
IMDConsumerHandle _md => security_md.md;
|
||||
|
||||
public string format_price(double price) =>
|
||||
security.ContractSpec.format(price);
|
||||
|
||||
public void raise_invalidated() =>
|
||||
_raise_invalidated.Invoke();
|
||||
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
#nullable enable
|
||||
namespace mbts.spark {
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Async;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Windows.Media;
|
||||
|
||||
using CellAnimation = ui.spark.CellAnimation;
|
||||
using ColType = MarketViewColumnType;
|
||||
|
||||
class MarketViewRowAnimationModel {
|
||||
static readonly TimeSpan _flash_duration = TimeSpan.FromSeconds(2);
|
||||
static readonly MarketViewAnimations _bank = new() {
|
||||
position_increase = new(ColType.Position, CellAnimation.Type.UpArrow, Brushes.Green),
|
||||
position_decrease = new(ColType.Position, CellAnimation.Type.DownArrow, Brushes.Red),
|
||||
day_change_increase = new(ColType.DayChange, CellAnimation.Type.UpArrow, Brushes.Green),
|
||||
day_change_decrease = new(ColType.DayChange, CellAnimation.Type.DownArrow, Brushes.Red),
|
||||
working_bids_active = new(ColType.WorkingBids, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
|
||||
working_bids_inside = new(ColType.WorkingBids, CellAnimation.Type.Border, BTSColors.MarketData.bid.to_brush()),
|
||||
working_bids_filled = new(ColType.WorkingBids, CellAnimation.Type.Border, Brushes.Green),
|
||||
working_asks_active = new(ColType.WorkingAsks, CellAnimation.Type.Border, BTSColors.warning.to_brush()),
|
||||
working_asks_inside = new(ColType.WorkingAsks, CellAnimation.Type.Border, BTSColors.MarketData.ask.to_brush()),
|
||||
working_asks_filled = new(ColType.WorkingAsks, CellAnimation.Type.Border, Brushes.Red)
|
||||
};
|
||||
|
||||
readonly ValueTimeline<CellAnimation?> _position;
|
||||
readonly ValueTimeline<CellAnimation?> _day_change;
|
||||
readonly ValueTimeline<CellAnimation?> _working_bids_active;
|
||||
readonly ValueTimeline<CellAnimation?> _working_bids_inside;
|
||||
readonly ValueTimeline<CellAnimation?> _working_bids_filled;
|
||||
readonly ValueTimeline<CellAnimation?> _working_asks_active;
|
||||
readonly ValueTimeline<CellAnimation?> _working_asks_inside;
|
||||
readonly ValueTimeline<CellAnimation?> _working_asks_filled;
|
||||
readonly DeferrableAction _refresh;
|
||||
|
||||
public MarketViewRowAnimationModel() {
|
||||
_refresh = new(() => animations_changed?.Invoke());
|
||||
_position = mk_animation_model();
|
||||
_day_change = mk_animation_model();
|
||||
_working_bids_filled = mk_animation_model();
|
||||
_working_bids_inside = mk_animation_model();
|
||||
_working_bids_active = mk_animation_model();
|
||||
_working_asks_filled = mk_animation_model();
|
||||
_working_asks_inside = mk_animation_model();
|
||||
_working_asks_active = mk_animation_model();
|
||||
ValueTimeline<CellAnimation?> mk_animation_model() {
|
||||
var animation_model = new ValueTimeline<CellAnimation?>(null);
|
||||
animation_model.value_changed += _refresh.Invoke;
|
||||
return animation_model;
|
||||
}
|
||||
}
|
||||
|
||||
public event Action? animations_changed;
|
||||
|
||||
public IEnumerable<CellAnimation> animations {
|
||||
get {
|
||||
return impl().SelectWhereValues();
|
||||
|
||||
IEnumerable<CellAnimation?> impl() {
|
||||
yield return _position.value;
|
||||
yield return _day_change.value;
|
||||
yield return _working_bids_active.value;
|
||||
yield return _working_bids_inside.value;
|
||||
yield return _working_bids_filled.value;
|
||||
yield return _working_asks_active.value;
|
||||
yield return _working_asks_inside.value;
|
||||
yield return _working_asks_filled.value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void animate_position(bool increased) {
|
||||
var anim = increased ? _bank.position_increase : _bank.position_decrease;
|
||||
_position.begin((anim, _flash_duration)).ignore();
|
||||
}
|
||||
|
||||
public void animate_day_change(bool increased) {
|
||||
var anim = increased ? _bank.day_change_increase : _bank.day_change_decrease;
|
||||
_day_change.begin((anim, _flash_duration)).ignore();
|
||||
}
|
||||
|
||||
public void animate_working_bids_active(bool active) =>
|
||||
_working_bids_active.value = active ? _bank.working_bids_active : null;
|
||||
|
||||
public void animate_working_bids_inside(bool inside) =>
|
||||
_working_bids_inside.value = inside ? _bank.working_bids_active : null;
|
||||
|
||||
public void animate_working_bids_filled() =>
|
||||
_working_bids_filled.begin((
|
||||
_bank.working_bids_filled, _flash_duration)).ignore();
|
||||
|
||||
public void animate_working_asks_active(bool active) =>
|
||||
_working_asks_active.value = active ? _bank.working_asks_active : null;
|
||||
|
||||
public void animate_working_asks_inside(bool inside) =>
|
||||
_working_asks_inside.value = inside ? _bank.working_asks_inside : null;
|
||||
|
||||
public void animate_working_asks_filled() =>
|
||||
_working_asks_filled.begin((
|
||||
_bank.working_asks_filled, _flash_duration)).ignore();
|
||||
|
||||
readonly struct MarketViewAnimations {
|
||||
public CellAnimation position_increase { get; init; }
|
||||
public CellAnimation position_decrease { get; init; }
|
||||
public CellAnimation day_change_increase { get; init; }
|
||||
public CellAnimation day_change_decrease { get; init; }
|
||||
public CellAnimation working_bids_active { get; init; }
|
||||
public CellAnimation working_bids_inside { get; init; }
|
||||
public CellAnimation working_bids_filled { get; init; }
|
||||
public CellAnimation working_asks_active { get; init; }
|
||||
public CellAnimation working_asks_inside { get; init; }
|
||||
public CellAnimation working_asks_filled { get; init; }
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -18,7 +18,9 @@ namespace mbts.spark {
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reflection;
|
||||
using Spark.Trading;
|
||||
|
||||
@@ -177,8 +179,8 @@ namespace mbts.spark {
|
||||
|
||||
// greeks
|
||||
add_col(ColKey.Volatility, r => fmt_greek(r.vol), nameof(Row.vol), vol_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Driver, r => fmt_greek(r.driver), nameof(Row.driver), driver_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Theo, r => fmt_greek(r.theo), nameof(Row.theo), theo_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Driver, r => r.format_price(r.driver), nameof(Row.driver), driver_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Theo, r => r.format_price(r.theo), nameof(Row.theo), theo_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Delta, r => fmt_greek(r.delta), nameof(Row.delta), delta_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Gamma, r => fmt_greek(r.gamma), nameof(Row.gamma), gamma_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
add_col(ColKey.Vega, r => fmt_greek(r.vega), nameof(Row.vega), vega_filter, FilterType.DoubleMinMax, ColWidth.Greeks);
|
||||
|
||||
@@ -1,274 +1,290 @@
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.collections;
|
||||
using bts.shell;
|
||||
using bts.shell.fills;
|
||||
using bts.shell.market_view;
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
|
||||
using mbts.persist;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Data;
|
||||
using Spark.Trading;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
|
||||
namespace mbts.spark {
|
||||
class MarketViewWindow : SparkWindow<MarketViewSettings>, ISharedWindow, ISlowMeasureContentSize {
|
||||
const string _window_type = "MarketView", _window_type_display_name = "Market View";
|
||||
|
||||
readonly OrdersModel _orders_model;
|
||||
readonly ISecurityMetadataStore _sec_meta_store;
|
||||
readonly IPositionModel _position_model;
|
||||
readonly AllowOnce _init_guard = new AllowOnce("MarketView");
|
||||
readonly UserSettingsHub _settings_hub;
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
|
||||
List<SortingCriteria> _current_sorting_criteria;
|
||||
MarketViewVM _vm;
|
||||
MarketViewView _view;
|
||||
MarketViewSettings _state;
|
||||
IReadOnlyList<SparkCommand> _commands;
|
||||
IDisposable _subscriptions;
|
||||
SecurityCriteria
|
||||
_selected_security_criteria_backing,
|
||||
_sorted_selected_security_criteria_backing;
|
||||
SparkMenuDisplayVM _menu_display_vm;
|
||||
SimpleGridSettingsManager<MarketViewVM.Row> _grid_settings_manager;
|
||||
|
||||
public MarketViewWindow(
|
||||
MarketViewWindowFactory factory,
|
||||
IBus bus,
|
||||
OrdersModel orders_model,
|
||||
IPositionModel position_model,
|
||||
ISecurityMetadataStore sec_meta_store,
|
||||
MarketViewSettings state,
|
||||
UserSettingsHub settings_hub)
|
||||
: base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) {
|
||||
_orders_model = orders_model;
|
||||
_position_model = position_model;
|
||||
_sec_meta_store = sec_meta_store;
|
||||
_state = state;
|
||||
_settings_hub = settings_hub;
|
||||
_settings_manager = settings_hub.create_mview_settings_manager(state.grid);
|
||||
Icon.Freeze();
|
||||
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().market_view ? "MarketView" : null;
|
||||
_dispose = Disposable.Create(() => {
|
||||
Disposable.dispose(ref _subscriptions);
|
||||
_vm.Dispose();
|
||||
Commands.OfType<IDisposable>().DisposeAll();
|
||||
});
|
||||
}
|
||||
|
||||
event Action<SecurityCriteria> _security_criteria_changed;
|
||||
|
||||
public override string window_type => _window_type;
|
||||
public override UIElement Content => _view;
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override MarketViewSettings SaveState =>
|
||||
_state = new MarketViewSettings(
|
||||
_state.security_criteria,
|
||||
_vm.get_filter_states(),
|
||||
_settings_manager.instance_settings,
|
||||
_current_sorting_criteria) {
|
||||
menu_display = _menu_display_vm.create()
|
||||
};
|
||||
|
||||
public override double MinWidth => MarketViewSettings.DefaultGridSettings.columns.Where(c => c.is_visible).Sum(gcs => gcs.width)
|
||||
+ SPARK_MENU_COLLAPSED_WIDTH
|
||||
+ LAUNCHER_BUTTON_BORDER_WIDTH
|
||||
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
|
||||
|
||||
public string thread_id { get; }
|
||||
|
||||
SecurityCriteria _selected_security_criteria {
|
||||
get {
|
||||
if (_selected_security_criteria_backing == null) {
|
||||
if (_sorted_selected_security_criteria_backing != null) {
|
||||
_selected_security_criteria_backing = _sorted_selected_security_criteria_backing;
|
||||
} else if (_vm != null)
|
||||
_selected_security_criteria_backing = SecurityCriteria.from_securities(_vm.selected_rows.Select(r => r.security));
|
||||
}
|
||||
return _selected_security_criteria_backing;
|
||||
}
|
||||
}
|
||||
|
||||
SecurityCriteria _sorted_selected_security_criteria => _sorted_selected_security_criteria_backing ?? (
|
||||
_sorted_selected_security_criteria_backing = _vm != null ?
|
||||
SecurityCriteria.from_securities(_vm.selected_rows.Ordered(_vm.comparer).Select(r => r.security)) :
|
||||
null);
|
||||
|
||||
bool _has_selected_rows() => _vm != null && _vm.selected_rows.Count > 0;
|
||||
|
||||
public void thread_init() {
|
||||
_init_guard.check_access();
|
||||
Log.notnull(_state);
|
||||
_menu_display_vm = new SparkMenuDisplayVM();
|
||||
_menu_display_vm.load_from(_state.menu_display);
|
||||
var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name);
|
||||
var security_md_map_src = Observable.Create<IReadOnlyDictionary<uint, SecurityMD>>(o => {
|
||||
IDisposable sub = null;
|
||||
_security_criteria_changed += on_security_criteria_changed;
|
||||
on_security_criteria_changed(_state.security_criteria);
|
||||
return Disposable.Create(dispose);
|
||||
void on_security_criteria_changed(SecurityCriteria security_criteria) {
|
||||
sub?.Dispose();
|
||||
sub = _state.security_criteria
|
||||
.subscribe_md_map(_bus.subscribe(SparkTags.SecuritiesTag)).Subscribe(o.OnNext);
|
||||
}
|
||||
void dispose() =>
|
||||
Disposable.dispose(ref sub);
|
||||
});
|
||||
_vm = new MarketViewVM(
|
||||
_bus,
|
||||
_orders_model,
|
||||
_position_model,
|
||||
_sec_meta_store,
|
||||
_settings_hub,
|
||||
security_md_map_src
|
||||
.BufferLatest(TimeSpan.FromSeconds(1))
|
||||
.Table(SecurityMD.key_fn)
|
||||
.Where(t => t.has_changes())
|
||||
.OnDispatcher());
|
||||
var sort_man = new ColumnSortManager(_vm.columns, MarketViewColumnType.Security.ToString());
|
||||
_current_sorting_criteria = _state.sorting_criteria.ToList();
|
||||
sort_man.SortingCriteria = _state.sorting_criteria;
|
||||
_vm.load_filters(_state.filters);
|
||||
_vm.comparer = sort_man.BuildComparer<MarketViewColumnType, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
|
||||
_view = new MarketViewView { DataContext = _vm };
|
||||
_view._grid.Sorting += on_grid_sorting;
|
||||
_grid_settings_manager = new SimpleGridSettingsManager<MarketViewVM.Row>(_vm.columns, null, _vm.rows);
|
||||
_grid_settings_manager.load_from(_settings_manager.current_settings());
|
||||
/// The 'CanExecute' plumbing for the cmds below is designed to avoid potentially costly .ToList() operations on the selected_rows/securities.
|
||||
/// Some of the cmds post ITags with data that is, or has, a SecurityCriteria member; the SecurityCriteria constructor creates a new List of the specified securities.
|
||||
/// For these commands, the objective is to evaluate 'CanExecute' without instantiating the SecurityCriteria (or more importantly, without creating a new List).
|
||||
// show time and sales
|
||||
var show_tas_cmd = new DelegateCommand(() => {
|
||||
var sc = _selected_security_criteria;
|
||||
if (sc.is_defined())
|
||||
_bus.post(SparkTags.ShowTimeAndSalesTag, sc);
|
||||
}, _has_selected_rows);
|
||||
var show_tas_actual_cmd = SparkCommands.ShowTimeAndSales;
|
||||
var show_tas_cmd_wrapper = new SparkCommandCommand(show_tas_actual_cmd.title, show_tas_actual_cmd.icon, show_tas_cmd);
|
||||
// show fills
|
||||
var show_fills_cmd = new DelegateCommand(() => {
|
||||
var sc = _selected_security_criteria;
|
||||
_bus.post(SparkTags.ShowFillsTag, new FillsSettings(
|
||||
new FillsFilterStates {
|
||||
security = sc.is_defined() ? sc : _state.security_criteria
|
||||
}));
|
||||
});
|
||||
var show_fills_actual_cmd = SparkCommands.ShowFills();
|
||||
var show_fills_cmd_wrapper = new SparkCommandCommand(show_fills_actual_cmd.title, show_fills_actual_cmd.icon, show_fills_cmd, SparkCommands.KeyGestures.ShowFills);
|
||||
var show_mini_fills_cmd = new DelegateCommand(() => _view.show_mini_fills(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
|
||||
var show_ticket_cmd = new DelegateCommand(() => {
|
||||
var smd = _vm.current_security_md;
|
||||
if (smd.HasValue)
|
||||
_view.show_order_ticket(smd.Value);
|
||||
}, () => _vm.current_security_md.HasValue);
|
||||
var show_ticket_actual_cmd = SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket);
|
||||
// show synthetic create
|
||||
var show_synth_create_cmd = new DelegateCommand(() => {
|
||||
var sc = _sorted_selected_security_criteria;
|
||||
if (sc.is_defined())
|
||||
_bus.post(SparkTags.ShowSyntheticCreateTag, sc);
|
||||
}, () => _vm.selected_rows.Count > 0 && _vm.selected_rows.Count <= 24);
|
||||
var show_synth_create_actual_cmd = SparkCommands.ShowSyntheticCreate();
|
||||
var show_synth_create_cmd_wrapper = new SparkCommandCommand(show_synth_create_actual_cmd.title, show_synth_create_actual_cmd.icon, show_synth_create_cmd, SparkCommands.KeyGestures.ShowSyntheticCreate);
|
||||
var show_working_orders_cmd = new DelegateCommand(() => _view.show_working_orders(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
|
||||
|
||||
var current_sec_md_src = Observable.Create<SecurityMD?>(o => {
|
||||
notify(null, null);
|
||||
_vm.current_row_changed += notify;
|
||||
return Disposable.Create(() => _vm.current_row_changed -= notify);
|
||||
void notify(MarketViewVM.Row oldval, MarketViewVM.Row newval) {
|
||||
if (newval != null)
|
||||
o.OnNext(newval.security_md);
|
||||
else o.OnNext(null);
|
||||
}
|
||||
});
|
||||
_commands = new List<SparkCommand> {
|
||||
SparkCommands.ShowLadders(SparkCommands.KeyGestures.ShowLadder).complete(_vm.selected_rows.Observe().Select(_ => _vm.selected_rows.WrapSelectorRO(r => r.security_md)), smds => smds.Count > 0),
|
||||
SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(current_sec_md_src, md => md.HasValue, ConvertUtils.ValueOrDefault),
|
||||
show_fills_cmd_wrapper,
|
||||
show_tas_cmd_wrapper,
|
||||
show_synth_create_cmd_wrapper,
|
||||
// Note: the commands commented out below open the mini popup versions of their respective windows
|
||||
// TODO: determine if/how to integrate the mini popups into the toolbar.
|
||||
//new SparkCommandCommand("Working Orders", Icons.Orders, show_working_orders_cmd),
|
||||
//new SparkCommandCommand("Fills", show_fills_actual_cmd.icon, show_mini_fills_cmd),
|
||||
//new SparkCommandCommand(show_ticket_actual_cmd.title, show_ticket_actual_cmd.icon, show_ticket_cmd),
|
||||
SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)),
|
||||
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
|
||||
SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
|
||||
_settings_manager,
|
||||
us => us.market_view_grid,
|
||||
UserSettings.FileExtensions.GRID,
|
||||
s => _grid_settings_manager.create_vm(
|
||||
// we need to get the most up to date GridSettings when launching b/c users may
|
||||
// have changed some settings on the grid directly, like column widths.
|
||||
s.with(_vm.columns.Select(c => c.create()))
|
||||
)
|
||||
);
|
||||
vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t));
|
||||
var dialog = new ShellSettingsDialog { DataContext = vm };
|
||||
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
})),
|
||||
_menu_display_vm.spark_cmd
|
||||
};
|
||||
//
|
||||
_vm.selected_rows.CollectionChanged += on_selection_changed;
|
||||
_subscriptions = new CompositeDisposable(
|
||||
_bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c => {
|
||||
_state = new MarketViewSettings(c, _state.filters, _state.grid, _state.sorting_criteria.ToList());
|
||||
_security_criteria_changed?.Invoke(c);
|
||||
}),
|
||||
_settings_manager.subscribe_current().OnDispatcher().Subscribe(new CompositeObserver<GridSettings>(_grid_settings_manager) {
|
||||
s => _vm.selection_highlight = s.selection_highlight
|
||||
})) {
|
||||
() => {
|
||||
_vm.selected_rows.CollectionChanged -= on_selection_changed;
|
||||
_view._grid.Sorting -= on_grid_sorting;
|
||||
}
|
||||
};
|
||||
|
||||
void on_selection_changed(object sender, NotifyCollectionChangedEventArgs e) {
|
||||
// invalidate selected security criteria
|
||||
_selected_security_criteria_backing = null;
|
||||
_sorted_selected_security_criteria_backing = null;
|
||||
show_tas_cmd.RaiseCanExecuteChanged();
|
||||
show_fills_cmd.RaiseCanExecuteChanged();
|
||||
show_synth_create_cmd.RaiseCanExecuteChanged();
|
||||
show_working_orders_cmd.RaiseCanExecuteChanged();
|
||||
show_mini_fills_cmd.RaiseCanExecuteChanged();
|
||||
show_ticket_cmd.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
void on_grid_sorting(object sender, ui.controls.DIYGridSortingEventArgs e) {
|
||||
_sorted_selected_security_criteria_backing = null;
|
||||
sort_man.OnColumnClick(e.Column, KeyboardExtensions.IsShiftDown());
|
||||
_vm.comparer = sort_man.BuildComparer<MarketViewColumnType, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
|
||||
_current_sorting_criteria = sort_man.SortingCriteria.ToList();
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
|
||||
_menu_display_vm.safe_bind_to_view(parent_view);
|
||||
}
|
||||
}
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.api.core;
|
||||
using bts.collections;
|
||||
using bts.shell;
|
||||
using bts.shell.fills;
|
||||
using bts.shell.market_view;
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
|
||||
using mbts.persist;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Data;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Trading;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
|
||||
namespace mbts.spark {
|
||||
class MarketViewWindow : SparkWindow<MarketViewSettings>, ISharedWindow, ISlowMeasureContentSize {
|
||||
const string _window_type = "MarketView", _window_type_display_name = "Market View";
|
||||
|
||||
readonly OrdersModel _orders_model;
|
||||
readonly ISecurityMetadataStore _sec_meta_store;
|
||||
readonly IPositionModel _position_model;
|
||||
readonly AllowOnce _init_guard = new AllowOnce("MarketView");
|
||||
readonly UserSettingsHub _settings_hub;
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
|
||||
List<SortingCriteria> _current_sorting_criteria;
|
||||
MarketViewVM _vm;
|
||||
MarketViewView _view;
|
||||
MarketViewSettings _state;
|
||||
IReadOnlyList<SparkCommand> _commands;
|
||||
IDisposable _subscriptions;
|
||||
SecurityCriteria
|
||||
_selected_security_criteria_backing,
|
||||
_sorted_selected_security_criteria_backing;
|
||||
SparkMenuDisplayVM _menu_display_vm;
|
||||
SimpleGridSettingsManager<MarketViewVM.Row> _grid_settings_manager;
|
||||
|
||||
public MarketViewWindow(
|
||||
MarketViewWindowFactory factory,
|
||||
IBus bus,
|
||||
OrdersModel orders_model,
|
||||
IPositionModel position_model,
|
||||
ISecurityMetadataStore sec_meta_store,
|
||||
MarketViewSettings state,
|
||||
UserSettingsHub settings_hub)
|
||||
: base("Market View", bus, factory, SparkCommands.ShowMarketView.icon) {
|
||||
_orders_model = orders_model;
|
||||
_position_model = position_model;
|
||||
_sec_meta_store = sec_meta_store;
|
||||
_state = state;
|
||||
_settings_hub = settings_hub;
|
||||
_settings_manager = settings_hub.create_mview_settings_manager(state.grid);
|
||||
Icon.Freeze();
|
||||
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().market_view ? "MarketView" : null;
|
||||
_dispose = Disposable.Create(() => {
|
||||
Disposable.dispose(ref _subscriptions);
|
||||
_vm.Dispose();
|
||||
Commands.OfType<IDisposable>().DisposeAll();
|
||||
});
|
||||
}
|
||||
|
||||
event Action<SecurityCriteria> _security_criteria_changed;
|
||||
|
||||
public override string window_type => _window_type;
|
||||
public override UIElement Content => _view;
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override MarketViewSettings SaveState =>
|
||||
_state = new MarketViewSettings(
|
||||
_state.security_criteria,
|
||||
_vm.get_filter_states(),
|
||||
_settings_manager.instance_settings,
|
||||
_current_sorting_criteria) {
|
||||
menu_display = _menu_display_vm.create()
|
||||
};
|
||||
|
||||
public override double MinWidth => MarketViewSettings.DefaultGridSettings.columns.Where(c => c.is_visible).Sum(gcs => gcs.width)
|
||||
+ SPARK_MENU_COLLAPSED_WIDTH
|
||||
+ LAUNCHER_BUTTON_BORDER_WIDTH
|
||||
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
|
||||
|
||||
public string thread_id { get; }
|
||||
|
||||
SecurityCriteria _selected_security_criteria {
|
||||
get {
|
||||
if (_selected_security_criteria_backing == null) {
|
||||
if (_sorted_selected_security_criteria_backing != null) {
|
||||
_selected_security_criteria_backing = _sorted_selected_security_criteria_backing;
|
||||
} else if (_vm != null)
|
||||
_selected_security_criteria_backing = SecurityCriteria.from_securities(_vm.selected_rows.Select(r => r.security));
|
||||
}
|
||||
return _selected_security_criteria_backing;
|
||||
}
|
||||
}
|
||||
|
||||
SecurityCriteria _sorted_selected_security_criteria => _sorted_selected_security_criteria_backing ?? (
|
||||
_sorted_selected_security_criteria_backing = _vm != null ?
|
||||
SecurityCriteria.from_securities(_vm.selected_rows.Ordered(_vm.comparer).Select(r => r.security)) :
|
||||
null);
|
||||
|
||||
bool _has_selected_rows() => _vm != null && _vm.selected_rows.Count > 0;
|
||||
|
||||
public void thread_init() {
|
||||
_init_guard.check_access();
|
||||
Log.notnull(_state);
|
||||
_menu_display_vm = new SparkMenuDisplayVM();
|
||||
_menu_display_vm.load_from(_state.menu_display);
|
||||
var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name);
|
||||
var security_md_map_src = Observable.Create<IReadOnlyDictionary<uint, SecurityMD>>(o => {
|
||||
IDisposable sub = null;
|
||||
_security_criteria_changed += on_security_criteria_changed;
|
||||
on_security_criteria_changed(_state.security_criteria);
|
||||
return Disposable.Create(dispose);
|
||||
void on_security_criteria_changed(SecurityCriteria security_criteria) {
|
||||
sub?.Dispose();
|
||||
sub = _state.security_criteria
|
||||
.subscribe_md_map(_bus.subscribe(SparkTags.SecuritiesTag)).Subscribe(o.OnNext);
|
||||
}
|
||||
void dispose() =>
|
||||
Disposable.dispose(ref sub);
|
||||
});
|
||||
_vm = new MarketViewVM(
|
||||
_bus,
|
||||
_orders_model,
|
||||
_position_model,
|
||||
_sec_meta_store,
|
||||
_settings_hub,
|
||||
security_md_map_src
|
||||
.BufferLatest(TimeSpan.FromSeconds(1))
|
||||
.Table(SecurityMD.key_fn)
|
||||
.Where(t => t.has_changes())
|
||||
.OnDispatcher());
|
||||
var sort_man = new ColumnSortManager(_vm.columns, MarketViewColumnType.Security.ToString());
|
||||
_current_sorting_criteria = _state.sorting_criteria.ToList();
|
||||
sort_man.SortingCriteria = _state.sorting_criteria;
|
||||
_vm.load_filters(_state.filters);
|
||||
_vm.comparer = sort_man.BuildComparer<MarketViewColumnType, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
|
||||
_view = new MarketViewView { DataContext = _vm };
|
||||
_view._grid.Sorting += on_grid_sorting;
|
||||
_grid_settings_manager = new SimpleGridSettingsManager<MarketViewVM.Row>(_vm.columns, null, _vm.rows);
|
||||
_grid_settings_manager.load_from(_settings_manager.current_settings());
|
||||
/// The 'CanExecute' plumbing for the cmds below is designed to avoid potentially costly .ToList() operations on the selected_rows/securities.
|
||||
/// Some of the cmds post ITags with data that is, or has, a SecurityCriteria member; the SecurityCriteria constructor creates a new List of the specified securities.
|
||||
/// For these commands, the objective is to evaluate 'CanExecute' without instantiating the SecurityCriteria (or more importantly, without creating a new List).
|
||||
// show time and sales
|
||||
var show_tas_cmd = new DelegateCommand(() => {
|
||||
var sc = _selected_security_criteria;
|
||||
if (sc.is_defined())
|
||||
_bus.post(SparkTags.ShowTimeAndSalesTag, sc);
|
||||
}, _has_selected_rows);
|
||||
var show_tas_actual_cmd = SparkCommands.ShowTimeAndSales;
|
||||
var show_tas_cmd_wrapper = new SparkCommandCommand(show_tas_actual_cmd.title, show_tas_actual_cmd.icon, show_tas_cmd);
|
||||
// show fills
|
||||
var show_fills_cmd = new DelegateCommand(() => {
|
||||
var sc = _selected_security_criteria;
|
||||
_bus.post(SparkTags.ShowFillsTag, new FillsSettings(
|
||||
new FillsFilterStates {
|
||||
security = sc.is_defined() ? sc : _state.security_criteria
|
||||
}));
|
||||
});
|
||||
var show_fills_actual_cmd = SparkCommands.ShowFills();
|
||||
var show_fills_cmd_wrapper = new SparkCommandCommand(show_fills_actual_cmd.title, show_fills_actual_cmd.icon, show_fills_cmd, SparkCommands.KeyGestures.ShowFills);
|
||||
var show_mini_fills_cmd = new DelegateCommand(() => _view.show_mini_fills(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
|
||||
var show_ticket_cmd = new DelegateCommand(() => {
|
||||
var smd = _vm.current_security_md;
|
||||
if (smd.HasValue)
|
||||
_view.show_order_ticket(smd.Value);
|
||||
}, () => _vm.current_security_md.HasValue);
|
||||
var show_ticket_actual_cmd = SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket);
|
||||
// show synthetic create
|
||||
var show_synth_create_cmd = new DelegateCommand(() => {
|
||||
var sc = _sorted_selected_security_criteria;
|
||||
if (sc.is_defined())
|
||||
_bus.post(SparkTags.ShowSyntheticCreateTag, sc);
|
||||
}, () => _vm.selected_rows.Count > 0 && _vm.selected_rows.Count <= 24);
|
||||
var show_synth_create_actual_cmd = SparkCommands.ShowSyntheticCreate();
|
||||
var show_synth_create_cmd_wrapper = new SparkCommandCommand(show_synth_create_actual_cmd.title, show_synth_create_actual_cmd.icon, show_synth_create_cmd, SparkCommands.KeyGestures.ShowSyntheticCreate);
|
||||
var show_working_orders_cmd = new DelegateCommand(() => _view.show_working_orders(_vm.selected_securities), () => _vm.selected_securities.Count > 0);
|
||||
|
||||
var current_sec_md_src = Observable.Create<SecurityMD?>(o => {
|
||||
notify(null, null);
|
||||
_vm.current_row_changed += notify;
|
||||
return Disposable.Create(() => _vm.current_row_changed -= notify);
|
||||
void notify(MarketViewVM.Row oldval, MarketViewVM.Row newval) {
|
||||
if (newval != null)
|
||||
o.OnNext(newval.security_md);
|
||||
else o.OnNext(null);
|
||||
}
|
||||
});
|
||||
_commands = new List<SparkCommand> {
|
||||
SparkCommands.ShowLadders(SparkCommands.KeyGestures.ShowLadder).complete(
|
||||
current_sec_md_src,
|
||||
smd => smd.HasValue,
|
||||
_ => _vm.selected_security_mds.ToList()),
|
||||
SparkCommands.ShowOrderTicketFromSecurity(SparkCommands.KeyGestures.ShowOrderTicket).complete(current_sec_md_src, md => md.HasValue, ConvertUtils.ValueOrDefault),
|
||||
show_fills_cmd_wrapper,
|
||||
show_tas_cmd_wrapper,
|
||||
show_synth_create_cmd_wrapper,
|
||||
SparkCommands.show_spread_box().complete(
|
||||
current_sec_md_src,
|
||||
smd => smd.HasValue,
|
||||
_ => _vm.selected_securities.ToImmutableList(s => s.Id)),
|
||||
SparkCommands.send_rfq.complete(
|
||||
current_sec_md_src,
|
||||
smd => smd.HasValue,
|
||||
smd => new(new() {
|
||||
Security = new() {
|
||||
SecurityId = smd.assert_value().security.Id
|
||||
}
|
||||
})),
|
||||
// Note: the commands commented out below open the mini popup versions of their respective windows
|
||||
// TODO: determine if/how to integrate the mini popups into the toolbar.
|
||||
//new SparkCommandCommand("Working Orders", Icons.Orders, show_working_orders_cmd),
|
||||
//new SparkCommandCommand("Fills", show_fills_actual_cmd.icon, show_mini_fills_cmd),
|
||||
//new SparkCommandCommand(show_ticket_actual_cmd.title, show_ticket_actual_cmd.icon, show_ticket_cmd),
|
||||
SparkCommands.change_securities_command(() => (update_securities_cmd, _state.security_criteria)),
|
||||
// wrap the grid settings view factory in a dialogCommand here since the vm is destroyed/recreated when the security criteria changes
|
||||
SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
|
||||
_settings_manager,
|
||||
us => us.market_view_grid,
|
||||
UserSettings.FileExtensions.GRID,
|
||||
s => _grid_settings_manager.create_vm(
|
||||
// we need to get the most up to date GridSettings when launching b/c users may
|
||||
// have changed some settings on the grid directly, like column widths.
|
||||
s.with(_vm.columns.Select(c => c.create()))
|
||||
)
|
||||
);
|
||||
vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t));
|
||||
var dialog = new ShellSettingsDialog { DataContext = vm };
|
||||
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
})),
|
||||
_menu_display_vm.spark_cmd
|
||||
};
|
||||
//
|
||||
_vm.selected_rows.CollectionChanged += on_selection_changed;
|
||||
_subscriptions = Disposable.Create(
|
||||
_bus.subscribe(update_securities_cmd.tag).OnDispatcher().Subscribe(c => {
|
||||
_state = new MarketViewSettings(c, _state.filters, _state.grid, _state.sorting_criteria.ToList());
|
||||
_security_criteria_changed?.Invoke(c);
|
||||
}),
|
||||
_settings_manager.subscribe_current().OnDispatcher().Subscribe(new CompositeObserver<GridSettings>(_grid_settings_manager) {
|
||||
s => _vm.selection_highlight = s.selection_highlight
|
||||
}),
|
||||
Disposable.Create(() => {
|
||||
_vm.selected_rows.CollectionChanged -= on_selection_changed;
|
||||
_view._grid.Sorting -= on_grid_sorting;
|
||||
}));
|
||||
|
||||
void on_selection_changed(object sender, NotifyCollectionChangedEventArgs e) {
|
||||
// invalidate selected security criteria
|
||||
_selected_security_criteria_backing = null;
|
||||
_sorted_selected_security_criteria_backing = null;
|
||||
show_tas_cmd.RaiseCanExecuteChanged();
|
||||
show_fills_cmd.RaiseCanExecuteChanged();
|
||||
show_synth_create_cmd.RaiseCanExecuteChanged();
|
||||
show_working_orders_cmd.RaiseCanExecuteChanged();
|
||||
show_mini_fills_cmd.RaiseCanExecuteChanged();
|
||||
show_ticket_cmd.RaiseCanExecuteChanged();
|
||||
}
|
||||
|
||||
void on_grid_sorting(object sender, ui.controls.DIYGridSortingEventArgs e) {
|
||||
_sorted_selected_security_criteria_backing = null;
|
||||
sort_man.OnColumnClick(e.Column, KeyboardExtensions.IsShiftDown());
|
||||
_vm.comparer = sort_man.BuildComparer<MarketViewColumnType, MarketViewVM.Row>(MarketViewVM.get_column_comparer);
|
||||
_current_sorting_criteria = sort_man.SortingCriteria.ToList();
|
||||
e.Handled = true;
|
||||
}
|
||||
}
|
||||
|
||||
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
|
||||
_menu_display_vm.safe_bind_to_view(parent_view);
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,10 @@
|
||||
|
||||
using bts.api;
|
||||
|
||||
using mbts;
|
||||
using mbts.ui;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
|
||||
@@ -10,10 +10,12 @@
|
||||
using mbts.ui.shell;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
class TimeAndSalesRowVM : ViewModelBase, DIYGrid.IRowVM, ISecurityRow, IEquatable<TimeAndSalesRowVM> {
|
||||
class TimeAndSalesRowVM : ViewModelBase, DIYGrid.IRowVM, IEquatable<TimeAndSalesRowVM> {
|
||||
// key comparer guarentees deterministic sorting
|
||||
// if the rows in the collection have unique row_keys.
|
||||
public static readonly IComparer<TimeAndSalesRowVM> key_comparer =
|
||||
@@ -50,7 +52,10 @@
|
||||
public uint trade_key => _trade.Key;
|
||||
public uint security_key => security.Id;
|
||||
public SecurityImmutable security { get; }
|
||||
public DateTime time => ((ulong)_trade.Time).lldatetime().ToLocalTime();
|
||||
|
||||
public DateTime time =>
|
||||
new LLDateTime((ulong)_trade.Time).to_datetime().ToLocalTime();
|
||||
|
||||
public double price => _trade.price();
|
||||
public double size => _trade.Size;
|
||||
public double display_size => _display_size ??
|
||||
@@ -62,10 +67,10 @@
|
||||
public double vol => _greeks_tuple.vol;
|
||||
public double display_vol => _greeks_tuple.vol * 100;
|
||||
public double driver => _greeks_tuple.driver;
|
||||
public double theo => _greeks_tuple.normalized_theo();
|
||||
public double theo => _greeks_tuple.normalized_theo;
|
||||
public double buy_edge => price - theo;
|
||||
public double sell_edge => theo - price;
|
||||
public double delta => _greeks_tuple.normalized_delta();
|
||||
public double delta => _greeks_tuple.delta;
|
||||
public double display_delta => delta * 100;
|
||||
|
||||
public void raise_invalidated() =>
|
||||
|
||||
@@ -18,6 +18,8 @@
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.Core.Reflection;
|
||||
|
||||
using System;
|
||||
@@ -387,7 +389,7 @@
|
||||
bd.AddRange(e.AddedItems.OfType<TimeAndSalesRowVM>());
|
||||
}
|
||||
if (e.RemovedItems is not null) {
|
||||
bd.removeRange(e.RemovedItems.OfType<TimeAndSalesRowVM>());
|
||||
bd.RemoveRange(e.RemovedItems.OfType<TimeAndSalesRowVM>());
|
||||
}
|
||||
_selected_rows = bd.ToImmutable();
|
||||
_refresh_selected_rows.Invoke();
|
||||
|
||||
@@ -15,6 +15,8 @@
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
|
||||
@@ -10,6 +10,8 @@
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
@@ -9,6 +9,8 @@ using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -9,6 +9,8 @@ using mbts.ui.utility;
|
||||
using mbts.user.settings;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
using mbts.ui.controls;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -6,6 +6,8 @@ using mbts.ui.converters;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
@@ -3,6 +3,8 @@ using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
@@ -1,256 +1,255 @@
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.spark;
|
||||
|
||||
using mbts;
|
||||
using mbts.collections;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
using mbts.user.settings;
|
||||
using mbts.utils;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
|
||||
using Disposable = mbts.Disposable;
|
||||
|
||||
namespace bts.shell.spreader {
|
||||
class SyntheticImportVM : DisposableViewModelBase, IRequestViewClose {
|
||||
IReadOnlyDictionary<uint, SecurityMD> _security_map = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public SyntheticImportVM() {
|
||||
var rows_view = new SyntheticImportRowCollectionView(flat_legs);
|
||||
rows_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ContractLegVM.owner)));
|
||||
this.rows_view = rows_view;
|
||||
ok_cmd = new DelegateCommand(() => import_request?.Invoke());
|
||||
cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs()));
|
||||
_dispose = ObservableAutoWrapper.connect_item_hooks(
|
||||
rows,
|
||||
r => {
|
||||
flat_legs.AddRange(r.legs);
|
||||
return Disposable.Create(() => flat_legs.removeRange(r.legs));
|
||||
});
|
||||
}
|
||||
|
||||
public event Action import_request;
|
||||
public event EventHandler RequestClose;
|
||||
|
||||
public ObservableCollection<SyntheticImportRowVM> rows { get; } = new ObservableCollection<SyntheticImportRowVM>();
|
||||
public ObservableCollection<ContractLegVM> flat_legs { get; } = new ObservableCollection<ContractLegVM>();
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map { get => _security_map; set => Set(ref _security_map, value); }
|
||||
public ICollectionView rows_view { get; }
|
||||
// commands
|
||||
public ICommand ok_cmd { get; }
|
||||
public ICommand cancel_cmd { get; }
|
||||
}
|
||||
|
||||
class SyntheticImportRowVM : DisposableViewModelBase, IEquatable<SyntheticImportRowVM> {
|
||||
readonly ReactiveThresholdMonitor<ContractLegVM> _leg_errors_mon = new ReactiveThresholdMonitor<ContractLegVM>(l => l.subscribe_has_errors(true));
|
||||
readonly Func<string, bool> _get_name_exists;
|
||||
SecurityImmutable? _security;
|
||||
ExecutionStrategyImmutable? _strategy;
|
||||
TickFactors _tick_factors;
|
||||
string _name;
|
||||
bool _is_selected;
|
||||
|
||||
public SyntheticImportRowVM(uint user_id, Func<string, bool> get_name_exists) {
|
||||
this.user_id = user_id;
|
||||
_get_name_exists = get_name_exists;
|
||||
_validate();
|
||||
add_leg_cmd = new DelegateCommand<SyntheticImportRowVM>(r => {
|
||||
if (r != null) {
|
||||
r.legs.Add(new ContractLegVM {
|
||||
price_multiplier = 1,
|
||||
quantity = 1,
|
||||
owner = r
|
||||
});
|
||||
}
|
||||
});
|
||||
remove_leg_cmd = new DelegateCommand<ContractLegVM>(l => l?.owner?.legs?.Remove(l));
|
||||
PropertyChanged += on_property_changed;
|
||||
var disp = new DisposableCombo(
|
||||
_leg_errors_mon.OnDispatcher().Subscribe(v => _validate()),
|
||||
ObservableAutoWrapper.connect_item_hooks(legs,
|
||||
l => {
|
||||
l.result_changed += invalidate;
|
||||
return new DisposableCombo(_leg_errors_mon.join(l), l) +
|
||||
new Action(() => l.result_changed -= invalidate);
|
||||
})) +
|
||||
new Action(() => PropertyChanged -= on_property_changed);
|
||||
|
||||
void invalidate() {
|
||||
_security = null;
|
||||
_strategy = null;
|
||||
_validate();
|
||||
result_changed?.Invoke();
|
||||
}
|
||||
|
||||
void on_property_changed(object sender, PropertyChangedEventArgs e) =>
|
||||
invalidate();
|
||||
}
|
||||
|
||||
public event Action result_changed;
|
||||
|
||||
public SecurityImmutable result =>
|
||||
_security ?? (_security = new SecurityImmutable(to_security())).Value;
|
||||
|
||||
public ExecutionStrategyImmutable strategy =>
|
||||
_strategy ?? (_strategy = new ExecutionStrategyImmutable(to_strategy())).Value;
|
||||
|
||||
public (SecurityImmutable security, ExecutionStrategyImmutable strategy) result_tuple =>
|
||||
(result, strategy);
|
||||
|
||||
public ParsedSyntheticContract parsed_synth { get; set; }
|
||||
|
||||
public string name { get => _name; set => Set(ref _name, value); }
|
||||
public uint user_id { get; }
|
||||
public TickFactors tick_factors { get => _tick_factors; set => Set(ref _tick_factors, value); }
|
||||
public ObservableCollection<ContractLegVM> legs { get; } = new ObservableCollection<ContractLegVM>();
|
||||
public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); }
|
||||
public ICommand add_leg_cmd { get; }
|
||||
public ICommand remove_leg_cmd { get; }
|
||||
|
||||
public Security to_security() {
|
||||
var sc = new SyntheticContract {
|
||||
Name = name,
|
||||
UserId = user_id
|
||||
};
|
||||
sc.Legs.AddRange(legs.Select(l => l.to_contract_leg()));
|
||||
return new Security {
|
||||
Synthetic = sc,
|
||||
Symbol = sc.Legs.FirstOrDefault()?.Security?.Symbol ?? string.Empty,
|
||||
Exchange = Venue.Bts,
|
||||
ContractSpec = tick_factors.to_spec()
|
||||
};
|
||||
}
|
||||
|
||||
public ExecutionStrategy to_strategy() {
|
||||
var strat = new ExecutionStrategy();
|
||||
foreach (var l in legs) {
|
||||
if (l.security.HasValue)
|
||||
strat.LegParamsMap[l.security.Value.Id] = l.to_leg_params();
|
||||
}
|
||||
return strat;
|
||||
}
|
||||
|
||||
void _validate() {
|
||||
using (validation()) {
|
||||
if (string.IsNullOrEmpty(name)) {
|
||||
validation_assert(false, "Name is not specified.", nameof(name));
|
||||
} else if (_get_name_exists(name)) {
|
||||
validation_assert(false, "Name already exists.", nameof(name));
|
||||
}
|
||||
validation_assert(tick_factors != null && tick_factors.is_valid(), "Invalid tick", nameof(tick_factors));
|
||||
validation_assert(legs.Count > 0 && !_leg_errors_mon.is_above_threshold, "Invalid legs.", nameof(legs));
|
||||
}
|
||||
}
|
||||
|
||||
public bool Equals(SyntheticImportRowVM other) =>
|
||||
other != null &&
|
||||
parsed_synth.unpersisted_id == other.parsed_synth.unpersisted_id;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as SyntheticImportRowVM);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
parsed_synth.unpersisted_id;
|
||||
}
|
||||
|
||||
class ContractLegVM : DisposableViewModelBase, IEquatable<ContractLegVM> {
|
||||
ContractLegImmutable? _leg;
|
||||
LegSpreaderParamsImmutable? _leg_params;
|
||||
SecurityImmutable? _security;
|
||||
double _price_multiplier, _quantity;
|
||||
ContractLegType _leg_type;
|
||||
bool _is_selected;
|
||||
|
||||
public ContractLegVM() {
|
||||
PropertyChanged += on_property_changed;
|
||||
_dispose = Disposable.Create(() => PropertyChanged -= on_property_changed);
|
||||
_validate();
|
||||
void on_property_changed(object sender, PropertyChangedEventArgs e) {
|
||||
switch (e.PropertyName) {
|
||||
case nameof(security):
|
||||
case nameof(price_multiplier):
|
||||
case nameof(quantity):
|
||||
_leg = null;
|
||||
break;
|
||||
case nameof(leg_type):
|
||||
_leg_params = null;
|
||||
break;
|
||||
default: return;
|
||||
}
|
||||
_validate();
|
||||
result_changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public event Action result_changed;
|
||||
|
||||
public ParsedContractLeg parsed_leg { get; set; }
|
||||
public SyntheticImportRowVM owner { get; set; }
|
||||
public int owner_id => owner.parsed_synth.unpersisted_id;
|
||||
public int id => parsed_leg.id;
|
||||
|
||||
public ContractLegImmutable leg =>
|
||||
_leg ?? (_leg = new ContractLegImmutable(to_contract_leg())).Value;
|
||||
|
||||
public LegSpreaderParamsImmutable leg_params =>
|
||||
_leg_params ?? (_leg_params = new LegSpreaderParamsImmutable(to_leg_params())).Value;
|
||||
|
||||
public (ContractLegImmutable leg, LegSpreaderParamsImmutable leg_params) result_tuple =>
|
||||
(leg, leg_params);
|
||||
|
||||
public SecurityImmutable? security { get => _security; set => Set(ref _security, value); }
|
||||
public double price_multiplier { get => _price_multiplier; set => Set(ref _price_multiplier, value); }
|
||||
public double quantity { get => _quantity; set => Set(ref _quantity, value); }
|
||||
public ContractLegType leg_type { get => _leg_type; set => Set(ref _leg_type, value); }
|
||||
public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); }
|
||||
|
||||
public void load(ContractLegImmutable leg) {
|
||||
security = leg.Security;
|
||||
price_multiplier = leg.PriceMultiplier;
|
||||
quantity = leg.Quantity;
|
||||
}
|
||||
|
||||
public ContractLeg to_contract_leg() =>
|
||||
new ContractLeg {
|
||||
Security = security?.CloneToMutable(),
|
||||
PriceMultiplier = price_multiplier,
|
||||
Side = quantity < 0 ? Side.Sell : Side.Buy,
|
||||
Quantity = Math.Abs(quantity)
|
||||
};
|
||||
|
||||
public LegSpreaderParams to_leg_params() {
|
||||
var lps = SyntheticDataHelper.Defaults.LegSpreaderParams;
|
||||
lps.EnableHedging = (leg_type & ContractLegType.Hedge) != 0;
|
||||
lps.IsActiveQuoting = (leg_type & ContractLegType.Quote) != 0;
|
||||
return lps;
|
||||
}
|
||||
|
||||
void _validate() {
|
||||
using (validation()) {
|
||||
validation_assert(security.is_exchange_security(), "Invalid security", nameof(security));
|
||||
validation_assert(price_multiplier.IsNonZero(), "Invalid price multiplier", nameof(price_multiplier));
|
||||
validation_assert(quantity.IsNonZero(), "Invalid quantity", nameof(quantity));
|
||||
}
|
||||
}
|
||||
|
||||
public bool Equals(ContractLegVM other) =>
|
||||
other != null && id == other.id;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as ContractLegVM);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
id;
|
||||
}
|
||||
}
|
||||
using bts.api;
|
||||
using bts.collections;
|
||||
using bts.spark;
|
||||
|
||||
using mbts;
|
||||
using mbts.collections;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
using mbts.user.settings;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Data;
|
||||
using System.Windows.Input;
|
||||
|
||||
namespace bts.shell.spreader {
|
||||
class SyntheticImportVM : DisposableViewModelBase, IRequestViewClose {
|
||||
IReadOnlyDictionary<uint, SecurityMD> _security_map = DictionaryHelper.empty<uint, SecurityMD>();
|
||||
|
||||
public SyntheticImportVM() {
|
||||
var rows_view = new SyntheticImportRowCollectionView(flat_legs);
|
||||
rows_view.GroupDescriptions.Add(new PropertyGroupDescription(nameof(ContractLegVM.owner)));
|
||||
this.rows_view = rows_view;
|
||||
ok_cmd = new DelegateCommand(() => import_request?.Invoke());
|
||||
cancel_cmd = new DelegateCommand(() => RequestClose?.Invoke(this, new EventArgs()));
|
||||
_dispose = ObservableAutoWrapper.connect_item_hooks(
|
||||
rows,
|
||||
r => {
|
||||
flat_legs.AddRange(r.legs);
|
||||
return Disposable.Create(() => flat_legs.removeRange(r.legs));
|
||||
});
|
||||
}
|
||||
|
||||
public event Action import_request;
|
||||
public event EventHandler RequestClose;
|
||||
|
||||
public ObservableCollection<SyntheticImportRowVM> rows { get; } = new ObservableCollection<SyntheticImportRowVM>();
|
||||
public ObservableCollection<ContractLegVM> flat_legs { get; } = new ObservableCollection<ContractLegVM>();
|
||||
public IReadOnlyDictionary<uint, SecurityMD> security_map { get => _security_map; set => Set(ref _security_map, value); }
|
||||
public ICollectionView rows_view { get; }
|
||||
// commands
|
||||
public ICommand ok_cmd { get; }
|
||||
public ICommand cancel_cmd { get; }
|
||||
}
|
||||
|
||||
class SyntheticImportRowVM : DisposableViewModelBase, IEquatable<SyntheticImportRowVM> {
|
||||
readonly ReactiveThresholdMonitor<ContractLegVM> _leg_errors_mon = new ReactiveThresholdMonitor<ContractLegVM>(l => l.subscribe_has_errors(true));
|
||||
readonly Func<string, bool> _get_name_exists;
|
||||
SecurityImmutable? _security;
|
||||
ExecutionStrategyImmutable? _strategy;
|
||||
TickFactors _tick_factors;
|
||||
string _name;
|
||||
bool _is_selected;
|
||||
|
||||
public SyntheticImportRowVM(uint user_id, Func<string, bool> get_name_exists) {
|
||||
this.user_id = user_id;
|
||||
_get_name_exists = get_name_exists;
|
||||
_validate();
|
||||
add_leg_cmd = new DelegateCommand<SyntheticImportRowVM>(r => {
|
||||
if (r != null) {
|
||||
r.legs.Add(new ContractLegVM {
|
||||
price_multiplier = 1,
|
||||
quantity = 1,
|
||||
owner = r
|
||||
});
|
||||
}
|
||||
});
|
||||
remove_leg_cmd = new DelegateCommand<ContractLegVM>(l => l?.owner?.legs?.Remove(l));
|
||||
PropertyChanged += on_property_changed;
|
||||
_dispose = Disposable.Create(
|
||||
_leg_errors_mon.OnDispatcher().Subscribe(v => _validate()),
|
||||
ObservableAutoWrapper.connect_item_hooks(legs, l => {
|
||||
l.result_changed += invalidate;
|
||||
return Disposable.Create(_leg_errors_mon.join(l), l,
|
||||
Disposable.Create(() => l.result_changed -= invalidate));
|
||||
}),
|
||||
Disposable.Create(() => PropertyChanged -= on_property_changed));
|
||||
|
||||
void invalidate() {
|
||||
_security = null;
|
||||
_strategy = null;
|
||||
_validate();
|
||||
result_changed?.Invoke();
|
||||
}
|
||||
|
||||
void on_property_changed(object sender, PropertyChangedEventArgs e) =>
|
||||
invalidate();
|
||||
}
|
||||
|
||||
public event Action result_changed;
|
||||
|
||||
public SecurityImmutable result =>
|
||||
_security ?? (_security = new SecurityImmutable(to_security())).Value;
|
||||
|
||||
public ExecutionStrategyImmutable strategy =>
|
||||
_strategy ?? (_strategy = new ExecutionStrategyImmutable(to_strategy())).Value;
|
||||
|
||||
public (SecurityImmutable security, ExecutionStrategyImmutable strategy) result_tuple =>
|
||||
(result, strategy);
|
||||
|
||||
public ParsedSyntheticContract parsed_synth { get; set; }
|
||||
|
||||
public string name { get => _name; set => Set(ref _name, value); }
|
||||
public uint user_id { get; }
|
||||
public TickFactors tick_factors { get => _tick_factors; set => Set(ref _tick_factors, value); }
|
||||
public ObservableCollection<ContractLegVM> legs { get; } = new ObservableCollection<ContractLegVM>();
|
||||
public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); }
|
||||
public ICommand add_leg_cmd { get; }
|
||||
public ICommand remove_leg_cmd { get; }
|
||||
|
||||
public Security to_security() {
|
||||
var sc = new SyntheticContract {
|
||||
Name = name,
|
||||
UserId = user_id
|
||||
};
|
||||
sc.Legs.AddRange(legs.Select(l => l.to_contract_leg()));
|
||||
return new Security {
|
||||
Synthetic = sc,
|
||||
Symbol = sc.Legs.FirstOrDefault()?.Security?.Symbol ?? string.Empty,
|
||||
Exchange = Venue.Bts,
|
||||
ContractSpec = tick_factors.to_spec()
|
||||
};
|
||||
}
|
||||
|
||||
public ExecutionStrategy to_strategy() {
|
||||
var strat = new ExecutionStrategy();
|
||||
foreach (var l in legs) {
|
||||
if (l.security.HasValue)
|
||||
strat.LegParamsMap[l.security.Value.Id] = l.to_leg_params();
|
||||
}
|
||||
return strat;
|
||||
}
|
||||
|
||||
void _validate() {
|
||||
using (validation()) {
|
||||
if (string.IsNullOrEmpty(name)) {
|
||||
validation_assert(false, "Name is not specified.", nameof(name));
|
||||
} else if (_get_name_exists(name)) {
|
||||
validation_assert(false, "Name already exists.", nameof(name));
|
||||
}
|
||||
validation_assert(tick_factors != null && tick_factors.is_valid(), "Invalid tick", nameof(tick_factors));
|
||||
validation_assert(legs.Count > 0 && !_leg_errors_mon.is_above_threshold, "Invalid legs.", nameof(legs));
|
||||
}
|
||||
}
|
||||
|
||||
public bool Equals(SyntheticImportRowVM other) =>
|
||||
other != null &&
|
||||
parsed_synth.unpersisted_id == other.parsed_synth.unpersisted_id;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as SyntheticImportRowVM);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
parsed_synth.unpersisted_id;
|
||||
}
|
||||
|
||||
class ContractLegVM : DisposableViewModelBase, IEquatable<ContractLegVM> {
|
||||
ContractLegImmutable? _leg;
|
||||
LegSpreaderParamsImmutable? _leg_params;
|
||||
SecurityImmutable? _security;
|
||||
double _price_multiplier, _quantity;
|
||||
ContractLegType _leg_type;
|
||||
bool _is_selected;
|
||||
|
||||
public ContractLegVM() {
|
||||
PropertyChanged += on_property_changed;
|
||||
_dispose = Disposable.Create(() => PropertyChanged -= on_property_changed);
|
||||
_validate();
|
||||
void on_property_changed(object sender, PropertyChangedEventArgs e) {
|
||||
switch (e.PropertyName) {
|
||||
case nameof(security):
|
||||
case nameof(price_multiplier):
|
||||
case nameof(quantity):
|
||||
_leg = null;
|
||||
break;
|
||||
case nameof(leg_type):
|
||||
_leg_params = null;
|
||||
break;
|
||||
default: return;
|
||||
}
|
||||
_validate();
|
||||
result_changed?.Invoke();
|
||||
}
|
||||
}
|
||||
|
||||
public event Action result_changed;
|
||||
|
||||
public ParsedContractLeg parsed_leg { get; set; }
|
||||
public SyntheticImportRowVM owner { get; set; }
|
||||
public int owner_id => owner.parsed_synth.unpersisted_id;
|
||||
public int id => parsed_leg.id;
|
||||
|
||||
public ContractLegImmutable leg =>
|
||||
_leg ?? (_leg = new ContractLegImmutable(to_contract_leg())).Value;
|
||||
|
||||
public LegSpreaderParamsImmutable leg_params =>
|
||||
_leg_params ?? (_leg_params = new LegSpreaderParamsImmutable(to_leg_params())).Value;
|
||||
|
||||
public (ContractLegImmutable leg, LegSpreaderParamsImmutable leg_params) result_tuple =>
|
||||
(leg, leg_params);
|
||||
|
||||
public SecurityImmutable? security { get => _security; set => Set(ref _security, value); }
|
||||
public double price_multiplier { get => _price_multiplier; set => Set(ref _price_multiplier, value); }
|
||||
public double quantity { get => _quantity; set => Set(ref _quantity, value); }
|
||||
public ContractLegType leg_type { get => _leg_type; set => Set(ref _leg_type, value); }
|
||||
public bool is_selected { get => _is_selected; set => Set(ref _is_selected, value); }
|
||||
|
||||
public void load(ContractLegImmutable leg) {
|
||||
security = leg.Security;
|
||||
price_multiplier = leg.PriceMultiplier;
|
||||
quantity = leg.Quantity;
|
||||
}
|
||||
|
||||
public ContractLeg to_contract_leg() =>
|
||||
new ContractLeg {
|
||||
Security = security?.CloneToMutable(),
|
||||
PriceMultiplier = price_multiplier,
|
||||
Side = quantity < 0 ? Side.Sell : Side.Buy,
|
||||
Quantity = Math.Abs(quantity)
|
||||
};
|
||||
|
||||
public LegSpreaderParams to_leg_params() {
|
||||
var lps = SyntheticDataHelper.Defaults.LegSpreaderParams;
|
||||
lps.EnableHedging = (leg_type & ContractLegType.Hedge) != 0;
|
||||
lps.IsActiveQuoting = (leg_type & ContractLegType.Quote) != 0;
|
||||
return lps;
|
||||
}
|
||||
|
||||
void _validate() {
|
||||
using (validation()) {
|
||||
validation_assert(security.is_exchange_security(), "Invalid security", nameof(security));
|
||||
validation_assert(price_multiplier.IsNonZero(), "Invalid price multiplier", nameof(price_multiplier));
|
||||
validation_assert(quantity.IsNonZero(), "Invalid quantity", nameof(quantity));
|
||||
}
|
||||
}
|
||||
|
||||
public bool Equals(ContractLegVM other) =>
|
||||
other != null && id == other.id;
|
||||
|
||||
public override bool Equals(object obj) =>
|
||||
Equals(obj as ContractLegVM);
|
||||
|
||||
public override int GetHashCode() =>
|
||||
id;
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,8 @@ using mbts.ui;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
@@ -110,7 +112,9 @@ namespace mbts.spark {
|
||||
Title = $"{_import_title} Conflicts",
|
||||
WindowStartupLocation = WindowStartupLocation.CenterOwner
|
||||
};
|
||||
dispose_op = new DisposableCombo(WindowUtilities.connect_vm(conflicts_win, conflicts_vm, conflicts_vm)) + dispose_op;
|
||||
dispose_op = Disposable.Create(
|
||||
WindowUtilities.connect_vm(conflicts_win, conflicts_vm, conflicts_vm),
|
||||
dispose_op);
|
||||
|
||||
conflicts_win.ShowDialog();
|
||||
}
|
||||
|
||||
@@ -6,6 +6,8 @@ using mbts;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
|
||||
@@ -7,6 +7,8 @@ using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
@@ -22,6 +24,7 @@ namespace bts.shell {
|
||||
readonly OrdersModel _model;
|
||||
readonly IBus _bus;
|
||||
|
||||
IReadOnlyDictionary<uint, SecurityMD> _security_md_map = new Dictionary<uint, SecurityMD>(0);
|
||||
IDisposable _dispose;
|
||||
|
||||
[ImportingConstructor]
|
||||
@@ -78,11 +81,21 @@ namespace bts.shell {
|
||||
_show_synthetic_create(securities.Select(s => new ContractLeg(SyntheticDataHelper.Defaults.ContractLeg(s))));
|
||||
}
|
||||
|
||||
void _show_synthetic_strategy(SecurityImmutable security) {
|
||||
if (security.ContractCase != api.Security.ContractOneofCase.Synthetic)
|
||||
Log.Ui.warn($"{GetType()} observed a non-synthetic-security posted on {nameof(SparkTags.ShowSyntheticStrategyTag)}: {security}");
|
||||
else
|
||||
_show_synthetic_strategy_async(security).ignore();
|
||||
void _show_synthetic_strategy(uint security_id) {
|
||||
if (!_security_md_map.TryGetValue(security_id, out var sec_md)) {
|
||||
Log.Ui.warn(
|
||||
$"Ignoring request to show synthetic strategy for sec '{security_id}' " +
|
||||
$"(haven't received security with that id yet)");
|
||||
return;
|
||||
}
|
||||
var sec = sec_md.security;
|
||||
if (sec.ContractCase != api.Security.ContractOneofCase.Synthetic) {
|
||||
Log.Ui.warn(
|
||||
$"{GetType()} observed a non-synthetic-security posted on " +
|
||||
$"{nameof(SparkTags.ShowSyntheticStrategyTag)}: {sec}");
|
||||
return;
|
||||
}
|
||||
_show_synthetic_strategy_async(sec).ignore();
|
||||
}
|
||||
|
||||
async Task _show_synthetic_strategy_async(SecurityImmutable verified_synthetic) {
|
||||
@@ -98,7 +111,7 @@ namespace bts.shell {
|
||||
mutable_sec.Synthetic.Name = _get_clone_name(mutable_sec.Synthetic.Name);
|
||||
_show_synthetic_editor(new SyntheticEditorVM(_bus, _model.spreader, new SecurityImmutable(mutable_sec), args.strategy, true));
|
||||
} else
|
||||
_show_synthetic_strategy(args.security);
|
||||
_show_synthetic_strategy(args.security.Id);
|
||||
}
|
||||
|
||||
void _show_synthetic_create(IEnumerable<ContractLeg> legs) {
|
||||
@@ -117,6 +130,7 @@ namespace bts.shell {
|
||||
void IInitializable.initialize() {
|
||||
Disposable.dispose(ref _dispose);
|
||||
_dispose = Disposable.Create(
|
||||
_bus.subscribe(SparkTags.SecuritiesTag).Subscribe(sec_map => _security_md_map = sec_map),
|
||||
_bus.subscribe(SparkTags.ShowSyntheticCreateTag).OnDispatcher().Subscribe(_show_synthetic_create),
|
||||
_bus.subscribe(SparkTags.ShowSyntheticStrategyTag).OnDispatcher().Subscribe(_show_synthetic_strategy),
|
||||
_bus.subscribe(SparkTags.ShowSyntheticCloneTag).OnDispatcher().Subscribe(_show_synthetic_clone)
|
||||
|
||||
@@ -1,173 +1,188 @@
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.shell;
|
||||
using bts.shell.spreader;
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
|
||||
using mbts.persist;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
|
||||
using static bts.shell.SyntheticManagementWindowFactory;
|
||||
|
||||
namespace mbts.spark {
|
||||
class SyntheticManagementWindow : SparkWindow<SyntheticManagementSettings>, ISharedWindow {
|
||||
const string
|
||||
_window_type = "SyntheticManagement",
|
||||
_import_title = "Import Synthetics";
|
||||
static readonly TimeSpan _import_op_sec_map_timeout = TimeSpan.FromSeconds(30);
|
||||
SingleValuePump<SyntheticManagementDialogVM> _vm = new SingleValuePump<SyntheticManagementDialogVM>();
|
||||
SyntheticManagementSettings _state;
|
||||
OrdersModel _orders_model;
|
||||
SyntheticManagementView _view;
|
||||
SparkMenuDisplayVM _menu_display_vm;
|
||||
IDisposable _subscriptions;
|
||||
List<SparkCommand> _commands;
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
|
||||
public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, SyntheticManagementSettings state, IWindowSettingsManager<GridSettings> settings_manager)
|
||||
: base("Synthetic Management", bus, factory, SparkCommands.ShowSyntheticManagement.icon) {
|
||||
_orders_model = orders_model;
|
||||
_state = state;
|
||||
_settings_manager = settings_manager;
|
||||
Icon.Freeze();
|
||||
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().synthetic_management ?
|
||||
"SyntheticManagement" : null;
|
||||
_dispose = Disposable.Create(() => {
|
||||
Disposable.dispose(ref _vm);
|
||||
if (_commands != null) {
|
||||
_commands.OfType<IDisposable>().DisposeAll();
|
||||
_commands = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public override string window_type => _window_type;
|
||||
public override UIElement Content => _view;
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override SyntheticManagementSettings SaveState => _state = _vm.value.create().with(menu_display: _menu_display_vm.safe_create());
|
||||
public override double MinWidth =>
|
||||
SyntheticManagementSettings.default_grid_settings.columns.Sum(gcs => gcs.width)
|
||||
+ SPARK_MENU_COLLAPSED_WIDTH
|
||||
+ LAUNCHER_BUTTON_BORDER_WIDTH
|
||||
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
|
||||
public string thread_id { get; }
|
||||
|
||||
public void thread_init() {
|
||||
Log.notnull(_state);
|
||||
_menu_display_vm = new SparkMenuDisplayVM();
|
||||
_menu_display_vm.load_from(_state.menu_display);
|
||||
|
||||
var vm_connectable_builder = new ConnectableSeriesBuilder<SyntheticManagementDialogVM>(_vm.observable);
|
||||
var current_row_source = vm_connectable_builder.create(vm => vm.current_row_observable);
|
||||
var current_row_connectable_builder = new ConnectableSeriesBuilder<SyntheticManagementDialogVM.Row>(current_row_source);
|
||||
|
||||
Log.isnull(_commands);
|
||||
_commands = new() {
|
||||
SparkCommand.create("Add", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag).complete(
|
||||
() => new SecurityCriteria(), () => true
|
||||
), SparkCommand.create("Remove", Icons.RemoveSynthetic, SparkTags.SyntheticDeleteTag).complete(
|
||||
current_row_connectable_builder.create(observe_row_mod_params),
|
||||
can_execute, select_security_id
|
||||
), SparkCommand.create("Change", Icons.ModifySynthetic, SparkTags.ShowSyntheticStrategyTag).complete(
|
||||
current_row_source,
|
||||
r => r != null, r => r?.security ?? Security.Defaults.SecurityImmutable
|
||||
), SparkCommand.create("Clone", Icons.CloneSynthetic, SparkTags.ShowSyntheticCloneTag).complete(
|
||||
current_row_connectable_builder.create(observe_row_strategy),
|
||||
rs => rs.HasValue, select_row_strategy_tuple
|
||||
), SparkCommands.ShowLadderAutoLookup(SparkCommands.KeyGestures.ShowLadder).complete(
|
||||
vm_connectable_builder.create(vm => vm.current_security_observable.Select(s => s.HasValue ? ImmutableHashSet<uint>.Empty.Add(s.Value.Id) : null)), id => id != null
|
||||
), SparkCommands.ShowOrders.complete(() => {
|
||||
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
|
||||
ob_settings.filters = new bts.shell.orderbook.FilterStates {
|
||||
security_criteria = SecurityCriteria.from_securities(_vm.value.row_vms.Select(r => r.security))
|
||||
};
|
||||
return ob_settings;
|
||||
}), SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
|
||||
_settings_manager,
|
||||
us => us.synthetic_management_grid,
|
||||
UserSettings.FileExtensions.GRID,
|
||||
s => _vm.value.grid_settings_manager.create_vm(
|
||||
// we need to get the most up to date GridSettings when launching b/c users may
|
||||
// have changed some settings on the grid directly, like column widths.
|
||||
s.with(_vm.value.columns.Select(c => c.create()))
|
||||
)
|
||||
);
|
||||
vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t));
|
||||
var dialog = new ShellSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm };
|
||||
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
})),
|
||||
new SparkCommandCommand(
|
||||
"Import Synthetics...", Icons.Import, FileDialogCommand.open_file(import, extensions: SyntheticSecurityParser.file_extension)) {
|
||||
show_in_toolbar = false
|
||||
},
|
||||
_menu_display_vm.spark_cmd
|
||||
};
|
||||
|
||||
_subscriptions = Disposable.Create(
|
||||
vm_connectable_builder.connect_all(),
|
||||
current_row_connectable_builder.connect_all());
|
||||
|
||||
IObservable<RowModificationParams?> observe_row_mod_params(SyntheticManagementDialogVM.Row r) =>
|
||||
r == null ? Observable.Return(new RowModificationParams?()) :
|
||||
_orders_model.security_has_working_orders(r.security_key).Select(hwo => RowModificationParams.create(r.security, hwo));
|
||||
|
||||
IObservable<RowStrategy?> observe_row_strategy(SyntheticManagementDialogVM.Row r) =>
|
||||
r == null ? Observable.Return(new RowStrategy?()) :
|
||||
_orders_model.spreader.security_strategy(r.security.Id).Select(strategy => RowStrategy.create(r.security, strategy));
|
||||
|
||||
IImmutableSet<uint> select_security_id(RowModificationParams? rmp) => ImmutableHashSet.Create(rmp.HasValue ? rmp.Value.security.Id : 0);
|
||||
(SecurityImmutable, ExecutionStrategyImmutable) select_row_strategy_tuple(RowStrategy? rs) => rs.HasValue ? (rs.Value.security, rs.Value.strategy) : default;
|
||||
bool can_execute(RowModificationParams? rmp) => rmp.HasValue && !rmp.Value.has_working_orders;
|
||||
|
||||
_vm.value = new SyntheticManagementDialogVM(_bus, _orders_model, _settings_manager, _state.sorting_criteria, _state.filters ?? new SyntheticManagementFilterSettings());
|
||||
if (_view == null) _view = new SyntheticManagementView { DataContext = _vm.value };
|
||||
else _view.DataContext = _vm.value;
|
||||
|
||||
void import(string path) =>
|
||||
SyntheticImporter.import_from_file(path, _bus, _orders_model);
|
||||
}
|
||||
|
||||
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
|
||||
_menu_display_vm.safe_bind_to_view(parent_view);
|
||||
|
||||
struct RowModificationParams {
|
||||
public readonly SecurityImmutable security;
|
||||
public readonly bool has_working_orders;
|
||||
|
||||
RowModificationParams(SecurityImmutable security, bool has_working_orders) {
|
||||
this.security = security;
|
||||
this.has_working_orders = has_working_orders;
|
||||
}
|
||||
|
||||
public static RowModificationParams? create(SecurityImmutable security, bool has_working_orders) =>
|
||||
new RowModificationParams(security, has_working_orders);
|
||||
}
|
||||
|
||||
struct RowStrategy {
|
||||
public readonly SecurityImmutable security;
|
||||
public readonly ExecutionStrategyImmutable strategy;
|
||||
|
||||
RowStrategy(SecurityImmutable security, ExecutionStrategyImmutable strategy) {
|
||||
this.security = security;
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public static RowStrategy? create(SecurityImmutable security, ExecutionStrategyImmutable strategy) =>
|
||||
new RowStrategy(security, strategy);
|
||||
}
|
||||
}
|
||||
}
|
||||
using bts;
|
||||
using bts.api;
|
||||
using bts.shell;
|
||||
using bts.shell.spreader;
|
||||
using bts.spark;
|
||||
using bts.view;
|
||||
|
||||
using mbts.persist;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows;
|
||||
|
||||
using static bts.shell.SyntheticManagementWindowFactory;
|
||||
|
||||
namespace mbts.spark {
|
||||
class SyntheticManagementWindow : SparkWindow<SyntheticManagementSettings>, ISharedWindow {
|
||||
const string
|
||||
_window_type = "SyntheticManagement",
|
||||
_import_title = "Import Synthetics";
|
||||
static readonly TimeSpan _import_op_sec_map_timeout = TimeSpan.FromSeconds(30);
|
||||
SyntheticManagementDialogVM _vm;
|
||||
SyntheticManagementSettings _state;
|
||||
OrdersModel _orders_model;
|
||||
SyntheticManagementView _view;
|
||||
SparkMenuDisplayVM _menu_display_vm;
|
||||
List<SparkCommand> _commands;
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
|
||||
public SyntheticManagementWindow(SyntheticManagementWindowFactory factory, IBus bus, OrdersModel orders_model, SyntheticManagementSettings state, IWindowSettingsManager<GridSettings> settings_manager)
|
||||
: base("Synthetic Management", bus, factory, SparkCommands.ShowSyntheticManagement.icon) {
|
||||
_orders_model = orders_model;
|
||||
_state = state;
|
||||
_settings_manager = settings_manager;
|
||||
Icon.Freeze();
|
||||
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().synthetic_management ?
|
||||
"SyntheticManagement" : null;
|
||||
_dispose = Disposable.Create(() => {
|
||||
Disposable.dispose(ref _vm);
|
||||
if (_commands != null) {
|
||||
_commands.OfType<IDisposable>().DisposeAll();
|
||||
_commands = null;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
public override string window_type => _window_type;
|
||||
public override UIElement Content => _view;
|
||||
public override IEnumerable<SparkCommand> Commands => _commands;
|
||||
public override SyntheticManagementSettings SaveState =>
|
||||
_state = _vm.create().with(menu_display: _menu_display_vm.safe_create());
|
||||
public override double MinWidth =>
|
||||
SyntheticManagementSettings.default_grid_settings.columns.Sum(gcs => gcs.width)
|
||||
+ SPARK_MENU_COLLAPSED_WIDTH
|
||||
+ LAUNCHER_BUTTON_BORDER_WIDTH
|
||||
+ EXTRA_FOR_NO_HORIZONTAL_SCROLLBAR_WIDTH;
|
||||
public string thread_id { get; }
|
||||
|
||||
public void thread_init() {
|
||||
Log.notnull(_state);
|
||||
Log.isnull(_vm, "SyntheticManagementWindow vm has already been created");
|
||||
Log.isnull(_view, "SyntheticManagementWindow _view has already been created");
|
||||
_menu_display_vm = new SparkMenuDisplayVM();
|
||||
_menu_display_vm.load_from(_state.menu_display);
|
||||
_vm = new SyntheticManagementDialogVM(
|
||||
_bus,
|
||||
_orders_model,
|
||||
_settings_manager,
|
||||
_state.sorting_criteria,
|
||||
_state.filters ?? new());
|
||||
_view = new SyntheticManagementView { DataContext = _vm };
|
||||
var curr_row =_vm.current_row_observable;
|
||||
|
||||
Log.isnull(_commands);
|
||||
_commands = new() {
|
||||
SparkCommand.create("Add", Icons.AddSynthetic, SparkTags.ShowSyntheticCreateTag)
|
||||
.complete(() => new SecurityCriteria(), () => true),
|
||||
|
||||
SparkCommand.create("Remove", Icons.RemoveSynthetic, SparkTags.SyntheticDeleteTag)
|
||||
.complete(curr_row.SelectSeries(observe_mod_params), can_modify, select_security_id),
|
||||
|
||||
SparkCommand.create("Change", Icons.ModifySynthetic, SparkTags.ShowSyntheticStrategyTag)
|
||||
.complete(
|
||||
curr_row,
|
||||
r => (r?.security).HasValue,
|
||||
r => (r?.security)?.Id ?? 0),
|
||||
|
||||
SparkCommand.create("Clone", Icons.CloneSynthetic, SparkTags.ShowSyntheticCloneTag)
|
||||
.complete(
|
||||
curr_row.SelectSeries(observe_row_strategy),
|
||||
rs => rs.HasValue,
|
||||
get_row_strategy),
|
||||
|
||||
SparkCommands.ShowLadderAutoLookup(SparkCommands.KeyGestures.ShowLadder).complete(
|
||||
_vm.current_security_observable.Select(
|
||||
s => s.HasValue ? ImmutableHashSet.Create(s.Value.Id) : null), id => id != null),
|
||||
|
||||
SparkCommands.ShowOrders.complete(() => {
|
||||
var ob_settings = bts.shell.orderbook.OrderBookStartupData.Default;
|
||||
ob_settings.filters = new bts.shell.orderbook.FilterStates {
|
||||
security_criteria = SecurityCriteria.from_securities(
|
||||
_vm.rows.Select(r => r.security))
|
||||
};
|
||||
return ob_settings;
|
||||
}),
|
||||
|
||||
SparkCommands.window_settings_command(new DialogCommand(() => {
|
||||
var vm = new ShellSettingsDialogVM<GridSettings, SimpleGridSettingsVM>(
|
||||
_settings_manager,
|
||||
us => us.synthetic_management_grid,
|
||||
UserSettings.FileExtensions.GRID,
|
||||
s => _vm.grid_settings_manager.create_vm(
|
||||
// we need to get the most up to date GridSettings when launching b/c users may
|
||||
// have changed some settings on the grid directly, like column widths.
|
||||
s.with(_vm.columns.Select(c => c.create()))));
|
||||
vm.SubscribeDisposed(literal_title_source.OnDispatcher().Subscribe(t => vm.title = t));
|
||||
var dialog = new ShellSettingsDialog { Title = "Synthetic Management Grid Settings", DataContext = vm };
|
||||
vm.RequestClose += (s, e) => WindowUtilities.force_close(dialog);
|
||||
return dialog;
|
||||
})),
|
||||
new SparkCommandCommand(
|
||||
"Import Synthetics...", Icons.Import, FileDialogCommand.open_file(import, extensions: SyntheticSecurityParser.file_extension)) {
|
||||
show_in_toolbar = false
|
||||
},
|
||||
_menu_display_vm.spark_cmd
|
||||
};
|
||||
|
||||
IObservable<RowModificationParams?> observe_mod_params(
|
||||
SyntheticManagementDialogVM.Row r) =>
|
||||
r == null ? Observable.Return(new RowModificationParams?()) :
|
||||
_orders_model.security_has_working_orders(r.security_key).Select(hwo => RowModificationParams.create(r.security, hwo));
|
||||
|
||||
IObservable<RowStrategy?> observe_row_strategy(SyntheticManagementDialogVM.Row r) =>
|
||||
r == null ? Observable.Return(new RowStrategy?()) :
|
||||
_orders_model.spreader.security_strategy(r.security.Id).Select(strategy => RowStrategy.create(r.security, strategy));
|
||||
|
||||
IImmutableSet<uint> select_security_id(RowModificationParams? rmp) => ImmutableHashSet.Create(rmp.HasValue ? rmp.Value.security.Id : 0);
|
||||
|
||||
(SecurityImmutable, ExecutionStrategyImmutable) get_row_strategy(RowStrategy? rs) =>
|
||||
rs.HasValue ? (rs.Value.security, rs.Value.strategy) : default;
|
||||
|
||||
bool can_modify(RowModificationParams? rmp) =>
|
||||
rmp.HasValue && !rmp.Value.has_working_orders;
|
||||
|
||||
void import(string path) =>
|
||||
SyntheticImporter.import_from_file(path, _bus, _orders_model);
|
||||
}
|
||||
|
||||
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
|
||||
_menu_display_vm.safe_bind_to_view(parent_view);
|
||||
|
||||
struct RowModificationParams {
|
||||
public readonly SecurityImmutable security;
|
||||
public readonly bool has_working_orders;
|
||||
|
||||
RowModificationParams(SecurityImmutable security, bool has_working_orders) {
|
||||
this.security = security;
|
||||
this.has_working_orders = has_working_orders;
|
||||
}
|
||||
|
||||
public static RowModificationParams? create(SecurityImmutable security, bool has_working_orders) =>
|
||||
new RowModificationParams(security, has_working_orders);
|
||||
}
|
||||
|
||||
struct RowStrategy {
|
||||
public readonly SecurityImmutable security;
|
||||
public readonly ExecutionStrategyImmutable strategy;
|
||||
|
||||
RowStrategy(SecurityImmutable security, ExecutionStrategyImmutable strategy) {
|
||||
this.security = security;
|
||||
this.strategy = strategy;
|
||||
}
|
||||
|
||||
public static RowStrategy? create(SecurityImmutable security, ExecutionStrategyImmutable strategy) =>
|
||||
new RowStrategy(security, strategy);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -3,6 +3,8 @@
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.spark;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
|
||||
@@ -2,10 +2,11 @@
|
||||
using mbts.ui.spark;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Windows;
|
||||
|
||||
namespace mbts.spark {
|
||||
@@ -37,10 +38,9 @@ namespace mbts.spark {
|
||||
ObservableAutoWrapper.connect_item_hooks(_cells, tup => {
|
||||
var (leg, cell) = tup;
|
||||
cell.value_changed += raise_cell_value_changed;
|
||||
return new CompositeDisposable {
|
||||
return Disposable.Create(
|
||||
Disposable.Create(() => cell.value_changed -= raise_cell_value_changed),
|
||||
cell as IDisposable ?? Disposable.empty
|
||||
};
|
||||
cell as IDisposable ?? Disposable.empty);
|
||||
void raise_cell_value_changed() =>
|
||||
cell_value_changed?.Invoke(cell, leg);
|
||||
}, true));
|
||||
|
||||
@@ -10,6 +10,7 @@ using mbts.ui.utility;
|
||||
using mbts.user.settings;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
@@ -368,7 +369,7 @@ namespace mbts.spark {
|
||||
protected override void Dispose(bool disposing) {
|
||||
foreach (var r in rows) r.Dispose();
|
||||
contract_picker_vm?.Dispose();
|
||||
Disposable.dispose(_resources);
|
||||
_resources.DisposeAll(true);
|
||||
base.Dispose(disposing);
|
||||
}
|
||||
|
||||
|
||||
@@ -9,11 +9,17 @@ using mbts.persist;
|
||||
using mbts.spark.filters;
|
||||
using mbts.ui;
|
||||
using mbts.ui.settings;
|
||||
using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Immutable;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.ComponentModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Data;
|
||||
@@ -23,17 +29,29 @@ using static mbts.ui.controls.DIYGrid;
|
||||
using static mbts.ui.spark.SyntheticManagementView;
|
||||
|
||||
namespace mbts.spark {
|
||||
class SyntheticManagementDialogVM : SecurityGrid<SyntheticManagementDialogVM.Row, SyntheticTuple> {
|
||||
class SyntheticManagementDialogVM : DisposableViewModelBase {
|
||||
readonly IBus _bus;
|
||||
readonly OrdersModel _orders_model;
|
||||
readonly IWindowSettingsManager<GridSettings> _settings_manager;
|
||||
readonly Dictionary<uint, Row> _rows_cache = new();
|
||||
readonly SparkObservableCollection<Row> _rows = new();
|
||||
readonly Property<Row> _current_row;
|
||||
|
||||
public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager<GridSettings> settings_manager) : this(bus, orders_model, settings_manager, null, null) { }
|
||||
public SyntheticManagementDialogVM(IBus bus, OrdersModel orders_model, IWindowSettingsManager<GridSettings> settings_manager, IReadOnlyCollection<SortingCriteria> sorting, SyntheticManagementFilterSettings filters)
|
||||
: base(orders_model.spreader.synthetic_tuples.Select(t => t.state.Values), sorting) {
|
||||
|
||||
public SyntheticManagementDialogVM(
|
||||
IBus bus,
|
||||
OrdersModel orders_model,
|
||||
IWindowSettingsManager<GridSettings> settings_manager,
|
||||
IReadOnlyCollection<SortingCriteria> sorting,
|
||||
SyntheticManagementFilterSettings filters) {
|
||||
rows_view = CollectionViewSource.GetDefaultView(_rows);
|
||||
rows_view.SetSortingCriteria(sorting.empty_if_null());
|
||||
|
||||
_bus = bus;
|
||||
_orders_model = orders_model;
|
||||
_settings_manager = settings_manager;
|
||||
_current_row = backing<Row>(nameof(current_row));
|
||||
// init filters
|
||||
user_filter = DiscreteValuesFilterVM.CreateTableUpdate<Row, UserTuple, uint>(r => r.user_tuple, UserTuple.key_fn, out var user_filter_items_observer, out var user_filter_items_view, nameof(Row.user_tuple));
|
||||
user_filter_items_view.CustomSort = Comparer<string>.Default.wrap<string, UserTuple>(ut => ut.name).to_non_generic();
|
||||
@@ -71,17 +89,35 @@ namespace mbts.spark {
|
||||
Width = width
|
||||
});
|
||||
//
|
||||
grid_settings_manager = new SimpleGridSettingsManager<Row>(columns, DictionaryHelper.empty<string, GridColumnSettingsFeatureFlags>(), row_vms);
|
||||
grid_settings_manager = new SimpleGridSettingsManager<Row>(columns, DictionaryHelper.empty<string, GridColumnSettingsFeatureFlags>(), _rows);
|
||||
// this will initialize the immutable properties that correspond to the col_settings_flags above (e.g. Bid/Ask font_color_override, etc.)
|
||||
grid_settings_manager.load_from(settings_manager.current_settings());
|
||||
|
||||
_resources.AddRange(
|
||||
_dispose = Disposable.Create(
|
||||
orders_model.admin_model.all_user_tuples.OnDispatcher().Subscribe(user_filter_items_observer),
|
||||
orders_model.spreader.synthetic_tuples
|
||||
.Select(t => t.state.Values)
|
||||
.OnDispatcher()
|
||||
.Subscribe(synth_tups => _rows.WrapSelector(
|
||||
r => r.synthetic_tuple,
|
||||
d => _rows_cache.GetOrAdd(d.security.Id, _ => new Row(_bus, d, _orders_model)))
|
||||
.sync_with(synth_tups)),
|
||||
DataGridFilterHelper.hook_all<SyntheticManagementDialogVM, Row>(this, rows_view),
|
||||
ObservableAutoWrapper.dispose_on_removed(_rows),
|
||||
settings_manager.subscribe_current().OnDispatcher().Subscribe(grid_settings_manager)
|
||||
);
|
||||
}
|
||||
|
||||
public ICollectionView rows_view { get; }
|
||||
public Row current_row {
|
||||
get => _current_row.Value;
|
||||
set => _current_row.set(value);
|
||||
}
|
||||
public IObservableCollection<Row> rows => _rows;
|
||||
public IObservable<Row> current_row_observable => _current_row.Select(v => v.newval);
|
||||
public SecurityImmutable? current_security => current_row?.security;
|
||||
public IObservable<SecurityImmutable?> current_security_observable => current_row_observable.Select(r => r?.security).DistinctUntilChanged();
|
||||
|
||||
public ObservableCollection<ColumnBase> columns { get; } = new ObservableCollection<ColumnBase>();
|
||||
public SimpleGridSettingsManager<Row> grid_settings_manager { get; }
|
||||
|
||||
@@ -99,12 +135,6 @@ namespace mbts.spark {
|
||||
public SyntheticManagementSettings create() =>
|
||||
new SyntheticManagementSettings(rows_view.get_sorting_criteria(columns), _get_filter_states(), get_grid_save_state());
|
||||
|
||||
protected override Row row_factory(SyntheticTuple row_model) =>
|
||||
new Row(_bus, row_model, _orders_model);
|
||||
|
||||
protected override void on_row_removed(Row row) =>
|
||||
row.Dispose();
|
||||
|
||||
SyntheticManagementFilterSettings _get_filter_states() =>
|
||||
new SyntheticManagementFilterSettings {
|
||||
description = description_filter.get_state(),
|
||||
@@ -116,13 +146,13 @@ namespace mbts.spark {
|
||||
user = user_filter.get_state()
|
||||
};
|
||||
|
||||
public class Row : SecurityRow, IEquatable<Row>, IRowVM, IActionableRowVM {
|
||||
public class Row : DisposableViewModelBase, IEquatable<Row>, IRowVM, IActionableRowVM {
|
||||
public readonly SyntheticTuple synthetic_tuple;
|
||||
|
||||
readonly IBus _bus;
|
||||
readonly Property<uint> _n_working_orders;
|
||||
|
||||
public Row(IBus bus, SyntheticTuple synthetic_tuple, OrdersModel orders_model) : base(synthetic_tuple.security) {
|
||||
public Row(IBus bus, SyntheticTuple synthetic_tuple, OrdersModel orders_model) {
|
||||
_bus = bus;
|
||||
this.synthetic_tuple = synthetic_tuple;
|
||||
_n_working_orders = backing(nameof(n_working_orders),
|
||||
@@ -149,6 +179,10 @@ namespace mbts.spark {
|
||||
public ExecutionStrategyImmutable? strategy => synthetic_tuple.strategy;
|
||||
public bool strategy_present => strategy.HasValue;
|
||||
public uint n_working_orders => _n_working_orders.Value;
|
||||
|
||||
public SecurityImmutable security => synthetic_tuple.security;
|
||||
public uint security_key => security.Id;
|
||||
|
||||
public ICommand show_ladder { get; }
|
||||
public ICommand show_order_book { get; }
|
||||
public ICommand default_command => show_ladder;
|
||||
|
||||
@@ -5,6 +5,8 @@ using mbts;
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
using bts.api;
|
||||
using bts.shell;
|
||||
|
||||
using mbts;
|
||||
using mbts.spark;
|
||||
using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Reactive.Linq;
|
||||
using System.Reactive.Subjects;
|
||||
|
||||
@@ -6,12 +6,12 @@ using mbts.ui;
|
||||
using mbts.ui.spark;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows;
|
||||
@@ -37,7 +37,7 @@ namespace mbts.spark {
|
||||
AlgoStudioVM _vm;
|
||||
AlgoStudioView _view;
|
||||
StartupData _state;
|
||||
CompositeDisposable _resources;
|
||||
List<IDisposable> _resources;
|
||||
|
||||
public AlgoStudioWindow(OrdersModel model, AlgoStudioWindowFactory factory, IBus bus, StartupData state, ErrorReporter error_reporter)
|
||||
: base(NAME, bus, factory, SparkCommands.ShowAlgoStudio.icon) {
|
||||
@@ -66,10 +66,10 @@ namespace mbts.spark {
|
||||
_vm = new AlgoStudioVM(_model);
|
||||
_vm.load_from(_state);
|
||||
_view = new AlgoStudioView { DataContext = _vm };
|
||||
_resources = new CompositeDisposable(
|
||||
_bus.subscribe(SparkTags.SecuritiesTag)
|
||||
.OnDispatcher()
|
||||
.Subscribe(sec_map => _view.Resources[ResourceKeys.Securities] = sec_map));
|
||||
_resources = new() {
|
||||
_bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(sec_map =>
|
||||
_view.Resources[ResourceKeys.Securities] = sec_map)
|
||||
};
|
||||
// add definition
|
||||
_commands.Add(new SparkCommandCommand("Add Algo", Icons.AddBoxes, _vm.add_definition_cmd));
|
||||
_commands.Add(new SparkCommandCommand("Clone Algo", Icons.CopyBoxes, _vm.clone_selected_definition_cmd));
|
||||
@@ -83,7 +83,7 @@ namespace mbts.spark {
|
||||
// undo
|
||||
var undo_cmd = new ObservantCommand(() => _vm.selected_definition?.try_undo());
|
||||
var undo_spark_cmd = new SparkCommandCommand("Undo", Icons.UndoCircular, undo_cmd);
|
||||
var can_undo_source = _vm.subscribe_definition().SelectManyInSeries(def =>
|
||||
var can_undo_source = _vm.subscribe_definition().SelectSeries(def =>
|
||||
def != null ?
|
||||
Observable.Create<bool>(o => {
|
||||
def.can_undo_changed += notify;
|
||||
@@ -97,7 +97,7 @@ namespace mbts.spark {
|
||||
// redo
|
||||
var redo_cmd = new ObservantCommand(() => _vm.selected_definition?.try_redo());
|
||||
var redo_spark_cmd = new SparkCommandCommand("Redo", Icons.RedoCircular, redo_cmd);
|
||||
var can_redo_source = _vm.subscribe_definition().SelectManyInSeries(def =>
|
||||
var can_redo_source = _vm.subscribe_definition().SelectSeries(def =>
|
||||
def != null ?
|
||||
Observable.Create<bool>(o => {
|
||||
def.can_redo_changed += notify;
|
||||
@@ -118,7 +118,7 @@ namespace mbts.spark {
|
||||
}
|
||||
|
||||
void _dispose_core() {
|
||||
Disposable.dispose(ref _resources);
|
||||
_resources.DisposeAll(true);
|
||||
if (_commands != null) _commands.OfType<IDisposable>().DisposeAll();
|
||||
Disposable.dispose(ref _vm);
|
||||
}
|
||||
|
||||
@@ -5,6 +5,8 @@ using bts.spark;
|
||||
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Composition;
|
||||
|
||||
@@ -6,6 +6,8 @@ using mbts.collections;
|
||||
using mbts.ui.utilities;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -13,13 +13,14 @@ using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core;
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Windows.Media;
|
||||
|
||||
@@ -66,7 +67,7 @@ namespace mbts.spark {
|
||||
_model = model;
|
||||
_permissions_mask.mask = init_permissions;
|
||||
_permissions_mask.raw = init_permissions;
|
||||
var resources = new CompositeDisposable();
|
||||
var resources = new List<IDisposable>();
|
||||
if (!model.algo_model.ui_configuration.can_modify_definition_values)
|
||||
editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowSaveValues);
|
||||
if (!model.algo_model.ui_configuration.can_modify_definition_structure)
|
||||
@@ -141,7 +142,7 @@ namespace mbts.spark {
|
||||
resources.Add(this.connect_data(permission_src));
|
||||
resources.Add(this.connect_data(Observable.Return(model)));
|
||||
resources.Add(_algo_root.Subscribe(_ => RaisePropertyChanged(nameof(IAlgoSelector.selected_algo), nameof(IAlgoParamVM.value), nameof(group))));
|
||||
_dispose = resources;
|
||||
_dispose = Disposable.Create(resources);
|
||||
algo_root.load_from(def_data.value);
|
||||
_version.increment_version();
|
||||
_edit_stack.reset(_version.value);
|
||||
|
||||
@@ -5,6 +5,8 @@ using mbts.ui;
|
||||
using mbts.ui.controls;
|
||||
using mbts.ui.shell;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
using System.Windows.Input;
|
||||
|
||||
@@ -12,13 +12,14 @@ using mbts.ui.shell;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
using Spark.ViewModel.Commands;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using System.Windows.Input;
|
||||
@@ -59,7 +60,9 @@ namespace mbts.spark {
|
||||
public AlgoStudioVM(OrdersModel model) {
|
||||
_model = model;
|
||||
_selected_definition = backing<AlgoDefinitionVM>(nameof(selected_definition));
|
||||
_editable_content = backing(nameof(editable_content), subscribe_definition().SelectManyInSeries(def => def?.observe_algo_root()).OnDispatcher());
|
||||
_editable_content = backing(
|
||||
nameof(editable_content),
|
||||
subscribe_definition().SelectSeries(def => def?.observe_algo_root()).OnDispatcher());
|
||||
_definitions_update_buffer = new TableUpdateBuffer<AlgoData, AlgoKey>(def => def.key);
|
||||
_definitions_view = new ListCollectionView<AlgoDefinitionVM>(definitions) {
|
||||
CustomSort = AlgoCollectionHelper.algo_definition_vm_comparer.to_non_generic()
|
||||
@@ -77,7 +80,7 @@ namespace mbts.spark {
|
||||
this.revert_cmd = revert_cmd;
|
||||
_revert_cmd_tooltip = backing(nameof(revert_cmd_tooltip), get_revert_tooltip);
|
||||
//
|
||||
_dispose = new CompositeDisposable(
|
||||
_dispose = Disposable.Create(
|
||||
_model.subscribe_complete_algos(allow_undefined_child: true).OnDispatcher().Subscribe(_definitions_update_buffer),
|
||||
_definitions_update_buffer.OnDispatcher()
|
||||
.SubscribeEach(u => {
|
||||
@@ -101,14 +104,19 @@ namespace mbts.spark {
|
||||
_persisted_meta = meta;
|
||||
definitions_view.Refresh();
|
||||
}),
|
||||
subscribe_definition().SelectManyInSeries(def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false)).OnDispatcher()
|
||||
.Subscribe(new CompositeObserver<bool>(save_cmd, revert_cmd) {
|
||||
val => {
|
||||
_save_cmd_tooltip.refresh();
|
||||
_revert_cmd_tooltip.refresh();
|
||||
}
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_hooks(definitions, d => new CompositeDisposable(_any_dirty_monitor.join(d), d), true));
|
||||
subscribe_definition().SelectSeries(
|
||||
def => def?.subscribe_is_definition_dirty() ?? Observable.Return(false))
|
||||
.OnDispatcher()
|
||||
.Subscribe(new CompositeObserver<bool>(save_cmd, revert_cmd) {
|
||||
val => {
|
||||
_save_cmd_tooltip.refresh();
|
||||
_revert_cmd_tooltip.refresh();
|
||||
}
|
||||
}),
|
||||
ObservableAutoWrapper.connect_item_hooks(
|
||||
definitions,
|
||||
d => Disposable.Create(_any_dirty_monitor.join(d), d),
|
||||
true));
|
||||
// local methods
|
||||
string get_revert_tooltip() {
|
||||
var def = selected_definition;
|
||||
@@ -198,7 +206,7 @@ namespace mbts.spark {
|
||||
await _model.algo_model.metadata_service.update_metadata(def.Value.key, _ => d.create_metadata().with(def.Value.key));
|
||||
}
|
||||
return def;
|
||||
})).ContinueOnDispatcher(t => {
|
||||
})).ContinueWith(t => {
|
||||
if (t.Status != TaskStatus.RanToCompletion) {
|
||||
Log.Ui.debug_fatal($"Algo Studio error saving definitions: unexpected Task.Status '{t.Status}'.");
|
||||
return;
|
||||
@@ -211,7 +219,8 @@ namespace mbts.spark {
|
||||
}
|
||||
if (selected_definition != orig_selected && orig_selected_index >= 0 && orig_selected_index < this.definitions.Count)
|
||||
selected_definition = this.definitions[orig_selected_index];
|
||||
});
|
||||
},
|
||||
TaskScheduler.FromCurrentSynchronizationContext());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+2
@@ -6,6 +6,8 @@ using mbts.ui.controls;
|
||||
using mbts.ui.converters;
|
||||
using mbts.ui.utility;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
|
||||
+17
-15
@@ -4,28 +4,30 @@ using mbts.ui.controls;
|
||||
using mbts.ui.utility;
|
||||
using mbts.utils;
|
||||
|
||||
using Spark.Core.Collections;
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Reactive.Disposables;
|
||||
using System.Reactive.Linq;
|
||||
|
||||
namespace mbts.spark {
|
||||
static class AlgoParamRowsHelper {
|
||||
public static IDisposable connect(AlgoDefinitionVM algo, ObservableAggregateCollection<AlgoParamRowVM> rows, bool include_algo_type_rows) =>
|
||||
algo == null ? null : new CompositeDisposable(algo.observe_algo_root().OnDispatcher().SubscribeEach(a => {
|
||||
rows.clear_collections();
|
||||
if (a == null)
|
||||
return Disposable.empty;
|
||||
var child_rows = new ObservableAggregateCollection<AlgoParamRowVM>();
|
||||
/// Note: the order of operations here matters
|
||||
/// <see cref="_wrap_rows(IAlgoVM, AlgoParamRowVM, ObservableAggregateCollection{AlgoParamRowVM}, bool)" /> has the potential to trigger a lot of CollectionChanged events (depending on how deep the algo-tree is).
|
||||
/// There is no need to burden the aggregate 'rows' with echoing all of these events, if the child-row collection is finished changing when it is added to the aggregate.
|
||||
var hook = _wrap_rows(a, null, child_rows, include_algo_type_rows);
|
||||
rows.add_collection(child_rows.AsReadOnly());
|
||||
return hook;
|
||||
})) {
|
||||
rows.clear_collections
|
||||
};
|
||||
algo is null ? null : Disposable.Create(
|
||||
algo.observe_algo_root().OnDispatcher().SubscribeEach(a => {
|
||||
rows.clear_collections();
|
||||
if (a == null)
|
||||
return Disposable.empty;
|
||||
var child_rows = new ObservableAggregateCollection<AlgoParamRowVM>();
|
||||
/// Note: the order of operations here matters
|
||||
/// <see cref="_wrap_rows(IAlgoVM, AlgoParamRowVM, ObservableAggregateCollection{AlgoParamRowVM}, bool)" /> has the potential to trigger a lot of CollectionChanged events (depending on how deep the algo-tree is).
|
||||
/// There is no need to burden the aggregate 'rows' with echoing all of these events, if the child-row collection is finished changing when it is added to the aggregate.
|
||||
var hook = _wrap_rows(a, null, child_rows, include_algo_type_rows);
|
||||
rows.add_collection(child_rows.AsReadOnly());
|
||||
return hook;
|
||||
}),
|
||||
Disposable.Create(rows.clear_collections));
|
||||
|
||||
public static IDisposable negate_is_dirty(IReadOnlyObservableCollection<AlgoParamRowVM> rows) {
|
||||
return ObservableAutoWrapper.connect_item_hooks(rows, hook);
|
||||
|
||||
+2
@@ -5,6 +5,8 @@ using mbts.ui.controls;
|
||||
using mbts.ui.extensions;
|
||||
using mbts.ui.spark.algo;
|
||||
|
||||
using Spark.Core.Disposables;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
|
||||
@@ -7,6 +7,8 @@ namespace Spark.Trading {
|
||||
using mbts.analytics;
|
||||
using mbts.spark;
|
||||
|
||||
using Spark.Api.Reactive;
|
||||
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
@@ -14,26 +16,26 @@ namespace Spark.Trading {
|
||||
|
||||
class DayFillsDataSource {
|
||||
public static IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> create(
|
||||
IBus bus, SecurityStore sec_store) {
|
||||
IBus bus, SecurityResolver sec_resolver) {
|
||||
var users = bus.subscribe(SparkTags.Users);
|
||||
var inverse_users = users
|
||||
.Select(d => d.ToDictionary(kv => kv.Value.name, kv => kv.Value))
|
||||
.Table(u => u.name);
|
||||
var pnl_data_source = bus.subscribe(SparkTags.ReportBlackboardTags.PNL.PNLData);
|
||||
return create(pnl_data_source, inverse_users, sec_store);
|
||||
return create(pnl_data_source, inverse_users, sec_resolver);
|
||||
}
|
||||
|
||||
public static IObservable<TableUpdate<DayFillsRowData, DayFillsRowKey>> create(
|
||||
IObservable<PNLData> pnl_data_source,
|
||||
IObservable<TableUpdate<UserTuple, string>> inverse_users,
|
||||
SecurityStore sec_store) =>
|
||||
SecurityResolver sec_resolver) =>
|
||||
// join pnl data w/ security and user
|
||||
pnl_data_source
|
||||
.Select(d => d.day_trades
|
||||
.Select(DayFillsRowData.from_trade)
|
||||
.ToDictionary(DayFillsRowData.key_fn))
|
||||
.Table(DayFillsRowData.key_fn)
|
||||
.join_table(sec_store, rd => rd.security_key)
|
||||
.join_table(sec_resolver, rd => rd.security_key)
|
||||
.Select(tup => new DayFillsRowData(tup.val.trade, tup.sec), DayFillsRowData.key_fn)
|
||||
.LeftJoin(
|
||||
inverse_users,
|
||||
|
||||
Loaded 100 of 859 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user