Compare commits

..
Author SHA1 Message Date
John Colvin 565343e7d2 Update externals 2022-08-02 22:23:18 -04:00
John Colvin 68a41ef89b tools: Try to organize the script soup that is the tools dir 2022-07-01 18:06:22 -05:00
John Colvin d9447ce7a1 tools: Move git-related scripts into 'git' dir 2022-07-01 18:06:22 -05:00
John Colvin aca6988a76 tools: Remove unused scripts/files 2022-07-01 18:06:22 -05:00
John Colvin 2422bd0c63 tools: Rename dir cpp_helper -> cme
The 'cpp' stands for 'cash-per-point' in this case.  Renaming the dir
'cme' to avoid confusion, as 'cpp' usually means c++ in our line of work.
Furthermore, the script only generates cash-per-points for CME symbols.
2022-07-01 18:06:22 -05:00
John Colvin 87d3cf16b7 chore: Update deprecated boost spirit/phoenix includes 2022-07-01 18:06:22 -05:00
John Colvin a6c3ef3d16 refactor (client cpp): Upgrade catch test framework to catch2 2022-07-01 18:06:22 -05:00
John Colvin 99451eb3e7 Replace external deps w/ conan pkgs 2022-07-01 18:06:22 -05:00
John Colvin 8301fdccf4 build (client cpp): Configure cmake build w/ presets 2022-07-01 13:18:05 -05:00
John Colvin 8122e22c1b build (client cpp): Remove ZERO_CHECK.vcxproj from spark_client.sln
The new cmake generates ZERO_CHECK.proj instead, which doesn't need to be
included in the sln
2022-07-01 13:18:05 -05:00
John Colvin 78fece194f build (client cpp): Copy cpp Directory.Build.Props during cmake build 2022-07-01 13:18:05 -05:00
John Colvin f5f01857d4 build (client): Remove unused option '--link-output-dir' 2022-07-01 13:18:05 -05:00
John Colvin 062eb531bd build (sparkd): Shorten install prefix 2022-07-01 13:18:05 -05:00
John Colvin 91c0661657 chore: Consolidate if/else WIN32 logic in libspark CMakeLists 2022-07-01 13:18:05 -05:00
John Colvin ddd51417a0 chore: Remove unnecessary websocketpp includes
No websocketpp symbols are referenced anywhere.  This dependency should be
removed from externals
2022-07-01 13:18:05 -05:00
John Colvin fd80914f15 chore: Remove unused sln, vcxproj files 2022-07-01 13:18:05 -05:00
John Colvin e537d3ce51 build (win client cpp): Remove vs_filters.cmake 2022-07-01 13:18:05 -05:00
John Colvin e6b1cbbe01 build (client cpp): Stop disabling compiler warnings 2022-07-01 13:18:05 -05:00
John Colvin a20b92bdbd fix build (cpp win): Use builtin memcpy
Our custom impl, bts::os::memcpy, only works in linux.
Note: The reason we have a custom memcpy impl is to disable a pesky warning
about using memcpy for non-trivial copy assignment
2022-07-01 13:18:05 -05:00
John Colvin 5faedf45cc chore: Remove custom optional.h (no longer needed)
Now windows builtin includes provide optional
2022-07-01 13:18:05 -05:00
John Colvin aad6d1b5e3 fix build (preemptive): Make numeric casts explicit 2022-07-01 13:18:05 -05:00
John Colvin 4692256751 fix build (win cpp): Change WIN32 macro to _WIN32 2022-07-01 13:18:04 -05:00
John Colvin 0eff4dcc86 fix build (gcc release): Include openssl files in global ns 2022-07-01 13:18:04 -05:00
John Colvin 245c22a040 webserver: Remove hardcoded 'sparkvm' host 2022-07-01 13:18:04 -05:00
John Colvin b5bd976aa6 build: Update dotnet-format 2022-07-01 13:18:04 -05:00
John Colvin 6162c4b42f build: Migrate web build to net6.0
Clean up the web build process a bit while we're at it
* Add 'custom_commands' to run npm install in CMakeLists
* Generate tsconfig files for CMake preset configurations
* Rename local variables to _snake_case in CMakeLists
2022-07-01 13:18:04 -05:00
John Colvin 817ec73b3e build: Replace setup_builds w/ CMakePresets.json
Clean up CMakeLists a bit in the process:
   * Define more cmake vars in CMakePresets
   * Split linux/windows presets into separate files
2022-07-01 13:18:04 -05:00
John Colvin e79e557e88 dev/gen: Add script to dump CMakeDeps in readable form 2022-07-01 13:10:45 -05:00
John Colvin 0c1698520b build: Remove server/sparkd from libspark include path 2022-07-01 12:35:01 -05:00
John Colvin 6abec0c035 chore (linux build): Add benign changes to satisfy gcc11 2022-06-28 02:15:57 -04:00
johncolvin-og f0021138e4 chore (linux build): Add benign changes to satisfy clang13 2022-06-28 02:15:57 -04:00
John Colvin 131f5e7465 build: Automate venv activation in server build 2022-06-28 02:15:57 -04:00
John Colvin 850d304590 build: Update cmake-min-version to 3.12
Several 'add_compile_definitions' calls were added to the root
CMakeLists.txt as part of the ccapi_cpp lib integration (3.12 is the
version in which that call was introduced)
2022-06-28 02:15:57 -04:00
John Colvin 0dfced02ef Update docker/linux to get ccapi_cpp deps 2022-06-28 02:15:57 -04:00
taha afzal 43cba548f4 Adding some details to the logs to track order flow 2022-06-24 15:05:15 -04:00
taha afzal 772910ffe5 Fixing filled qty's fractional part not being filled on the server 2022-06-23 14:38:57 -05:00
John Colvin 767179caf7 chore (man fills): Format qty w/ sec metadata config 2022-06-23 14:38:57 -05:00
John Colvin ee4a9150b8 refactor (man fills): Rename 'size' members 'quantity' 2022-06-23 14:24:04 -05:00
John Colvin 58914fa703 chore: Replace remaining refs to uint 'filled' fn w/ double impl 2022-06-23 14:24:04 -05:00
John Colvin ba40e7044a fix (ladder, preemptive): Fix typo in _fmt_mkt_depth_item
Bugs (fixed):
   * The _fmt_mkt_depth_item fn potentially will return the result of the
     delegate.ToString(), instead of invoking the delegate and returning the
     result
2022-06-23 14:10:15 -05:00
John Colvin 010d0073fe chore: Set BTC qty display config defaults 2022-06-23 02:05:23 -05:00
John Colvin 40210ce42e chore: Remove unnecessary price_display config default 2022-06-23 01:35:22 -05:00
John Colvin 59cdafba21 fix: Don't cast manual fill qty to uint 2022-06-23 01:22:09 -05:00
John Colvin fe6226baa5 ui (reconcile rep): Match all undefined positions
Now, all positions without real non-zero quantities are considered matches
2022-06-23 01:19:27 -05:00
John Colvin 45987c7652 feat: Show fractional qty in orderbook Filled col 2022-06-22 16:04:24 -05:00
John Colvin a18ce97fb4 feat (ui): Support fractional qtys for order entry 2022-06-22 15:38:38 -05:00
John Colvin 13d5080bbc refactor: Shorten modify/revert cmd prop names
Also consolidate modify_price/qty fns into single modify_order fn
2022-06-22 15:38:38 -05:00
John Colvin 9f07a36d1d refactor: Move order-update-desc fn into OrderUtils for gen use 2022-06-22 15:38:38 -05:00
John Colvin bc2e7f428a chore: Add formal/consistent numeric exceptions/messages 2022-06-22 15:38:38 -05:00
John Colvin 53bfbdd349 fix: Sync 'has_value' prop for qty param
Bugs (fixed):
   * Can't tick qty up/down in the orderbook right panel (clicking the
   button has no discernible effect)
2022-06-22 15:38:38 -05:00
John Colvin 174eac9a59 refactor: Move OrderParamsVM into own file
OrderBookVM.cs was (and frankly still is) massive.  Too massive
2022-06-22 15:38:38 -05:00
John Colvin 3775b86d9e refactor: Rename 'size_' props 'quantity_' to be consistent 2022-06-22 15:38:38 -05:00
John Colvin 5e1c6d6209 fix build (windows): Don't include stdint-uintn.h on windows 2022-06-22 15:38:37 -05:00
taha afzal 0d0fb036ab EmMDListener now get_open_orders and logging the open orders 2022-06-22 15:38:37 -05:00
taha afzal f8668802ab Fixing oder updates on fractional quantity orders (just a few lines) 2022-06-22 15:38:37 -05:00
taha afzal c22a1382a1 Fractional qtys now work on the server (need some client side work) 2022-06-22 15:38:37 -05:00
Taha Afzal 941a0d91cc Enabled Combo report to show fractions (ITradeLow had size of type int) 2022-06-13 20:01:47 -04:00
355 changed files with 23737 additions and 17901 deletions

No files matched your search

+28
View File
@@ -0,0 +1,28 @@
[settings]
os=Windows
compiler='Visual Studio'
build_type=Debug
arch=x86_64
compiler.version=17
compiler.runtime=MTd
[options]
boost:without_graph=True
boost:without_iostreams=True
boost:without_json=True
boost:without_log=True
boost:without_math=True
boost:without_nowide=True
boost:without_program_options=True
boost:without_python=True
boost:without_random=True
boost:without_serialization=True
boost:without_test=True
boost:without_timer=True
boost:without_wave=True
boost:layout=system
boost:multithreading=True
[build_requires]
[env]
+28
View File
@@ -0,0 +1,28 @@
[settings]
os=Windows
compiler='Visual Studio'
build_type=Release
arch=x86_64
compiler.version=17
compiler.runtime=MT
[options]
boost:without_graph=True
boost:without_iostreams=True
boost:without_json=True
boost:without_log=True
boost:without_math=True
boost:without_nowide=True
boost:without_program_options=True
boost:without_python=True
boost:without_random=True
boost:without_serialization=True
boost:without_test=True
boost:without_timer=True
boost:without_wave=True
boost:layout=system
boost:multithreading=True
[build_requires]
[env]
+7 -1
View File
@@ -3,10 +3,16 @@
"isRoot": true,
"tools": {
"dotnet-format": {
"version": "5.1.225507",
"version": "5.1.250801",
"commands": [
"dotnet-format"
]
},
"protobuf-net.protogen": {
"version": "3.1.17",
"commands": [
"protogen"
]
}
}
}
+2
View File
@@ -50,3 +50,5 @@ trace_data/
*.tmp/*
/.venv*/*
.cache/
src/web/api/tsconfig.*.g.json
.conan/windows/install/*
+22 -50
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.12)
project(spark)
if(WIN32)
@@ -7,73 +7,45 @@ else()
set(platform "linux")
endif()
set(EXTERNALS_ROOT "${CMAKE_SOURCE_DIR}/externals/${platform}")
set(SPARK_PYTHON "${EXTERNALS_ROOT}/python")
set(
EXTERNALS_ROOT
"${CMAKE_SOURCE_DIR}/externals/${platform}"
CACHE
STRING
"External dependencies root folder (should contain folders: lib, bin, include")
set(SPARK_BIN "${EXTERNALS_ROOT}/bin")
set(SPARK_INCLUDE "${EXTERNALS_ROOT}/include")
set(SPARK_LIB "${EXTERNALS_ROOT}/lib/${CMAKE_BUILD_TYPE}")
set(TOOLS "${CMAKE_SOURCE_DIR}/tools")
set(BUILD_SDK OFF CACHE BOOL "Build the sdk")
set(BUILD_WEB ON CACHE BOOL "Build the web server")
include(${CMAKE_SOURCE_DIR}/.conan/${platform}/install/debug/conanbuildinfo.cmake)
set(CONAN_SYSTEM_INCLUDES ON)
conan_basic_setup()
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")
# subdirs
add_subdirectory(src/lib)
add_custom_command(
OUTPUT ${CMAKE_BINARY_DIR}/Directory.Build.Props
COMMAND cp ARGS ${TOOLS}/cpp.build.props ${CMAKE_BINARY_DIR}/Directory.Build.Props
DEPENDS ${TOOLS}/cpp.build.props
COMMENT "Copy cpp.build.props -> Directory.Build.Props")
add_custom_target(client_layout ALL DEPENDS ${CMAKE_BINARY_DIR}/Directory.Build.Props)
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_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_subdirectory(src/lib)
if (BUILD_WEB)
if(BUILD_WEB)
add_subdirectory(src/web)
endif()
add_subdirectory(doc/user)
@@ -90,9 +62,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"
+224
View File
@@ -0,0 +1,224 @@
{
"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 /bigobj /EHsc /DCURL_STATICLIB /D_WINSOCK_DEPRECATED_NO_WARNINGS /D__TBB_NO_IMPLICIT_LINKAGE /DBOOST_ALL_NO_LIB /std:c++17 /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",
"CONAN_COMPILER": "Visual Studio",
"CONAN_COMPILER_VERSION": "17",
"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}",
"CMAKE_EXE_LINKER_FLAGS": "-Wno-undef",
"EXTERNALS_ROOT": "${sourceDir}/externals/linux",
"CMAKE_C_COMPILER": "cc",
"CMAKE_CXX_STANDARD": "17",
"WEB_TSCONFIG_NAME": "${presetName}",
"BUILD_SDK": {
"type": "BOOL",
"value": "OFF"
},
"BUILD_WEB": {
"type": "BOOL",
"value": "ON"
}
}
},
{
"name": "sparkd-dev",
"hidden": true,
"inherits": "sparkd",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Debug",
"CMAKE_CXX_FLAGS_DEBUG": "-fPIC -Wall -pedantic -Wextra -Werror -Wno-missing-braces -Wno-ignored-qualifiers --std=c++17 -fdiagnostics-color",
"CMAKE_EXPORT_COMPILE_COMMANDS": {
"type": "BOOL",
"value": "ON"
}
}
},
{
"name": "sparkd-prod",
"hidden": true,
"inherits": "sparkd",
"cacheVariables": {
"CMAKE_BUILD_TYPE": "Release",
"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-dev-clang",
"inherits": "sparkd-dev",
"displayName": "Development (clang)",
"description": "Debug build compiled w/ clang",
"cacheVariables": {
"CMAKE_CXX_COMPILER": "clang++"
}
},
{
"name": "sparkd-dev-gcc",
"inherits": "sparkd-dev",
"displayName": "Development (gcc)",
"description": "Debug build compiled w/ gcc",
"cacheVariables": {
"CMAKE_CXX_COMPILER": "g++"
}
},
{
"name": "sparkd-prod-clang",
"inherits": "sparkd-prod",
"displayName": "Production (clang)",
"description": "Release build compiled w/ clang",
"cacheVariables": {
"CMAKE_CXX_COMPILER": "clang++"
}
},
{
"name": "sparkd-prod-gcc",
"inherits": "sparkd-prod",
"displayName": "Production (gcc)",
"description": "Release build compiled w/ gcc",
"cacheVariables": {
"CMAKE_CXX_COMPILER": "g++"
}
},
{
"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"
}
]
}
+3 -4
View File
@@ -1,6 +1,4 @@
set(Protobuf_PROTOC_EXECUTABLE "${SPARK_BIN}/protoc")
set(PROTOBUF_INCLUDE_DIRS "${SPARK_INCLUDE}")
set(PROTOBUF_STATIC_LIB "libprotobuf")
function(Protobuf_Generate_Cpp SRCS HDRS)
set(${SRCS})
@@ -106,8 +104,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
+16
View File
@@ -0,0 +1,16 @@
from conans import ConanFile
class SparkCryptoConan(ConanFile):
name = "spark_crypto"
version = "0.1"
author = "Blue Trading Solutions"
topics = (
"crypto", "trading", "options", "futures", "derivatives", "api",
"risk", "volatility", "finance")
requires = [
"boost/1.79.0", "catch2/3.0.1", "cmake/3.23.2", "fmt/8.1.1",
"libcurl/7.83.1", "nlohmann_json/3.10.5", "openssl/1.1.1o",
"protobuf/3.21.1", "onetbb/2021.3.0", "zlib/1.2.12"
]
generators = ("cmake", "virtualenv")
+40
View File
@@ -0,0 +1,40 @@
import os
import subprocess
import argparse
def _exit(code=0, msg=None):
if msg is not None:
print(msg)
exit(code)
def _literal_linesep():
ls = os.linesep
if ls == '\r\n':
return r'\r\n'
if ls == '\n':
return r'\n'
return ls
def _get_arg_parser():
parser = argparse.ArgumentParser(description='Build spark_client.sln')
parser.add_argument('input', nargs='?', help='The CMakeDeps file to dump')
return parser
def _main():
parser = _get_arg_parser()
args = parser.parse_args()
cmd_args = ['sed', fr"'s/;/{_literal_linesep()}/g'", args.input]
return subprocess.run(cmd_args)
if __name__ == '__main__':
try:
res = _main()
if res.returncode != 0:
_exit(1, str(res))
except Exception as e:
_exit(1, str(e))
+22
View File
@@ -1,17 +1,39 @@
astroid==2.7.3
autopep8==1.5.7
bottle==0.12.21
certifi==2022.6.15
cffi==1.14.6
charset-normalizer==2.1.0
colorama==0.4.4
conan==1.50.0
fasteners==0.17.3
gitdb==4.0.9
idna==3.3
isort==5.9.3
Jinja2==3.1.2
lazy-object-proxy==1.6.0
MarkupSafe==2.1.1
mccabe==0.6.1
node-semver==0.6.1
patch-ng==1.17.4
platformdirs==2.3.0
pluginbase==1.0.1
protobuf==3.19.1
pybars3==0.9.7
pycodestyle==2.7.0
pycparser==2.20
Pygments==2.12.0
PyJWT==2.4.0
pylint==2.10.2
PyMeta3==0.5.1
python-dateutil==2.8.2
PyYAML==6.0
requests==2.28.1
six==1.16.0
smmap==5.0.0
termcolor==1.1.0
toml==0.10.2
tqdm==4.64.0
urllib3==1.26.9
wrapt==1.12.1
yapf==0.31.0
-41
View File
@@ -1,41 +0,0 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 15
VisualStudioVersion = 15.0.26730.10
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "sparkd", "src\server\sparkd\sparkd.vcxproj", "{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{502FD050-679A-3B50-B438-098500700919}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
MinSizeRel|x64 = MinSizeRel|x64
Release|x64 = Release|x64
RelWithDebInfo|x64 = RelWithDebInfo|x64
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Debug|x64.ActiveCfg = Debug|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Debug|x64.Build.0 = Debug|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.MinSizeRel|x64.ActiveCfg = Release|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.MinSizeRel|x64.Build.0 = Release|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Release|x64.ActiveCfg = Release|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.Release|x64.Build.0 = Release|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{BBBAFD38-312D-4A8D-9AF0-F2BDEE72CE6F}.RelWithDebInfo|x64.Build.0 = Release|x64
{502FD050-679A-3B50-B438-098500700919}.Debug|x64.ActiveCfg = Debug|x64
{502FD050-679A-3B50-B438-098500700919}.Debug|x64.Build.0 = Debug|x64
{502FD050-679A-3B50-B438-098500700919}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{502FD050-679A-3B50-B438-098500700919}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{502FD050-679A-3B50-B438-098500700919}.Release|x64.ActiveCfg = Release|x64
{502FD050-679A-3B50-B438-098500700919}.Release|x64.Build.0 = Release|x64
{502FD050-679A-3B50-B438-098500700919}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{502FD050-679A-3B50-B438-098500700919}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {6A7249D7-B40C-4656-9347-60072D0B8FDB}
EndGlobalSection
EndGlobal
+22 -22
View File
@@ -1,10 +1,10 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.30114.105
# Visual Studio Version 17
VisualStudioVersion = 17.2.32616.157
MinimumVisualStudioVersion = 15.0.26124.0
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_api", "src\client\spark_api\spark_api.csproj", "{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}"
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "libspark", "build\src\lib\libspark.vcxproj", "{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Spark", "src\client\spark\Spark.csproj", "{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}"
EndProject
@@ -12,15 +12,15 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "sparkcmd", "src\client\spar
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_core", "src\client\spark_core\spark_core.csproj", "{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ZERO_CHECK", "build\ZERO_CHECK.vcxproj", "{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_sdk", "src\client\spark_sdk\spark_sdk.csproj", "{6963C314-83C4-4667-B0D0-C2F7AE208C29}"
ProjectSection(ProjectDependencies) = postProject
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40} = {9FA60215-26AF-3EB7-AB89-D4F4B126EF40}
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25} = {FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}
EndProjectSection
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "spark_test", "src\client\spark_test\spark_test.csproj", "{ECD78CC5-138F-4809-A764-2358C2AC2E82}"
EndProject
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "client_layout", "build\client_layout.vcxproj", "{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -37,14 +37,14 @@ Global
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.Release|x64.Build.0 = Release|x64
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{DC9A8975-8211-4FC9-A9BA-C8B9D26AD481}.RelWithDebInfo|x64.Build.0 = Release|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Debug|x64.ActiveCfg = Debug|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Debug|x64.Build.0 = Debug|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Release|x64.ActiveCfg = Release|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.Release|x64.Build.0 = Release|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{9FA60215-26AF-3EB7-AB89-D4F4B126EF40}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Debug|x64.ActiveCfg = Debug|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Debug|x64.Build.0 = Debug|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Release|x64.ActiveCfg = Release|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.Release|x64.Build.0 = Release|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{FDC3A021-386E-3A2C-A7EB-CBE94A95BE25}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.Debug|x64.ActiveCfg = Debug|x64
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.Debug|x64.Build.0 = Debug|x64
{9A4D4D07-1AB6-4B2B-B111-A4F34D6C267E}.MinSizeRel|x64.ActiveCfg = Release|x64
@@ -69,14 +69,6 @@ Global
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.Release|x64.Build.0 = Release|x64
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{6E449EB6-20AC-4FA6-B8D9-10F4BB7E1FEE}.RelWithDebInfo|x64.Build.0 = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.ActiveCfg = Debug|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Debug|x64.Build.0 = Debug|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.ActiveCfg = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.Release|x64.Build.0 = Release|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{A1B7276B-8F81-3D58-A22E-870AF28DF9B9}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.ActiveCfg = Debug|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.Debug|x64.Build.0 = Debug|x64
{6963C314-83C4-4667-B0D0-C2F7AE208C29}.MinSizeRel|x64.ActiveCfg = Release|x64
@@ -93,6 +85,14 @@ Global
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.Release|x64.Build.0 = Release|x64
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.RelWithDebInfo|x64.ActiveCfg = Release|x64
{ECD78CC5-138F-4809-A764-2358C2AC2E82}.RelWithDebInfo|x64.Build.0 = Release|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.Debug|x64.ActiveCfg = Debug|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.Debug|x64.Build.0 = Debug|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.MinSizeRel|x64.ActiveCfg = MinSizeRel|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.MinSizeRel|x64.Build.0 = MinSizeRel|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.Release|x64.ActiveCfg = Release|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.Release|x64.Build.0 = Release|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.RelWithDebInfo|x64.ActiveCfg = RelWithDebInfo|x64
{7BD9B47C-9AEA-3F81-B8E4-73C74C1932A9}.RelWithDebInfo|x64.Build.0 = RelWithDebInfo|x64
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
+2 -2
View File
@@ -29,8 +29,8 @@
<PropertyGroup Label="ProtoBuf">
<ProtocPluginBase>$(SparkRoot)\src\lib\api\service_compiler</ProtocPluginBase>
<protoc>$(Externals)\bin\protoc.exe</protoc>
<protogen>$(Externals)\bin\protogen.exe</protogen>
<protoc>protoc</protoc>
<protogen>dotnet protogen</protogen>
</PropertyGroup>
<ItemDefinitionGroup>
+3 -6
View File
@@ -3,7 +3,7 @@
<Target
Name="CompileProto2"
Condition="'@(Proto2)'!=''"
Inputs="$(MSBuildProjectFile);$(protogen);%(Proto2.FullPath)"
Inputs="$(MSBuildProjectFile);%(Proto2.FullPath)"
Outputs="$(GenDir)\proto2\%(Proto2.filename).cs"
AfterTargets="PreBuildEvent">
<PropertyGroup>
@@ -17,9 +17,6 @@
DestinationFolder="$(WorkingDirectory)"
SkipUnchangedFiles="True"
UseHardLinksIfPossible="True" />
<Error
Text="protogen.exe does not exist. If you forgot to clone with externals try: git submodule update --init --recursive"
Condition="!Exists($(protogen))" />
<Exec
Command="$(Protogen) %(Proto2.filename)%(proto2.extension) --csharp_out=. -I. -I$(SourceRoot) -I$(Externals)\include"
WorkingDirectory="$(WorkingDirectory)" />
@@ -37,7 +34,7 @@
Name="CompileProto3"
AfterTargets="GetAssemblyVersion"
Condition="'@(Proto3)'!=''"
Inputs="$(protoc);
Inputs="
%(Proto3.Identity);$(ProtocPluginBase)\plugin.py;
$(ProtocPluginBase)\templates\c#\client.pb.cs;
$(ProtocPluginBase)\templates\c#\server.pb.cs;
@@ -52,7 +49,7 @@
<Exec Command="set PYTHONPATH=$(SparkRoot)\.venv\Scripts\python" />
<Exec
Command="
$(SparkRoot)\tools\build_protos.cmd ^
$(protoc) ^
%(Proto3.FullPath) ^
--error_format=msvs ^
--proto_path=$(SourceRoot) ^
@@ -13,28 +13,21 @@ namespace mbts.spark {
bts.Log.Gen.info($"SingleVolSurfaceTimeSource cons vs_id:{vs_id}");
_vs_id = vs_id;
_bb = bb;
_bb.subscribe(SparkTags.VolSurfaceStandardServerTimeTag);
_bb.data_callback += _on_data;
_read_and_publish();
_bb.timer_callback += _on_timer;
}
private void _on_data(object tag, object data) {
if (tag.Equals(SparkTags.VolSurfaceStandardServerTimeTag)) {
_read_and_publish();
}
}
private void _read_and_publish() {
VolSurfaceStandardTime vs_time = _bb.read_state(SparkTags.VolSurfaceStandardServerTimeTag);
if (vs_time != null) {
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{vs_time.ToString()}");
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), vs_time);
private void _on_timer() {
if (DateTime.Now - _last_publish_time >= _publish_period) {
_last_publish_time = DateTime.Now;
VolSurfaceStandardTime time = VolSurfaceStandardTime.get_local_default();
bts.Log.Gen.info($"SingleVolSurfaceTimeSource vs_id:{_vs_id} posting time:{time.ToString()}");
_bb.post(SparkTags.VolSurfaceStandardTimeTag(_vs_id), time);
}
}
#region IDisposable
public void Dispose() {
_bb.data_callback -= _on_data;
_bb.timer_callback -= _on_timer;
}
#endregion
}
@@ -96,10 +96,6 @@ namespace mbts.spark {
var vs_usage_sub = _analytics_service.subscribei_volsurface_usage()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(_on_vs_usage_update);
var vs_time_sub = _analytics_service.subscribei_volsurface_time()
.ObserveOn(SynchronizationContext.Current)
.Subscribe(_on_vs_time);
_subs.Add(vs_time_sub);
_subs.Add(vs_sub);
_subs.Add(vs_usage_sub);
_subs.Add(new AnalyticsParametersManager(bus, _analytics_service));
@@ -121,10 +117,10 @@ namespace mbts.spark {
}
Log.Ui.info($"VolSurfaceUsageList name_to_ids count: {name_to_ids.Count}");
var vs_usage = mbts.config.Configuration.get<bts.config.toggles.VolSurfaceUsage>();
Log.Ui.info($"VolSurfaceUsageList vs_usage acount: {vs_usage.vol_surface_usage.Count}");
foreach (var u in vs_usage.vol_surface_usage) {
string option_name = u.option_name;
string vs_name = u.vs_name;
Log.Ui.info($"VolSurfaceUsageList vs_usage acount: {vs_usage.VolSurfaceUsages.Count}");
foreach (var u in vs_usage.VolSurfaceUsages) {
string option_name = u.OptionName;
string vs_name = u.VsName;
int vs_key;
if (name_to_ids.TryGetValue(vs_name, out vs_key)) {
ulist.UsageList.Add(new VolSurfaceUsageEntry() {
@@ -167,17 +163,6 @@ namespace mbts.spark {
_init_vss(to_publish.Keys);
}
void _on_vs_time(bts.api.core.Update<VolSurfaceServerTimeImmutable, int> update) {
if (update.all.Count() != 1) {
return;
}
VolSurfaceStandardTime vs_time =
new VolSurfaceStandardTime(update.all.ElementAt(0).UtcTime.Seconds);
bts.Log.Gen.info(String.Format("VSBusManager._on_vs_time vs_time: {0}",
vs_time.ToString()));
_bb.post(SparkTags.VolSurfaceStandardServerTimeTag, vs_time);
}
private void _init_vss(IEnumerable<int> vs_ids) {
// we consider every vs in the db as "activated" which might prove to be expensive
// (will take care of it later)
@@ -20,7 +20,7 @@ namespace mbts.spark {
[ImportingConstructor]
public AlgoProviderFactory(IAlgoStudioModel studio_model, DynamicOrderHelper dynamic_helper, ISecurityAuxiliaryDataModel security_auxiliary_model) {
var from_conf = config.Configuration.get<bts.config.AlgoTypeRuleSet>();
if (from_conf.rules.Count == 0) {
if (from_conf.Rules.Count == 0) {
// There seems to be a config race bug, where the returned config values are empty, despite having entries in spark.conf.
// [John]I've only noticed it happen when attached to the debugger,
// but best to have a contingency plan in place anyways, to prevent any chance of regression.
@@ -108,7 +108,7 @@ namespace mbts.spark {
.Select(t => _get_type_data(t))
.Concat(dynamic_helper.dynamic_types.Select(dt => _get_type_data(AlgoType.Dynamic, dt)))
.ToListLazy();
var conf_sets = from_conf.rules.Select(r => _to_security_algo_set(r, dynamic_helper, algo_type_data)).ToList();
var conf_sets = from_conf.Rules.Select(r => _to_security_algo_set(r, dynamic_helper, algo_type_data)).ToList();
security_algo_provider = new AlgoProvider(conf_sets.Select(tup => tup.standard).ToList(), studio_model, dynamic_helper, security_auxiliary_model);
attachable_algo_provider = new AttachableAlgoProvider(conf_sets.Select(tup => tup.attachable).ToList(), studio_model, dynamic_helper, security_auxiliary_model);
}
@@ -128,9 +128,9 @@ namespace mbts.spark {
context == null ?
new SecurityCriteriaClause() :
new SecurityCriteriaClause(
exchanges: context.exchanges?.Select(EnumHelper.parse<Venue>)?.ToArray(),
security_types: context.security_types?.Select(EnumHelper.parse<Security.ContractOneofCase>)?.Select(t => t.security_type())?.ToArray(),
symbols: context.symbols?.ToArray());
exchanges: context.Exchanges?.Select(EnumHelper.parse<Venue>)?.ToArray(),
security_types: context.SecurityTypes?.Select(EnumHelper.parse<Security.ContractOneofCase>)?.Select(t => t.security_type())?.ToArray(),
symbols: context.Symbols?.ToArray());
static (SecurityAlgoTypeSetImmutable standard, SecurityAlgoTypeSetImmutable attachable) _to_security_algo_set(
bts.config.AlgoTypeRule rule,
@@ -141,24 +141,24 @@ namespace mbts.spark {
var dynamic_types = ImmutableHashSet<string>.Empty.ToBuilder();
var attachable_factory_types = ImmutableHashSet<AlgoType>.Empty.ToBuilder();
var attachable_dynamic_types = ImmutableHashSet<string>.Empty.ToBuilder();
foreach (var a in rule.algos) {
if (Enum.TryParse(a.name, out AlgoType sys_algo) && sys_algo != AlgoType.Composite && sys_algo != AlgoType.Dynamic) {
on_sys_match(sys_algo, a.is_attachable);
} else if (dynamic_helper.try_parse(a.name, out var dyn_type)) {
on_dyn_match(dyn_type, a.is_attachable);
foreach (var a in rule.Algos) {
if (Enum.TryParse(a.Name, out AlgoType sys_algo) && sys_algo != AlgoType.Composite && sys_algo != AlgoType.Dynamic) {
on_sys_match(sys_algo, a.IsAttachable);
} else if (dynamic_helper.try_parse(a.Name, out var dyn_type)) {
on_dyn_match(dyn_type, a.IsAttachable);
} else {
foreach (var (name, factory, dynamic) in algo_type_data) {
if (Regex.Match(name, a.name).Success) {
if (Regex.Match(name, a.Name).Success) {
switch (factory) {
case AlgoType.None:
case AlgoType.Composite:
// unexpected, but no need to crash
continue;
case AlgoType.Dynamic:
on_dyn_match(dynamic, a.is_attachable);
on_dyn_match(dynamic, a.IsAttachable);
break;
default:
on_sys_match(factory, a.is_attachable);
on_sys_match(factory, a.IsAttachable);
break;
}
}
@@ -168,13 +168,13 @@ namespace mbts.spark {
return (
// standard
new SecurityAlgoTypeSetImmutable(
_to_clause(rule.context),
_to_clause(rule.Context),
new AlgoTypeSetImmutable(
factory_types.ToImmutable(),
dynamic_types.ToImmutable())),
// attachable
new SecurityAlgoTypeSetImmutable(
_to_clause(rule.context),
_to_clause(rule.Context),
new AlgoTypeSetImmutable(
attachable_factory_types.ToImmutable(),
attachable_dynamic_types.ToImmutable())));
@@ -17,13 +17,6 @@ namespace mbts.analytics {
this.server_time_utc = server_time_utc;
}
public VolSurfaceStandardTime(long seconds_from_epoch) {
timezone = TimeZoneInfo.Local;
server_time_utc =
DateTimeOffset.FromUnixTimeSeconds(seconds_from_epoch).DateTime;
server_time = server_time_utc.ToLocalTime();
}
public static VolSurfaceStandardTime get_local_default() {
DateTime local_rounded = VolSurfaceUtilityFunctions.round_time_mins(
DateTime.Now, VolSurfaceConstants.vol_time_sample_mins);
+1 -1
View File
@@ -37,7 +37,7 @@ namespace bts.ui {
Window about = Application.LoadComponent(new Uri("/view/Shell/About.xaml", UriKind.Relative)) as Window;
enable_crash_on_dblclick(about);
if (about != null) {
about.DataContext = new { Version = Configuration.get<bts.config.System>().version, User = _user };
about.DataContext = new { Version = Configuration.get<bts.config.System>().Version, User = _user };
about.Topmost = true;
about.CommandBindings.Add(new CommandBinding(ApplicationCommands.Close, (a, b) => about.Close()));
about.CommandBindings.Add(new CommandBinding(ApplicationCommands.Open, (arg, e) => {
+1 -1
View File
@@ -49,7 +49,7 @@ namespace bts {
ss,
user,
security_metadata,
TimeSpan.FromMilliseconds(Configuration.get<RelayOptions>().naggle_ms),
TimeSpan.FromMilliseconds(Configuration.get<RelayOptions>().NaggleMs),
TimeSpan.FromSeconds(1)) { }
public MDDaemon(
@@ -33,7 +33,7 @@ namespace bts.shell {
[ImportingConstructor]
public OrderTicketDaemon(IBus bus, OrdersModel model, UserSettingsHub settings_hub, ErrorReporter error_reporter)
: this(bus, model, settings_hub, error_reporter, Configuration.get<bts.config.OrderTicketOptions>().close_on_send) { }
: this(bus, model, settings_hub, error_reporter, Configuration.get<bts.config.OrderTicketOptions>().CloseOnSend) { }
public OrderTicketDaemon(IBus bus, OrdersModel model, UserSettingsHub settings_hub, ErrorReporter error_reporter, bool close_on_send) {
_bus = bus;
+1 -1
View File
@@ -21,7 +21,7 @@ namespace mbts.ui {
[ImportingConstructor]
public RecenterDaemon(IBus bus) {
_bus = bus;
_time_to_center = TimeSpan.FromSeconds(config.Configuration.get<bts.config.LadderKnobs>().seconds_to_recenter);
_time_to_center = TimeSpan.FromSeconds(config.Configuration.get<bts.config.LadderKnobs>().SecondsToRecenter);
_last_recenter = DateTime.UtcNow;
_dispose = _bus.subscribe(SparkTags.RequestRecenterLadder).Subscribe(_ => trigger_recenter(SparkTags.RecenterLadderNow));
@@ -24,7 +24,7 @@ namespace bts.perf {
[ImportingConstructor]
public ShellLatencyDaemon(ShellLatencyService service, Lazy<UserTuple> user) {
_service = service;
_version = Configuration.get<bts.config.System>().version;
_version = Configuration.get<bts.config.System>().Version;
_username = user.Value.name;
_hostname = Environment.MachineName;
@@ -49,32 +49,32 @@ namespace bts.perf {
async void _forever_ping_host(Ping pinger) {
var config = Configuration.get<bts.config.ShellPingOptions>();
string server_ip = Configuration.get<bts.config.System>().config_ip;
int delay = config.workloop_milliseconds_interval;
string server_ip = Configuration.get<bts.config.System>().ConfigIp;
int delay = config.WorkloopMillisecondsInterval;
int _current_missed_ping_count = 0;
if (config.shell_ping_is_enabled && pinger != null) {
if (config.ShellPingIsEnabled && pinger != null) {
while (true) {
try {
await Task.Delay(delay);
var response = await pinger.SendPingAsync(server_ip, config.timeout_milliseconds_threshold);
var response = await pinger.SendPingAsync(server_ip, config.TimeoutMillisecondsThreshold);
if (response.Status == IPStatus.Success) {
_current_missed_ping_count = 0;
if (response.RoundtripTime > config.logging_milliseconds_threshold) {
if (response.RoundtripTime > config.LoggingMillisecondsThreshold) {
Log.Ui.warn($"Ping response not received in a timely manner:\n" +
$"\tAddress:\t{response.Address}\n" +
$"\tRoundTrip:\t{response.RoundtripTime} ms");
}
// potentially reset delay to initial work period (no-op otherwise)
delay = config.workloop_milliseconds_interval;
delay = config.WorkloopMillisecondsInterval;
} else {
_current_missed_ping_count++;
delay = _get_exp_delay(_current_missed_ping_count, config.workloop_milliseconds_interval, config.maximum_backoff_milliseconds);
delay = _get_exp_delay(_current_missed_ping_count, config.WorkloopMillisecondsInterval, config.MaximumBackoffMilliseconds);
Log.Ui.warn($"Ping was not successful. Ping response: {response.Status}. Missed ping count: {_current_missed_ping_count}. Backing off for {delay} milliseconds.");
}
} catch (PingException e) {
_current_missed_ping_count++;
delay = _get_exp_delay(_current_missed_ping_count, config.workloop_milliseconds_interval, config.maximum_backoff_milliseconds);
delay = _get_exp_delay(_current_missed_ping_count, config.WorkloopMillisecondsInterval, config.MaximumBackoffMilliseconds);
Log.Ui.error($"Ping exception. {e}\nBacking off for {delay} milliseconds.");
}
} // end while
+1 -1
View File
@@ -28,7 +28,7 @@ namespace bts.shell {
}
}
bool check_version() {
string current = Configuration.get<bts.config.System>().version;
string current = Configuration.get<bts.config.System>().Version;
if (!string.IsNullOrWhiteSpace(current) && current != "private") {
using (var key = Registry.CurrentUser.CreateSubKey(@"Software\BTS")) {
var value = key.GetValue("version");
@@ -31,7 +31,7 @@
public override string window_type => WINDOW_TYPE;
string ISharedWindow.thread_id =>
config.Configuration.get<bts.config.MultiThreadedWindows>().vol_surface ? "VolSurface" : null;
config.Configuration.get<bts.config.MultiThreadedWindows>().VolSurface ? "VolSurface" : null;
public int vs_id => _startup_data.id;
public string vs_name { get; }
@@ -8,6 +8,8 @@
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using System.Collections.Generic;
using System.Composition;
using System.IO;
@@ -24,9 +26,11 @@
MDConsumer consumer,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model) =>
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) =>
_window_factories = new() {
new MarketViewWindowFactory(this, bus, settings_hub, orders_model, position_model),
new MarketViewWindowFactory(
this, bus, settings_hub, orders_model, position_model, sec_meta_store),
new OptionsViewWindowFactory(this, bus),
new TimeAndSalesWindowFactory(this, bus, consumer, settings_hub, orders_model.security_auxiliary_model),
};
@@ -24,12 +24,14 @@
using System.Reactive.Linq;
using System.Windows.Input;
using TickFactors = bts.api.domain.TickFactorsImmutable;
partial class MarketViewVM {
public class Row : DisposableViewModelBase, ISecurityMDRow, IEquatable<Row>, DIYGrid.IRowVM, DIYGrid.IActionableRowVM {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly AnimationManager _animation = new();
readonly MyOrderSummarizer _order_summarizer = new();
readonly MyOrderSummarizer _order_summarizer;
readonly DeferrableActionWrapper _raise_invalidated;
readonly Property<double> _bid_price;
@@ -79,6 +81,9 @@
_bus = bus;
security_md = smd;
_orders_model = orders_model;
_order_summarizer = new(
smd.quantity_display.HasTickFactors ?
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);
@@ -444,11 +449,16 @@
OrderDataHelper.CompareUtils.ask_price_comparer,
OrderDataHelper.CompareUtils.order_record_id_eq_comparer);
int _best_bid_working_qty;
int _best_ask_working_qty;
int _position;
int _working_bid_qty;
int _working_ask_qty;
readonly TickFactors _tick_factors;
double _best_bid_working_qty;
double _best_ask_working_qty;
double _position;
double _working_bid_qty;
double _working_ask_qty;
public MyOrderSummarizer(TickFactors tick_factors) =>
_tick_factors = tick_factors;
// bid
public double best_working_bid => _bids.Count > 0 ? _bids.at_index(0).Key : double.NaN;
@@ -456,22 +466,22 @@
public double working_bid_qty => _working_bid_qty;
// ask
public double best_working_ask => _asks.Count > 0 ? _asks.at_index(0).Key : double.NaN;
public int best_working_ask_qty => _best_ask_working_qty;
public double best_working_ask_qty => _best_ask_working_qty;
public double working_ask_qty => _working_ask_qty;
// pos
public int position => _position;
public double position => _position;
public void add_order(OrderRecordImmutable o) {
switch (o.side()) {
case Side.Buy:
_position += (int)o.filled();
_position += o.filled_quantity();
if (o.is_active()) {
_working_bid_qty += o.working_quantity();
_bids.add(o.price(), o);
}
break;
case Side.Sell:
_position -= (int)o.filled();
_position -= o.filled_quantity();
if (o.is_active()) {
_working_ask_qty += o.working_quantity();
_asks.add(o.price(), o);
@@ -485,14 +495,14 @@
public void remove_order(OrderRecordImmutable o) {
switch (o.side()) {
case Side.Buy:
_position -= (int)o.filled();
_position -= o.filled_quantity();
if (o.is_active()) {
_working_bid_qty -= o.working_quantity();
_bids.remove(o.price(), o);
}
break;
case Side.Sell:
_position += (int)o.filled();
_position += o.filled_quantity();
if (o.is_active()) {
_working_ask_qty -= o.working_quantity();
_asks.remove(o.price(), o);
@@ -504,6 +514,7 @@
}
void _refresh() {
_position = _tick_factors.round(_position);
_best_bid_working_qty = _bids.Count > 0 ? _bids.at_index(0).Sum(o => o.working_quantity()) : 0;
_best_ask_working_qty = _asks.Count > 0 ? _asks.at_index(0).Sum(o => o.working_quantity()) : 0;
}
@@ -18,6 +18,7 @@ namespace mbts.spark {
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
@@ -56,6 +57,7 @@ namespace mbts.spark {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly UserSettingsHub _settings_hub;
readonly ObservableCollection<Row> _rows = new();
readonly IList<SecurityMD> _wrapped_rows;
@@ -81,12 +83,14 @@ namespace mbts.spark {
IBus bus,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
UserSettingsHub settings_hub,
IObservable<TableUpdate<SecurityMD, uint>> security_mds_source,
bool use_mouse_state_transitions = false) {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_settings_hub = settings_hub;
security_filter = new RegexFilterVM<Row>(r => r.security.ToString(), nameof(Row.security));
// rows
@@ -636,8 +640,8 @@ namespace mbts.spark {
state.orderbook_grid.general = _hide_cols(state.orderbook_grid.general, hide_cols);
var settings_man = new WindowSettingsManager<bts.shell.orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, _position_model, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, orders_source, settings_man, true);
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, orders_source, settings_man, true);
foreach (var c in OrderBookVM.OrderBookColumnCollection.editable_columns) {
obvm.columns.Insert(0, c);
}
@@ -16,6 +16,8 @@ using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -29,6 +31,7 @@ namespace mbts.spark {
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;
@@ -51,16 +54,18 @@ namespace mbts.spark {
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;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().MarketView ? "MarketView" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _subscriptions);
_vm.Dispose();
@@ -131,6 +136,7 @@ namespace mbts.spark {
_bus,
_orders_model,
_position_model,
_sec_meta_store,
_settings_hub,
security_md_map_src
.BufferLatest(TimeSpan.FromSeconds(1))
@@ -9,6 +9,8 @@ using mbts.spark;
using mbts.ui;
using mbts.ui.settings;
using Spark.Core.Data;
using System;
using System.Composition;
using System.Linq;
@@ -23,18 +25,20 @@ namespace bts.shell {
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly UserSettingsHub _settings_hub;
readonly ISecurityMetadataStore _sec_meta_store;
public MarketViewWindowFactory(
MarketShellModule module,
IBus bus,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model) : base(module, "MarketView") {
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) : base(module, "MarketView") {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_settings_hub = settings_hub;
_sec_meta_store = sec_meta_store;
_dispose = bus.subscribe(SparkTags.ShowMarketViewTag).OnDispatcher().Subscribe(_show);
}
@@ -48,7 +52,7 @@ namespace bts.shell {
IShellWindow _create(MarketViewSettings state) =>
new MarketViewWindow(
this, _bus, _orders_model, _position_model, state, _settings_hub);
this, _bus, _orders_model, _position_model, _sec_meta_store, state, _settings_hub);
// migration rules
[Export(typeof(IMarketViewGridSettingsMigrationRule))]
@@ -42,7 +42,7 @@
public override Task<IShellWindow> load(TimeAndSalesSettings state) {
var conf = Configuration.get<bts.config.TimeAndSalesOptions>();
var thread_id = Configuration.get<bts.config.MultiThreadedWindows>().time_and_sales ?
var thread_id = Configuration.get<bts.config.MultiThreadedWindows>().TimeAndSales ?
TimeAndSalesWindow.WINDOW_TYPE_NAME : null;
var settings_man = new WindowSettingsManager<GridSettings>(
_settings_hub, state.grid, s => s.time_and_sales_grid, (s, g) => s.with(time_and_sales: g));
@@ -52,7 +52,7 @@
_consumer,
state,
settings_man,
conf.can_pause_updates,
conf.CanPauseUpdates,
_security_auxiliary_model.get_display_quantity_divisor,
thread_id);
return Task.FromResult<IShellWindow>(win);
@@ -32,7 +32,7 @@ namespace bts.ui {
SparkCommands.ShowGlobalAlerts,
SparkCommands.ShowWorkspaces
};
if (Configuration.get<bts.config.toggles.ToastNotifications>().enabled) {
if (Configuration.get<bts.config.toggles.ToastNotifications>().Enabled) {
actions_list.Add(SparkCommands.ShowSettings);
}
actions = actions_list;
@@ -26,9 +26,9 @@ namespace bts {
static bool _is_hidden(IShellModule module) {
var props = Configuration.get<IShellModuleProps>();
string name = module.GetType().Name;
foreach (var p in props.module) {
if (p.name.ToLower() == name.ToLower()) {
return !p.visible;
foreach (var p in props.Modules) {
if (p.Name.ToLower() == name.ToLower()) {
return !p.Visible;
}
}
return false;
@@ -42,7 +42,7 @@ namespace mbts.spark {
_state = state;
_settings_manager = settings_manager;
Icon.Freeze();
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().synthetic_management ?
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().SyntheticManagement ?
"SyntheticManagement" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _vm);
@@ -44,8 +44,8 @@ namespace bts.shell {
string uristr = uri.ToString();
string http_base =
"http://{0}:{1}/".fmt(
Configuration.get<bts.config.System>().config_host,
Configuration.get<bts.config.System>().config_port);
Configuration.get<bts.config.System>().ConfigHost,
Configuration.get<bts.config.System>().ConfigPort);
string temp = uristr;
if (uristr.StartsWith("bts://m/")) {
temp = uristr.Replace("bts://m/", http_base + "docs/");
@@ -94,7 +94,7 @@ namespace bts.shell {
emulation_key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey(ke_name);
}
var process_name = Configuration.get<bts.config.System>().process_name;
var process_name = Configuration.get<bts.config.System>().ProcessName;
emulation_key.SetValue(process_name, 11001); // IE11
}
#endregion
@@ -43,7 +43,7 @@ namespace mbts.spark {
: base(NAME, bus, factory, SparkCommands.ShowAlgoStudio.icon) {
_model = model;
_state = state;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().algo_studio ? "AlgoStudio" : null;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().AlgoStudio ? "AlgoStudio" : null;
_dispose = Disposable.Create(_dispose_core);
}
@@ -74,12 +74,12 @@ namespace mbts.spark {
_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));
_commands.Add(new SparkCommandCommand("Save Algo", Icons.DiskFile, _vm.save_cmd) {
show_in_toolbar = _ui_configuration.can_save_specific
show_in_toolbar = _ui_configuration.CanSaveSpecific
});
_commands.Add(new SparkCommandCommand("Save All", Icons.Disk, ObservantAsyncCommand.create(_vm.save_all, out var save_all_observer)));
_resources.Add(_vm.subscribe_dirty().OnDispatcher().Subscribe(save_all_observer));
// undo/redo
if (_ui_configuration.can_undo_redo) {
if (_ui_configuration.CanUndoRedo) {
// undo
var undo_cmd = new ObservantCommand(() => _vm.selected_definition?.try_undo());
var undo_spark_cmd = new SparkCommandCommand("Undo", Icons.UndoCircular, undo_cmd);
@@ -17,10 +17,10 @@ namespace mbts.spark {
static class AlgoStudioModelUtils {
public static IReadOnlyDictionary<object, object> get_dynamic_resources(bts.config.AlgoStudioOptions ui_configuration) =>
new Dictionary<object, object> {
{ AlgoStudioWindow.ShowAlgoToolBarRenameDefinitionKey, ui_configuration.can_modify_definition_name && ui_configuration.show_algo_toolbar_rename },
{ AlgoStudioWindow.ShowAlgoToolBarSaveDefinitionKey, ui_configuration.can_modify_definition_values && ui_configuration.show_algo_toolbar_save },
{ AlgoStudioWindow.ShowAlgoToolBarRevertDefinitionKey, ui_configuration.show_algo_toolbar_revert },
{ AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey, ui_configuration.show_algo_toolbar_undo_redo }
{ AlgoStudioWindow.ShowAlgoToolBarRenameDefinitionKey, ui_configuration.CanModifyDefinitionName && ui_configuration.ShowAlgoToolbarRename },
{ AlgoStudioWindow.ShowAlgoToolBarSaveDefinitionKey, ui_configuration.CanModifyDefinitionValues && ui_configuration.ShowAlgoToolbarSave },
{ AlgoStudioWindow.ShowAlgoToolBarRevertDefinitionKey, ui_configuration.ShowAlgoToolbarRevert },
{ AlgoStudioWindow.ShowAlgoToolBarUndoRedoDefinitionKey, ui_configuration.ShowAlgoToolbarUndoRedo }
};
}
}
@@ -65,9 +65,9 @@ namespace mbts.spark {
_permissions_mask.mask = init_permissions;
_permissions_mask.raw = init_permissions;
var resources = new CompositeDisposable();
if (!model.algo_model.ui_configuration.can_modify_definition_values)
if (!model.algo_model.ui_configuration.CanModifyDefinitionValues)
editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditValues | AlgoEditingPermissions.AllowSaveValues);
if (!model.algo_model.ui_configuration.can_modify_definition_structure)
if (!model.algo_model.ui_configuration.CanModifyDefinitionStructure)
editing_permissions_mask ^= (AlgoEditingPermissions.AllowEditStructure | AlgoEditingPermissions.AllowSaveStructure);
key = def_data.key;
algos_view = ObservableAutoWrapper.create_sorted_wrapper(_algo_roots, AlgoCollectionHelper.algo_vm_comparer);
@@ -128,7 +128,7 @@ namespace mbts.spark {
case AlgoKey.Mode.Persisted:
_metadata = new AlgoDefinitionMetadata(key);
resources.Add(model.algo_model.metadata_service.subscribe_metadata(key).OnDispatcher().Subscribe(_on_metadata));
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, conf.can_modify_definition_name ? VisualStateNames.Name.Active : VisualStateNames.Name.CannotRenameDefinition);
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, conf.CanModifyDefinitionName ? VisualStateNames.Name.Active : VisualStateNames.Name.CannotRenameDefinition);
break;
case AlgoKey.Mode.Factory:
_edit_pane_vs_model.set_state(VisualStateNames.Name.GroupName, VisualStateNames.Name.Inactive);
@@ -385,15 +385,21 @@
and only necessary for the size param as of 6/8/2020 (slightly more uniform code doesn't warrant rocking the boat).-->
<u:TemplateSelectorKeyValue Key="{x:Static usp:AlgoParamTemplateKeys.Size}">
<DataTemplate>
<c:TickUpDownNullableInt32 Focusable="False" HorizontalAlignment="Stretch" Value="{Binding param.display_value, UpdateSourceTrigger=PropertyChanged}" ArrowKeyTickModifiers="Ctrl">
<c:TickUpDownNullableInt32.CommandBindings>
<c:TickUpDownNullableDouble
Focusable="False"
HorizontalAlignment="Stretch"
Value="{Binding param.display_value, UpdateSourceTrigger=PropertyChanged}"
TickDownCommand="{Binding param.tick_down_cmd, Mode=OneWay}"
TickUpCommand="{Binding param.tick_up_cmd, Mode=OneWay}"
ArrowKeyTickModifiers="Ctrl">
<c:TickUpDownNullableDouble.CommandBindings>
<CommandBinding Command="{x:Static u:NavigationHelper.MoveFocusCommand}" Executed="{x:Static u:NavigationHelper.KeyboardMoveFocusExecuted}"/>
</c:TickUpDownNullableInt32.CommandBindings>
<c:TickUpDownNullableInt32.InputBindings>
</c:TickUpDownNullableDouble.CommandBindings>
<c:TickUpDownNullableDouble.InputBindings>
<KeyBinding Key="Up" Command="{x:Static u:NavigationHelper.MoveFocusCommand}" CommandParameter="{x:Static FocusNavigationDirection.Up}"/>
<KeyBinding Key="Down" Command="{x:Static u:NavigationHelper.MoveFocusCommand}" CommandParameter="{x:Static FocusNavigationDirection.Down}"/>
</c:TickUpDownNullableInt32.InputBindings>
</c:TickUpDownNullableInt32>
</c:TickUpDownNullableDouble.InputBindings>
</c:TickUpDownNullableDouble>
</DataTemplate>
</u:TemplateSelectorKeyValue>
</usp:AlgoParamTemplateSelector.KeyedTemplates>
@@ -37,7 +37,7 @@ namespace mbts.spark {
_orders_model = orders_model;
_state = state;
_settings_manager = settings_manager;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().fills ? "Fills" : null;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().Fills ? "Fills" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(ref _vm);
if (_commands != null) {
@@ -7,6 +7,8 @@ using bts.md;
using mbts.co2;
using Spark.Core.Data;
using System;
using System.Threading.Tasks;
@@ -18,11 +20,13 @@ namespace mbts.spark {
SecurityMD source,
OrdersModel ordergw,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
MBOService mbo,
Func<OrderSecurity, bool> order_filter = null) {
security_md = source;
_order_gateway = ordergw;
this.position_model = position_model;
this.sec_meta_store = sec_meta_store;
orders = ordergw.on_security_working_orders_with_piq(source.security.Id);
this.mbo_service = mbo;
if (order_filter != null) {
@@ -37,6 +41,7 @@ namespace mbts.spark {
public IMDConsumerHandle md => security_md.md;
public OrdersModel order_gateway => _order_gateway;
public IPositionModel position_model { get; }
public ISecurityMetadataStore sec_meta_store { get; }
public IObservable<TableUpdate<OrderSecurity, uint>> orders { get; }
public MBOService mbo_service { get; }
@@ -515,7 +515,7 @@ namespace mbts.spark {
static LadderSettings() {
var knobs = config.Configuration.get<bts.config.LadderKnobs>();
mimic_tt = knobs.mimic_tt;
mimic_tt = knobs.MimicTt;
}
// Default proto constructor
@@ -12,6 +12,8 @@ namespace mbts.spark {
using mbts.ui.spark;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -36,6 +38,8 @@ namespace mbts.spark {
[DisallowNull]
readonly IPositionModel _position_model;
[DisallowNull]
readonly ISecurityMetadataStore _sec_meta_store;
[DisallowNull]
readonly UserSettingsHub _settings_hub;
[DisallowNull]
readonly LadderWindowSettings _window_settings;
@@ -60,6 +64,7 @@ namespace mbts.spark {
[DisallowNull] IBus bus,
[DisallowNull] OrdersModel orders_model,
[DisallowNull] IPositionModel position_model,
[DisallowNull] ISecurityMetadataStore sec_meta_store,
SecurityMD security_md,
LadderWindowSettings window_settings,
[NotNull] UserSettingsHub settings_hub,
@@ -75,6 +80,7 @@ namespace mbts.spark {
_orders_model = orders_model ?? throw new ArgumentNullException(nameof(orders_model));
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_ladder_conf = ladder_conf;
_security_md = security_md;
_mbo = mbo ?? throw new ArgumentNullException(nameof(mbo));
@@ -108,7 +114,8 @@ namespace mbts.spark {
public void thread_init() {
// resources
var model = new LadderModel(_security_md, _orders_model, _position_model, _mbo);
var model = new LadderModel(
_security_md, _orders_model, _position_model, _sec_meta_store, _mbo);
_profile_service = new SettingsProfileService<LadderSettings>(_settings_hub,
us => ImmutableDictionary<uint, SettingsProfile<LadderSettings>>.Empty.AddRange(us.ladder_profiles.ToDictionary(
lp => lp.id,
@@ -14,6 +14,8 @@
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -33,6 +35,7 @@
readonly UserSettingsHub _settings_hub;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IShellWindowThreadIDProvider _thread_id_provider;
IReadOnlyDictionary<uint, SecurityMD> _securities = new Dictionary<uint, SecurityMD>();
@@ -44,6 +47,7 @@
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
MBOService mbo)
: base(owner, _window_type, 2) {
_bus = bus;
@@ -51,9 +55,10 @@
_settings_hub = settings_hub;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_ladder_conf = new LadderConfig(
Configuration.get<bts.config.LadderKnobs>(),
Configuration.get<bts.config.MultiThreadedWindows>().ladder);
Configuration.get<bts.config.MultiThreadedWindows>().Ladder);
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, _ladder_conf.ladders_on_threads);
_mbo = mbo;
_dispose = Disposable.Create(
@@ -77,7 +82,18 @@
IShellWindow _create_ladder_window(SecurityMD sec_md, LadderWindowSettings ws) {
var thread_id = _thread_id_provider.next_id();
return new LadderWindow(
module, _mbo, this, _bus, _orders_model, _position_model, sec_md, ws, _settings_hub, thread_id, _ladder_conf);
module,
_mbo,
this,
_bus,
_orders_model,
_position_model,
_sec_meta_store,
sec_md,
ws,
_settings_hub,
thread_id,
_ladder_conf);
}
void _show_windows(IEnumerable<SecurityMD> securities) {
@@ -101,10 +117,10 @@
public readonly TimeSpan security_timeout;
public LadderConfig(bts.config.LadderKnobs knobs, bool ladders_on_threads) {
max_open_ladders = knobs.max_open_ladders;
open_algo_popup_on_select = knobs.open_algo_popup_on_select;
use_algo_param_grid = knobs.use_algo_param_grid;
security_timeout = TimeSpan.FromSeconds(Math.Max(15, knobs.security_timeout_secs));
max_open_ladders = knobs.MaxOpenLadders;
open_algo_popup_on_select = knobs.OpenAlgoPopupOnSelect;
use_algo_param_grid = knobs.UseAlgoParamGrid;
security_timeout = TimeSpan.FromSeconds(Math.Max(15, knobs.SecurityTimeoutSecs));
this.ladders_on_threads = ladders_on_threads;
}
}
@@ -49,7 +49,7 @@ namespace mbts.spark {
ImmutableDictionary<uint, OrderSecurity>.Empty;
LadderSettings.BadgeStyle _current_badge_style;
double _phantom_price = double.NaN;
uint _filled;
double _filled;
uint _num_root_orders;
double _quantity;
uint? _min_piq = uint.MaxValue;
@@ -64,7 +64,7 @@ namespace mbts.spark {
_orders = orders;
_real_price = real_price;
_text_lines = backing(nameof(text_lines), () => {
var fmt = MDDisplayHelper.get_value_formatter(_owner.display_quantity_divisor);
var fmt = MDDisplayHelper.get_value_formatter(_owner.model.security_md.quantity_display);
return BadgeRender.format(side, _quantity, _filled, _current_badge_style, fmt);
});
_clear_phantom_price = new(() => {
@@ -199,7 +199,7 @@ namespace mbts.spark {
using var _ = _clear_phantom_price.defer_execution(true);
if (await _owner.model.order_gateway.update_order(
order, new_price, order.State.Quantity, null)) {
order, new_price, order.State.quantity(), null)) {
// wait 3 secs before clearing the phantom price
await Task.Delay(3000);
}
@@ -218,7 +218,7 @@ namespace mbts.spark {
hoverbackground = _mk_hover_bg_brush(dark, _darkbg, 0);
(_num_root_orders, _filled, _quantity) = _root_nodes
.Select(n => (1u, n.filled(), n.quantity()))
.Select(n => (1u, n.filled_quantity(), n.quantity()))
.Sum();
if (_num_root_orders == 1) {
@@ -262,6 +262,7 @@ namespace mbts.spark {
null,
_owner.model.order_gateway,
_owner.model.position_model,
_owner.model.sec_meta_store,
settings_man,
true,
global_filter: order_price_filter);
@@ -19,6 +19,7 @@ namespace mbts.spark {
using Spark.Api.Position;
using Spark.Core;
using Spark.Core.Data;
using Spark.ViewModel.Commands;
using System;
@@ -8,6 +8,7 @@ namespace mbts.spark {
using mbts.ui.shell;
using Spark.Core.Collections;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
@@ -18,15 +19,21 @@ namespace mbts.spark {
readonly IBus _bus;
readonly OrdersModel _model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
LadderVM? _value;
SecurityMD? _security_md;
HashSet<uint> _selected_order_tree = new();
public LadderVMContainer(IBus bus, OrdersModel model, IPositionModel position_model) {
public LadderVMContainer(
IBus bus,
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) {
_bus = bus;
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
}
public SecurityMD? security_md {
@@ -69,7 +76,12 @@ namespace mbts.spark {
}
var model = new LadderModel(
_security_md.Value, _model, _position_model, _model.mbo_service, order_filter);
_security_md.Value,
_model,
_position_model,
_sec_meta_store,
_model.mbo_service,
order_filter);
var settings_src = Observable.Return(LadderSettings.sanitize(LadderSettings.Default));
_value = LadderVM.create_readonly(_bus, model, settings_src);
@@ -88,7 +88,8 @@ namespace mbts.spark {
double _last_origin_price;
readonly MarketBreakLines _mkt_break_lines;
NativePriceSize _last_trade;
Func<NativePriceSize, string> _fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default());
Func<NativePriceSize, string> _fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
MarketSizeDisplay.get_default(), SecurityDataHelper.Defaults.quantity_display_settingsi);
Func<double, string> _fmt_mkt_quantity_impl = v => v.ToString();
int _old_tooltip_row = int.MaxValue;
NativePriceSize? _old_last_trade;
@@ -100,16 +101,16 @@ namespace mbts.spark {
static LadderGridHost() {
var knobs = config.Configuration.get<bts.config.LadderKnobs>();
_show_scrollbar = knobs.show_scrollbar;
_lighten_market_cells = knobs.lighten_market_cells;
_initial_row_count = (int)knobs.scrollable_tick_window_size;
_show_scrollbar = knobs.ShowScrollbar;
_lighten_market_cells = knobs.LightenMarketCells;
_initial_row_count = (int)knobs.ScrollableTickWindowSize;
// For market cell backgrounds, 0 means null. Note that the full
// range of colors can still be expressed, as zero is merely one of
// 2^24 possible representations of 'transparent.'
if (knobs.bid_market_cell_background != 0)
_bid_market_cell_background = knobs.bid_market_cell_background.argb_color();
if (knobs.ask_market_cell_background != 0)
_ask_market_cell_background = knobs.ask_market_cell_background.argb_color();
if (knobs.BidMarketCellBackground != 0)
_bid_market_cell_background = knobs.BidMarketCellBackground.argb_color();
if (knobs.AskMarketCellBackground != 0)
_ask_market_cell_background = knobs.AskMarketCellBackground.argb_color();
}
public LadderGridHost() {
@@ -395,6 +396,11 @@ namespace mbts.spark {
int _row_count => _price_list?.Count ?? 0;
bts.api.domain.TickDisplaySettingsImmutable _qty_display =>
_vm is null ?
SecurityDataHelper.Defaults.quantity_display_settingsi :
_vm.model.security_md.quantity_display;
public void drag_out_of_bounds() =>
_tactile_adorner?.drag_out_of_bounds();
@@ -1428,9 +1434,9 @@ namespace mbts.spark {
static GlyphContext glyph_context(LadderColumnSettings cs) =>
GlyphContext.create(cs.font_family, cs.font_weight);
var mkt_qty_display_divisor = _vm?.display_quantity_divisor ?? 1;
_fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(_settings.size_display, mkt_qty_display_divisor);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(mkt_qty_display_divisor);
_fmt_mkt_depth_item_impl = MDDisplayHelper.get_formatter_nps(
_settings.size_display, _qty_display);
_fmt_mkt_quantity_impl = MDDisplayHelper.get_value_formatter(_qty_display);
_set_columns();
_apply_column_visual_offset();
if (prev_row_height != _settings.row_height)
@@ -1508,7 +1514,8 @@ namespace mbts.spark {
// Assign the impl delegate to a local variable, just in case it is reassigned on another thread.
// This shouldn't happen, but better to avoid the potential null ref just in case it does. Expect the unexpected.
var impl = _fmt_mkt_depth_item_impl;
return impl is null ? MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default())?.ToString() ?? "Error" : impl(value);
impl ??= MDDisplayHelper.get_formatter_nps(MarketSizeDisplay.get_default(), _qty_display);
return impl(value);
}
// This is designed to be a redundant null check for _fmt_mkt_quantity_impl.
@@ -24,7 +24,7 @@ namespace mbts.spark {
public static IReadOnlyList<string> format(
Side side,
double quantity,
uint filled,
double filled,
LadderSettings.BadgeStyle style,
Func<double, string> fmt_value = null
) {
@@ -27,7 +27,7 @@ namespace mbts.spark {
static LadderView() {
var knobs = config.Configuration.get<bts.config.LadderKnobs>();
MimicTT = knobs.mimic_tt;
MimicTT = knobs.MimicTt;
}
public static bool MimicTT { get; }
@@ -1,166 +1,184 @@
using bts.api;
using bts.api.position;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.shell;
using Spark.Core.Reflection;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace bts.shell.manual_fills {
class ManualFillRow : DisposableViewModelBase, IEquatable<ManualFillRow> {
public const int _uncommitted_record_id = -1;
static readonly PropertyInfo[] _snapshot_props =
Array.ConvertAll(new[] {
nameof(security),
nameof(account),
nameof(user),
nameof(side),
nameof(size),
nameof(price)
}, typeof(ManualFillRow).GetProperty);
readonly Property<bool> _is_dirty;
readonly Property<EditableItemState> _editable_item_state;
readonly DelegateProperty<bool> _is_valid;
readonly DisplayQuantityMultiplier<double> _size = DisplayQuantityMultiplier.create_double();
readonly Func<SecurityImmutable?, double> _get_display_qty_divisor;
SecurityImmutable? _security;
AccountTuple? _account;
UserTuple? _user;
Side _side;
double _price;
bool _is_selected;
ManualFillData? _data;
IDisposable _committed_snapshot;
public ManualFillRow(ManualFillData data, Func<SecurityImmutable?, double> get_display_qty_divisor) {
_data = data;
_get_display_qty_divisor = get_display_qty_divisor ?? new Func<SecurityImmutable?, double>(sec => 1);
key = data.key;
_security = data.value.security;
_account = data.value.account;
_user = data.value.user;
_side = data.value.manual_fill.Side;
_size.actual_value = data.value.manual_fill.Quantity;
_size.conversion_data = new(
_get_display_qty_divisor(data.value.security), QuantityConversionOpType.DivideActual);
_price = data.value.manual_fill.Price;
if (placeholder_key.HasValue) {
_is_dirty = backing(nameof(is_dirty), false);
_editable_item_state = backing(nameof(editable_item_state), EditableItemState.Uncommitted);
_committed_snapshot = ReflectionHelper.create(this, _snapshot_props);
} else {
_is_dirty = backing(
nameof(is_dirty),
ReflectionHelper.dirty_monitor(this, out _committed_snapshot, _snapshot_props));
_editable_item_state = backing(nameof(editable_item_state), _is_dirty, ch => ch.newval ? EditableItemState.Modified : EditableItemState.None);
}
_is_valid = backing(nameof(is_valid), () => _validate(this));
_dispose = _size.connect_owner(this, nameof(size), nameof(display_size));
}
public event Action<bool> is_selected_changed;
// key/id
public ManualFillKey key { get; }
public long? placeholder_key => key.unpersisted;
public int record_id => key.persisted ?? _uncommitted_record_id;
public string record_id_display_text => key.persisted?.ToString();
// security/spec
public SecurityImmutable? security {
get => _security;
set {
if (_set(ref _security, value)) {
_size.conversion_data = new(
_get_display_qty_divisor(value), QuantityConversionOpType.DivideActual);
RaisePropertyChanged(nameof(spec));
}
}
}
public ContractSpecificationImmutable? spec => security.spec_or_default();
// account/user
public AccountTuple? account { get => _account; set => _set(ref _account, value); }
public UserTuple? user { get => _user; set => _set(ref _user, value); }
// side/size/price
public Side side { get => _side; set => _set(ref _side, value); }
public double size { get => _size.actual_value; set => _size.actual_value = value; }
public double display_size { get => _size.display_value; set => _size.display_value = value; }
public double price { get => _price; set => _set(ref _price, value); }
// is selected
public bool is_selected {
get => _is_selected;
set {
if (_set(ref _is_selected, value))
is_selected_changed?.Invoke(value);
}
}
// dirty/valid/editable-state
public bool is_dirty => _is_dirty.Value;
public bool is_valid => _is_valid.Value;
public EditableItemState editable_item_state => _editable_item_state.Value;
public ManualFillData data => _data ??
(_data = new ManualFillData(key, new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user))).Value;
public void revert() =>
_committed_snapshot.Dispose();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
public IObservable<bool> subscribe_is_selected() =>
Observable.Create<bool>(o => {
o.OnNext(is_selected);
is_selected_changed += o.OnNext;
return Disposable.Create(() => is_selected_changed -= o.OnNext);
});
public ManualFill to_man_fill() =>
new ManualFill {
RecordId = record_id,
AccountId = account?.id ?? 0,
AccountName = account?.name ?? string.Empty,
FillType = ManualFill.Types.FillType.AdminDay,
UserId = user?.id ?? 0,
Price = price,
Side = side,
Quantity = (uint)size,
SecurityKey = security?.Id ?? 0
};
public ManualFillTuple to_tuple() =>
new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user);
public bool Equals(ManualFillRow other) =>
data == other?.data;
public override bool Equals(object obj) => Equals(obj as ManualFillRow);
public override int GetHashCode() => record_id;
static bool _validate(ManualFillRow row) =>
row.security.HasValue &&
row.account.HasValue &&
row.user.HasValue &&
row.side != Side.Undefined &&
!double.IsNaN(row._price);
bool _set<T>(ref T backing, T value, [CallerMemberName] string prop_name = "") =>
_set(ref backing, value, EqualityComparer<T>.Default, prop_name);
bool _set<T>(ref T backing, T value, IEqualityComparer<T> comparer, [CallerMemberName] string prop_name = "") {
if (Set(ref backing, value, comparer, prop_name)) {
_is_valid.refresh();
_data = null;
return true;
}
return false;
}
}
}
using bts.api;
using bts.api.position;
using bts.utils;
using mbts;
using mbts.spark;
using mbts.ui;
using mbts.ui.shell;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
using System.Collections.Generic;
using System.Reactive.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
namespace bts.shell.manual_fills {
class ManualFillRow : DisposableViewModelBase, IEquatable<ManualFillRow> {
public const int _uncommitted_record_id = -1;
static readonly PropertyInfo[] _snapshot_props =
Array.ConvertAll(new[] {
nameof(security),
nameof(account),
nameof(user),
nameof(side),
nameof(quantity),
nameof(price)
}, typeof(ManualFillRow).GetProperty);
readonly ISecurityMetadataStore _sec_meta_store;
readonly Property<bool> _is_dirty;
readonly Property<EditableItemState> _editable_item_state;
readonly DelegateProperty<bool> _is_valid;
readonly DisplayQuantityMultiplier<double> _quantity = DisplayQuantityMultiplier.create_double();
readonly DelegateProperty<TickDisplaySettingsImmutable> _quantity_display;
SecurityImmutable? _security;
AccountTuple? _account;
UserTuple? _user;
Side _side;
double _price;
bool _is_selected;
ManualFillData? _data;
IDisposable _committed_snapshot;
public ManualFillRow(ManualFillData data, ISecurityMetadataStore sec_meta_store) {
_data = data;
_sec_meta_store = sec_meta_store;
key = data.key;
_security = data.value.security;
_account = data.value.account;
_user = data.value.user;
_side = data.value.manual_fill.Side;
_quantity.actual_value = data.value.manual_fill.Quantity;
_quantity_display = backing(
nameof(quantity_display),
() => {
var sec_meta = security.HasValue ? _sec_meta_store.get(security.Value) : null;
return sec_meta?.QuantityDisplay ??
SecurityDataHelper.Defaults.quantity_display_settingsi;
});
// TODO (prob): remove conversion_data. Replace get_qty_display_divisor delegates w/
// TickDisplaySettingsImmutable for qty, obtained via ISecurityMetadataStore.
_quantity.conversion_data = new(1, QuantityConversionOpType.DivideActual);
_price = data.value.manual_fill.Price;
if (placeholder_key.HasValue) {
_is_dirty = backing(nameof(is_dirty), false);
_editable_item_state = backing(nameof(editable_item_state), EditableItemState.Uncommitted);
_committed_snapshot = ReflectionHelper.create(this, _snapshot_props);
} else {
_is_dirty = backing(
nameof(is_dirty),
ReflectionHelper.dirty_monitor(this, out _committed_snapshot, _snapshot_props));
_editable_item_state = backing(nameof(editable_item_state), _is_dirty, ch => ch.newval ? EditableItemState.Modified : EditableItemState.None);
}
_is_valid = backing(nameof(is_valid), () => _validate(this));
_dispose = _quantity.connect_owner(this, nameof(quantity), nameof(display_quantity));
}
public event Action<bool> is_selected_changed;
// key/id
public ManualFillKey key { get; }
public long? placeholder_key => key.unpersisted;
public int record_id => key.persisted ?? _uncommitted_record_id;
public string record_id_display_text => key.persisted?.ToString();
// security/spec
public SecurityImmutable? security {
get => _security;
set {
if (_set(ref _security, value)) {
_quantity.conversion_data = new(1, QuantityConversionOpType.DivideActual);
_quantity_display.refresh();
RaisePropertyChanged(nameof(spec));
}
}
}
public ContractSpecificationImmutable? spec => security.spec_or_default();
// account/user
public AccountTuple? account { get => _account; set => _set(ref _account, value); }
public UserTuple? user { get => _user; set => _set(ref _user, value); }
// side/quantity/price
public Side side { get => _side; set => _set(ref _side, value); }
public double quantity { get => _quantity.actual_value; set => _quantity.actual_value = value; }
public double? display_quantity {
get => _quantity.display_value;
set => _quantity.display_value = value ?? double.NaN;
}
public TickDisplaySettingsImmutable quantity_display => _quantity_display.Value;
public double price { get => _price; set => _set(ref _price, value); }
// is selected
public bool is_selected {
get => _is_selected;
set {
if (_set(ref _is_selected, value))
is_selected_changed?.Invoke(value);
}
}
// dirty/valid/editable-state
public bool is_dirty => _is_dirty.Value;
public bool is_valid => _is_valid.Value;
public EditableItemState editable_item_state => _editable_item_state.Value;
public ManualFillData data => _data ??
(_data = new ManualFillData(key, new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user))).Value;
public void revert() =>
_committed_snapshot.Dispose();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
public IObservable<bool> subscribe_is_selected() =>
Observable.Create<bool>(o => {
o.OnNext(is_selected);
is_selected_changed += o.OnNext;
return Disposable.Create(() => is_selected_changed -= o.OnNext);
});
public ManualFill to_man_fill() =>
new ManualFill {
RecordId = record_id,
AccountId = account?.id ?? 0,
AccountName = account?.name ?? string.Empty,
FillType = ManualFill.Types.FillType.AdminDay,
UserId = user?.id ?? 0,
Price = price,
Side = side,
Quantity = quantity,
SecurityKey = security?.Id ?? 0
};
public ManualFillTuple to_tuple() =>
new ManualFillTuple(new ManualFillImmutable(to_man_fill()), security, account, user);
public bool Equals(ManualFillRow other) =>
data == other?.data;
public override bool Equals(object obj) => Equals(obj as ManualFillRow);
public override int GetHashCode() => record_id;
static bool _validate(ManualFillRow row) =>
row.security.HasValue &&
row.account.HasValue &&
row.user.HasValue &&
row.side != Side.Undefined &&
!double.IsNaN(row._price);
bool _set<T>(ref T backing, T value, [CallerMemberName] string prop_name = "") =>
_set(ref backing, value, EqualityComparer<T>.Default, prop_name);
bool _set<T>(ref T backing, T value, IEqualityComparer<T> comparer, [CallerMemberName] string prop_name = "") {
if (Set(ref backing, value, comparer, prop_name)) {
_is_valid.refresh();
_data = null;
return true;
}
return false;
}
}
}
@@ -71,7 +71,12 @@
<ComboBox Grid.Row="2" Grid.Column="2" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Accounts}}" SelectedItem="{Binding account}"/>
<ComboBox Grid.Row="2" Grid.Column="4" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Users}}" SelectedItem="{Binding user}"/>
<ComboBox Grid.Row="2" Grid.Column="6" ItemsSource="{DynamicResource ResourceKey={x:Static u:ResourceKeys.Sides}}" SelectedItem="{Binding side}" Width="48"/>
<c:TickUpDownUInt Grid.Row="2" Grid.Column="8" MinWidth="40" Value="{Binding display_size}"/>
<c:TickUpDownNullableDouble
Grid.Row="2"
Grid.Column="8"
MinWidth="40"
TickDisplaySettings="{Binding quantity_display}"
Value="{Binding display_quantity}" />
<usp:PriceEntryControl Grid.Row="2" Grid.Column="10" MinWidth="55" Value="{Binding price}" ContractSpec="{Binding spec}"/>
</Grid>
<c:DialogSkirt Grid.Row="1" Margin="0,6,0,0">
@@ -59,7 +59,7 @@
<ComboBox ItemsSource="{Binding DataContext.sides, RelativeSource={RelativeSource AncestorType=DataGrid}}" SelectedItem="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
</u:TemplateSelectorKeyValue>
<u:TemplateSelectorKeyValue Key="{x:Static Size, MemberType={u:Nested usp:ManualFillsImportConflictsView.ManualFillComponentNames}}">
<u:TemplateSelectorKeyValue Key="{x:Static Quantity, MemberType={u:Nested usp:ManualFillsImportConflictsView.ManualFillComponentNames}}">
<DataTemplate>
<c:TickUpDownUInt Value="{Binding value, UpdateSourceTrigger=PropertyChanged}"/>
</DataTemplate>
@@ -13,7 +13,7 @@ namespace mbts.ui.spark {
Account,
User,
Side,
Size,
Quantity,
Price
}
@@ -23,7 +23,7 @@ namespace mbts.ui.spark {
Account = ManualFillComponent.Account.ToString(),
User = ManualFillComponent.User.ToString(),
Side = ManualFillComponent.Side.ToString(),
Size = ManualFillComponent.Size.ToString(),
Quantity = ManualFillComponent.Quantity.ToString(),
Price = ManualFillComponent.Price.ToString();
}
}
@@ -5,6 +5,8 @@ using bts.collections;
using mbts.spark;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -80,13 +82,22 @@ namespace bts.shell.manual_fills {
class ManualFillsModel {
readonly OrdersModel _model;
public ManualFillsModel(OrdersModel model)
: this(model, model.on_manual_fill_tuples,
model.factory.subscribe_accounts().Select(d => MappedDictionary.create(d, (k, v) => new AccountTuple(k, v))).Table(u => u.id),
model.factory.subscribe_users().Select(d => MappedDictionary.create(d, (k, v) => new UserTuple(k, v))).Table(a => a.id)) { }
public ManualFillsModel(OrdersModel model, ISecurityMetadataStore sec_meta_store)
: this(
model,
sec_meta_store,
model.on_manual_fill_tuples,
model.factory.subscribe_accounts().Select(d => MappedDictionary.create(d, (k, v) => new AccountTuple(k, v))).Table(u => u.id),
model.factory.subscribe_users().Select(d => MappedDictionary.create(d, (k, v) => new UserTuple(k, v))).Table(a => a.id)) { }
public ManualFillsModel(OrdersModel model, IObservable<TableUpdate<ManualFillTuple, int>> manual_fills, IObservable<TableUpdate<AccountTuple, uint>> accounts, IObservable<TableUpdate<UserTuple, uint>> users) {
public ManualFillsModel(
OrdersModel model,
ISecurityMetadataStore sec_meta_store,
IObservable<TableUpdate<ManualFillTuple, int>> manual_fills,
IObservable<TableUpdate<AccountTuple, uint>> accounts,
IObservable<TableUpdate<UserTuple, uint>> users) {
_model = model;
this.sec_meta_store = sec_meta_store;
this.manual_fills = manual_fills.SelectKeyValue(
mft => new ManualFillData(new ManualFillKey(mft.manual_fill.RecordId), mft),
ManualFillData.key_fn);
@@ -94,6 +105,7 @@ namespace bts.shell.manual_fills {
this.users = users;
}
public ISecurityMetadataStore sec_meta_store { get; }
public IObservable<TableUpdate<ManualFillData, ManualFillKey>> manual_fills { get; }
public IObservable<TableUpdate<AccountTuple, uint>> accounts { get; }
public IObservable<TableUpdate<UserTuple, uint>> users { get; }
@@ -39,7 +39,7 @@ namespace bts.shell.manual_fills {
case ManualFillComponent.Account: return (mf, val) => mf.AccountId = ConvertUtils.try_convert<AccountTuple?>(val)?.id ?? 0;
case ManualFillComponent.User: return (mf, val) => mf.UserId = ConvertUtils.try_convert<UserTuple?>(val)?.id ?? 0;
case ManualFillComponent.Side: return (mf, val) => mf.Side = ConvertUtils.try_convert<Side>(val, Side.Undefined);
case ManualFillComponent.Size: return (mf, val) => mf.Quantity = ConvertUtils.try_convert<uint>(val);
case ManualFillComponent.Quantity: return (mf, val) => mf.Quantity = ConvertUtils.try_convert<uint>(val);
case ManualFillComponent.Price: return (mf, val) => mf.Price = ConvertUtils.try_convert(val, double.NaN);
default: throw new NotImplementedException();
}
@@ -60,7 +60,7 @@ namespace bts.shell.manual_fills {
add_missing(ManualFillComponent.User, pmf.user.text, pmf);
}
if (!pmf.quantity.success) {
add_missing(ManualFillComponent.Size, pmf.quantity.text, pmf);
add_missing(ManualFillComponent.Quantity, pmf.quantity.text, pmf);
}
if (!pmf.side.success) {
add_missing(ManualFillComponent.Side, pmf.side.text, pmf);
@@ -12,6 +12,7 @@ using mbts.ui.shell;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.ViewModel.Commands;
using System;
@@ -47,8 +48,9 @@ namespace bts.shell.manual_fills {
long _placeholder_id_counter = long.MinValue;
IDisposable _import_fills_hooks;
public static ManualFillsVM create(IBus bus, OrdersModel model) =>
new ManualFillsVM(bus, new ManualFillsModel(model));
public static ManualFillsVM create(
IBus bus, OrdersModel model, ISecurityMetadataStore sec_meta_store) =>
new(bus, new ManualFillsModel(model, sec_meta_store));
public ManualFillsVM(IBus bus, ManualFillsModel model) {
_bus = bus;
@@ -73,7 +75,7 @@ namespace bts.shell.manual_fills {
RXCollection.connect(_persisted_rows,
_model.manual_fills.OnDispatcher(),
Observable.Return(Comparer<ManualFillData>.Create((a, b) => a.key.CompareTo(b.key))),
mfd => new ManualFillRow(mfd, model.get_display_qty_divisor),
mfd => new ManualFillRow(mfd, model.sec_meta_store),
mfr => mfr.data),
_bus.subscribe(SparkTags.SecuritiesTag).OnDispatcher().Subscribe(m => {
security_map = new FilteredDictionary<uint, SecurityMD>(
@@ -137,7 +139,7 @@ namespace bts.shell.manual_fills {
new ManualFillTuple(new ManualFillImmutable(new ManualFill {
Side = Side.Buy
}), null, accounts.FirstOrDefault(), users.FirstOrDefault())),
_model.get_display_qty_divisor);
_model.sec_meta_store);
void _add_fill(ManualFillRow new_row) =>
_placeholder_rows.InsertSorted((new_row ?? (new_row = row_factory())).placeholder_key.HasValue ?
@@ -214,7 +216,7 @@ namespace bts.shell.manual_fills {
object get_error_value(ManualFillComponent component) {
switch (component) {
case ManualFillComponent.Price: return double.NaN;
case ManualFillComponent.Size: return 0;
case ManualFillComponent.Quantity: return 0;
default: return null;
}
}
@@ -232,7 +234,7 @@ namespace bts.shell.manual_fills {
pmf.result.SecurityKey != 0 && security_map.TryGetValue(pmf.result.SecurityKey, out var smd) ? smd.security : (SecurityImmutable?)null,
accounts.FirstOrDefault(a => a?.id == pmf.result.AccountId),
users.FirstOrDefault(a => a?.id == pmf.result.UserId)));
return new ManualFillRow(data, _model.get_display_qty_divisor);
return new(data, _model.sec_meta_store);
}
}
} catch (Exception ex) {
@@ -208,16 +208,26 @@
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
<!--Size-->
<DataGridTemplateColumn c:DataGridEx.CellKey="{x:Static Size, MemberType={u:Nested usp:ManualFillsView.Columns}}" Header="Qty" SortMemberPath="side">
<!--Quantity-->
<DataGridTemplateColumn c:DataGridEx.CellKey="{x:Static Quantity, MemberType={u:Nested usp:ManualFillsView.Columns}}" Header="Qty" SortMemberPath="side">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding display_size}" VerticalAlignment="Center"/>
<TextBlock VerticalAlignment="Center">
<TextBlock.Text>
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="display_quantity" />
<Binding Path="quantity_display" />
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<c:TickUpDownUInt MinWidth="40" Value="{Binding display_size, UpdateSourceTrigger=PropertyChanged}"/>
<c:TickUpDownNullableDouble
MinWidth="40"
TickDisplaySettings="{Binding quantity_display}"
Value="{Binding display_quantity, UpdateSourceTrigger=PropertyChanged}" />
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
@@ -28,7 +28,7 @@ namespace mbts.ui.spark {
Account,
User,
Side,
Size,
Quantity,
Price
}
@@ -9,6 +9,8 @@ using mbts.ui;
using mbts.ui.controls;
using mbts.ui.spark;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
@@ -27,11 +29,18 @@ namespace bts.shell {
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly ManualFillsConfig _manual_fills_conf = ManualFillsConfig.read();
public ManualFillsWindowFactory(IShellModule owner, IBus bus, OrdersModel orders_model) : base(owner, window_name) {
public ManualFillsWindowFactory(
IShellModule owner,
IBus bus,
OrdersModel orders_model,
ISecurityMetadataStore sec_meta_store)
: base(owner, window_name) {
_bus = bus;
_orders_model = orders_model;
_sec_meta_store = sec_meta_store;
_dispose = bus.subscribe(SparkTags.ShowManualFillsTag).Subscribe(open_window);
//
async void open_window(ManualFillsSettings state) =>
@@ -43,7 +52,7 @@ namespace bts.shell {
window_type, window_name, _bus, this, Icons.DataEdit, _manual_fills_conf.thread_id, thread_init, _window_min_width));
//
(UIElement, IEnumerable<SparkCommand>, Func<ManualFillsSettings>, IDisposable) thread_init() {
var vm = ManualFillsVM.create(_bus, _orders_model);
var vm = ManualFillsVM.create(_bus, _orders_model, _sec_meta_store);
var view = new ManualFillsView { DataContext = vm };
view.data_grid.Sorting += on_sorting;
IReadOnlyList<SortingCriteria> last_sorting_criteria = Array.Empty<SortingCriteria>();
@@ -121,8 +130,8 @@ namespace bts.shell {
}
public static ManualFillsConfig read() => new ManualFillsConfig(
mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().manual_fills ? window_type : null,
mbts.config.Configuration.get<bts.config.ManualFillsOptions>().modal_transactions);
mbts.config.Configuration.get<bts.config.MultiThreadedWindows>().ManualFills ? window_type : null,
mbts.config.Configuration.get<bts.config.ManualFillsOptions>().ModalTransactions);
}
static class CommandGroups {
File diff suppressed because it is too large. Load diff
@@ -30,7 +30,7 @@ namespace mbts.spark {
readonly OrderBookVM _owner;
Color? _root_algo_badge_color_backing;
Brush _badge_fill, _root_algo_badge_fill;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _detach_command, _attach_command, _update_command, _modify_order_quantity_andor_price, _revert_prospective_order_quantity_andor_price;
IRaiseCanExecuteChangedCommand _show_order_modify_cmd, _toggle_expanded_cmd, _cancel_cmd, _detach_command, _attach_command, _update_command, _modify_order_cmd, _revert_order_cmd;
bool _is_parent, _is_expanded, _is_selected, _is_attachable, _is_detachable;
int _depth_level;
TickDisplaySettingsImmutable _quantity_display_settings =
@@ -115,9 +115,13 @@ namespace mbts.spark {
});
}
}
public uint filled_quantity => order.filled();
public double filled_quantity => order.filled_quantity();
public string filled_quantity_text =>
quantity_display_settings.to_tick_display_settings().format(filled_quantity);
// TODO: get rid of 'display_filled_quantity/_text' (it was added before we had a proper
// SecurityMetadata config structure, with entries keyed by SecurityCriteria)
public double display_filled_quantity =>
((double)filled_quantity).safe_divide(_display_qty_divisor);
filled_quantity.safe_divide(_display_qty_divisor);
public string display_filled_quantity_text =>
quantity_display_settings.to_tick_display_settings().format(display_filled_quantity);
public string last_msg => order.last_msg();
@@ -128,7 +132,8 @@ namespace mbts.spark {
public bool is_non_terminal => order.is_non_terminal();
public bool is_attachable { get => _is_attachable; set => SetVisual(ref _is_attachable, value); }
public bool is_detachable { get => _is_detachable; set => SetVisual(ref _is_detachable, value); }
public string filled_status_desc => order.filled_status_description(security.spec_or_default(), _display_qty_divisor);
public string filled_status_desc =>
order.filled_status_description(security.spec_or_default(), _quantity_display_settings);
// Root Algo
public CustomOrderDefinition.CustomOneofCase root_algo_order_type => order_tuple.root.algo.value.CustomCase;
@@ -168,6 +173,7 @@ namespace mbts.spark {
set {
if (Set(ref _prospective_price, value)) {
RaisePropertyChanged(nameof(is_price_dirty));
_revert_order_cmd?.RaiseCanExecuteChanged();
}
}
}
@@ -184,37 +190,35 @@ namespace mbts.spark {
public ICommand cancel_command => _cancel_cmd ??
(_cancel_cmd = new DelegateCommand(() => _owner.cancel_order(this), () => status == OrderStatus.Working || status == OrderStatus.Disconnected));
public ICommand modify_order_quantity_andor_price {
public ICommand modify_order_cmd {
get {
if (_modify_order_quantity_andor_price == null) {
_modify_order_quantity_andor_price = new DelegateCommand(execute, can_execute);
invalidated += _modify_order_quantity_andor_price.RaiseCanExecuteChanged;
// impl
void execute() {
if (is_qty_dirty && is_price_dirty) {
_owner.modify_order_price_and_quantity(this, prospective_price, prospective_quantity);
} else if (is_qty_dirty) {
_owner.modify_order_quantity(this, prospective_quantity);
} else if (is_price_dirty) {
_owner.modify_order_price(this, this.prospective_price);
}
_unselect_me();
}
bool can_execute() => status == OrderStatus.Working && (is_price_dirty || is_qty_dirty);
if (_modify_order_cmd is not null) {
return _modify_order_cmd;
}
return _modify_order_quantity_andor_price;
_modify_order_cmd = new Command(execute, can_execute);
invalidated += _modify_order_cmd.RaiseCanExecuteChanged;
return _modify_order_cmd;
void execute() {
double? new_price = is_price_dirty ? prospective_price : null;
double? new_qty = is_qty_dirty ? prospective_quantity : null;
_owner.modify_order(this, new_price, new_qty);
_unselect_me();
}
bool can_execute() =>
status == OrderStatus.Working && (is_price_dirty || is_qty_dirty);
}
}
public ICommand revert_prospective_order_quantity_andor_price => _revert_prospective_order_quantity_andor_price ??
(_revert_prospective_order_quantity_andor_price = new DelegateCommand(
public ICommand revert_order_cmd =>
_revert_order_cmd ??= new Command(
() => {
prospective_price = price;
prospective_quantity = quantity;
},
() => this.status == OrderStatus.Working && (is_price_dirty || is_qty_dirty)
)
);
() => status == OrderStatus.Working && (is_price_dirty || is_qty_dirty));
public ICommand detach_command => _detach_command ??
(_detach_command = new DelegateCommand(() => {
@@ -265,8 +269,11 @@ namespace mbts.spark {
_prospective_qty_translator_backing.conversion_data = new(
_display_qty_divisor, QuantityConversionOpType.DivideActual);
_prospective_qty_translator_backing.actual_value = quantity;
_prospective_qty_translator.value_changed += () =>
_prospective_qty_translator.value_changed += () => {
RaisePropertyChanged(nameof(is_qty_dirty));
_modify_order_cmd?.RaiseCanExecuteChanged();
_revert_order_cmd?.RaiseCanExecuteChanged();
};
} else {
_sync_display_qty_if_dirty();
}
@@ -488,7 +495,7 @@ namespace mbts.spark {
dirty |= Columns.Security;
if (oldval.order.order.last_change() != newval.order.order.last_change())
dirty |= Columns.LastChange;
if (oldval.order.order.filled() != newval.order.order.filled())
if (oldval.order.order.filled_quantity() != newval.order.order.filled_quantity())
dirty |= Columns.Filled;
if (oldval.order.order.last_price() != newval.order.order.last_price())
dirty |= Columns.LastPrice;
File diff suppressed because it is too large. Load diff
@@ -17,6 +17,8 @@ using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -38,6 +40,7 @@ namespace mbts.spark {
List<IDisposable> _thread_init_resources;
OrderBookStartupData _state;
OrdersModel _model;
ISecurityMetadataStore _sec_meta_store;
OrderBookVM _vm;
OrderBookView _view;
OrderBookWindowFactory _factory;
@@ -47,6 +50,7 @@ namespace mbts.spark {
public OrderBookWindow(
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
OrderBookWindowFactory factory,
IBus bus,
INotificationService notification_service,
@@ -57,12 +61,13 @@ namespace mbts.spark {
: base(_default_title, bus, factory, SparkCommands.ShowOrders.icon) {
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_factory = factory;
_notification_service = notification_service;
_state = state;
_settings_manager = settings_manager;
_can_edit_specific_algo_params = can_edit_specific_algo_params;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().order_book ? "OrderBook" : null;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().OrderBook ? "OrderBook" : null;
_dispose = Disposable.Create(() => {
Disposable.dispose(_thread_init_resources);
Disposable.dispose(ref _attachment_exit_sub);
@@ -95,7 +100,7 @@ namespace mbts.spark {
_menu_display_vm = new SparkMenuDisplayVM();
if (_state != null)
_menu_display_vm.load_from(_state.menu_display);
_vm = new(_bus, _notification_service, _model, _position_model, _settings_manager);
_vm = new(_bus, _notification_service, _model, _position_model, _sec_meta_store, _settings_manager);
_vm.load_from(_state);
_view = new OrderBookView(_vm);
_vm.SubscribeDisposed(
@@ -8,6 +8,8 @@ using mbts.persist;
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using System;
using System.Reactive.Linq;
using System.Threading.Tasks;
@@ -19,6 +21,7 @@ namespace bts.shell {
readonly INotificationServiceDataCache _notification_service_data_cache;
readonly OrdersModel _model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly UserSettingsHub _settings_hub;
readonly OrderBookConfig _config;
@@ -29,14 +32,16 @@ namespace bts.shell {
INotificationServiceDataCache notification_service_data_cache,
OrdersModel model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
UserSettingsHub settings_hub) : base(owner, "SparkOrderBookWindow") {
var raw_config = Configuration.get<bts.config.OrderBookOptions>();
_config = new OrderBookConfig(raw_config.can_edit_specific_algo_params);
_config = new OrderBookConfig(raw_config.CanEditSpecificAlgoParams);
_bus = bus;
_notification_service = notification_service;
_notification_service_data_cache = notification_service_data_cache;
_model = model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_settings_hub = settings_hub;
_dispose = bus.subscribe(SparkTags.ShowOrderBookTag).OnDispatcher().Subscribe(show);
}
@@ -45,8 +50,17 @@ namespace bts.shell {
var settings_manager = new WindowSettingsManager<OrderBookGridSettings>(_settings_hub, state.grid_settings_wrapper(),
us => us.order_book_grid ?? OrderBookStartupData.DefaultGrid,
(us, s) => us.with(order_book_grid: s));
var w = new OrderBookWindow(_model, _position_model, this, _bus, _notification_service, state,
SparkCommands.ShowOrders.icon, settings_manager.as_non_shared(), _config.can_edit_specific_algo_params);
var w = new OrderBookWindow(
_model,
_position_model,
_sec_meta_store,
this,
_bus,
_notification_service,
state,
SparkCommands.ShowOrders.icon,
settings_manager.as_non_shared(),
_config.can_edit_specific_algo_params);
return Task.FromResult<IShellWindow>(w);
}
@@ -0,0 +1,273 @@
namespace mbts.spark {
using bts;
using bts.api;
using bts.api.orderman;
using bts.collections;
using bts.utils;
using mbts.spark.utilities;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.shell;
using mbts.ui.spark;
using mbts.ui.utility;
using mbts.utils;
using Spark.ViewModel.Commands;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using System.Windows.Input;
using CompositeDisposable = System.Reactive.Disposables.CompositeDisposable;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
class OrderParamsVM : DisposableViewModelBase {
readonly OrdersModel _model;
readonly OrderParamsAggregator _selected_params_mon;
readonly SelectorProperty<AccountTuple, AccountTuple?> _accounts;
readonly Property<bool> _is_dirty;
readonly Func<SecurityImmutable?, double> _get_display_qty_divisor;
IRaiseCanExecuteChangedCommand _payup_bid_cmd;
IRaiseCanExecuteChangedCommand _payup_ask_cmd;
IAlgoParamVM<double> _price_param;
AlgoParamVM<double?> _quantity_param;
AlgoParamPermissions _price_permissions =
AlgoParamPermissions.ReadOnly | AlgoParamPermissions.Write;
AlgoParamPermissions _quantity_permissions =
AlgoParamPermissions.ReadOnly | AlgoParamPermissions.Write;
SecurityMD? _security_md;
public OrderParamsVM(
OrdersModel model,
OrderParamsAggregator selected_params_mon,
AlgoEditingPermissions init_permissions,
Func<SecurityImmutable?, double> get_display_qty_divisor
) {
_model = model;
_selected_params_mon = selected_params_mon;
_get_display_qty_divisor = get_display_qty_divisor;
algo_vm = AlgoDefinitionVM.create(
model,
AlgoData.create_unpersisted(
OrderDataHelper.Defaults.CustomOrderDefinitionImmutable(
CustomOrderDefinition.CustomOneofCase.Iceberg),
CustomOrderDefinition.CustomOneofCase.Iceberg.display_name()),
editing_permissions: init_permissions);
// accounts
_accounts = new SelectorProperty<AccountTuple, AccountTuple?>(this,
nameof(selected_account),
a => new AccountTuple?(a),
() => accounts.Cast<AccountTuple?>().FirstOrDefault(),
EqualityComparer<AccountTuple?>.Default,
Array.Empty<PropertyValidation<AccountTuple?>>());
attach(
_accounts,
_model.factory.subscribe_account_tuples(),
_model.admin_model.on_account_tuples
.Where(ts => ts.Count > 0)
.Select(ts => new InlineUserProperty<AccountTuple>(ts[0])).Take(1));
bbo = new BBOVM { security_md = security_md };
_payup_bid_cmd = new Command<int>(payup_bid, payup_can_execute);
_payup_ask_cmd = new Command<int>(payup_ask, payup_can_execute);
var algo_param_rows = new ObservableAggregateCollection<AlgoParamRowVM>();
var appended_param_rows = new ObservableAppendCollection<AlgoParamRowVM>(algo_param_rows);
param_rows = appended_param_rows;
var dirty_params_mon = new ReactiveThresholdMonitor<AlgoParamRowVM>(r => r.param.subscribe_is_dirty());
_is_dirty = backing(nameof(is_dirty), dirty_params_mon);
_dispose = new CompositeDisposable(bbo, algo_vm,
AlgoParamRowsHelper.connect(algo_vm, algo_param_rows, false),
algo_vm.observe_algo_root().Subscribe(on_algo_root_changed),
ObservableAutoWrapper.connect_item_hooks(param_rows, dirty_params_mon.join),
algo_vm);
// payup methods
void payup_bid(int ticks) => payup(bbo.bid, -ticks);
void payup_ask(int ticks) => payup(bbo.ask, ticks);
void payup(double from_price, int ticks) {
if (spec.HasValue && _selected_params_mon.all_active)
price = spec.Value.tickup(from_price, ticks);
}
bool payup_can_execute(int ticks) => spec.HasValue && _selected_params_mon.all_active;
void on_algo_root_changed(IAlgoVM root) {
appended_param_rows.clear_front();
if (root is null) {
_price_param = null;
_quantity_param = null;
return;
}
_quantity_param = new(
"size", "Size", _selected_params_mon.size, EqualityComparer<double?>.Default,
to_display_value: v => v.HasValue ? v.Value / display_quantity_divisor : v,
from_display_value: v => v.HasValue ? v.Value * display_quantity_divisor : v
) {
permissions = _quantity_permissions & _param_permissions,
tick_up_cmd = new Command(() => tick_qty(1)),
tick_down_cmd = new Command(() => tick_qty(-1))
};
_quantity_param.has_value = is_qty_valid(_quantity_param.value);
_quantity_param.value_changed += on_qty_changed;
var price_param = new AlgoParamVM<double>(
"price",
"Price",
_selected_params_mon.price,
spec?.tick_equality_comparer() ?? MathUtils.epsilon_eq_comparer) {
permissions = _price_permissions & _param_permissions
};
_price_param = price_param;
_price_param.value_changed += on_price_changed;
appended_param_rows.insert_front(
new(root, _quantity_param, null, AlgoParamTemplateKeys.Size));
appended_param_rows.insert_front(
new(root, _price_param, null, AlgoParamTemplateKeys.Price));
static bool is_qty_valid(double? qty) =>
qty?.is_real_non_negative() ?? false;
void on_qty_changed(double? oldval, double? newval) =>
_quantity_param.has_value = is_qty_valid(newval);
void tick_qty(int count) {
if (_quantity_param is null
|| !_quantity_param.has_value
|| !(quantity_display?.HasTickFactors ?? false)) {
return;
}
_quantity_param.value = quantity_display.Value.tick(
_quantity_param.value ?? 0D, count);
}
void on_price_changed(double oldval, double newval) =>
price_param.has_value = !double.IsNaN(newval);
}
}
public bool is_dirty => _is_dirty.Value;
public AlgoParamPermissions price_permissions {
get => _price_permissions;
set => _assign_param_permissions(_price_param, ref _price_permissions, value);
}
public AlgoParamPermissions quantity_permissions {
get => _quantity_permissions;
set => _assign_param_permissions(_quantity_param, ref _quantity_permissions, value);
}
public ReadOnlyObservableCollection<AccountTuple> accounts => _accounts.items;
public AccountTuple? selected_account {
get => _accounts.selected_item;
set => _accounts.selected_item = value;
}
public SecurityImmutable? security => _selected_params_mon.security;
/// <see cref="security_md"/> should be synced with the root of the selected row(s),
public SecurityMD? security_md {
get => _security_md;
set {
if (_security_md == value) {
return;
}
using var _ = detect_property_changes(
nameof(spec),
nameof(display_quantity_divisor),
nameof(quantity_display),
nameof(unit_quantity));
_security_md = value;
bbo.security_md = value;
_payup_bid_cmd.RaiseCanExecuteChanged();
_payup_ask_cmd.RaiseCanExecuteChanged();
_quantity_param?.refresh_display_value();
RaisePropertyChanged(nameof(security_md), nameof(security));
}
}
public ContractSpecificationImmutable? spec => security?.ContractSpec;
public TickDisplaySettingsImmutable? quantity_display =>
security_md?.quantity_display;
public double price {
get => _price_param?.value ?? double.NaN;
set {
if (_price_param != null)
_price_param.value = value;
}
}
public double? quantity {
get => _quantity_param?.value;
set {
if (_quantity_param != null)
_quantity_param.value = value;
}
}
public double unit_quantity =>
(security?.ContractSpec)?.tick_factors()?.tick_unit_frac() ?? 1;
public AlgoDefinitionVM algo_vm { get; }
public IReadOnlyObservableCollection<AlgoParamRowVM> param_rows { get; }
public BBOVM bbo { get; }
public double display_quantity_divisor => _get_display_qty_divisor(security);
public ICommand send_order { get; }
public ICommand payup_bid_cmd => _payup_bid_cmd;
public ICommand payup_ask_cmd => _payup_ask_cmd;
AlgoParamPermissions _param_permissions =>
_selected_params_mon.all_active ?
AlgoParamPermissions.ReadWrite : AlgoParamPermissions.ReadOnly;
AlgoEditingPermissions _algo_permissions =>
_selected_params_mon.all_active ?
AlgoEditingPermissions.AllowEditValues : AlgoEditingPermissions.None;
public void on_common_price(double price) {
if (_price_param is null) {
return;
}
_price_param.value = price;
_price_param.mark_committed();
}
public void on_common_size(double? size) {
if (_quantity_param is null) {
return;
}
_quantity_param.value = size;
_quantity_param.mark_committed();
}
public void on_all_active_changed() {
algo_vm.editing_permissions_mask = _algo_permissions;
if (!_selected_params_mon.all_active)
revert();
}
public void revert() =>
param_rows.revert_all();
public IObservable<bool> subscribe_is_dirty() =>
_is_dirty.observe_current(true);
void _assign_param_permissions<T>(
IAlgoParamVM<T> param,
ref AlgoParamPermissions permissions_backing,
AlgoParamPermissions permissions) {
if (permissions_backing == permissions) {
return;
}
permissions_backing = permissions;
if (param is not null) {
param.permissions = permissions & _param_permissions;
}
}
}
}
@@ -42,7 +42,7 @@ namespace bts.shell.orderbook {
[ProtoMember(11)]
public DoubleMinMaxState price;
[ProtoMember(12)]
public UIntMinMaxState qty_filled;
public DoubleMinMaxState qty_filled;
[ProtoMember(13)]
public DoubleMinMaxState avg_price;
[ProtoMember(14)]
@@ -148,7 +148,7 @@ namespace bts.shell.orderbook {
// numeric
pb.add_numeric(fs.qty, o => o.order.order.quantity());
pb.add_price(fs.price, o => o.order.order.ui_price(), o => o.order.security);
pb.add_numeric(fs.qty_filled, o => o.order.order.filled());
pb.add_numeric(fs.qty_filled, o => o.order.order.filled_quantity());
pb.add_numeric(fs.avg_price, o => o.order.order.avg_price());
pb.add_numeric(fs.last_price, o => o.order.order.last_price());
pb.add_numeric(fs.piq, o => o.order.piq ?? uint.MaxValue);
@@ -8,6 +8,8 @@ using mbts.ui.controls;
using mbts.ui.settings;
using mbts.ui.utility;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
@@ -40,6 +42,7 @@ namespace bts.shell.orderbook {
IBus bus,
INotificationService notification_service,
OrdersModel model,
ISecurityMetadataStore sec_meta_store,
IEnumerable<OrderBookRowVM> rows,
ObservableCollection<DIYGrid.ColumnBase> columns) {
core_manager = new GridSettingsManager<OrderBookRowVM, OrderSecurity, OrderRecordTuplePredicate, OrderBookGridSettings>(
@@ -58,8 +61,8 @@ namespace bts.shell.orderbook {
return pvm;
},
(gen, anims) => new OrderBookGridSettings(gen, anims.empty_if_null().Select(a => new OrderRecordTuplePredicateAnimations(a.predicate_data, a.cell_animations, a.row_animations, a.sound_notifications))) { algo_tree_display_mode = _algo_tree_display_mode },
p => p.create_predicate(notification_service.data_cache),
p => p.create_notification_predicate(notification_service.data_cache),
p => p.create_predicate(notification_service.data_cache, sec_meta_store),
p => p.create_notification_predicate(notification_service.data_cache, sec_meta_store),
notification_service == null ? new Func<IPredicate<OrderSecurity>, SoundNotification, IDisposable>((p, sn) => Disposable.empty) : notification_service.link_to_order,
notification_service == null ? new Func<INotificationPredicate<OrderSecurity>, IDisposable>(t => Disposable.empty) : notification_service.link_to_order,
hard_column_flags);
@@ -70,7 +70,7 @@ namespace mbts.spark {
var bg_binding = new MultiBinding();
bg_binding.Bindings.Add(new Binding(nameof(OrderBookRowVM.status)));
bg_binding.Bindings.Add(new Binding(nameof(ListBoxItem.IsSelected)) { RelativeSource = new RelativeSource(RelativeSourceMode.FindAncestor, typeof(ListBoxItem), 1) });
double overlay_opacity = config.Configuration.get<bts.config.OrderBookOptions>().status_color_opacity_when_selected;
double overlay_opacity = config.Configuration.get<bts.config.OrderBookOptions>().StatusColorOpacityWhenSelected;
if (overlay_opacity > 0.1 && overlay_opacity < 0.9) {
bg_binding.Converter = ValueConverter.create<OrderStatus, bool, Brush>((status, is_selected) => {
var color = _status_color(status);
@@ -22,8 +22,6 @@ using System.Windows.Data;
using System.Windows.Input;
using System.Windows.Media;
using OrderParamsVM = mbts.spark.OrderBookVM.OrderParamsVM;
namespace mbts.spark {
internal partial class OrderBookView : UserControl {
public const double
@@ -186,7 +186,7 @@ namespace bts.shell.pnl {
public double display_top_volume =>
data.Count > 0 ?
data.Values.First().Values.Sum(o => o.qty_conversion
.convert_numeric_type<int>()
.convert_numeric_type<double>()
.to_display(o.order.working_quantity())) :
0;
@@ -195,7 +195,7 @@ namespace bts.shell.pnl {
public WorkingOrderSideData Add(
OrderRecordImmutable order_record, QuantityConversionData<double> qty_conversion) {
int working_qty = order_record.working_quantity();
var working_qty = order_record.working_quantity();
if (working_qty <= 0)
throw new ArgumentException(nameof(working_qty));
uint order = order_record.Key;
@@ -19,6 +19,8 @@ namespace bts.shell {
using mbts.ui.spark;
using mbts.ui.utility;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
@@ -44,14 +46,22 @@ namespace bts.shell {
readonly PNLConfig _pnl_conf;
readonly IShellWindowThreadIDProvider _thread_id_provider;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
public PNLWindowFactory(IShellModule owner, IBus bus, UserSettingsHub settings_hub, OrdersModel orders_model, IPositionModel position_model) : base(owner, _window_type) {
public PNLWindowFactory(
IShellModule owner,
IBus bus,
UserSettingsHub settings_hub,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store) : base(owner, _window_type) {
_bus = bus;
_orders_model = orders_model;
_settings_hub = settings_hub;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_pnl_conf = new PNLConfig(Configuration.get<bts.config.PNLOptions>());
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().pnl);
_thread_id_provider = ShellWindowThreadIDFactory.create(_window_type, Configuration.get<bts.config.MultiThreadedWindows>().Pnl);
_dispose = bus.subscribe(SparkTags.ShowPNLTag).OnDispatcher().Subscribe(_show);
}
@@ -85,7 +95,7 @@ namespace bts.shell {
menu_display_vm.load_from(init_settings.menu_display);
on_parent_view_created_impl = menu_display_vm.safe_bind_to_view;
var vm = new PNLVM(
_bus, _orders_model, _position_model, init_settings);
_bus, _orders_model, _position_model, _sec_meta_store, init_settings);
var content = new PNLView {
DataContext = vm
};
@@ -298,8 +308,8 @@ namespace bts.shell {
show_pause_resume;
public PNLConfig(bts.config.PNLOptions options) {
enable_animations = options.enable_animations;
show_pause_resume = options.show_pause_resume;
enable_animations = options.EnableAnimations;
show_pause_resume = options.ShowPauseResume;
}
}
@@ -18,6 +18,7 @@
using mbts.ui.utility;
using mbts.utils;
using Spark.Core.Data;
using Spark.Core.Reflection;
using System;
@@ -48,6 +49,7 @@
readonly IBus _bus;
readonly OrdersModel _orders_model;
readonly IPositionModel _position_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IObservableCollectionAddRemoveOnly<PNLRowVM> _selected_rows = new ObservableSortedCollection<PNLRowVM>(PNLRowVM.key_comparer);
/// treat <see cref="_rows_data_wrapper"/> and <see cref="_rows_key_wrapper"/>
/// as IReadOnlyLists - don't call any mutation methods.
@@ -84,10 +86,12 @@
IBus bus,
OrdersModel orders_model,
IPositionModel position_model,
ISecurityMetadataStore sec_meta_store,
PNLSettings settings) {
_bus = bus;
_orders_model = orders_model;
_position_model = position_model;
_sec_meta_store = sec_meta_store;
_rows_data_wrapper = rows.WrapSelector(r => r.data, null);
_rows_key_wrapper = rows.WrapSelector(r => r.key, null);
_rows_view = new PNLRowCollectionView(rows, _default_group_appearances, _group_triggers);
@@ -726,8 +730,8 @@
state.orderbook_grid.general = GridSettingsHelper.hide_cols(state.orderbook_grid.general, hide_counterparts);
var settings_man = new WindowSettingsManager<orderbook.OrderBookGridSettings>.DisconnectedImpl(state.orderbook_grid);
var obvm = orders_source == null ?
new OrderBookVM(_bus, null, _orders_model, _position_model, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, orders_source, settings_man, true);
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, settings_man, true) :
new OrderBookVM(_bus, null, _orders_model, _position_model, _sec_meta_store, orders_source, settings_man, true);
foreach (var c in OrderBookVM.OrderBookColumnCollection.editable_columns)
obvm.columns.Insert(0, c);
obvm.load_from(state);
@@ -6,6 +6,8 @@ namespace Spark.Trading {
using bts.api.position;
using bts.utils;
using mbts.utils;
using Spark.Api.Position;
using System;
@@ -122,8 +124,35 @@ namespace Spark.Trading {
public static double sys_price(this ReconcileReportRowData rd) =>
rd.sys_position?.total_net_avg_price() ?? double.NaN;
public static bool has_exch_position(this ReconcileReportRowData rd) =>
(rd.exch_position?.Position).is_real_non_zero();
public static bool has_sys_position(this ReconcileReportRowData rd) =>
(rd.sys_position?.total_pos()).is_real_non_zero();
public static bool is_match(this ReconcileReportRowData rd) =>
rd.sys_quantity().epsilon_equals(rd.exch_quantity()) &&
rd.sys_price().epsilon_equals(rd.exch_price());
rd.match_type() ==
(ReconcileReportMatchType.Quantity | ReconcileReportMatchType.Price);
/// <summary>
/// Determines which components of the system/exchange positions (if any) match. If both
/// positions are undefined (i.e., the quantity is finite positive), then the position is
/// considered a proper match, and both the 'price' and 'quantity' flags are returned.
/// </summary>
public static ReconcileReportMatchType match_type(this ReconcileReportRowData rd) {
if (!rd.has_exch_position() && !rd.has_sys_position()) {
return ReconcileReportMatchType.Price | ReconcileReportMatchType.Quantity;
}
var mt = ReconcileReportMatchType.None;
// allow for rounding error
if (rd.sys_quantity().epsilon_equals(rd.exch_quantity())) {
mt |= ReconcileReportMatchType.Quantity;
}
if (rd.sys_price().epsilon_equals(rd.exch_price())) {
mt |= ReconcileReportMatchType.Price;
}
return mt;
}
}
}
@@ -55,18 +55,7 @@ namespace Spark.Trading {
public double exchange_quantity => _data.exch_quantity();
public double price => _data.sys_price();
public double exchange_price => _data.exch_price();
public ReconcileReportMatchType match_type {
get {
var mt = ReconcileReportMatchType.None;
if (quantity.epsilon_equals(exchange_quantity)) {
mt |= ReconcileReportMatchType.Quantity;
}
if (price.epsilon_equals(exchange_price)) {
mt |= ReconcileReportMatchType.Price;
}
return mt;
}
}
public ReconcileReportMatchType match_type => _data.match_type();
public bts.api.domain.TickDisplaySettingsImmutable quantity_display {
get => _quantity_display;
@@ -79,7 +68,7 @@ namespace Spark.Trading {
}
public bool is_match =>
quantity.epsilon_equals(exchange_quantity) && price.epsilon_equals(exchange_price);
_data.is_match();
public bool has_system_position => _data.sys_position.HasValue;
public bool has_exchange_position => _data.exch_position.HasValue;
@@ -51,7 +51,7 @@ namespace Spark.Trading {
IWindowSettingsManager<GridSettings> settings_manager,
UserTuple user)
: base("Reconcile Report", bus, save, Icons.Reports) {
thread_id = Configuration.get<bts.config.MultiThreadedWindows>().reconcile_report ?
thread_id = Configuration.get<bts.config.MultiThreadedWindows>().ReconcileReport ?
WINDOW_TYPE_NAME : null;
_position_model = position_model;
_security_metadata = security_metadata;
@@ -48,12 +48,22 @@
/// as they are responsible for launching windows in response to a SparkTag being published to the bus.
/// The tags may be published by anything (i.e., not just the spark commands in <see cref="actions"/>).
_window_factories = new() {
new LadderWindowFactory(this, bus, wm, settings_hub, orders_model, position_model, mbo),
new OrderBookWindowFactory(this, bus, notification_service, notification_service_data_cache, orders_model, position_model, settings_hub),
new LadderWindowFactory(
this, bus, wm, settings_hub, orders_model, position_model, security_metadata, mbo),
new OrderBookWindowFactory(
this,
bus,
notification_service,
notification_service_data_cache,
orders_model,
position_model,
security_metadata,
settings_hub),
new FillsWindowFactory(this, bus, settings_hub, orders_model),
new PNLWindowFactory(this, bus, settings_hub, orders_model, position_model),
new PNLWindowFactory(
this, bus, settings_hub, orders_model, position_model, security_metadata),
new AlgoStudioWindowFactory(this, bus, orders_model, error_reporter),
new ManualFillsWindowFactory(this, bus, orders_model),
new ManualFillsWindowFactory(this, bus, orders_model, security_metadata),
new ReconcileReportWindowFactory(
this, bus, settings_hub, position_model, security_metadata, user.Value),
};
@@ -26,7 +26,7 @@ namespace BCG
Right
}
private readonly bool _is_remoted = mbts.config.Configuration.get<bts.config.System>().is_remote_app;
private readonly bool _is_remoted = mbts.config.Configuration.get<bts.config.System>().IsRemoteApp;
[Category("Grid Lines")]
[DisplayName("Row Seperator Line Color")]
@@ -99,6 +99,7 @@
this._toolstripseperator_zoom = new System.Windows.Forms.ToolStripSeparator();
this._toolstripmenuitem_sheet_settings_window = new System.Windows.Forms.ToolStripMenuItem();
this._statusbar_toolstripstatus_security = new System.Windows.Forms.ToolStripStatusLabel();
this._statusbar_vs_dropdown = new System.Windows.Forms.ToolStripComboBox();
this._statusbar_toolstripstatus_column = new System.Windows.Forms.ToolStripStatusLabel();
this._statustrip_main = new System.Windows.Forms.StatusStrip();
this._statusbar_toolstripstatus_task = new System.Windows.Forms.ToolStripStatusLabel();
@@ -716,6 +717,15 @@
this._statusbar_toolstripstatus_security.Size = new System.Drawing.Size(49, 17);
this._statusbar_toolstripstatus_security.Text = "Contract";
this._statusbar_toolstripstatus_security.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// _statusbar_vs_dropdown
//
this._statusbar_vs_dropdown.Font = new System.Drawing.Font("Tahoma", 8F);
this._statusbar_vs_dropdown.Name = "_statusbar_vs_dropdown";
this._statusbar_vs_dropdown.Size = new System.Drawing.Size(49, 17);
this._statusbar_vs_dropdown.Enabled = false;
this._statusbar_vs_dropdown.Text = "Vol Time";
this._statusbar_vs_dropdown.TextAlign = System.Drawing.ContentAlignment.MiddleRight;
//
// _statusbar_toolstripstatus_column
//
@@ -731,6 +741,7 @@
this._statustrip_main.GripMargin = new System.Windows.Forms.Padding(0);
this._statustrip_main.GripStyle = System.Windows.Forms.ToolStripGripStyle.Visible;
this._statustrip_main.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this._statusbar_vs_dropdown,
this._statusbar_toolstripstatus_security,
this._statusbar_toolstripstatus_task,
this._statusbar_toolstripstatus_quoterdata,
@@ -830,6 +841,9 @@
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_edgesize;
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_settings_show_quoteset_midprice;
private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_security;
private System.Windows.Forms.ToolStripComboBox _statusbar_vs_dropdown;
private System.Windows.Forms.ToolStripStatusLabel _statusbar_toolstripstatus_column;
private System.Windows.Forms.StatusStrip _statustrip_main;
private System.Windows.Forms.ToolStripMenuItem _toolstripmenuitem_sheet_column_settings;
@@ -21,7 +21,7 @@ namespace BCG {
Down
}
private readonly bool _is_remoted = mbts.config.Configuration.get<bts.config.System>().is_remote_app;
private readonly bool _is_remoted = mbts.config.Configuration.get<bts.config.System>().IsRemoteApp;
private readonly PerfStatsLogger _recorder = new PerfStatsLogger();
private readonly HighPerformanceTimer _timer = new HighPerformanceTimer();
private System.ComponentModel.Container components = null;
@@ -350,4 +350,4 @@ namespace BCG {
}
#endregion
}
}
}
+3 -3
View File
@@ -56,8 +56,8 @@ namespace mbts.ui {
SoundNotificationPlayer _sound_player;
Dispatcher _dispatcher;
bool
_sound_notifications_enabled = Configuration.get<bts.config.toggles.SoundNotifications>().enabled,
_toast_notifications_enabled = Configuration.get<bts.config.toggles.ToastNotifications>().enabled;
_sound_notifications_enabled = Configuration.get<bts.config.toggles.SoundNotifications>().Enabled,
_toast_notifications_enabled = Configuration.get<bts.config.toggles.ToastNotifications>().Enabled;
[ImportingConstructor]
public Notifier(IBus bus, UserSettingsHub settings_hub) {
@@ -77,7 +77,7 @@ namespace mbts.ui {
if (_disposer.has_dispose_started)
return;
_sound_player = SoundNotificationPlayer.create();
if (Configuration.get<bts.config.toggles.ToastNotifications>().enabled) {
if (Configuration.get<bts.config.toggles.ToastNotifications>().Enabled) {
_toast_controller = new ToastNotificationController(bus);
_settings_sub = settings_hub.subscribe_default_settings().StartWith(settings_hub.current).OnDispatcher().Subscribe(s => {
if (s == null || _disposer.has_dispose_started)
@@ -1,4 +1,5 @@
using bts.api;
using bts.api.domain;
using bts.api.orderman;
using bts.spark;
using bts.utils;
@@ -65,11 +66,15 @@ namespace bts.shell {
public static IToastNotification order_filled(OrderSecurity oldval, OrderSecurity newval) =>
new OrderFilledToastNotification(oldval.order, newval.order, newval.security);
public static IToastNotification order_completed(OrderRecordImmutable order, SecurityImmutable? security) =>
new OrderCompletedToastNotification(order, security);
public static IToastNotification order_completed(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) =>
new OrderCompletedToastNotification(order, security, qty_display);
public static IToastNotification order_completed(OrderSecurity order) =>
new OrderCompletedToastNotification(order.order, order.security);
public static IToastNotification order_completed(
OrderSecurity order, TickDisplaySettingsImmutable qty_display) =>
new OrderCompletedToastNotification(order.order, order.security, qty_display);
public static IToastNotification order_status_changed(uint key, OrderStatus? old_status, OrderStatus new_status, SecurityImmutable? security) =>
new OrderStatusChangeToastNotification(key, old_status, new_status, security);
@@ -145,13 +150,19 @@ namespace bts.shell {
class OrderCompletedToastNotification : ToastNotificationBase, IEquatable<OrderCompletedToastNotification> {
readonly OrderRecordImmutable _order;
readonly SecurityImmutable? _security;
readonly TickDisplaySettingsImmutable _qty_display;
public OrderCompletedToastNotification(OrderRecordImmutable order, SecurityImmutable? security) {
public OrderCompletedToastNotification(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) {
_order = order;
_security = security;
_qty_display = qty_display;
}
public override string text => OrderActivitySummarizer.order_completion_debrief(_order, _security);
public override string text => OrderActivitySummarizer.order_completion_debrief(
_order, _security, _qty_display);
public override ImageSource content_icon => Icons.OrderCompleted;
public bool Equals(OrderCompletedToastNotification other) =>
@@ -185,18 +196,18 @@ namespace bts.shell {
other != null &&
_security.HasValue == other._security.HasValue &&
_newval.Key == other._newval.Key &&
_newval.filled() == other._newval.filled() &&
_newval.filled_quantity().Equals(other._newval.filled_quantity()) &&
_newval.quantity() == other._newval.quantity() &&
_oldval.filled() == other._oldval.filled();
_oldval.filled_quantity().Equals(other._oldval.filled_quantity());
public override bool Equals(object obj) => Equals(obj as OrderFilledToastNotification);
public override int GetHashCode() =>
EqualityComparer.aggregate_hash(
(int)_newval.Key,
(int)_newval.filled(),
(int)_newval.quantity(),
(int)_oldval.filled());
HashCode.Combine(
_newval.Key,
_newval.filled_quantity(),
_newval.quantity(),
_oldval.filled_quantity());
public override string ToString() => text;
}
+15
View File
@@ -6,15 +6,19 @@ using System.Collections.Generic;
using System.ComponentModel;
using System.Reactive.Linq;
using System.Runtime.CompilerServices;
using System.Windows.Input;
namespace mbts.spark {
class AlgoParamVM<T> : IAlgoParamVM<T>, INotifyPropertyChanged, ITemplateSelectorKey {
readonly IEqualityComparer<T> _comparer;
readonly string _template_key;
readonly Func<T, T> _to_display_value, _from_display_value;
AlgoParamPermissions _permissions;
bool _is_enabled, _has_value;
T _committed_value, _value;
ICommand _tick_up_cmd;
ICommand _tick_down_cmd;
public AlgoParamVM(string id, string display_name)
: this(id, display_name, default, EqualityComparer<T>.Default) { }
@@ -61,6 +65,17 @@ namespace mbts.spark {
public bool is_enabled { get => _is_enabled; set => _set(ref _is_enabled, value); }
public bool has_value { get => _has_value; set => _set(ref _has_value, value); }
public bool is_dirty { get; private set; }
public ICommand tick_up_cmd {
get => _tick_up_cmd;
set => _set(ref _tick_up_cmd, value);
}
public ICommand tick_down_cmd {
get => _tick_down_cmd;
set => _set(ref _tick_down_cmd, value);
}
object IAlgoParamVM.value { get => value; set => this.value = (T)value; }
object IAlgoParamVM.display_value { get => display_value; set => display_value = (T)value; }
@@ -8,6 +8,8 @@ using mbts;
using mbts.spark;
using mbts.ui.controls;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -16,6 +18,7 @@ using System.Text;
using System.Threading.Tasks;
using OrderPair = System.ValueTuple<bts.api.SecurityImmutable?, bts.api.orderman.OrderRecordImmutable>;
using TickDisplaySettingsImmutable = bts.api.domain.TickDisplaySettingsImmutable;
namespace bts.spark {
internal class Activity {
@@ -87,8 +90,12 @@ namespace bts.spark {
_format_status_change(header, key, new_status);
}
public static string order_completion_debrief(OrderRecordImmutable order, SecurityImmutable? security) =>
_format_order_completion(_header(order.Key, security), order, security?.ContractSpec);
public static string order_completion_debrief(
OrderRecordImmutable order,
SecurityImmutable? security,
TickDisplaySettingsImmutable qty_display) =>
_format_order_completion(
_header(order.Key, security), order, security?.ContractSpec, qty_display);
public static string modified_description(OrderRecordImmutable old_order, OrderRecordImmutable new_order, ContractSpecificationImmutable? spec) {
double old_price = old_order.State.Price, new_price = new_order.State.Price;
@@ -122,8 +129,15 @@ namespace bts.spark {
static string _format_status_change(string header, uint key, OrderStatus old_status, OrderStatus new_status) =>
$"{header} Status changed from {old_status} to {new_status}";
public static string _format_order_completion(string header, OrderRecordImmutable order, ContractSpecificationImmutable? spec) =>
$"{header} Completed: {order.side().past_tense()} {order.filled()}, @ {spec.spec_or_default().format(order.avg_price())} (avg)";
static string _format_order_completion(
string header,
OrderRecordImmutable order,
ContractSpecificationImmutable? spec,
TickDisplaySettingsImmutable qty_display) {
var filled_qty_str = qty_display.format(order.filled_quantity());
return $"{header} Completed: {order.side().past_tense()} {filled_qty_str}, " +
$"@ {spec.spec_or_default().format(order.avg_price())} (avg)";
}
#endregion
@@ -208,18 +222,24 @@ namespace bts.spark {
}
const string algo_change_text = "change algo parameters";
var security = try_get_security(order.Def.SecurityKey);
var spec = security?.ContractSpec;
var desc_builder = new StringBuilderEx();
if (price != order.price() || size != order.working_quantity()) {
desc_builder.Add(order.State.Quantity.ToString(), "@", spec.format(order.State.Price), "to ", size.ToString(), "@", spec.format(price));
if (algo_changed)
desc_builder.Add("; ", algo_change_text);
} else if (algo_changed) {
desc_builder.Add(algo_change_text);
var change_descs = new List<string>(1);
TickDisplaySettingsImmutable? price_display =
security.HasValue && security.Value.HasContractSpec ?
security.Value.ContractSpec.tick_factors().to_api_tick_display_settingsi() : null;
var price_qty_change_desc = OrderUtils.update_description(
order, price, size, price_display);
if (!price_qty_change_desc.is_null_or_empty()) {
change_descs.Add(price_qty_change_desc);
}
desc_builder.Insert(0, $"{change_desc_prefix} ");
desc_builder.Insert(0, $"({order.Key}) ");
log_status(ActivityLogCategory.modify, security, desc_builder.ToString());
if (algo_changed) {
change_descs.Add(algo_change_text);
}
var desc = $"({order.Key}) {change_desc_prefix} {"; ".join(change_descs)}";
log_status(ActivityLogCategory.modify, security, desc);
}
}
}
+72 -11
View File
@@ -11,6 +11,8 @@ using mbts.ui.utilities;
using mbts.ui.utility;
using mbts.utils;
using Spark.Core;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -24,17 +26,35 @@ namespace mbts.spark {
static class OrderUtils {
public static readonly Func<OrderRecordImmutable, uint> RecordKeySelector = o => o.Key;
public static uint filled(this OrderRecordImmutable order) =>
order.HasState ? order.State.FilledQuantity : 0u;
#region OrderStateImmutable extension methods
public static double quantity(this OrderStateImmutable state) =>
Convert.ToDouble(state.Quantity) +
(state.HasFractionalQuantity ? state.FractionalQuantity.Fraction : 0.0);
public static double filled_quantity(this OrderStateImmutable state) =>
Convert.ToDouble(state.FilledQuantity) +
(state.HasFractionalFilledQuantity ? state.FractionalFilledQuantity.Fraction : 0.0);
public static double working_quantity(this OrderStateImmutable state) =>
state.quantity() - state.filled_quantity();
public static double fill_ratio(this OrderStateImmutable state) =>
state.filled_quantity() / state.quantity();
#endregion
public static double filled_quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.filled_quantity() : 0.0;
public static double fill_ratio(this OrderRecordImmutable order) =>
order.HasState ? order.State.FilledQuantity / (double)order.State.Quantity : double.NaN;
public static double quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.Quantity : 0;
order.HasState ? order.State.quantity() : 0;
public static double working_quantity(this OrderRecordImmutable order) =>
order.HasState ? order.State.working_quantity() : 0;
public static int working_quantity(this OrderRecordImmutable order) =>
order.HasState ? (int)order.State.Quantity - (int)order.State.FilledQuantity : 0;
public static double price(this OrderRecordImmutable order) =>
order.HasState ? order.State.Price : double.NaN;
@@ -196,14 +216,20 @@ namespace mbts.spark {
return "Undefined";
}
public static string full_description(this OrderRecordImmutable order, SecurityImmutable security) {
public static string full_description(
this OrderRecordImmutable order,
SecurityImmutable security,
bts.api.domain.TickDisplaySettingsImmutable? qty_display = null) {
StringBuilder sb = new StringBuilder();
string sec_key_text;
if (order.HasDef) {
sec_key_text = $"Security: {order.Def.SecurityKey}";
if (order.HasState) {
qty_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var qty_str = qty_display.Value.format(order.quantity());
var filled_qty_str = qty_display.Value.format(order.filled_quantity());
sb.AppendLine($"{order.Def.Side}: {TickUtils.format(security.ContractSpec, order.State.Price)}");
sb.AppendLine($"Filled: {filled(order)} / {order.State.Quantity}");
sb.AppendLine($"Filled: {filled_qty_str} / {qty_str}");
} else {
sb.AppendLine($"{order.Def.Side}: (price-unknown)");
sb.AppendLine("Filled: (quantity-unknown)");
@@ -247,21 +273,56 @@ namespace mbts.spark {
public static string price_quantity_description(
double price, double quantity, ContractSpecificationImmutable spec) =>
new StringBuilderEx(quantity.ToString(), " @ ", spec.format(price) ?? price.ToString("#0.00##")).ToString();
price_quantity_description(
price, quantity, spec.tick_factors().to_api_tick_display_settingsi());
public static string price_quantity_description(
double price,
double quantity,
bts.api.domain.TickDisplaySettingsImmutable? price_display = null,
bts.api.domain.TickDisplaySettingsImmutable? quantity_display = null) {
price_display ??= SecurityDataHelper.Defaults.price_display_settingsi;
quantity_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
return $"{quantity_display.Value.format(quantity)} @ {price_display.Value.format(price)}";
}
public static string filled_status_description(
this OrderRecordImmutable order,
ContractSpecificationImmutable spec,
double display_qty_divisor = 1
bts.api.domain.TickDisplaySettingsImmutable? qty_display = null
) {
qty_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var sb = new StringBuilderEx(
"filled ", ((double)order.filled()).safe_divide(display_qty_divisor).ToString());
if (order.filled() > 0)
"filled ", qty_display.Value.format(order.filled_quantity()));
if (order.filled_quantity() > 0)
sb.Add(" @ ", spec.format(order.avg_price()));
sb.Add(", ", camel_to_title_case(order.status().ToString(), TextCapitalizationFormat.NoCaps));
return sb.ToString();
}
public static string update_description(
OrderRecordImmutable order,
double? new_price = null,
double? new_quantity = null,
bts.api.domain.TickDisplaySettingsImmutable? price_display = null,
bts.api.domain.TickDisplaySettingsImmutable? quantity_display = null
) {
var price = new_price ?? order.price();
var quantity = new_quantity ?? order.working_quantity();
if (price == order.price() && quantity == order.working_quantity()) {
// nothing actually changed
return null;
}
price_display ??= SecurityDataHelper.Defaults.price_display_settingsi;
quantity_display ??= SecurityDataHelper.Defaults.quantity_display_settingsi;
var from_desc = price_quantity_description(
order.quantity(), order.price(), price_display, quantity_display);
var to_desc = price_quantity_description(
quantity, price, price_display, quantity_display);
return $"{from_desc} to {to_desc}";
}
public static bool has_parent(this OrderRecordImmutable order) =>
order.ParentKey != 0;
+35 -5
View File
@@ -25,6 +25,7 @@
using System.Collections.Immutable;
using System.Collections.Specialized;
using System.Composition;
using System.Diagnostics.Contracts;
using System.Linq;
using System.Reactive.Concurrency;
using System.Reactive.Linq;
@@ -35,7 +36,7 @@
[Export]
class OrdersModel : IDisposable {
public static readonly bool piq_enabled = Configuration.get<bts.config.toggles.PlacementInQueue>().enabled;
public static readonly bool piq_enabled = Configuration.get<bts.config.toggles.PlacementInQueue>().Enabled;
public readonly MarketDataAuxiliaryModel md_auxiliary_model;
public readonly ISecurityAuxiliaryDataModel security_auxiliary_model;
@@ -52,6 +53,10 @@
readonly TableUpdateDemuxer<OrderRecordImmutable, uint, uint> _security_orders_demuxer;
readonly TableUpdateDemuxer<OrderSecurity, uint, uint> _security_working_orders_with_piq_demuxer;
readonly OrderDataSource _data_source;
/// <see cref="_securities"/> is updated atomically from multiple threads (use a local copy to
/// perform lookups, etc.)
IReadOnlyDictionary<uint, SecurityMD> _securities = new Dictionary<uint, SecurityMD>(0);
IDisposable _dispose;
[ImportingConstructor]
@@ -218,6 +223,7 @@
on_order_tuples_with_piq
.Filter(os => os.order.is_active() && os.order.State.DisplayStatus == OrderState.Types.DisplayStatus.Visible, key => key.order.Key)
.Subscribe(_security_working_orders_with_piq_demuxer),
_bus.subscribe(SparkTags.SecuritiesTag).Subscribe(s => _securities = s),
_bus.subscribe(SparkTags.RecreateOrder).Subscribe(a => a.ForEach(x => send_order(x.definition, x.price, x.size).ignore())),
_bus.subscribe(SparkTags.CancelOrders).Subscribe(x => cancel_orders(x).ignore()),
_bus.subscribe(SparkTags.DetachOrders).Subscribe(x => detach_orders(x).ignore()),
@@ -300,10 +306,12 @@
}
async Task<(uint? key, string error)> send_order_get_error(OrderDefinitionImmutable order, double price, double size) {
var (iqty, fqty) = _break_quantity(order.SecurityKey, size);
var result = await _service.create_order_async(new Create() {
NewOrder = order.CloneToMutable(),
Price = price,
Quantity = (uint)size
Quantity = iqty,
FractionalQuantity = fqty
});
return _handle_error(result, "Error sending order: {0}");
}
@@ -319,6 +327,26 @@
return success;
}
public bool try_get_sec(uint sec_key, out SecurityMD result) =>
_securities.TryGetValue(sec_key, out result);
public SecurityMD? find_sec(uint sec_key) =>
try_get_sec(sec_key, out var sec) ? sec : null;
(uint iqty, FractionalQuantity fqty) _break_quantity(
uint sec_key, double qty) {
Contract.Requires(qty.is_real_non_negative());
var display = try_get_sec(sec_key, out var sec) ? sec.quantity_display :
SecurityDataHelper.Defaults.quantity_display_settingsi;
var rounded_qty = display.TickFactors.to_tick_factors().round(qty);
ExceptionAssert.InvalidOperation.That(
rounded_qty.is_real_non_negative(),
$"Expected rounded qty to be real, non-negative. " +
$"qty: {qty}; rounded_qty: {rounded_qty}; display: {display})");
var iqty = Math.Floor(rounded_qty);
return ((uint)iqty, new() { Fraction = rounded_qty - iqty });
}
private CustomOrderDefinitionImmutable? _create_custom_def_for_stop_and_stop_limit(OrderRecordImmutable order, ref double stop_price) {
CustomOrderDefinition modified_custom_def = null;
var ord_type = order.order_type();
@@ -356,10 +384,12 @@
new_algo = _create_custom_def_for_stop_and_stop_limit(order, ref price);
}
_activity.update_order(order, price, size, new_algo.HasValue);
var (iqty, fqty) = _break_quantity(order.security_key(), size);
var result = await _service.update_order_async(new Update() {
OrderKey = order.Key,
Price = price,
Quantity = (uint)size,
Quantity = iqty,
FractionalQuantity = fqty,
Custom = new_algo?.CloneToMutable()
});
(var key, string msg) = _handle_error(result, "Failed to update order: {0}");
@@ -598,7 +628,7 @@
if (result.HasValue) {
var o = result.Value;
if (o.State.Price == price) return true;
int wq = o.working_quantity();
var wq = o.working_quantity();
if (wq > 0) {
return await orders_model.update_order(o, price, o.State.Quantity);
}
@@ -611,7 +641,7 @@
var result = await order_from_key(orders_model, order);
if (result.HasValue) {
var o = result.Value;
int wq = o.working_quantity();
var wq = o.working_quantity();
if (wq > 0) {
if (wq == size) return true;
return await orders_model.update_order(o, o.State.Price, size);
@@ -8,6 +8,8 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
@@ -17,12 +19,15 @@ namespace mbts {
public static Dictionary<OrderCompletedEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderCompletedEventPredicate>> get_oneofs(IBus bus) =>
new Dictionary<OrderCompletedEventPredicate.PredicateTypeOneofCase, ITemplatedPropertyWrapperVM<OrderCompletedEventPredicate>> {
{ OrderCompletedEventPredicate.PredicateTypeOneofCase.AnyOrder, PredicateVMWrapper.create<OrderCompletedEventPredicate>(p => p.security = null) },
{ OrderCompletedEventPredicate.PredicateTypeOneofCase.SecurityOrder, SecurityCriteriaVMFactory.create<OrderCompletedEventPredicate>(bus, o => o.security?.is_value ?? new SecurityCriteria(),
(p, s) => {
if (p.security == null)
p.security = new SecurityPredicate();
p.security.is_value = s;
})
{
OrderCompletedEventPredicate.PredicateTypeOneofCase.SecurityOrder,
SecurityCriteriaVMFactory.create<OrderCompletedEventPredicate>(
bus, o => o.security?.is_value ?? new SecurityCriteria(),
(p, s) => {
if (p.security == null)
p.security = new SecurityPredicate();
p.security.is_value = s;
})
}
};
}
@@ -53,8 +58,9 @@ namespace mbts {
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) =>
OrderEventPredicateHelper.create_status_transition_predicate(OrderStatus.Completed, security, data_cache);
public INotificationPredicate<OrderSecurity> create_toast(INotificationServiceDataCache data_cache) =>
new MyToaster(security?.create(), data_cache);
public INotificationPredicate<OrderSecurity> create_toast(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) =>
new MyToaster(security?.create(), data_cache, sec_meta_store);
public bool Equals(OrderCompletedEventPredicate other) => other != null && other.security.safe_equals(other.security);
public override bool Equals(object obj) => Equals(obj as OrderCompletedEventPredicate);
@@ -66,15 +72,28 @@ namespace mbts {
class MyToaster : INotificationPredicate<OrderSecurity>, IEquatable<MyToaster> {
readonly IPredicate<SecurityImmutable> _security_predicate;
readonly INotificationServiceDataCache _data_cache;
readonly ISecurityMetadataStore _sec_meta_store;
public MyToaster(IPredicate<SecurityImmutable> security_predicate, INotificationServiceDataCache data_cache) {
public MyToaster(
IPredicate<SecurityImmutable> security_predicate,
INotificationServiceDataCache data_cache,
ISecurityMetadataStore sec_meta_store) {
_security_predicate = security_predicate;
_data_cache = data_cache;
_sec_meta_store = sec_meta_store;
}
public IToastNotification trigger(OrderSecurity order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache) ?
ToastNotifications.order_completed(order) : ToastNotifications.empty;
public IToastNotification trigger(OrderSecurity order) {
if (!OrderEventPredicateHelper.check_order_transition_predicate(
order, _is_completed, _security_predicate, _data_cache)) {
return ToastNotifications.empty;
}
var sec = order.security;
var sec_meta = sec.HasValue ? _sec_meta_store.get(sec.Value) : null;
var qty_display = sec_meta?.QuantityDisplay ??
SecurityDataHelper.Defaults.quantity_display_settingsi;
return ToastNotifications.order_completed(order, qty_display);
}
bool IPredicate<OrderSecurity>.trigger(OrderSecurity order) =>
OrderEventPredicateHelper.check_order_transition_predicate(order, _is_completed, _security_predicate, _data_cache);
@@ -78,10 +78,10 @@
public (OrderSecurity oldval, OrderSecurity newval)? get_filled_order_args(OrderSecurity ort) {
if (ort.order.is_exchange_order() && OrderEventPredicateHelper.check_security_predicate(ort, _security_predicate)) {
if (_data_cache.get_previous_order_state(ort.order.Key) is var oldval && oldval.HasValue) {
if (ort.order.filled() > oldval?.order.filled()) {
if (ort.order.filled_quantity() > oldval?.order.filled_quantity()) {
return (oldval.Value, ort);
}
} else if (!_data_cache.is_first_order_update && ort.order.filled() > 0) {
} else if (!_data_cache.is_first_order_update && ort.order.filled_quantity() > 0) {
// old order will be a copy of new order, except with filledQuantity set to 0
var old_state = ort.order.State.CloneToMutable();
old_state.FilledQuantity = 0;
@@ -32,7 +32,7 @@
class OrderSentEventPredicate : IEquatable<OrderSentEventPredicate> {
static readonly int _type_hash = typeof(OrderSentEventPredicate).GetHashCode();
// arbitrary short time period (can override in config)
static readonly TimeSpan _stale_order_threshold = TimeSpan.FromSeconds(config.Configuration.get<bts.config.OrderAlerts>().stale_order_threshold_seconds);
static readonly TimeSpan _stale_order_threshold = TimeSpan.FromSeconds(config.Configuration.get<bts.config.OrderAlerts>().StaleOrderThresholdSeconds);
public enum PredicateTypeOneofCase {
[Description("(any order)")]
@@ -9,6 +9,8 @@ using mbts.ui.settings;
using ProtoBuf;
using Spark.Core.Data;
using System;
using System.Collections.Generic;
@@ -64,8 +66,11 @@ namespace mbts {
class OrderRecordTuplePredicate : IEquatable<OrderRecordTuplePredicate> {
SecurityPredicate _security;
SidePredicate _side;
DoublePredicate _price, _last_price, _avg_price;
UIntPredicate _filled_quantity, _security_key, _order_key, _parent_key, _attached_target_order_key;
DoublePredicate _price;
DoublePredicate _last_price;
DoublePredicate _avg_price;
DoublePredicate _filled_quantity;
UIntPredicate _security_key, _order_key, _parent_key, _attached_target_order_key;
DoublePredicate _quantity;
OrderStatusPredicate _order_status;
OrderTypePredicate _order_type;
@@ -155,7 +160,7 @@ namespace mbts {
[ProtoMember(10)]
public DoublePredicate quantity { get => _quantity; set => _set(ref _quantity, value); }
[ProtoMember(11)]
public UIntPredicate filled_quantity { get => _filled_quantity; set => _set(ref _filled_quantity, value); }
public DoublePredicate filled_quantity { get => _filled_quantity; set => _set(ref _filled_quantity, value); }
[ProtoMember(12)]
public DoublePredicate last_price { get => _last_price; set => _set(ref _last_price, value); }
[ProtoMember(13)]
@@ -218,7 +223,8 @@ namespace mbts {
}
}
public IPredicate<OrderSecurity> create_predicate(INotificationServiceDataCache data_cache) {
public IPredicate<OrderSecurity> create_predicate(
INotificationServiceDataCache data_cache, ISecurityMetadataStore sec_meta_store) {
switch (predicate_type_case) {
case PTOC.Security: return wrap(_security.create(), r => r.security ?? SecurityDataHelper.Defaults.SecurityImmutable);
case PTOC.Time: return wrap(_time_created.create(), r => r.order.created());
@@ -232,7 +238,7 @@ namespace mbts {
case PTOC.Side: return wrap(_side.create(), r => r.order.side());
case PTOC.Size: return wrap(_quantity.create(), r => r.order.quantity());
case PTOC.Price: return wrap(_price.create(), r => r.order.price());
case PTOC.Filled: return wrap(_filled_quantity.create(), r => r.order.filled());
case PTOC.Filled: return wrap(_filled_quantity.create(), r => r.order.filled_quantity());
case PTOC.AvgFilled: return wrap(_avg_price.create(), r => r.order.avg_price());
case PTOC.LastPrice: return wrap(_last_price.create(), r => r.order.last_price());
case PTOC.Status: return wrap(_order_status.create(), r => r.order.status());
@@ -252,15 +258,18 @@ namespace mbts {
trigger.wrap<OrderSecurity, T>(select);
}
public INotificationPredicate<OrderSecurity> create_notification_predicate(INotificationServiceDataCache notification_service_data_cache) {
public INotificationPredicate<OrderSecurity> create_notification_predicate(
INotificationServiceDataCache notification_service_data_cache,
ISecurityMetadataStore sec_meta_store) {
if (!is_toast_enabled)
return null;
switch (predicate_type_case) {
case PTOC.FilledEvent: return _filled_event.create_toast(notification_service_data_cache);
case PTOC.CompletedEvent: return _completed_event.create_toast(notification_service_data_cache);
case PTOC.CanceledEvent: return _canceled_event.create_toast(notification_service_data_cache);
default: return null;
}
return predicate_type_case switch {
PTOC.FilledEvent => _filled_event.create_toast(notification_service_data_cache),
PTOC.CompletedEvent => _completed_event.create_toast(
notification_service_data_cache, sec_meta_store),
PTOC.CanceledEvent => _canceled_event.create_toast(notification_service_data_cache),
_ => null,
};
}
public bool Equals(OrderRecordTuplePredicate other) {
+1 -1
View File
@@ -30,7 +30,7 @@ namespace mbts.ui.settings {
}
static class PredicateVMWrapper {
static readonly bool _toast_notifications_enabled_global = Configuration.get<bts.config.toggles.ToastNotifications>().enabled;
static readonly bool _toast_notifications_enabled_global = Configuration.get<bts.config.toggles.ToastNotifications>().Enabled;
public static ITemplatedPropertyWrapperVM<TSource> wrap_child_oneof<TSource, TChild, TChildOneof>(
Func<TSource, TChild> get, Action<TSource, TChild> set, Func<TChild, TChildOneof> get_child_oneof, Dictionary<TChildOneof, ITemplatedPropertyWrapperVM<TChild>> oneof_vms)
@@ -29,7 +29,7 @@ namespace mbts.analytics {
IBus bus, ISaveWindow<ComboReportSettings> save,
ComboReportSettings settings)
: base(settings.id.ToString(), bus, save, Icons.Reports) {
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().combo_report ?
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().ComboReport ?
"Combo" : null;
_settings = settings;
_dispose = Disposable.Create(() => (_vm, _model));
+2 -2
View File
@@ -11,7 +11,7 @@ namespace mbts {
SecurityExpiration security_expiration,
double? strike,
PutOrCall? call_put,
int size,
double size,
double price,
double theo,
string account,
@@ -47,7 +47,7 @@ namespace mbts {
public SecurityExpiration? security_expiration { get; }
public SecurityStrike? security_strike { get; }
public PutOrCall? call_put { get; }
public int size { get; }
public double size { get; }
public double price { get; }
public double theo { get; }
public string account { get; }
+1 -1
View File
@@ -15,7 +15,7 @@ namespace mbts {
SecurityExpiration? security_expiration { get; }
SecurityStrike? security_strike { get; }
PutOrCall? call_put { get; }
int size { get; }
double size { get; }
double price { get; }
double theo { get; }
string account { get; }
@@ -34,7 +34,7 @@ namespace mbts.analytics {
ISaveWindow<SlideReportSettings> save,
SlideReportSettings settings)
: base(settings.id.ToString(), bus, save, Icons.Reports) {
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().slide_report ? "Slide" : null;
thread_id = config.Configuration.get<bts.config.MultiThreadedWindows>().SlideReport ? "Slide" : null;
_settings = settings;
_dispose = Disposable.Create(() => Disposable.dispose(ref _vm));
}
+3 -4
View File
@@ -18,8 +18,7 @@ namespace mbts {
expiration = sec.security_expiration();
strike = sec.strike();
call_put = sec.HasOption ? sec.Option.CallPut : null;
// TOOD make it a double
size = Convert.ToInt32(m_fill.Quantity);
size = m_fill.Quantity;
if (m_fill.Side == Side.Sell) {
size = size * -1;
}
@@ -46,7 +45,7 @@ namespace mbts {
strike = sec.strike();
call_put = sec.HasOption ? sec.Option.CallPut : null;
// TOOD make it a double
size = Convert.ToInt32(fill.LastShares);
size = fill.LastShares;
if (fill.Side == Side.Sell) {
size = size * -1;
}
@@ -71,7 +70,7 @@ namespace mbts {
public SecurityExpiration? security_expiration { get; }
public SecurityStrike? security_strike { get; }
public PutOrCall? call_put { get; }
public int size { get; }
public double size { get; }
public double price { get; }
public double theo { get; }
public string account { get; }
@@ -28,9 +28,9 @@ namespace mbts.spark {
public SecurityAuxiliaryDataModel() {
var sym_config = Configuration.get<bts.config.SymbolUIConfiguration>();
var sym_config_items = Configuration.get<bts.config.SymbolUIConfiguration>().items;
var sym_config_items = Configuration.get<bts.config.SymbolUIConfiguration>().Items;
foreach (var item in sym_config_items)
_auxiliary_data[item.symbol] = new SecurityAuxiliaryData(item.display_quantity_divisor);
_auxiliary_data[item.Symbol] = new SecurityAuxiliaryData(item.DisplayQuantityDivisor);
}
public SecurityAuxiliaryData? get_auxiliary_data(SecurityImmutable security) =>
+1 -1
View File
@@ -88,7 +88,7 @@
}
public override void CreateShell(ShellModel model) {
if (Configuration.get<bts.config.ShellRenderMode>().software_only) {
if (Configuration.get<bts.config.ShellRenderMode>().SoftwareOnly) {
System.Windows.Media.RenderOptions.ProcessRenderMode = System.Windows.Interop.RenderMode.SoftwareOnly;
}
Loaded 100 of 355 files, more files were not shown because too many files have changed in this diff. Show more