Compare commits

..
Author SHA1 Message Date
John Colvin 511aeaf648 check pt: fix deribit_emumba build 2025-01-12 19:35:13 +00:00
John Colvin a37c5b396a fix deribit_emumba build 2025-01-12 15:20:34 +00:00
John Colvin 039e836acc check pt: fix emumba deribit build
It works if you build --target deribit_emumba first.
2025-01-11 17:24:02 +00:00
John Colvin 7dee64ea70 refactor: Split MarketDataGateway up into providers/sources
MarketDataGateway still exists, but is greatly simplified. It creates
several `IMarketDataProvider`s, each of which generates a list of
`IMarketDataSource`s. The market data sources provide market data to an
`IMarketDataListener`.

* EmumbaMarketDataProvider
* CCApiMarketDataProvider
* PyMarketDataProvider
* OnixsMarketDataProvider
* ReplayMarketDataProvider

As a side effect, individual py market data sources are now explicitly
limited to a single venue (it probably should have been this way all
along, since the shared memory writers do not expect updates to involve
multiple venues).
2025-01-10 20:01:44 +00:00
John Colvin c30e23406c fix build: Trivial changes to fix emumba_deribit build
* Use "Unix Makefiles" generator when building websocket-library.
  - Ninja tries to build things in parallel, and doesn't build the
    ExternalProject dependencies in the right order. Consequently, the
    websocket-library build fails because it can't find "libspdlog.a".

* Replace a few leftover SPDLOG_ERROR macros w/ LOG_ERROR (the latter
  logs in our system, not spdlog).
2025-01-10 20:01:44 +00:00
Mohammad Arham 836f22597d scafolding 2025-01-10 20:01:44 +00:00
John Colvin 38c1ebcf01 cleanup: Remove erroneous include 2025-01-10 20:01:44 +00:00
John Colvin b887cbebab fix: Actually capture emumba deribit cfg obj by value
The previous "fix" didn't actually work because, although the lambda
captured the obj by value, the thread captured the lambda by reference!
2025-01-09 16:53:22 +00:00
John Colvin 14e975bc7e vscode: Add Spark (Skip Build) entry to tasks.json 2025-01-09 11:23:30 -05:00
John Colvin 064f557057 ui: Sort accounts in ladder/ticket dropdown 2025-01-09 11:23:30 -05:00
John Colvin 4d106b5e6c ui: Fix alignment issues in order ticket 2025-01-09 11:23:30 -05:00
John Colvin 9fbeaf0d68 ui: Make TickUpDown style match default (dark) Button
* Set BorderThickness to 0
* Use same mouse-hover background as Button
2025-01-09 11:23:30 -05:00
John Colvin 4018ac8b78 ui: Add tooltips to order ticket 2025-01-09 11:23:30 -05:00
John Colvin 81c9503300 ui: Apply dark theme to order ticket buttons 2025-01-09 11:23:30 -05:00
John Colvin 477210926d ui: Fix text color in algo popup 2025-01-09 11:23:29 -05:00
John Colvin 0aa48a79a9 ui: Remove single quotes from tooltip
It looked busy
2025-01-09 01:38:26 -05:00
John Colvin 9e71c7af02 ui: Add tooltips to ladder 2025-01-09 01:38:26 -05:00
John Colvin 4647751409 vscode: Add Spark Test entry to launch.json, tasks.json 2025-01-09 01:03:33 -05:00
John Colvin a3087b874b cleanup: Remove unused code 2025-01-09 01:03:32 -05:00
John Colvin 5b2f5c5c8f Don't throw/catch type exception needlessly 2025-01-09 01:03:32 -05:00
John Colvin 479227090e ui: Remove overly rigid validation for "ticks per row" setting 2025-01-09 01:03:32 -05:00
John Colvin 2dfcf320f5 fix: Refresh ladder levels when "ticks per row" changes 2025-01-09 01:03:32 -05:00
John Colvin b4c7213cb2 fix: Refresh ladder prices in view when they change
Bugs (fixed):
  * Sometimes the prices in the left panel of the ladder get stale
2025-01-09 01:03:32 -05:00
John Colvin c7dfd69b90 Consolidate tick rounding functions
Too many functions were performing essentially the same service:
rounding ticks. It was confusing.
2025-01-09 01:03:32 -05:00
John Colvin 4fdc866485 build: Propagate py script exit codes back to the shell
I noticed the build cmds were broken on Windows because the debugger
would still start even when the preLaunchTask (build) failed!
2025-01-09 01:03:32 -05:00
John Colvin f5d5ca9a1c ui: Use appropriate colors in font picker control
We must have missed this when we switched to dark theme.
2025-01-09 01:03:32 -05:00
John Colvin cfafcf77b9 ui: Use appropriate text color in ladder settings dialog
We must have missed this black text when we switched to dark theme.
While we're at it, freeze the brushes it uses, since they are stored in
a StaticResource which could potentially be shared by multiple controls.
2025-01-09 01:03:32 -05:00
John Colvin 8ebe783139 fix: Clear low/high lines in ladder when scrolled out of view 2025-01-09 01:03:32 -05:00
John Colvin 1851a96a58 vscode: Add Spark (Skip Build) entry to launch.json 2025-01-09 01:03:32 -05:00
John Colvin 0b334ef870 fix: Remove erroneous early exit condition in Ladder render
Bugs (fixed):
  * The ladder doesn't always render ask prices
2025-01-09 01:03:32 -05:00
John Colvin ee811a729a ui: Make ladder price line colors match button text 2025-01-09 01:03:32 -05:00
John Colvin cb15be276d ui: Show bid, ask, mid lines in ladder by default 2025-01-09 01:03:32 -05:00
John Colvin 7d5af6729b ui: Show bid, ask, mid prices in ladder left panel 2025-01-09 01:03:31 -05:00
John Colvin e5679cf082 ui: Make ladder price links prettier
* Change them from hyperlinks to buttons
* Add mouse hover animation
* Align text to the right (so decimal places line up)
2025-01-09 01:03:31 -05:00
John Colvin 98f89b9ad4 fix: Capture emumba deribit cfg by value in thread body
Bugs (fixed):
  * Sparkd occasionally assert crashes on startup because it fails to
    read emumba deribit config.

    Cause: This is a simple race bug. The config obj isn't captured by
    value, so it can be destructed before the thread references it.
2025-01-08 19:03:01 +00:00
John Colvin ba4f8f67e3 fix: Disable binance usds futs symbol filter config
This was a premature optimization, and has become a burden now that we
need to subscribe to large symbol sets for Alphaworx.
2025-01-06 05:00:04 +00:00
John Colvin 9c78380490 fix build (gcc rel): Don't fallthrough switch cases 2025-01-06 03:52:25 +00:00
John Colvin f6166f0674 fix: Show iceberg show qty in algo params grid
Bugs (fixed):
  * In the ladder, you can't view/edit the iceberg show quantity.

  Cause: No view template was defined for nullable double params. Most
  likely, we changed the show qty in the vm from double to nullable
  double at some point, and forgot to reflect this change in the view.
  An easy mistake to make as it would not have broken the build.
2025-01-05 15:58:29 -05:00
John Colvin 6334a902e7 fix: Reclaim keyboard focus when mview popup is clicked 2025-01-05 15:29:11 -05:00
John Colvin 082ca62fff fix: Focus price textbox when mview order ticket popup opens 2025-01-05 15:18:46 -05:00
John Colvin 9dbd8dd7c6 fix: Set focus through FocusScope element if one exists 2025-01-05 15:18:46 -05:00
John Colvin 8f7a4d0df6 Fix typo in AutoFocusTargetProvider dependency prop 2025-01-05 15:18:46 -05:00
John Colvin f372dd56b3 fix: Return synthetic name in get_security_desc
If the security is a synthetic (of course).

Bugs (fixed):
  * Changing limits in the risk ui causes sparkd to assert crash
2025-01-05 20:15:10 +00:00
John Colvin 86eba20d61 build: Make compiler/build type case insensitive 2025-01-05 06:25:11 +00:00
John Colvin 35a985280d fix: Run heartbeat timer in MarketDataGateway
This is why we were getting those heartbeat asserts. Previously, only
ExchangeSimApplication would start this timer. Since MarketDataGateway
doesn't share its MDProducer with ExchangeSimApplication, it must start
one itself.
2025-01-03 16:59:07 +00:00
John Colvin f5e1b3319c cleanup: Don't write to cout in SparkDataDirectory
Don't need that noise.
2025-01-03 16:59:07 +00:00
John Colvin 65c3948e4f cleanup: Remove unused code 2025-01-03 16:59:07 +00:00
John Colvin 002bdff9a3 fix: Don't parse non-existent json files in SparkDataDirectory
Bugs (fixed):
  * Sparkd assert crashes if binance_usds_futures_execution.json file
    doesn't exist
2025-01-03 16:59:07 +00:00
John Colvin bb6e5dd548 diag: Fix sparkd log path in show_last_run.sh 2025-01-03 16:59:07 +00:00
John Colvin 7c1aed3339 fix build (api server): Remove old cpps from source file list 2025-01-03 16:59:07 +00:00
John Colvin 22ae51fb99 build: Clean up build py scripts 2025-01-03 16:59:07 +00:00
John Colvin a53d347f81 fix build (warns): Update cmake min version to 3.10
Versions < 3.10 will soon be deprecated (we just started getting
warnings about it).
2025-01-03 16:59:07 +00:00
John Colvin 838dbcd886 build: In py build scripts, exit with code 1 on failure
Previously, they would exit with 0 no matter what happened.
2025-01-03 16:59:07 +00:00
John Colvin 5ed2309d22 fix: Add switch case for VENUE_BTS in VenueIndex 2025-01-03 16:59:07 +00:00
John Colvin 4d41704dd2 build: Configure admin webapp build entirely in CMakeLists
Get rid of build_admin_web_app.py
2025-01-03 16:59:07 +00:00
John Colvin bd1000e518 build: Get rid of explicit "targets" in CMakePresets for sparkd
So we don't have to worry about keeping it synchronized with the actual
targets in the build (just one more thing that can break). You can build
specific targets via the cmake cli anyways.
2025-01-03 16:59:07 +00:00
John Colvin dd4aa3c2ed build: Update fable in dotnet-tools.json 2025-01-03 16:59:07 +00:00
John Colvin fee9d3f597 build: Update webpack-cli in admin webapp 2025-01-03 16:59:07 +00:00
John Colvin 416f9aef31 vscode: Add Sparkd Test to launch.json 2025-01-03 16:59:07 +00:00
John Colvin 48f5e4c201 vscode: Fix sparkd launch.json 2025-01-03 16:59:07 +00:00
John Colvin 4438b4ca8d feat: Support fractional quantities in synthetic book 2025-01-03 16:59:07 +00:00
John Colvin 73356e0d61 cli: Add cmd to print security info from the db to console
Usage: sparkd md dump --db
2025-01-03 16:59:07 +00:00
John Colvin 4a285fa581 cleanup: Make fn const 2025-01-03 16:59:07 +00:00
John Colvin cfa82c2177 cleanup: Remove erroneous fwd declared class 2025-01-03 16:59:07 +00:00
John Colvin 0410a0431a fix: Encode exp in valid date int when storing in sqlite
The strange bit shifting we were doing before doesn't support large
dates.

Bugs (fixed):
  * Synthetics with Binance perpetual future legs don't appear on the
    front end after sparkd restarts.

  * Cause: Exp dates for Binance perpetual futures aren't properly
    encoded in the database. As a result, when loaded from disk, they
    are mistakenly identified as expired, along with any synthetics that
    have them as legs.
2025-01-03 16:59:07 +00:00
John Colvin 02843f14ff cleanup: Get rid of trivial fn that's only used in one place
Move the logic into the function that used to call it.
2025-01-03 16:59:07 +00:00
John Colvin f1f1d4259c diag: Add logs around security discovery in MDConsumer
This is multi-threaded event driven code. Without descriptive logs in
the right places, diagnosing problems is difficult and tedious.
2025-01-03 16:59:07 +00:00
John Colvin 71fc43af68 cleanup: Flatten nested if blocks with continue statements
Easier to read
2025-01-03 16:59:07 +00:00
John Colvin 350144ffd5 fix: Use security desc to get unique id (along with venue, type)
I'm guessing this typo went unnoticed because it didn't break the build
(another arg of the same was being used instead).
2025-01-03 16:59:07 +00:00
John Colvin da227a5550 Support synths at Binance, Binance USDS Futures, Deribit, and Okx 2025-01-03 16:59:07 +00:00
John Colvin 0c92cf3a87 Add double ops to IntPrice 2025-01-03 16:59:07 +00:00
John Colvin 1188af391e Add trivial fns to TimeStamp for convenience
* += and -= operators
* 'date' fn
* 'to_date_int' fn
2025-01-03 16:59:07 +00:00
John Colvin 0bb85cf915 refactor: Change month and day params from uint32 to uint8
They only need to hold values 1-12 and 1-31, respectively. A single byte
is more than sufficient. Also add ymdhms TimeStamp constructor.
2025-01-03 16:59:07 +00:00
John Colvin d77f5996fe cleanup: Make a couple TimeStamp fns const 2025-01-03 16:59:07 +00:00
John Colvin 940c41a274 Add int32 arithmetic operators to domain::Price 2025-01-03 16:59:07 +00:00
John Colvin e671960dc3 Add double arithmetic operators to domain::Price 2025-01-03 16:59:07 +00:00
John Colvin 8fa34b6b39 fix: Multiply additive factors by exponent in domain::Price
We must not have been using these operators because the implementation
was very broken (yet it doesn't seemed to have caused any bugs).
2025-01-03 16:59:07 +00:00
John Colvin f9d5429b5b cleanup: Remove unused code 2025-01-03 16:53:05 +00:00
Mohammad Arham 2c342482eb Merge branch 'development.crypto' of bitbucket.org:bluetradesys/spark into development.crypto 2025-01-02 15:30:13 -05:00
Mohammad Arham 3aefac26c2 fix: Timer condition was incorrect 2025-01-02 20:15:38 +00:00
John Colvin 1554594cdd diag: Throttle noisy log in Ladder 2025-01-02 12:15:22 -05:00
John Colvin 727a0f38b5 fix: Prevent arithmetic overflow when converting long to int in Ladder 2025-01-02 12:13:58 -05:00
John Colvin 7a0e8cdb26 fix: Properly format spread/synth leg qty in generated desc 2025-01-01 13:12:17 -05:00
John Colvin a4e97b04d7 fix: Don't propagate security criteria changes to other windows
Bugs (fixed):
  * Security criteria changes in mview and time/sales propagate to other
    windows of the same type.
2024-12-31 11:06:24 -05:00
John Colvin 463980a6ef Fix typo in get_binance_md.py 2024-12-29 18:37:54 +00:00
John Colvin 9b25857042 fix: Ensure "earliest_expiration" fn actually returns min exp
Previously, it assumed the first leg would have the earliest exp. While
this may be true for most securities, it isn't guarenteed by our data
model.
2024-12-29 13:26:44 -05:00
John Colvin ef19e7d76b fix: Don't assume all securities have expirations in pnl vm
Bugs (fixed):
  * PNL window crashes if data has Spots (i.e., securities without exps)
2024-12-29 13:17:17 -05:00
Taha Afzal 471faec2cb Added more etsts for fractional qtys 2024-12-28 08:31:16 +00:00
Taha Afzal ce96d42db8 Merging 2024-12-26 07:01:30 +00:00
Mohammad Arham 187894ca84 FIX: makes gateway factory work 2024-12-24 17:56:49 +00:00
John Colvin 63492c4575 fix: Remove erroneous assert in LadderRender 2024-12-21 23:24:52 -05:00
John Colvin e150c611f6 fix: Round fractional order qty to 6 decimal places
It was previously rounding to 2 decimal places, which isn't enough for
many crypto currencies (e.g., BTCUSDT at Binance)
2024-12-21 23:17:52 -05:00
John Colvin bb837d6c26 fix build: Trivial changes in DatabentoDataHandler 2024-12-22 04:00:23 +00:00
John Colvin 965e541ac8 Fix json structures and endpoints for Binance USDS Futures md 2024-12-22 04:00:23 +00:00
John Colvin 1b232aa610 feat: Add Binance USDS Futures execution 2024-12-22 04:00:23 +00:00
John Colvin 25439b094a improvement: Perform sec lookup in const time 2024-12-21 20:08:19 +00:00
John Colvin f927ef2c5e Add conf_json dir to spark data file tree
So we don't have to add proto files to the build for trivial config.
2024-12-21 20:08:19 +00:00
John Colvin d42389b75a Don't needlessly download cme config xml
When we aren't subscribing to cme md (i.e., no glbx symbols in spark
conf).
2024-12-21 20:08:19 +00:00
John Colvin 671cbcf03a Fix bts::Quantity string fmt so it includes fractional qty 2024-12-21 20:01:55 +00:00
John Colvin e589e23f41 Add py script to get md at binance
For quick/easy troubleshooting (much easier than doing stuff in c++)
2024-12-21 20:01:55 +00:00
John Colvin 11fadc0a3e Expose "run" fn in WebsocketClient
So it doesn't have to be hidden in a background thread
2024-12-21 20:01:55 +00:00
John Colvin b8c2d93866 Add ping/pong facilities to WebsocketClient 2024-12-21 20:01:55 +00:00
John Colvin 67a23dd196 Add open/close callbacks to WebsocketClient 2024-12-21 20:01:55 +00:00
John Colvin ff22c4eb5f diag: Change WebsocketClient log category to "Http"
A better fit than "Gen"
2024-12-21 20:01:55 +00:00
John Colvin 5addff4c50 cleanup: Remove redundant fn HttpRequest::perform
This was doing the same thing as HttpClient::send. I likely refactored
this function during development, then forgot to remove it.
2024-12-21 20:01:55 +00:00
John Colvin 142e1bd2da Add HttpMethod "DELETE"
In Binance's REST api, orders are canceled via DELETE requests.
2024-12-21 20:01:55 +00:00
John Colvin d05d91bbe7 diag: Log Http requests 2024-12-21 20:01:55 +00:00
Mohammad Arham 3a90ca9cb5 Add: Johns changes to sec oracle 2024-12-17 14:47:37 +00:00
John Colvin 85a46727be Improve c++ http client facilities 2024-12-11 19:28:36 +00:00
Mohammad Arham 624fd2c976 FIX: BUILD Error 2024-12-09 01:34:29 +00:00
Mohammad Arham 16d599d2d6 Add: OKX execution gateway connected 2024-12-08 20:14:16 -05:00
John Colvin c00e4fcb6b feat: Add Binance Coin Futures market data 2024-12-06 00:39:41 +00:00
John Colvin 03e19afe1d Fix qty display conf for BTC/ETH futs at Binance
Need to show 3 decimal places (qty tick size is 0.001)
2024-12-05 21:05:53 +00:00
385 changed files with 29347 additions and 22478 deletions

No files matched your search

+2 -2
View File
@@ -9,7 +9,7 @@
]
},
"fable": {
"version": "4.0.6",
"version": "4.24.0",
"commands": [
"fable"
]
@@ -27,4 +27,4 @@
]
}
}
}
}
+167 -11
View File
@@ -31,7 +31,24 @@
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/sparkd-debug-clang/server/sparkd",
"args": ["run"],
"args": [
"run"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/sparkd-debug-clang/server",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
},
{
"name": "spreader tests2",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/sparkd-debug-clang/server/sparkd",
"args": [
"test",
"[spreader2]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/sparkd-debug-clang/server",
"environment": [],
@@ -91,6 +108,18 @@
"stopAtEntry": false,
"console": "integratedTerminal"
},
{
"name": "Spark (Skip Build)",
"type": "coreclr",
"request": "launch",
"program": "",
"windows": {
"program": "Spark.exe",
"cwd": "build/Debug/bin/net7.0-windows",
},
"stopAtEntry": false,
"console": "integratedTerminal"
},
{
"name": "Spark (Parameterized)",
"type": "coreclr",
@@ -109,21 +138,138 @@
"console": "integratedTerminal"
},
{
"name": "Sparkd",
"name": "Spark Test",
"type": "coreclr",
"request": "launch",
"preLaunchTask": "Build Sparkd (Debug | Clang)",
"program": "",
"linux": {
"program": "sparkd",
"windows": {
"preLaunchTask": "Build Spark (Debug)",
"program": "Spark.Console.exe",
"cwd": "build/Debug/bin/net7.0",
"args": [
"test",
"${input:sparkTest}"
]
},
"args": [
"run"
],
"cwd": "build/sparkd-debug-clang/server",
"stopAtEntry": false,
"console": "integratedTerminal"
}
},
{
"name": "Spark Test (Skip Build)",
"type": "coreclr",
"request": "launch",
"program": "",
"windows": {
"program": "Spark.Console.exe",
"cwd": "build/Debug/bin/net7.0",
"args": [
"test",
"${input:sparkTest}"
]
},
"stopAtEntry": false,
"console": "integratedTerminal"
},
{
"name": "Sparkd",
"type": "cppdbg",
"request": "launch",
"program": "",
"linux": {
"preLaunchTask": "Build Sparkd (Debug)",
"program": "${workspaceFolder}/build/sparkd-debug-clang/server/sparkd",
"args": [
"run"
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build/sparkd-debug-clang/server",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
},
{
"name": "Sparkd (Skip Build)",
"type": "cppdbg",
"request": "launch",
"program": "",
"linux": {
"program": "${workspaceFolder}/build/sparkd-debug-clang/server/sparkd",
"args": [
"run"
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build/sparkd-debug-clang/server",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
},
{
"name": "Sparkd Test",
"type": "cppdbg",
"request": "launch",
"program": "",
"linux": {
"preLaunchTask": "Build Sparkd (Debug)",
"program": "${workspaceFolder}/build/sparkd-debug-clang/server/sparkd",
"args": [
"test",
"${input:sparkdTest}",
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build/sparkd-debug-clang/server",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
},
{
"name": "Sparkd Test (Skip Build)",
"type": "cppdbg",
"request": "launch",
"program": "",
"linux": {
"program": "${workspaceFolder}/build/sparkd-debug-clang/server/sparkd",
"args": [
"test",
"${input:sparkdTest}",
],
"stopAtEntry": false,
"cwd": "${workspaceFolder}/build/sparkd-debug-clang/server",
"environment": [],
"externalConsole": false,
"MIMode": "gdb",
"setupCommands": [
{
"description": "Enable pretty-printing for gdb",
"text": "-enable-pretty-printing",
"ignoreFailures": true
}
]
}
},
],
"inputs": [
{
@@ -154,5 +300,15 @@
"description": "Config Server URL",
"default": "http://localhost:8000/config",
},
{
"id": "sparkTest",
"type": "promptString",
"description": "Test to run",
},
{
"id": "sparkdTest",
"type": "promptString",
"description": "Test to run",
},
]
}
}
+41 -1
View File
@@ -641,6 +641,21 @@
"color": "terminal.ansiGreen",
}
},
{
"label": "Run Spark (Skip Build)",
"type": "process",
"command": "",
"windows": {
"command": "Spark.exe",
"options": {
"cwd": "${workspaceFolder}/build/${input:buildConfiguration}/bin/net7.0-windows"
},
},
"icon": {
"id": "run",
"color": "terminal.ansiGreen",
}
},
{
"label": "Run Spark Config Query",
"dependsOn": "Build Spark",
@@ -705,6 +720,26 @@
"color": "terminal.ansiGreen",
},
},
{
"label": "Test Spark (Debug)",
"dependsOn": "Build Spark (Debug)",
"type": "process",
"icon": {
"id": "coverage",
"color": "terminal.ansiYellow",
},
"command": "",
"windows": {
"command": "Spark.Console.exe",
"args": [
"test",
"${input:sparkTest}"
],
"options": {
"cwd": "${workspaceFolder}/build/Debug/bin/net7.0",
}
},
},
{
"label": "View DataStreamQueryAnalyzer Logs (Last Run)",
"type": "process",
@@ -823,6 +858,11 @@
"id": "sparkdConfigQuery",
"type": "promptString",
"description": "Config Type(s)"
}
},
{
"id": "sparkTest",
"type": "promptString",
"description": "Test to run",
},
]
}
+19 -4
View File
@@ -34,6 +34,7 @@ else()
set(BUILD_ADMIN_WEB_APP ON CACHE BOOL "Build the Admin WebApp")
endif()
list(APPEND CMAKE_PREFIX_PATH ${CMAKE_SOURCE_DIR}/cmake_modules)
include_directories(BEFORE SYSTEM ${SPARK_INCLUDE} ${EXTERNALS_ROOT}/include/zlib)
link_directories(${SPARK_LIB})
@@ -88,9 +89,15 @@ else()
add_compile_definitions(BINANCE_US_PRICE_STATS_PATH="/api/v3/ticker/24hr")
# ** Binance USDS Futures **
add_compile_definitions(CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE="https://dapi.binance.com")
add_compile_definitions(BINANCE_USDS_FUTURES_INSTRUMENTS_PATH="/dapi/v1/exchangeInfo")
add_compile_definitions(BINANCE_USDS_FUTURES_PRICE_STATS_PATH="/dapi/v1/ticker/24hr")
add_compile_definitions(CCAPI_BINANCE_USDS_FUTURES_URL_REST_BASE="https://fapi.binance.com")
add_compile_definitions(BINANCE_USDS_FUTURES_INSTRUMENTS_PATH="/fapi/v1/exchangeInfo")
add_compile_definitions(BINANCE_USDS_FUTURES_PRICE_STATS_PATH="/fapi/v1/ticker/24hr")
add_compile_definitions(BINANCE_USDS_FUTURES_USER_DATA_PATH="/api/v3/userDataStream")
# ** Binance Coin Futures **
add_compile_definitions(CCAPI_BINANCE_COIN_FUTURES_URL_REST_BASE="https://dapi.binance.com")
add_compile_definitions(BINANCE_COIN_FUTURES_INSTRUMENTS_PATH="/dapi/v1/exchangeInfo")
add_compile_definitions(BINANCE_COIN_FUTURES_PRICE_STATS_PATH="/dapi/v1/ticker/24hr")
# ** Deribit **
add_compile_definitions(DERIBIT_INSTRUMENT_PATH="/api/v2/public/get_instrument")
@@ -110,10 +117,18 @@ else()
# subdirs
if (BUILD_SPARKD)
# deribit_emumba deps
add_subdirectory(third_party/lib_flat_hash_map)
add_subdirectory(third_party/lib_spdlog)
add_subdirectory(src/lib)
add_subdirectory(src/lib_binance_execution)
add_subdirectory(src/lib_deribit_emumba)
add_subdirectory(src/server/sparkd)
add_subdirectory(src/data_files)
else()
add_subdirectory(src/lib)
endif()
add_subdirectory(src/lib)
if (BUILD_ADMIN_WEB_APP)
add_subdirectory(src/Spark.Admin.WebApp)
endif()
+1 -10
View File
@@ -302,16 +302,7 @@
"lhs": "${hostSystemName}",
"rhs": "Linux"
},
"hidden": true,
"targets": [
"data_files_dir",
"admin_web_app_bundle",
"install",
"libspark",
"rapidjson_project",
"server_layout",
"sparkd"
]
"hidden": true
},
{
+34
View File
@@ -0,0 +1,34 @@
include_guard(GLOBAL)
include(${CMAKE_SOURCE_DIR}/cmake/SetFirstNonEmpty.cmake)
function(git_version_tag)
set(_options)
set(_one_value_args RESULT DEFAULT)
set(_multi_value_args)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
set(_result "${_ARGS_RESULT}")
if (_result STREQUAL "")
foreach(_arg ${ARGN})
set(_result ${_arg})
break()
endforeach()
if (_result STREQUAL "")
set(_result "${PROJECT_NAME}_VERSION")
endif()
endif()
find_package(Git QUIET)
if(GIT_FOUND)
execute_process(
COMMAND ${GIT_EXECUTABLE} describe --tags --always --dirty
WORKING_DIRECTORY ${CMAKE_SOURCE_DIR}
OUTPUT_VARIABLE ${_result}
OUTPUT_STRIP_TRAILING_WHITESPACE)
endif()
if("${${_result}}" STREQUAL "")
set_first_non_empty(${_result} "${_ARGS_DEFAULT}" "0.0.0")
endif()
set(${_result} "${${_result}}" PARENT_SCOPE)
message("GIT VERSION: ${_result} = ${${_result}}")
endfunction()
+61
View File
@@ -0,0 +1,61 @@
include_guard(DIRECTORY)
include(GNUInstallDirs)
include(${CMAKE_SOURCE_DIR}/cmake/PackBasic.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/SetFirstDefined.cmake)
function(install_basic)
set(_options)
set(_one_value_args NAME INCLUDE_DIR BUILD_INCLUDE_DIR VERSION)
set(_multi_value_args)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
set_first_defined(_name _ARGS_NAME PROJECT_NAME)
set_first_defined(_include_dir _ARGS_INCLUDE_DIR _name)
set_first_defined(_build_include_dir _ARGS_BUILD_INCLUDE_DIR _name)
set(_base_dirs)
# Look for headers in source dir and build dir
set(_headers)
if (_include_dir)
list(APPEND _base_dirs "${CMAKE_CURRENT_SOURCE_DIR}")
file(
GLOB_RECURSE _headers
${CMAKE_CURRENT_SOURCE_DIR}/${_include_dir}/*.h
${CMAKE_CURRENT_SOURCE_DIR}/${_include_dir}/*.hpp
)
endif()
set(_build_headers)
if(_build_include_dir)
list(APPEND _base_dirs "${CMAKE_CURRENT_BINARY_DIR}")
file(
GLOB_RECURSE _build_headers
${CMAKE_CURRENT_BINARY_DIR}/${_build_include_dir}/*.h
${CMAKE_CURRENT_BINARY_DIR}/${_build_include_dir}/*.hpp
)
endif()
target_sources(
${_name}
PUBLIC
FILE_SET HEADERS
BASE_DIRS ${_base_dirs}
FILES
${_headers}
${_build_headers}
)
install(
TARGETS ${_name}
EXPORT ${_name}Targets
RUNTIME DESTINATION ${CMAKE_INSTALL_BINDIR}
LIBRARY DESTINATION ${CMAKE_INSTALL_LIBDIR}
ARCHIVE DESTINATION ${CMAKE_INSTALL_LIBDIR}
FILE_SET HEADERS DESTINATION ${CMAKE_INSTALL_INCLUDEDIR}
)
install(
EXPORT ${_name}Targets
FILE ${_name}Targets.cmake
NAMESPACE ${_name}::
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${_name})
pack_basic(NAME ${_name} VERSION "${_ARGS_VERSION}")
endfunction()
+34
View File
@@ -0,0 +1,34 @@
include_guard(DIRECTORY)
include(CMakePackageConfigHelpers)
include(${CMAKE_SOURCE_DIR}/cmake/GitVersionTag.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/SetFirstDefined.cmake)
function(pack_basic)
set(_options)
set(_one_value_args NAME VERSION)
set(_multi_value_args)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
set_first_defined(_name _ARGS_NAME PROJECT_NAME)
set(_version "${_ARGS_VERSION}")
if (NOT _ARGS_VERSION)
git_version_tag(_version)
endif()
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/${_name}ConfigVersion.cmake"
VERSION ${_version}
COMPATIBILITY AnyNewerVersion
)
configure_package_config_file(
"${CMAKE_CURRENT_SOURCE_DIR}/Config.cmake.in"
"${CMAKE_CURRENT_BINARY_DIR}/${_name}Config.cmake"
INSTALL_DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${_name}
)
install(
FILES
"${CMAKE_CURRENT_BINARY_DIR}/${_name}Config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/${_name}ConfigVersion.cmake"
DESTINATION ${CMAKE_INSTALL_LIBDIR}/cmake/${_name})
endfunction()
+49
View File
@@ -0,0 +1,49 @@
include_guard(DIRECTORY)
function(protobuf_generate_fs)
set(_options)
set(_one_value_args TARGET_NAME OUT_DIR PROTOC)
set(_multi_value_args PROTO_INCLUDE_DIRS PROTO_SOURCES)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
if (NOT DEFINED _ARGS_TARGET_NAME)
set(_ARGS_TARGET_NAME "${PROJECT_NAME}_generate_fs_protos")
endif()
if (NOT DEFINED _ARGS_PROTOC)
set(_ARGS_PROTOC "${SPARK_BIN}/protoc")
endif()
set(_proto_include_cli_args)
foreach(_dir ${_ARGS_PROTO_INCLUDE_DIRS})
list(APPEND _proto_include_cli_args -I ${_dir})
endforeach()
set(_outputs)
foreach(_proto_source ${_ARGS_PROTO_SOURCES})
# get_filename_component(_abs_proto_source ${_proto_source} ABSOLUTE)
get_filename_component(_proto_source_we ${_proto_source} NAME_WE)
# get_filename_component(_proto_source_dir ${_proto_source} DIRECTORY)
list(APPEND _outputs ${_ARGS_OUT_DIR}/${_proto_source_we}.fable.fs)
endforeach()
set(_venv_exec ${CMAKE_SOURCE_DIR}/tools/venv_exec.sh)
set(_plugin_py ${CMAKE_SOURCE_DIR}/src/lib/api/service_compiler/plugin.py)
set(_template_fs ${CMAKE_SOURCE_DIR}/src/lib/api/service_compiler/templates/fs/fable.fs)
add_custom_command(
OUTPUT ${_outputs}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND ${_venv_exec}
${_ARGS_PROTOC}
--plugin=protoc-gen-service=${_plugin_py}
--service_out=lang=fs,strip_out_path=1:${_ARGS_OUT_DIR}
${_proto_include_cli_args}
${_ARGS_PROTO_SOURCES}
DEPENDS
${_venv_exec}
${_plugin_py}
${_template_fs}
${CMAKE_CURRENT_SOURCE_DIR}/package-lock.json
${_ARGS_PROTO_SOURCES}
)
add_custom_target(${_ARGS_TARGET_NAME} ALL DEPENDS "${_outputs}")
endfunction()
+33
View File
@@ -0,0 +1,33 @@
include_guard(DIRECTORY)
function(protobuf_generate_js)
set(_options)
set(_one_value_args TARGET_NAME OUTPUT)
set(_multi_value_args PROTO_INCLUDE_DIRS PROTO_SOURCES)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
if (NOT DEFINED _ARGS_TARGET_NAME)
set(_ARGS_TARGET_NAME "${PROJECT_NAME}_generate_js_protos")
endif()
set(_proto_include_cli_args)
foreach(_dir ${_ARGS_PROTO_INCLUDE_DIRS})
list(APPEND _proto_include_cli_args -p ${_dir})
endforeach()
add_custom_command(
OUTPUT ${_ARGS_OUTPUT}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND npx
--no-install pbjs
-t json-module
-w commonjs
-o ${_ARGS_OUTPUT}
${_proto_include_cli_args}
${_ARGS_PROTO_SOURCES}
DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/package-lock.json
${_ARGS_PROTO_SOURCES}
)
add_custom_target(${_ARGS_TARGET_NAME} ALL DEPENDS ${_ARGS_OUTPUT})
endfunction()
+10
View File
@@ -0,0 +1,10 @@
include_guard(GLOBAL)
macro(set_first_defined RESULT)
foreach(_arg ${ARGN})
if (DEFINED ${_arg})
set(${RESULT} ${${_arg}})
break()
endif()
endforeach()
endmacro()
+10
View File
@@ -0,0 +1,10 @@
include_guard(GLOBAL)
macro(set_first_non_empty RESULT)
foreach(_arg ${ARGN})
if (NOT "${_arg}" STREQUAL "")
set(${RESULT} ${_arg})
break()
endif()
endforeach()
endmacro()
+49
View File
@@ -0,0 +1,49 @@
include_guard(DIRECTORY)
include(${CMAKE_SOURCE_DIR}/cmake/TernaryOperator.cmake)
function(sym_link_dir)
set(_options)
set(_one_value_args TARGET_NAME SOURCE DEST COMMENT)
set(_multi_value_args)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
add_custom_command(
OUTPUT ${_ARGS_DEST}
COMMAND ln ARGS -sf ${_ARGS_SOURCE} ${_ARGS_DEST}
)
set_ternary(_comment _ARGS_COMMENT "${_ARGS_COMMENT}" "linking dir ${_ARGS_SOURCE} -> ${_ARGS_DEST}")
add_custom_target(
${_ARGS_TARGET_NAME} ALL
DEPENDS ${_ARGS_DEST}
COMMENT "${_comment}"
)
endfunction()
function(sym_link_file)
set(_options)
set(_one_value_args SOURCE DEST INSTALL_DEST)
set(_multi_value_args)
cmake_parse_arguments(_ARGS "${_options}" "${_one_value_args}" "${_multi_value_args}" ${ARGN})
file(
CREATE_LINK
${_ARGS_SOURCE}
${_ARGS_DEST}
SYMBOLIC
)
if (DEFINED _ARGS_INSTALL_DEST)
install(
FILES
${_ARGS_SOURCE}
DESTINATION ${_ARGS_INSTALL_DEST}
)
endif()
endfunction()
function(sym_link_local_lib LIB_NAME)
set(_lib_file_name "${CMAKE_SHARED_LIBRARY_PREFIX}${LIB_NAME}.so")
file(
CREATE_LINK
"${CMAKE_BINARY_DIR}/src/lib_${LIB_NAME}/${_lib_file_name}"
"${CMAKE_CURRENT_BINARY_DIR}/${_lib_file_name}"
SYMBOLIC
)
endfunction()
+9
View File
@@ -0,0 +1,9 @@
include_guard(GLOBAL)
macro(set_ternary RESULT CONDITION TRUE_VALUE FALSE_VALUE)
if(${CONDITION})
set(${RESULT} ${TRUE_VALUE})
else()
set(${RESULT} ${FALSE_VALUE})
endif()
endmacro()
+14
View File
@@ -0,0 +1,14 @@
include(ExternalProject)
if(NOT TARGET flathashmap_project)
ExternalProject_Add(flathashmap_project
GIT_REPOSITORY https://github.com/skarupke/flat_hash_map.git
PREFIX ${CMAKE_CURRENT_BINARY_DIR}/flathashmap
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
)
endif()
ExternalProject_Get_Property(flathashmap_project SOURCE_DIR)
set(flathashmap_INCLUDE_DIR ${SOURCE_DIR})
@@ -0,0 +1,35 @@
include(ExternalProject)
include(GNUInstallDirs)
if(NOT TARGET websocket-library_project)
ExternalProject_Add(
websocket-library_project
GIT_REPOSITORY
https://fintech.websocket:h_ubh-4dsWRB569wwKyg@gitlab.com/cryptoexchanges1/websocket-client-using-epoll.git
GIT_TAG enhancement/config-ssl
CMAKE_GENERATOR "Unix Makefiles"
CMAKE_ARGS
-DCMAKE_INSTALL_PREFIX=${CMAKE_INSTALL_PREFIX}
-DCMAKE_BUILD_TYPE=Release
-DLOG_LEVEL=INFO
-DENABLE_ENCRYPTION=True
BUILD_BYPRODUCTS
"${CMAKE_CURRENT_BINARY_DIR}/websocket-library_project-prefix/src/websocket-library_project-build/src/libemumba-websocket-library.a"
)
endif()
ExternalProject_Get_Property(websocket-library_project BINARY_DIR)
ExternalProject_Get_Property(websocket-library_project SOURCE_DIR)
set(websocket-library_INCLUDE_DIR ${SOURCE_DIR}/include)
set(websocket-library_LIB_DIR ${BINARY_DIR}/src)
add_library(websocket-library STATIC IMPORTED)
set_property(
TARGET websocket-library
PROPERTY IMPORTED_LOCATION
${websocket-library_LIB_DIR}/libemumba-websocket-library.a
)
add_dependencies(websocket-library websocket-library_project)
install(
FILES ${websocket-library_LIB_DIR}/libemumba-websocket-library.a
DESTINATION ${CMAKE_INSTALL_LIBDIR}
)
@@ -23,7 +23,6 @@
<PackageReference Include="MongoDB.Driver" Version="2.23.1" />
<PackageReference Include="Parquet.Net" Version="5.0.1" />
<PackageReference Include="System.Data.SQLite" Version="1.0.118" />
<PackageReference Include="MathNet.Numerics" Version="5.0.0" />
</ItemGroup>
</Project>
@@ -4,46 +4,42 @@ namespace bts.SilverPine {
using System;
using System.Collections.Generic;
using System.Linq;
//using MathNet.Numerics.Statistics;
using ZstdSharp.Unsafe;
public enum MultiRowOp {
public enum GroupByBundleOp {
Mean,
Median,
Mode,
Range,
StdDev,
Max,
Min,
First,
Last,
Sum,
EdgeDiff,
EdgeDiffPercentage,
//IsEdgeDiff,
Sum
}
public class MultiRowOpHelper {
public readonly List<Tuple<string, MultiRowOp>> operations;
public class GroupByBundle {
public readonly List<Tuple<string, GroupByBundleOp>> operations;
public static MultiRowOpHelper parse(string text) {
public static GroupByBundle parse(string text) {
// text is inp_col: op, inp_col: op, inp_col:op
List<Tuple<string, MultiRowOp>> rv = new List<Tuple<string, MultiRowOp>>();
List<Tuple<string, GroupByBundleOp>> rv = new List<Tuple<string, GroupByBundleOp>>();
string[] calcs = text.Split(',');
foreach (string c in calcs) {
string[] toks = c.Split(':');
string inp_col = toks[0].Trim();
string op_txt = toks[1].Trim();
MultiRowOp op = Enum.Parse<MultiRowOp>(op_txt, true);
GroupByBundleOp op = Enum.Parse<GroupByBundleOp>(op_txt, true);
rv.Add(Tuple.Create(inp_col, op));
}
return new MultiRowOpHelper(rv);
return new GroupByBundle(rv);
}
public MultiRowOpHelper(List<Tuple<string, MultiRowOp>> operations_) {
public GroupByBundle(List<Tuple<string, GroupByBundleOp>> operations_) {
operations = operations_;
}
public static IBlueRow group_by(List<IBlueRow> rows, MultiRowOpHelper parameters) {
public static IBlueRow group_by(List<IBlueRow> rows, GroupByBundle parameters) {
if (rows.Count() == 0) {
return null;
}
@@ -51,8 +47,8 @@ namespace bts.SilverPine {
IBlueRow ir = rows.ElementAt(0);
IBlueTableSchema in_schema = ir.schema;
IBlueTableSchema out_schema = in_schema;
IDictionary<string, Tuple<string, MultiRowOp>> out_col_map =
new Dictionary<string, Tuple<string, MultiRowOp>>();
IDictionary<string, Tuple<string, GroupByBundleOp>> out_col_map =
new Dictionary<string, Tuple<string, GroupByBundleOp>>();
foreach (var t in parameters.operations) {
string out_col_name = $"{t.Item1}_{t.Item2}".ToLower();
out_schema = out_schema.add_column(TypeCode.Double, out_col_name);
@@ -62,7 +58,7 @@ namespace bts.SilverPine {
foreach (var kv in out_col_map) {
string out_col_name = kv.Key;
string in_col_name = kv.Value.Item1;
MultiRowOp op = kv.Value.Item2;
GroupByBundleOp op = kv.Value.Item2;
IEnumerable<double> col_vals = BlueDataUtility.get_colvalues<double>(rows, in_col_name);
double comp_res = compute_op(col_vals, op);
or.setValue(out_col_name, comp_res);
@@ -70,51 +66,20 @@ namespace bts.SilverPine {
return or;
}
// rolling_rows are the rolling window of rows. the 0th row is the one thats gettin
// calculated. rows 1 - n-1 are its window rows. the schema is based on the operations.
public IBlueRow rolling_calc(List<IBlueRow> rolling_rows) {
if (rolling_rows.Count() == 0) {
return null;
}
IBlueRow ir = rolling_rows.ElementAt(0);
IBlueTableSchema in_schema = ir.schema;
IBlueTableSchema out_schema = in_schema;
IDictionary<string, Tuple<string, MultiRowOp>> out_col_map =
new Dictionary<string, Tuple<string, MultiRowOp>>();
foreach (var t in operations) {
string out_col_name = $"{t.Item1}_{t.Item2}".ToLower();
out_schema = out_schema.add_column(TypeCode.Double, out_col_name);
out_col_map[out_col_name] = t;
}
MutableBlueRow or = new MutableBlueRow(out_schema, ir);
foreach (var kv in out_col_map) {
string out_col_name = kv.Key;
string in_col_name = kv.Value.Item1;
MultiRowOp op = kv.Value.Item2;
IEnumerable<double> col_vals = BlueDataUtility.get_colvalues<double>(rolling_rows, in_col_name);
double comp_res = compute_op(col_vals, op);
or.setValue(out_col_name, comp_res);
}
return or;
}
public static double compute_op(IEnumerable<double> col_vals, MultiRowOp op) {
public static double compute_op(IEnumerable<double> col_vals, GroupByBundleOp op) {
switch (op) {
case MultiRowOp.Max:
case GroupByBundleOp.Max:
return col_vals.Max<double>();
case MultiRowOp.Min:
case GroupByBundleOp.Min:
return col_vals.Min<double>();
case MultiRowOp.Mean:
case GroupByBundleOp.Mean:
return col_vals.Sum() / col_vals.Count();
case MultiRowOp.Sum:
case GroupByBundleOp.Sum:
return col_vals.Sum();
case MultiRowOp.First:
case GroupByBundleOp.First:
return col_vals.First();
case MultiRowOp.Last:
case GroupByBundleOp.Last:
return col_vals.Last();
case MultiRowOp.StdDev:
return MathNet.Numerics.Statistics.Statistics.StandardDeviation(col_vals);
default:
// TODO
Log.assert(false);
@@ -1,20 +0,0 @@
namespace bts.SilverPine {
using BCG;
using System;
[DataStreamUserRespresentation("AggregationStream")]
public class AgregationStream : ViewStream {
public AgregationStream(ViewStream parent_str, string operation_txt) {
ViewStream rs = new NonIncGroupByStream(parent_str, String.Empty, operation_txt);
mySetRealSource(rs);
}
public AgregationStream(ViewStream parent_str, string groupby_col, string operation_txt) {
ViewStream rs = new NonIncGroupByStream(parent_str, groupby_col, operation_txt);
mySetRealSource(rs);
}
}
}
@@ -8,7 +8,7 @@ using bts;
using bts.SilverPine;
namespace BCG {
[DataStreamUserRespresentation("AggregateStream")]
[DataStreamUserRespresentation("aggregate")]
public class NonIncGroupByStream : ViewStream {
private class DelNonIncGroupByEvaluator : INonIncGroupByEvaluator {
Func<string[]> _groupby_cols_func;
@@ -53,18 +53,15 @@ namespace BCG {
Func<List<IBlueRow>, List<IBlueRow>> evaluate_func)
: this(main_stream, new DelNonIncGroupByEvaluator(groupby_cols_func, evaluate_func)) { }
public NonIncGroupByStream(ViewStream parent_str, string groupby_col, string standard_group_by_text)
: this(parent_str, groupby_col, standard_group_by_text, String.Empty) { }
public NonIncGroupByStream(ViewStream parent_str, string groupby_col, string standard_group_by_text, string optional_sort_col) {
MultiRowOpHelper std_group_by = MultiRowOpHelper.parse(standard_group_by_text);
public NonIncGroupByStream(ViewStream parent_str, string groupby_col, string standard_group_by_text, string optional_sort_col = null) {
GroupByBundle std_group_by = GroupByBundle.parse(standard_group_by_text);
Func<string[]> groupby_cols_func = () => {
return String.IsNullOrEmpty(groupby_col) ? null : new string[] { groupby_col };
};
Func<List<IBlueRow>, List<IBlueRow>> evaluate_func = (group_rows) => {
if (!String.IsNullOrEmpty(optional_sort_col))
group_rows.Sort((r1, r2) => BlueDataUtility.compare_rows(r2, r1, optional_sort_col));
IBlueRow rv = MultiRowOpHelper.group_by(group_rows, std_group_by);
IBlueRow rv = GroupByBundle.group_by(group_rows, std_group_by);
return new IBlueRow[] { rv }.ToList();
};
ViewStream rs = new NonIncGroupByStream(parent_str, groupby_cols_func, evaluate_func);
@@ -69,6 +69,4 @@ namespace bts {
myFireEvent(dp_out);
}
}
}
@@ -13,8 +13,9 @@ namespace BCG {
/// desired row ie newRow = f(row), where f is the mapping fucntion. Note that the id
/// is preserved across the rows, ie row["id"] = f(row)["id"]
/// </summary>
[DataStreamUserRespresentation(false)]
public class MapStream : MethodDrivenStream {
[DataStreamUserRespresentation (false)]
public class MapStream : MethodDrivenStream
{
protected IStreamMapper myMapper;
protected IChangeableStreamMapper myChangeableMapper = null;
private bool myUseNewMap = Configuration.get<DataStreamConfig>().UseNewMap;
@@ -1,14 +0,0 @@
namespace bts.SilverPine
{
using BCG;
[DataStreamUserRespresentation("RollingComputationStream")]
public class RollingComputationStream : ViewStream
{
private ViewStream _parent_str;
public RollingComputationStream(ViewStream parent_str, string operation_txt, string roll_column, uint window_sz)
{
}
}
}
@@ -1,10 +0,0 @@
namespace bts.SilverPine {
using BCG;
[DataStreamUserRespresentation("RollingComputationStream")]
public class RollingComputationStream : ViewStream {
public RollingComputationStream(ViewStream parent_str, string operation_txt, string roll_column, uint window_sz) {
}
}
}
@@ -108,7 +108,6 @@ namespace bts {
}
[DataStreamUserRespresentation("Project")]
public class NewProjectStream : ViewStream, IStreamMapper {
private ViewStream _stream;
@@ -1,15 +1,18 @@
using System;
using System.Collections.Generic;
using mbts;
namespace BCG {
internal class MutableAppendTable : IBlueRowCollection {
private class MyRow : IBlueRow {
namespace BCG
{
internal class MutableAppendTable : IBlueRowCollection
{
private class MyRow : IBlueRow
{
private IBlueRow myRow;
private int myID;
public MyRow(IBlueRow r, int id) {
public MyRow(IBlueRow r, int id)
{
myRow = r;
myID = id;
}
@@ -18,8 +21,10 @@ namespace BCG {
public IBlueTableSchema schema { get { return myRow.schema; } }
public object this[int index] {
get {
public object this[int index]
{
get
{
if (myRow.schema[index].colName == "id")
return myID;
else
@@ -47,17 +52,20 @@ namespace BCG {
public System.Collections.ICollection Keys { get { return myRow.Keys; } }
public void Remove(object key) { throw new Exception("The method or operation is not implemented."); }
public void Remove(object key) {throw new Exception("The method or operation is not implemented.");}
public System.Collections.ICollection Values {
get {
public System.Collections.ICollection Values
{
get
{
object[] vals = new object[myRow.Count];
CopyTo(vals, 0);
return vals;
}
}
public object this[object key] {
public object this[object key]
{
get { return key is string ? this[key as string] : this[(int)key]; }
set { throw new Exception("The method or operation is not implemented."); }
}
@@ -66,7 +74,8 @@ namespace BCG {
#region ICollection Members
public void CopyTo(Array array, int index) {
public void CopyTo(Array array, int index)
{
myRow.CopyTo(array, index);
array.SetValue(myID, index + myRow.schema["id"].colNo);
}
@@ -81,7 +90,8 @@ namespace BCG {
#region IEnumerable Members
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new BlueRowEnumerator(this); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
{ return new BlueRowEnumerator(this); }
#endregion
}
@@ -96,7 +106,8 @@ namespace BCG {
public MutableAppendTable(IBlueTableSchema schema) { myRows = new BlueTable(schema); }
public IBlueRow addRow(IBlueRow r, int tableNo) {
public IBlueRow addRow(IBlueRow r, int tableNo)
{
if (!myIDMap.ContainsKey(tableNo))
myIDMap.Add(tableNo, new Dictionary<int, IBlueRow>());
IBlueRow nr = new MyRow(r, myID++); // BlueDataUtility.getNewReplacedRow(r, myID++, "id");
@@ -105,17 +116,20 @@ namespace BCG {
return nr;
}
public IBlueRow removeRow(IBlueRow r, int tableNo) {
public IBlueRow removeRow(IBlueRow r, int tableNo)
{
IBlueRow dr = myIDMap[tableNo][(int)r["id"]];
myRows.deleteRow(dr);
myIDMap[tableNo].Remove((int)r["id"]);
return dr;
}
public IBlueRowCollection removeTable(int tableNo) {
public IBlueRowCollection removeTable(int tableNo)
{
if (!myIDMap.ContainsKey(tableNo))
return null;
else {
else
{
BlueTable rv = new BlueTable(myRows.schema);
foreach (IBlueRow r in myIDMap[tableNo].Values)
rv.addRow(r);
@@ -125,7 +139,8 @@ namespace BCG {
}
}
public void clear() {
public void clear()
{
myRows.clear();
myIDMap.Clear();
}
@@ -136,7 +151,7 @@ namespace BCG {
public IBlueTableSchema schema { get { return myRows.schema; } }
public bool containsID(int id) { return myRows.containsID(id); }
public bool containsID(int id) {return myRows.containsID(id);}
#endregion
@@ -154,7 +169,7 @@ namespace BCG {
#region IEnumerable Members
public System.Collections.IEnumerator GetEnumerator() { return myRows.GetEnumerator(); }
public System.Collections.IEnumerator GetEnumerator() {return myRows.GetEnumerator();}
#endregion
}
@@ -164,8 +179,8 @@ namespace BCG {
/// to append (or remove) more streams at
/// runtime
/// </summary>
[DataStreamUserRespresentation("UnionStream")]
public class MutableAppendStream : ViewStream {
public class MutableAppendStream : ViewStream
{
private bool mySubscriptionActive = false;
private MutableAppendTable myTable;
private int myMovingIndex;
@@ -173,17 +188,22 @@ namespace BCG {
private bool _allign_col_orders = true;
public MutableAppendStream(params ViewStream[] streams)
: this(new List<ViewStream>(streams)) { }
: this(new List<ViewStream>(streams))
{ }
public MutableAppendStream(bool allign_col_order, params ViewStream[] streams)
: this(allign_col_order, new List<ViewStream>(streams)) { }
: this(allign_col_order, new List<ViewStream>(streams))
{ }
public MutableAppendStream(ICollection<ViewStream> streams)
: this(true, streams) { }
: this(true, streams)
{ }
public MutableAppendStream(bool allign_col_orders, ICollection<ViewStream> streams) {
public MutableAppendStream(bool allign_col_orders, ICollection<ViewStream> streams)
{
_allign_col_orders = allign_col_orders;
foreach (ViewStream vs in streams) {
foreach (ViewStream vs in streams)
{
myMovingIndex++;
ViewStream pj = new ChangeTableNameStream(vs, myMovingIndex.ToString());
if (_allign_col_orders)
@@ -192,7 +212,8 @@ namespace BCG {
}
}
public void addStream(ViewStream vs) {
public void addStream(ViewStream vs)
{
myMovingIndex++;
///the change name is done to identify the callbacks, and the project to
///make all the schemas col orders the same
@@ -204,14 +225,19 @@ namespace BCG {
pj.onChange += new ChangeDelegate(myHandleStreamChanges);
}
public void removeStream(ViewStream vs) {
public void removeStream(ViewStream vs)
{
int index = -1;
foreach (KeyValuePair<int, Pair<ViewStream, ViewStream>> p in myStreamIndex) {
if (p.Value.first == vs) {
foreach (KeyValuePair<int, Pair<ViewStream, ViewStream>> p in myStreamIndex)
{
if (p.Value.first == vs)
{
index = p.Key;
if (mySubscriptionActive) {
if (mySubscriptionActive)
{
p.Value.second.onChange -= new ChangeDelegate(myHandleStreamChanges);
if (myTable != null) {
if (myTable != null)
{
IBlueRowCollection delRows = myTable.removeTable(p.Key);
if (delRows != null)
myFireEvent(new DataPacket(myTable, new BlueTable(myTable.schema), delRows));
@@ -224,13 +250,15 @@ namespace BCG {
}
}
protected override void myOnFirstSubscriber() {
protected override void myOnFirstSubscriber()
{
mySubscriptionActive = true;
foreach (KeyValuePair<int, Pair<ViewStream, ViewStream>> p in myStreamIndex)
p.Value.second.onChange += new ChangeDelegate(myHandleStreamChanges);
}
protected override void myOnLastSubscriber() {
protected override void myOnLastSubscriber()
{
mySubscriptionActive = false;
foreach (KeyValuePair<int, Pair<ViewStream, ViewStream>> p in myStreamIndex)
p.Value.second.onChange -= new ChangeDelegate(myHandleStreamChanges);
@@ -238,17 +266,20 @@ namespace BCG {
myTable.clear();
}
private void myHandleStreamChanges(object newValue) {
private void myHandleStreamChanges(object newValue)
{
DataPacket dp = newValue as DataPacket;
myTable = myTable ?? new MutableAppendTable(new BlueTableSchema("MutableAppend", dp.schema.columnInfo));
BlueTable adds = new BlueTable(myTable.schema),
dels = new BlueTable(myTable.schema);
int index = Int32.Parse(dp.schema.tableName);
foreach (IBlueRow r in dp.deletedRows) {
foreach (IBlueRow r in dp.deletedRows)
{
IBlueRow dr = myTable.removeRow(r, index);
dels.addRow(dr);
}
foreach (IBlueRow r in dp.addedRows) {
foreach (IBlueRow r in dp.addedRows)
{
IBlueRow nr = myTable.addRow(r, index);
adds.addRow(nr);
}
@@ -148,27 +148,14 @@ namespace bts.SilverPine {
[DataStreamUserRespresentation("FutureHistoricalBars")]
public class FutureHistoricalBarsStream : ViewStream {
public FutureHistoricalBarsStream(string fut_contract, string bar_size_txt, string range_beg, string range_end) {
DateTime dt_range_beg = DateTime.Parse(range_beg);
DateTime dt_range_end = DateTime.Parse(range_end);
TimeSpan diff = dt_range_end - dt_range_beg;
BarSize bar_size = Enum.Parse<BarSize>(bar_size_txt, true);
ViewStream rs = new FutureHistoricalBarsStream(fut_contract, bar_size.ToString(), dt_range_beg, dt_range_end);
mySetRealSource(rs);
}
public FutureHistoricalBarsStream(string fut_contract, string range_beg, string range_end) {
DateTime dt_range_beg = DateTime.Parse(range_beg);
DateTime dt_range_end = DateTime.Parse(range_end);
TimeSpan diff = dt_range_end - dt_range_beg;
BarSize bar_size = diff < TimeSpan.FromDays(1.0) ? BarSize.ONE_DAY : BarSize.ONE_MIN;
BarSize bar_size = diff < TimeSpan.FromDays(1.0) ? BarSize.ONE_MIN : BarSize.ONE_DAY;
ViewStream rs = new FutureHistoricalBarsStream(fut_contract, bar_size.ToString(), dt_range_beg, dt_range_end);
mySetRealSource(rs);
}
public FutureHistoricalBarsStream(string fut_contract, string bar_size)
: this(fut_contract, bar_size, DateTime.MinValue, DateTime.MaxValue) { }
public FutureHistoricalBarsStream(string fut_contract, string bar_size,
DateTime dt_range_beg, DateTime dt_range_end)
:
@@ -43,11 +43,4 @@ namespace bts.SilverPine {
mySetRealSource(r);
}
}
[DataStreamUserRespresentation("PeriodicVolumeAgg")]
public class PeriodicVolumeAggregationStream : ViewStream {
public PeriodicVolumeAggregationStream(string future_contract, string contract_type, DateTime range_beg, DateTime range_end,
TimeSpan period, ViewStreamDatabase db) {
}
}
}
@@ -100,9 +100,9 @@ namespace bts.SilverPine {
this(symbol_or_contract, beg_dt, end_dt, ViewStreamDatabase.instance) { }
public VWAPStream(string symbol_or_contract, DateTime beg_dt, DateTime end_dt, ViewStreamDatabase db) {
//var fc = new ContractUtils.FutureContract(symbol_or_contract);
ViewStream r = new FutureHistoricalBarsStream(symbol_or_contract, beg_dt.ToString(), end_dt.ToString());
// since this is already filtered, we can groupBy iit without a groupBy column
var fc = new ContractUtils.FutureContract(symbol_or_contract);
ViewStream r = new FutureHistoricalBarsStream(fc, BarSize.ONE_DAY, new DateTimeRange(beg_dt, end_dt));
r = new MathStream(r,
"vprice = volume * close");
r = new NonIncGroupByStream(r,
@@ -90,15 +90,20 @@ namespace bts.SilverPine {
// the argument is symbol, like "ES" etc and not the contract itself
public FuturesContinousContractStream(string symbol) : this(symbol, ViewStreamDatabase.instance) { }
public FuturesContinousContractStream(string symbol, ViewStreamDatabase db) {
symbol = symbol.EndsWith("*") ? symbol : symbol + "*";
ViewStream r = new FuturesHistorical1DayBarsStream(symbol);
r = new ContractExpanderStream(r, "symbol");
r = new FilterStream(r, "contract_type='Future'");
// finding the max volume across symbols, if we need to do this for open_interest, then join here
// with the open interest stream on symbol/contract
r = new NonIncGroupByStream(r, "ts_event", "volume:Max");
r = new NewProjectStream(r, "ts_event symbol !");
r = new SortStream(r, "-ts_event");
// filtering for futures only
r = new FilterStream(r, r => {
string contract = r.get<string>("symbol");
var fc = new ContractUtils.FutureContract(contract);
return fc.future_tradable_contract != null;
});
r = new NonIncGroupByStream(r,
"ts_event",
"volume:Max");
r = new NewProjectStream(r,
"ts_event symbol !");
r = new SortStream(r,
"-ts_event");
mySetRealSource(r);
}
}
@@ -2,14 +2,15 @@ namespace bts.SilverPine {
using bts;
using BCG;
// it uses the volume (better to use open interest perhap) to detect the rollover, ie when a new
// future exp becomes the highest volume one
// it uses the volume - better to use open interst perhap - to detect the rollover, is when a new
// futuere exp becomes the highest volume one
[DataStreamUserRespresentation("FuturesRoll")]
public class FuturesRollStream : ViewStream {
public FuturesRollStream(string future_symbol) {
ViewStream rs = new FuturesContinousContractStream(future_symbol);
rs = new ColumnEvolutionStream(rs, "ts_event", "symbol");
rs = new NewProjectStream(rs, "symbol ts_event:roll_date !");
//ViewStream ohlcv_str = new OHLCVStream(future_symbol);
ViewStream rs = new FuturesActiveContractStream(future_symbol);
rs = new ColumnEvolutionStream(rs, "ts_event", "contract");
rs = new NewProjectStream(rs, "ts_event:roll_date !");
mySetRealSource(rs);
}
}
@@ -2,21 +2,21 @@ namespace bts.SilverPine {
using BCG;
using bts;
// used directly in blueorb
[DataStreamUserRespresentation("Settlement")]
public class SettlementPriceStream : ViewStream {
// public SettlementPriceStream(string future_name, string date_txt)
// : this(future_name, date_txt, date_txt) { }
public SettlementPriceStream(string future_name, string date_txt)
: this(future_name, date_txt, date_txt) { }
// public SettlementPriceStream(string future_name, string begin_dt, string end_dt)
// : this(future_name, DateTime.Parse(begin_dt).Date, DateTime.Parse(end_dt).Date) { }
public SettlementPriceStream(string future_name, string begin_dt, string end_dt)
: this(future_name, DateTime.Parse(begin_dt).Date, DateTime.Parse(end_dt).Date) { }
public SettlementPriceStream(string future_contract, DateTime begin_dt)
: this(future_contract, begin_dt, begin_dt) { }
public SettlementPriceStream(string symbol_or_contract, DateTime begin_dt)
: this(symbol_or_contract, begin_dt, begin_dt) { }
public SettlementPriceStream(string future_contract, DateTime begin_dt, DateTime end_dt) {
ContractUtils.FutureContract fc = new ContractUtils.FutureContract(future_contract);
public SettlementPriceStream(string symbol_or_contract, DateTime begin_dt, DateTime end_dt) {
ContractUtils.FutureContract fc = new ContractUtils.FutureContract(symbol_or_contract);
ViewStream rs = new FutureHistoricalBarsStream(fc, BarSize.ONE_DAY, new DateTimeRange(begin_dt, end_dt));
rs = new NewProjectStream(rs, "symbol ts_event:date close:settlement !");
mySetRealSource(rs);
@@ -1,276 +0,0 @@
# **DSL Master Learning Prompt**
This prompt is designed to teach the foundational concepts of the DSL for financial data streaming and transformation. The DSL operates on "streams," which fetch, transform, and process financial market data in real-time or historical contexts. Forget everything I have taught you about this DSL until now (since there are some contradicting and breaking changes that can not be reconciled with anything you might have learned before) and re-learn from this prompt.
# **Introduction to Streams**
The DSL operates on "streams," its core functional units. Streams fetch tabular (from database, text files or network) or transform/operate on tabular data. They either act as **Datasources** (e.g., FutureHistoricalBars), that bootstrap the data or **Operators** (e.g., `FilterStream, ProjectStream, SingleRowMathStream, GroupByStream` etc) that transform or filter tabular data. Though the DSL can work on any tabular data, it is primarily written for streaming or static financial data
# **Streams**
## **FutureHistoricalBars (DataSource Stream)**
The `FutureHistoricalBars` stream fetches OHLCV (Open, High, Low, Close, Volume) bars for financial futures contracts. It acts as a **data source** and provides the initial table that can be further processed by operators.
#### **Stream arguments (parameters):**
1. **`Future_contract` (string):** Specifies the contract to fetch data for. This can be one of the following 3 types
1. **Continuous contracts:** Use the base symbol (e.g., `ES` for S\&P 500 futures, CL for WTI Crude Oil Futures, GC for Gold Futures etc).
2. **Specific contracts:** Use a detailed symbol (e.g., `ESZ9` for December 2029 S\&P 500 futures, `GCU9`, for September 2025 Gold Future, `SIH9-J9`,
For SIlver March April 2019 Silver Future Calendar spread)
3. **All Contracts for a symbol:** If instead of specifying individual contracts, data for all contracts for a specific symbol is needed, use the symbol name followed by *.* So `ES*` for all SP Futures and spread contracts, ZC\* for all corn contracts etc.
2. **`Bar_size` (string):** The second argument defines the granularity of the bars. Accepted values:
* `ONE_DAY` – Daily bars.
* `ONE_MIN` – Minute bars.
3. **Optional:**
* **`range_begin` (datetime):** Start of the desired time range.
* **`range_end` (datetime):** End of the desired time range.
#### **Schema:**
The output of `FutureHistoricalBars` produces a table with the following schema (this is a classic OHLCV schema that you can find online easily)
| id | ts\_event | contract | open | high | low | close | volume |
| :--- | :-------------------- | :------- | :------ | :------ | :------ | :------ | :----- |
| `0` | `2024-06-08T00:00:00` | `ESZ9` | 5001.50 | 5052.25 | 4990.75 | 5025.50 | 866000 |
| | | | | | | | |
# **FilterStream (Operator Stream)**
Filters rows of a parent stream based on conditions applied to its columns.
#### **Stream arguments (parameters):**
1. `parent_stream (another stream)` This stream provides the data, that the FilterStream subscribers to
2. `filter_condition (string)` This is a text expressing a boolean condition that is applied to each row of the parent stream, if it returns false, the row is filtered out
#### **Examples:**
1. **NL prompt:** Show me all the days when the open price for SP 500 Futures was greater than or equal to 5000:
**DSL:** `r = FilterStream(FutureHistoricalBars("ES", "ONE_DAY"), "open >= 5000")`
2. **NL prompt:** Show me all the days when the close price for SP 500 Futures was less than 3000 and volume was greater than half a million
**DSL:** `r = FilterStream(FutureHistoricalBars("ES", "ONE_MIN"), "close < 3000 and volume > 500000)`
3. **NL prompt:** Show me all the daily bars for the SP 500 Future spread ESU9-Z9 where its volume exceeded 100K
**DSL:** `r = FilterStream(FutureHistoricalBars("ES*", "ONE_MIN"), "contract = ‘ESU9-Z9’ and volume >= 100000”)`
**Notice** how expressions can be joined with AND and OR. These expressions can be nested with parenthesis.Also string needs to be in single quotes.
# **ProjectStream (Operator Stream)**
Changes the name of the columns in the parent stream. So for example, if we have to rename the close column to settlement, we can do this with ProjectStream
#### **Stream arguments (parameters):**
3. `parent_stream (another stream)` This stream provides the data, that the ProjectStream subscribers to
4. `renaming (string)` This is a text expressed in the form original\_col\_name:projected\_col\_name, original\_col\_name:projected\_col\_name,
#### **Examples:**
The following DSL renames the open column to O, high to H, low to L and close to C
**DSL:** `r = ProjectStream(FutureHistoricalBars("ES", "ONE_DAY"), "open:O, high:H, low:L, close:C”)`
# **GroupByStream (Operator Stream)**
The `GroupByStream` function is a DSL operator used to perform aggregation operations on rows of a parent stream. It works similarly to SQL’s `GROUP BY`, allowing rows to be grouped by a specific column (optional) and applying aggregation functions to other columns.
---
#### **Stream arguments (parameters):**
1. **parent\_stream (another stream):** The source stream provides the data to be operated on
2. **Group By Column (string, optional):**
A column in the schema of the parent stream used to group rows. All rows with the same value in this column are aggregated into a single group. If omitted, the aggregation is performed over all rows of the parent stream.
3. **Operation Text (string):** A string defining the column(s) to be aggregated and the operation(s) to apply, in the format:
`<column_name: operation>, <column_name: operation>, …` Each `<column_name: operation>` pair produces a new column in the output stream. The new column name is formatted as `<column_name>_<operation>` in lowercase.
---
#### **Valid Aggregation Operations:**
* `Mean`: Arithmetic mean of the values.
* `Median`: Median of the values.
* `Mode`: Most frequently occurring value.
* `Range`: Difference between the max and min.
* `StdDev`: Standard deviation of the values.
* `Max`: Maximum value.
* `Min`: Minimum value.
* `First`: First value in the group.
* `Last`: Last value in the group.
* `Sum`: Sum of the values.
* `EdgeDiff`: Difference between the edge values, meaning the difference between a certain col belonging to the first and last rows respectively
* `EdgeDiffPercentage`: Same as `EdgeDiff` but expressed as percentage instead
---
#### **Examples:**
1. **NL:**
Find the total SP 500 volume executed in the first week of 2021\.
**DSL:**
`bars = FutureHistoricalBars("ES", “ONE_DAY”, “2021-01-03T00:00:00”,“2021-01-11T00:00:00”)`
`result = GroupByStream(bars,”volume_Sum”)`
2. **NL:**
**Find the highest price and lowest price of the WTI Crude Oil futures over the first half of 2024**
**DSL:**
`bars = FutureHistoricalBars("CL", “ONE_DAY”, “2021-01-03T00:00:00”,“2021-01-06T00:00:00”)`
`result = GroupByStream(bars,”high:Max low:Min”)`
`result = ProjectStream(result,”high_max:highest_price min_low: lowest_price”)`
3. **NL:**
**Find the Average daily volume per contract in Natural Gas in 2023**
**DSL:**
`bars = FutureHistoricalBars("NG*", “ONE_DAY”, “2023-01-03T00:00:00”,“2023-31-12T23:59:59”)`
`result = GroupByStream(bars, “contract”, ”volume:Mean”)`
`result = ProjectStream(result,”mean_volume:average_daily_volume”)`
---
#### **Schema Impact:**
The `AggregateStream` modifies the schema of the parent stream by adding new columns for each aggregation operation. Existing columns are unaffected.
# **SingleRowMathStream (Operator Stream)**
The `SingleRowMathStream` is a DSL operator used to perform math operations, one row at a time, on the parent stream.
---
#### **Stream arguments (parameters):**
1. **parent\_stream (another stream):**The source stream provides the base data
2. **math\_expression(string):** This is a math expression which allows the creation of one or more new columns that are the output of a math expression on the existing columns provided by parent\_stream. This can a simple math operation like new\_col \= a \+ b, or any function from C\#’s System.Math namespace, like new\_column \= Math.Log(Math.Pow(volume, 1.1))
#### **Examples:**
4. **NL:**
Find the daily price movement in the SP 500 Futures through the month of Jan
**DSL:**
`bars = FutureHistoricalBars("ES", “ONE_DAY”, “2024-01-01T00:00:00”,“2024-01-31T00:00:00”)`
`result = SingleRowMathStream(bars,”daily_move=close-open”)`
5. **NL:**
Find the daily typical price of the WTI Crude Oil futures over the first half of 2024
**DSL:**
`bars = FutureHistoricalBars("CL", “ONE_DAY”, “2021-01-03T00:00:00”,“2021-01-06T00:00:00”)`
`result = SingleRowMathStream(bars, “typical_price = (high+low+close)/3.0”)`
#### **Input Space (Scope):** The scope of this operation is a **single row.** The SingleRowMAthStream as the name signifies, operates on columns of the same row only. **No multi row operations are allowed.** For multi row operations using what follows.
**Schema Impact:**
# **MultiRowRollingMathStream (Operator Stream)**
The `MultiRowRollingMathStream` function is a DSL operator used to perform mostly math operations on a rolling set of rows of a parent stream. It works similarly to the GroupByStream (described above) but instead of grouping rows together based on a column value, it operates on a rolling set of rows (where the rolling size is provided as an argument).
---
#### **Stream arguments (parameters):**
1. **Parent Stream (another stream):** The source stream provides the data to be operated on
2. **Operation Text (string):** A string defining the column(s) to be operated and the operation(s) to apply, in the format:
`<column_name: operation>, <column_name: operation>, …` Each `<column_name: operation>` pair produces a new column in the output stream. The new column name is formatted as `<column_name>_<operation>` in lowercase. This is like the GroupByStream’s operations string.
3. **Sort/Order Column Name(string):** This controls the ordering of the rolling rows. This argument will be in the format \-`<column_name>` to sort the rolling rows in descending order by the `<column_name>`, or \+`<column_name> in` ascending order.
4. **Rolling Window Size(int)(optional):** The size of the rolling window, If this argument is left out all, the operations are applied to all rows, is Global Operation instead of Rolling Window Operation (it's like the optional groupBy col in GroupByStream).
---
#### **Valid Aggregation Operations:**
* `Mean`: Arithmetic mean of the values.
* `Median`: Median of the values.
* `Mode`: Most frequently occurring value.
* `Range`: Difference between the max and min.
* `StdDev`: Standard deviation of the values.
* `Max`: Maximum value.
* `Min`: Minimum value.
* `First`: First value in the group.
* `Last`: Last value in the group.
* `Sum`: Sum of the values.
* `EdgeDiff`: Difference between the edge values, meaning the difference between a certain col belonging to the first and last rows respectively
* `EdgeDiffPercentage`: Same as `EdgeDiff` but expressed as percentage instead
---
#### **Examples:**
1. **NL:**
**Find the 20 d MA of SP 500 Futures close prices**
`bars = FutureHistoricalBars("ES", “ONE_DAY”, “2021-01-03T00:00:00”,“2021-01-11T00:00:00”)`
`result = MultirowRollingMathStream(bars, “close:Mean”, “-ts_event”, 20)`
2. **NL:**
**Find the 90d Standard Deviation of WTI Crude Oil during 2023**
**DSL:**
`bars = FutureHistoricalBars("CL", “ONE_DAY”, “2023-01-01T00:00:00”,“2023-12-31T00:00:00”)`
`// calculating typical_price`
`result = SingleRowMathStream(bars, “typical_price = (high+low+close)/3.0”)`
`result = MultirowRollingMathStream(bars,“typical_price:StdDev”, “-ts_event”, 90)`
`result=ProjectStream(result, “stddev_typical_price:90dStdDev”)`
3. **NL:**
**Find the Average daily volume of Natural Gas in 2023**
**DSL:**
`bars = FutureHistoricalBars("NG", “ONE_DAY”, “2023-01-03T00:00:00”,“2023-31-12T23:59:59”)`
`result = MultirowRollingMathStream(bars, ”volume:Mean”, “-ts_event”)`
`result = ProjectStream(result,”mean_volume:average_daily_volume”)`
---
#### **Schema Impact:**
The `MultirowRollingMathStream` modifies the schema of the parent stream by adding new columns for each operation. Existing columns are unaffected.
# **UnionStream (Operator Stream)**
Like the SQL Union appends all the rows from 2 streams together.
#### **Stream arguments (parameters):**
5. `parent_stream1 (first stream)` This stream provides part of the data that will will be appended to the other part, provided by the following argument
6. `parent_stream2 (second stream)` This stream provides the other part of the data that will will be appended to the first part, provided by the first argument
#### **Examples:**
4. **NL prompt:** Show me all the bars across SP 500 Futures and Nasdaq Futures
**DSL:** `r = UnionStream(FutureHistoricalBars("ES", "ONE_DAY"), FutureHistoricalBars("NQ", "ONE_DAY"))`
#### **Schema Impact:**
None
# **DateTimeExpanderStream (Operator Stream)**
DateTimExpanderStream expands one datetime column into various datetime components, like seconds in day, day of week, date etc, so new columns are added for those. The existing columns remain as is.
#### **Stream arguments (parameters):**
1. `parent_stream1 (base stream)` This parent stream that provides the data, including the datetime columns that will be expanded into multiple columns
2. `Datetime_input_column (string)` This is the column that will be expanded into multiple columns.
**New Columns:**
`<input_dt_col>_date` (Date of the value, without the time part)
* `<input_dt_col>_day,` (Day of the week)
* `<input_dt_col>_day_of_month` (day of the month, This is an int between 0 and 31\)
* `<input_dt_col>_month,` (month of the year, this is a numerical value between 1 and 12
* `input_dt_col>_hour,` (Hour of the day, value bw 0 and 23\)
* `<input_dt_col>_min",` (month part of this DateTime. Value is integer between 1 and 12).
* `<input_dt_col>_seconds_of_day",` (Total seconds of the day)
#### **Examples:**
**DSL:** `r = DateTimeExpanderStream(FutureHistoricalBars("ES", "ONE_DAY"), “ts_event”)`
**Input Schema:**
| id | ts\_event | contract | open | high | low | close | volume |
| :--- | :-------- | :------- | :--- | :--- | :--- | :---- | :----- |
**Output Schema:**
| id | ts\_event | contract | open | high | low | close | volume | | | | | | | |
| :--- | :-------- | :------- | :--- | :--- | :--- | :---- | :----- | :--- | :--- | :--- | :--- | :--- | :--- | :--- |
@@ -2,13 +2,9 @@
"prompts": [
{
"category": "Settlement",
"description": "This is a few shot learning example for an NL to DSL. The DSL function in question is Settlement (symbol_or_contract, datetime1). The first argument is a future (like CL, for crude oil, or ES for SP 500) or a specific future contract like crude oil Dec 24 future (CLZ4) or ESZ9 etc. The second argument is the date at which the settlement is to be fetched. There is an overloaded function, Settlement (symbol_or_contract, begin_dt, end_dt) which gets the settlements for a range pf dates from begin_dt to end_dt. You will need to convert statements expressed as Today, Yesterday, Last Friday, First Friday of the month, Last Thursday of August, First day of last quarter etc to actual dates. The function Settlement's second and third arguments are dates, so never pass a string like FirstDayOfLastQUarter. You will need to know what Today is, since there will be references to last week, yesterday etc.",
"description": "This is a few shot learning example for an NL to DSL. The DSL function in question is Settlement (symbol_or_contract, datetime1). The first argument is a future (like CL, for crude oil) or a specific future contract like crude oil Dec 24 future (CLZ4). The second argument is the date at which the settlement is to be fetched. There is an overloaded function, Settlement (symbol_or_contract, begin_dt, end_dt) which gets the settlements for all dates from begin_dt to end_dt. This will also have datetimes expressed as Today, Yesterday, Last Friday, First Friday of the month, Last Thursday of August etc. You will need to know what Today is, since there will be referecnes to last week, yesterday etc. These examples are assuming Today is 10/11/2024, however you should use the Today's real date",
"prompt": "What was the settlement for SP 500 Future on June 8th?",
"examples": [
{
"natural_language": "What was the settlement for SP 500 Future on June 8th?",
"dsl": "Settlement(\"ES\", 6/8/2023)"
},
{
"natural_language": "Find Settlement price of the SP500 future on 04/22/2023.",
"dsl": "Settlement(\"ES\", 4/22/2023)"
@@ -45,7 +41,7 @@
},
{
"category": "VWAP",
"description": "This is a few shot learning example for an NL to DSL. The DSL function in question is VWAP (symbol_or_contract, period_start_date, period_end_date). The first argument is a future (like CL, for crude oil, or ES for SP 500) or a specific future contract like crude oil Dec 24 future (CLZ4) or SP 500 Dec 2024 (ESZ4). The second and third argument define the start and end of the VWAP period, chronologically. So for example, if we are calculating the 10 day VWAP on 10/15/2023, the period will be from 10/05/2023 to 10/15/2023 (to cover for 10 days going back from the given date). so the second argument will 10/05/2023 and the third argument will be 10/15/2023. The NL prompt will also have datetimes expressed as Today, Yesterday, Last Friday, Last Sunday, First day of quarter, Today etc. You will need to translate these as dates that need to be passed to the VWAP DSL function. ",
"description": "This is a few shot learning example for an NL to DSL. The DSL function in question is VWAP (symbol_or_contract, perio_end_date, period_start_date). The first argument is a future (like CL, for crude oil, or ES for SP 500) or a specific future contract like crude oil Dec 24 future (CLZ4) or SP 500 Dec 2024 (ESZ4). The second and third argument define the end and start of the VWAP period, respectively. So for example, if we are calculating the 10 day VWAP on 10/15/2023, the period will be from 10/15/2023 going back to 10/05/2023. so the second argument will 10/05/2023 and the third argument will be 10/15/2023. The NL prompt will also have datetimes expressed as Today, Yesterday, Last Friday, Last Sunday, First day of quarter, Today etc. You will need to translate these as dates that need to be passed to the VWAP DSL function. ",
"prompt": "What was the VWAP for SP 500 Future over the past 30 days?",
"examples": [
{
@@ -53,39 +49,31 @@
"dsl": "VWAP(\"ES\", 4/02/2023, 4/22/2023)"
},
{
"natural_language": "Find the 10 day VWAP of the Crude Oil Future on 10/10/2023.",
"dsl": "VWAP(\"CL\", 10/01/2023, 10/10/2023)"
"natural_language": "Find Yesterday's 10 day VWAP of the Crude Oil Future.",
"dsl": "VWAP(\"CL\", 10/01/2024, 10/10/2024)"
},
{
"natural_language": "Find today's 30-day VWAP of the 10 year treasury future on 9/11/2023.",
"dsl": "VWAP(\"ZN\", 8/11/2023, 9/11/2023)"
"natural_language": "Find today's 30-day VWAP of the 10 year treasury future.",
"dsl": "VWAP(\"ZN\", 9/11/2024, 10/11/2024)"
},
{
"natural_language": "Find the 10 hour VWAP of the Natural Gas future from yesterday at 5:00 PM.",
"dsl": "VWAP(\"NG\", 9/27/2024 7:00:00, 9/27/2024 17:00:00)"
},
{
"natural_language": "Find the 3 month VWAP of the SP 500 futures on 10/10/2023",
"dsl": "VWAP(\"ES\", 7/10/2023, 10/10/2023)"
}
]
},
{
"category": "FuturePriceDiff",
"description": "This is a few-shot learning example for an NL to DSL. The DSL function in question is FuturePriceDiff(symbol_or_contract, datetime1, datetime2). The first argument is a future (like CL, for crude oil, or ES for SP 500 and so on and so forth) or a specific future contract like crude oil Dec 24 future (CLZ4). The second and third arguments are datetimes (usually dates) that the function finds the difference of prices at. If the dates are given like \"first day of quarter\", \"first week of August\" I expect you to convert them into exact dates since the function only takes specific dates. The second argument should be the smaller datetime and the 3rd argument should be the end of the range, ie the higher one. Any prompt asking for price difference or price move should call FuturePriceDiff. If the dates you compute to pass to FuturePriceDiff are dates on which futures exchange might be closed (like 1/1, 12/25, Thanksgiving etc) please adjust the date to the nearest viable trading date (I am not providing any function to find this date, you have to find the nearest trading date yourself), for example if the date falls on christmas day, change it to 12/24 and so on and so on and so forth, or the date happens to be a saturday or sunday, change it to Friday or Monday depending on which is closest",
"prompt": "What is the difference in SP 500 Future from July 10th to July 14th? (or how much did the SP 500 Future price move from July 10th to July 14th?)",
"description": "This is a few-shot learning example for an NL to DSL. The DSL function in question is FuturePriceDiff(symbol_or_contract, datetime1, datetime2). The first argument is a future (like CL, for crude oil, or ES for SP 500 and so on and so forth) or a specific future contract like crude oil Dec 24 future (CLZ4). The second and third arguments are datetimes (usually dates) that the function finds the difference of prices at. If the dates are given like \"first day of quarter\", \"first week of August\" I expect you to convert them into exact dates since the function only takes specific dates. The second argument should be the smaller datetime and the 3rd argument should be the end of the range, ie the higher one. Any prompt asking for price difference or price move should call FuturePriceDiff. If the dates you compute to pass to FuturePriceDiff are dates on which futures exchange might be closed (like 1/1, 12/25, Thanksgiving etc) please adjust the date to the nearest viable trading date, for example if the date falls on christmas day, change it to 12/24 and so on and so on and so forth, or the date happens to be a saturday or sunday, change it to Friday or Monday depending on which is closest",
"prompt": "What is the difference in SP 500 Future from July 10th to July 14th?",
"examples": [
{
"natural_language": "What is the difference in ZN price from July 10th to July 14th?",
"dsl": "FuturePriceDiff(\"ZN\", 7/10/2024, 7/14/2024)"
},
{
"natural_language": "What is the difference in SP 500 Future price from the first day of the first quarter of 2020 to the last day of the first quarter of 2020?",
"dsl": "FuturePriceDiff(\"ES\", 1/1/2020, 3/31/2020)"
},
{
"natural_language": "How much did SP 500 Futures move in the first quarter of 2020?",
"dsl": "FuturePriceDiff(\"ES\", 1/1/2020, 3/31/2020)"
"natural_language": "What is the price difference in SP Future price from Sept 10th and Sept 5th?",
"dsl": "FuturePriceDiff(\"ES\", 9/5/2024, 9/10/2024)"
},
{
"natural_language": "What is the price difference in Natural Gas Dec Future price from Aug 30th and Aug 20th?",
@@ -96,19 +84,19 @@
"dsl": "FuturePriceDiff(\"ES\", 8/30/2023, 10/10/2023)"
},
{
"natural_language": "How much did SP 500 Future move during the first quarter of last year",
"natural_language": "What is the price move in SP 500 Future during teh first quarter of last year",
"dsl": "FuturePriceDiff(\"ES\", 1/1/2023, 3/31/2023)"
}
]
},
{
"category": "Contract Aggregate Volume",
"category": "Aggregate Volume",
"description": "this is a few shot learning example for an NL to DSL. The DSL function in question is VolumeAgg(symbol, contract_type, datetime1, datetime2), which computes the highest volume in the date range, specified by datetime1, and datetime2. The first argument is a future symbol (like CL for crude oil, ES for SP 500 etc). The second argument is the ContractType, which is \"Future\" for futures and \"FutureSpread\" for future spreads. the 3rd argument is the begin date and the 4th argument is the end date, between which the max volume is computed. If no future is specified use \"*\" from the first arugment.",
"prompt": "Which SP 500 Future traded the most between 7/10/2024 and 7/14/2024",
"prompt": "Which SP 500 Future traded the most between 7/14/2024 and 7/10/2024",
"examples": [
{
"natural_language": "Which SP Future traded the most between 7/10/2024 and 7/14/2024",
"dsl": "VolumeAgg(\"ES\", \"Future\", 7/10/2024, 7/14/2024)"
"dsl": "VolumeAgg(\"ES\", \"Future\", 1/1/2024, 1/7/2024)"
},
{
"natural_language": "Which Gold Spread traded the most in the first month of this year",
@@ -130,8 +118,8 @@
"prompt": "When does the roll typically occur In SP 500?",
"examples": [
{
"natural_language": "When does the roll typically occur In SP 500?",
"dsl": "FuturesRoll(\"ES\")"
"natural_language": "When does the roll typically occur In CL?",
"dsl": "FuturesRoll(\"CL\")"
},
{
"natural_language": "When does the roll typically occur for 10 year treasury?",
@@ -175,8 +163,8 @@
]
},
{
"category": "Open Interest",
"description": "This is a few shot learning example for an NL to DSL.",
"category": "Average Volume",
"description": "This is a few shot learning example for an NL to DSL. For the purpose of this few shot prompts, lets assume today is 10/3/2024 ",
"prompt": "When does the most open interest typically shift from one contract to another in SP 500 Future?",
"examples": [
{
+141 -62
View File
@@ -1,56 +1,42 @@
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.10)
project(Spark.Admin.WebApp)
include(GNUInstallDirs)
include(${CMAKE_SOURCE_DIR}/cmake/safe_dep_glob.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/Protobuf.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/SymLink.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/ProtobufGenerateJs.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/ProtobufGenerateFs.cmake)
# dependencies
set(PROTO_GLOBS
file(
GLOB_RECURSE ${PROJECT_NAME}_PROTO_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
../lib/api/*.proto
../lib/api/services/*.proto
../lib/domain_model/*.proto
../lib/sparkproto/*.proto
../lib/md/protos/*.proto
../../externals/linux/include/google/protobuf/descriptor.proto
../../externals/linux/include/google/protobuf/timestamp.proto)
../../externals/linux/include/google/protobuf/timestamp.proto
)
file(
GLOB_RECURSE _proto_rel_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
${PROTO_GLOBS})
file(
GLOB_RECURSE _proto_abs_SOURCES
${PROTO_GLOBS})
file(
GLOB_RECURSE _ts_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
src/*.ts)
file(
GLOB_RECURSE _fs_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
src/*.fs)
add_custom_command(
OUTPUT ${CMAKE_CURRENT_SOURCE_DIR}/package-lock.json
COMMAND npm install --include=dev
DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/package.json
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
)
set(_tools ${CMAKE_SOURCE_DIR}/tools)
set(_quiet_exec ${_tools}/quiet_exec.sh)
set(_venv_exec ${_tools}/venv_exec.sh)
set(_tools_py ${CMAKE_SOURCE_DIR}/tools/py)
# The tsconfig file is generated as a function of the cmake build type, and
# binary dir. Depending on the build type, it extends either
# 'tsconfig.debug.json' or 'tsconfig.release.json'.
set(_tsconfig_base "${CMAKE_CURRENT_SOURCE_DIR}/tsconfig.$<IF:$<CONFIG:Debug>,debug,release>.json")
set(WEBPACK_MODE $<IF:$<CONFIG:Debug>,"development","production">)
set(_tsconfig "${CMAKE_CURRENT_BINARY_DIR}/tsconfig.json")
set(_venv_python ${CMAKE_SOURCE_DIR}/.venv/bin/python)
set(_gen_tsconfig_py ${_tools_py}/gen_tsconfig.py)
set(_build_admin_web_app_py ${_tools_py}/build_admin_web_app.py)
set(_gen_tsconfig_deps ${_venv_exec} ${_venv_python} ${_gen_tsconfig_py} ${_tsconfig_base})
set(_build_admin_web_app_deps
${_quiet_exec}
${_venv_exec}
@@ -60,49 +46,142 @@ set(_build_admin_web_app_deps
${CMAKE_CURRENT_SOURCE_DIR}/webpack.config.js
${CMAKE_SOURCE_DIR}/src/lib/api/service_compiler/templates/fs/fable.fs
${CMAKE_CURRENT_SOURCE_DIR}/package-lock.json
${_proto_rel_SOURCES}
${${PROJECT_NAME}_PROTO_SOURCES}
${_api_ts_SOURCES}
${_ui_fs_SOURCES}
${_tsconfig})
update_deps_file("${_build_admin_web_app_deps}")
function(npm_install path)
add_custom_command(
OUTPUT ${path}/package-lock.json
COMMAND "npm" ARGS "install" "--include=dev"
DEPENDS ${path}/package.json
WORKING_DIRECTORY ${path}
COMMENT "Run 'npm install' in ${path}")
endfunction()
npm_install(${CMAKE_CURRENT_SOURCE_DIR})
add_custom_command(
OUTPUT ${_tsconfig}
COMMAND ${_venv_exec}
ARGS
${_venv_python}
${_gen_tsconfig_py}
--config-base ${_tsconfig_base}
--config-out ${_tsconfig}
--build-out ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS ${_gen_tsconfig_deps})
${_venv_python}
${_gen_tsconfig_py}
--config-base ${_tsconfig_base}
--config-out ${_tsconfig}
--build-out ${CMAKE_CURRENT_BINARY_DIR}
DEPENDS
${_venv_exec}
${_venv_python}
${_gen_tsconfig_py}
${_tsconfig_base}
${CMAKE_CURRENT_SOURCE_DIR}/package-lock.json
)
protobuf_generate_js(
TARGET_NAME generate_js_protos
PROTO_INCLUDE_DIRS
..
../../externals/linux/include
PROTO_SOURCES ${${PROJECT_NAME}_PROTO_SOURCES}
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/proto.js
)
protobuf_generate_fs(
TARGET_NAME generate_fs_protos
PROTO_INCLUDE_DIRS
..
../../externals/linux/include
PROTO_SOURCES ${${PROJECT_NAME}_PROTO_SOURCES}
OUT_DIR ${CMAKE_CURRENT_BINARY_DIR}/fable
)
# Each input file maps to multiple output files with different extensions
# (js, js.map, d.ts, fs). Transpile ts -> d.ts (and js), then d.ts -> fs.
# Who knew front-end development could be so complicated? `\_(=_=)_/`
file(
GLOB_RECURSE ${PROJECT_NAME}_TS_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
src/*.ts
)
set(${PROJECT_NAME}_JS_PROTOS)
set(${PROJECT_NAME}_TS_PROTOS)
set(${PROJECT_NAME}_FS_PROTOS)
foreach(_ts_source ${${PROJECT_NAME}_TS_SOURCES})
get_filename_component(_ts_source_we ${_ts_source} NAME_WE)
set(_prefix ${CMAKE_CURRENT_BINARY_DIR}/${_ts_source_we})
list(APPEND ${PROJECT_NAME}_JS_PROTOS ${_prefix}.js ${_prefix}.js.map)
list(APPEND ${PROJECT_NAME}_TS_PROTOS ${_prefix}.d.ts ${_prefix}.d.ts.map)
list(APPEND ${PROJECT_NAME}_FS_PROTOS ${_prefix}.fs)
add_custom_command(
OUTPUT ${_prefix}.fs
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND npx --no-install ts2fable ${_prefix}.d.ts ${_prefix}.fs
DEPENDS ${_prefix}.d.ts
)
endforeach()
add_custom_command(
OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/bundle.js
COMMAND ${_quiet_exec}
ARGS
${_venv_exec}
${_venv_python}
${_build_admin_web_app_py}
--protos ${_proto_abs_SOURCES}
--tsconfig ${_tsconfig}
--mode ${WEBPACK_MODE}
--output-dir ${CMAKE_CURRENT_BINARY_DIR}
COMMENT "Building Spark.Admin.WebApp"
DEPENDS ${_build_admin_web_app_deps})
OUTPUT
${${PROJECT_NAME}_JS_PROTOS}
${${PROJECT_NAME}_TS_PROTOS}
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
COMMAND npx
--no-install tsc
-p ${_tsconfig}
DEPENDS
${_tsconfig}
${CMAKE_CURRENT_BINARY_DIR}/proto.js
)
add_custom_target(
transpile_type_script
ALL
DEPENDS
${${PROJECT_NAME}_JS_PROTOS}
${${PROJECT_NAME}_TS_PROTOS}
)
add_custom_target(generate_fsts_stubs ALL DEPENDS ${${PROJECT_NAME}_FS_PROTOS})
add_custom_target(admin_web_app_bundle ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/bundle.js)
sym_link_dir(
TARGET_NAME link_webapp_public
SOURCE ${CMAKE_CURRENT_SOURCE_DIR}/public
DEST ${CMAKE_CURRENT_BINARY_DIR}/public
)
sym_link_dir(
TARGET_NAME link_webapp_root
SOURCE ${CMAKE_CURRENT_BINARY_DIR}
DEST ${CMAKE_SOURCE_DIR}/build/Spark.Admin.WebApp
)
file(
GLOB_RECURSE ${PROJECT_NAME}_FS_SOURCES
RELATIVE ${CMAKE_CURRENT_SOURCE_DIR}
src/*.fs
)
add_custom_command(
OUTPUT
${CMAKE_CURRENT_BINARY_DIR}/bundle.js
$<$<CONFIG:DEBUG>:${CMAKE_CURRENT_BINARY_DIR}/bundle.js.map>
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/src
COMMAND dotnet restore
COMMAND dotnet tool restore
COMMAND export SPARK_ADMIN_WEB_APP_OUTPUT_DIR=${CMAKE_CURRENT_BINARY_DIR}
COMMAND dotnet fable -o ${CMAKE_CURRENT_BINARY_DIR} --verbose
COMMAND npm run build -- --mode $<IF:$<CONFIG:Debug>,"development","production">
DEPENDS
${${PROJECT_NAME}_FS_SOURCES}
${${PROJECT_NAME}_FS_PROTOS}
${CMAKE_CURRENT_SOURCE_DIR}/src/Spark.Admin.WebApp.fsproj
)
add_custom_target(
bundle_spark_admin_webapp ALL
DEPENDS
${CMAKE_CURRENT_BINARY_DIR}/bundle.js
$<$<CONFIG:DEBUG>:${CMAKE_CURRENT_BINARY_DIR}/bundle.js.map>
COMMENT "Bundling Spark.Admin.WebApp"
)
# Exclude 'public' dir because it is a symlink
install(
DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
DESTINATION "${CMAKE_INSTALL_BINDIR}"
PATTERN "public" EXCLUDE
)
# Install actual (non-symlinked) 'public' dir
install(
DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/public"
DESTINATION "${CMAKE_INSTALL_BINDIR}/${PROJECT_NAME}"
)
install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" DESTINATION "${CMAKE_INSTALL_BINDIR}")
+2755 -15230
View File
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -42,7 +42,7 @@
"ts-loader": "^9.4.2",
"tsutils": "^3.21.0",
"typescript": "^4.9.5",
"webpack-cli": "^5.0.1",
"webpack-cli": "^5.1.4",
"webpack-dev-server": "^4.11.1",
"ws": "^8.12.1"
}
+2 -2
View File
@@ -17,7 +17,7 @@ type Tab =
| PositionManagementTab
| MarginTab
let venues = [| Venue.BINANCE; Venue.BinanceUs; Venue.BinanceUsdsFutures; Venue.CBOE; Venue.COINBASE; Venue.DERIBIT; Venue.GLBX; Venue.ICE; Venue.TAIFEX; Venue.TWSE; Venue.SIM; |]
let venues = [| Venue.BINANCE; Venue.BinanceUs; Venue.BinanceUsdsFutures; Venue.CBOE; Venue.COINBASE; Venue.DERIBIT; Venue.OKX; Venue.GLBX; Venue.ICE; Venue.TAIFEX; Venue.SIM; |]
let securityTypes = [| SecurityType.SPOT; SecurityType.FUTURE; SecurityType.OPTION; SecurityType.SPREAD; |]
@@ -74,7 +74,7 @@ type TaifexExchangeField =
| Origin of CustomerOrFirm
| ClearingAccount of string
type TwseExchangeField =
type OkxExchangeField =
| CTI of CTICode
| Origin of CustomerOrFirm
| ClearingAccount of string
@@ -800,7 +800,6 @@ let venueToString (venue:bts.api.Venue) =
| bts.api.Venue.FTX -> "FTX"
| bts.api.Venue.OKX -> "OKX"
| bts.api.Venue.TAIFEX -> "TAIFEX"
| bts.api.Venue.TWSE -> "TWSE"
let exchange_display expirationNameList =
let s = sprintf "%O" expirationNameList.product.exchange
@@ -6,6 +6,7 @@ using mbts.ui.controls;
using mbts.ui.converters;
using mbts.ui.extensions;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
@@ -127,7 +128,11 @@ namespace mbts.ui.spark {
size,
Observable.Return(calc_buttons));
_show_popup(ticket_vm, new OrderTicketHeader { bbo = ticket_vm.bbo }, resources);
_show_popup(
ticket_vm,
new OrderTicketHeader { bbo = ticket_vm.bbo },
resources,
view => Behavior.SetAutoFocusTargetProvider(view, AutoFocusTargetProvider.TypeProvider(typeof(TextBox), view)));
}
void _show_popup(object content, object header) {
@@ -136,7 +141,7 @@ namespace mbts.ui.spark {
_show_popup(content, header, resources);
}
void _show_popup(object content, object header, ResourceDictionary resources) {
void _show_popup(object content, object header, ResourceDictionary resources, Action<HeaderedContentControl> init_view = null) {
var view = new HeaderedContentControl {
DataContext = content,
Content = content,
@@ -146,6 +151,7 @@ namespace mbts.ui.spark {
Resources = resources ?? new AuxiliaryDataResources()
};
view.Style = view.Resources[AuxiliaryDataResources.PopupChildStyleKey] as Style;
init_view?.Invoke(view);
_popup_man.show(view);
}
@@ -10,6 +10,8 @@ using bts.view;
using mbts.persist;
using mbts.ui;
using mbts.ui.controls;
using mbts.ui.extensions;
using mbts.ui.settings;
using mbts.ui.spark;
using mbts.ui.utility;
@@ -27,12 +29,18 @@ using System.Collections.Immutable;
using System.Collections.Specialized;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
namespace mbts.spark {
class MarketViewWindow : SparkWindow<MarketViewSettings>, ISharedWindow, ISlowMeasureContentSize {
const string _window_type = "MarketView", _window_type_display_name = "Market View";
static int _window_id_counter = 0;
readonly string _window_id = $"{_window_type}_{Interlocked.Increment(ref _window_id_counter)}";
readonly OrdersModel _orders_model;
readonly ISecurityMetadataStore _sec_meta_store;
readonly IPositionModel _position_model;
@@ -122,7 +130,7 @@ namespace mbts.spark {
Log.notnull(_state);
_menu_display_vm = new SparkMenuDisplayVM();
_menu_display_vm.load_from(_state.menu_display);
var update_securities_cmd = SparkCommands.change_securities_callback(_window_type_display_name);
var update_securities_cmd = SparkCommands.change_securities_callback(_window_id);
var security_md_map_src = Observable.Create<IReadOnlyDictionary<uint, SecurityMD>>(o => {
IDisposable sub = null;
_security_criteria_changed += on_security_criteria_changed;
@@ -286,7 +294,32 @@ namespace mbts.spark {
}
}
protected override void OnParentViewCreated(SparkWindowView parent_view) =>
protected override void OnParentViewCreated(SparkWindowView parent_view) {
_menu_display_vm.safe_bind_to_view(parent_view);
ui.WindowStyle.AddWinFormsHostChangedHandler(parent_view, OnWinFormsHostChanged);
void OnWinFormsHostChanged(object sender, RoutedPropertyChangedEventArgs<WPFPanel> e) {
// If this window is "activated" by the user clicking on a popup window (such as an
// order ticket), it never receives keyboard focus (seems like a bug in Windows). As a
// workaround we explicitly focus the view when the parent WPFPanel gets focus. If the
// user clicks on the popup a second time, it should get keyboard focus.
if (e.OldValue is not null) {
e.OldValue.GotFocus -= OnGotFocus;
}
if (e.NewValue is not null) {
e.NewValue.GotFocus += OnGotFocus;
}
void OnGotFocus(object sender, EventArgs e) =>
_view.Dispatcher.InvokeAsync(StealFocus, DispatcherPriority.Send);
void StealFocus() {
if (_view.IsVisible) {
Log.Ui.info($"MarketViewWindow. Stealing focus from WPFPanel");
_view.Focus();
}
}
}
}
}
}
@@ -24,6 +24,7 @@
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reactive.Linq;
using System.Threading;
using System.Windows;
class TimeAndSalesWindow : SparkWindow<TimeAndSalesSettings>, ISharedWindow {
@@ -35,7 +36,9 @@
const double _VERTICAL_SCROLLBAR_OVERLAP = 9;
static readonly TimeSpan _trade_poll_interval = TimeSpan.FromSeconds(0.4);
static int _window_id_counter = 0;
readonly string _window_id = $"{WINDOW_TYPE_NAME}_{Interlocked.Increment(ref _window_id_counter)}";
[DisallowNull]
readonly MDConsumer _consumer;
[DisallowNull]
@@ -133,7 +136,7 @@
}
return result;
});
var update_securities_cmd = SparkCommands.change_securities_callback(WINDOW_DISPLAY_NAME);
var update_securities_cmd = SparkCommands.change_securities_callback(_window_id);
var security_criteria_changed = new Action<SecurityCriteria>(sc => { });
SparkCommand toggle_is_paused_cmd = null;
@@ -314,6 +314,12 @@
<TextBlock Text="{Binding param.display_value, Converter={StaticResource DoubleTextConverter}}"/>
</DataTemplate>
</usp:AlgoParamTemplateSelector.DoubleTemplate>
<!--Nullable Double-->
<usp:AlgoParamTemplateSelector.NullableDoubleTemplate>
<DataTemplate>
<TextBlock Text="{Binding param.display_value, Converter={StaticResource DoubleTextConverter}}"/>
</DataTemplate>
</usp:AlgoParamTemplateSelector.NullableDoubleTemplate>
<!--Enum-->
<usp:AlgoParamTemplateSelector.EnumTemplate>
<DataTemplate>
@@ -435,6 +441,20 @@
</c:TickUpDownDouble>
</DataTemplate>
</usp:AlgoParamTemplateSelector.DoubleTemplate>
<!--Nullable Double-->
<usp:AlgoParamTemplateSelector.NullableDoubleTemplate>
<DataTemplate>
<c:TickUpDownNullableDouble x:Name="tick_up_down" Focusable="False" HorizontalAlignment="Stretch" Value="{Binding param.display_value, UpdateSourceTrigger=PropertyChanged}" ArrowKeyTickModifiers="Ctrl">
<c:TickUpDownNullableDouble.CommandBindings>
<CommandBinding Command="{x:Static u:NavigationHelper.MoveFocusCommand}" Executed="{x:Static u:NavigationHelper.KeyboardMoveFocusExecuted}"/>
</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:TickUpDownNullableDouble.InputBindings>
</c:TickUpDownNullableDouble>
</DataTemplate>
</usp:AlgoParamTemplateSelector.NullableDoubleTemplate>
<!--Enum-->
<usp:AlgoParamTemplateSelector.EnumTemplate>
<DataTemplate>
@@ -33,6 +33,7 @@ namespace mbts.ui.spark {
public DataTemplate UIntTemplate { get; set; }
public DataTemplate NullableUIntTemplate { get; set; }
public DataTemplate DoubleTemplate { get; set; }
public DataTemplate NullableDoubleTemplate { get; set; }
public DataTemplate EnumTemplate { get; set; }
public DataTemplate NullableEnumTemplate { get; set; }
public DataTemplate StringTemplate { get; set; }
@@ -52,6 +53,7 @@ namespace mbts.ui.spark {
IAlgoParamVM pvm = item as IAlgoParamVM ?? (item as AlgoParamRowVM)?.param;
if (pvm != null) {
if (pvm is IAlgoParamVM<double>) return DoubleTemplate;
if (pvm is IAlgoParamVM<double?>) return NullableDoubleTemplate;
if (pvm is IAlgoParamVM<int>) return IntTemplate;
if (pvm is IAlgoParamVM<int?>) return NullableIntTemplate;
if (pvm is IAlgoParamVM<uint>) return UIntTemplate;
File diff suppressed because it is too large. Load diff
@@ -100,6 +100,9 @@ namespace mbts.spark {
readonly OrderEntryPanelItemVisibilityVM _cancel_all_visibility = new("Cancel All");
readonly OrderEntryPanelItemVisibilityVM _status_message_visibility = new("Status Message");
readonly PanelPricePointVM _bid_price = new("Bid");
readonly PanelPricePointVM _ask_price = new("Ask");
readonly PanelPricePointVM _mid_price = new("Mid");
readonly PanelRelativePricePointVM _day_change = new("Day Change");
readonly PanelPricePointVM _session_high = new("High");
readonly PanelPricePointVM _session_low = new("Low");
@@ -139,9 +142,6 @@ namespace mbts.spark {
accounts_view = new ListCollectionView<AccountTuple?>(_accounts) {
CustomSort = NullCheckComparer<AccountTuple>.Default
};
// cmds
tick_up_ticks_per_row_cmd = new DelegateCommand(increment_ticks_per_row);
tick_down_ticks_per_row_cmd = new DelegateCommand(decrement_ticks_per_row);
// update
_update = new DeferrableAction(() => result_changed?.Invoke());
mini_ob.result_changed += _update.Invoke;
@@ -191,26 +191,6 @@ namespace mbts.spark {
}
AlgoDefinitionVM algo_factory(AlgoData data) => AlgoDefinitionVM.create(_model, data);
void increment_ticks_per_row() {
var tpr = ticks_per_row;
for (uint i = 1; i < 100; i++) {
var new_tpr = TickUtils.fit_ticks_per_row_to_dollars(security, ticks_per_row + i);
if (new_tpr != tpr) {
ticks_per_row = new_tpr;
break;
}
}
}
void decrement_ticks_per_row() {
var tpr = ticks_per_row;
for (uint i = 1; i < tpr; i++) {
var new_tpr = TickUtils.fit_ticks_per_row_to_dollars(security, tpr - i);
if (new_tpr != tpr) {
ticks_per_row = new_tpr;
break;
}
}
}
}
public event Action result_changed;
@@ -235,15 +215,8 @@ namespace mbts.spark {
}
public uint ticks_per_row {
get => _ticks_per_row;
set => Set(ref _ticks_per_row, value, dependent_props: nameof(rounded_ticks_per_row));
set => Set(ref _ticks_per_row, value);
}
public ICommand tick_up_ticks_per_row_cmd { get; }
public ICommand tick_down_ticks_per_row_cmd { get; }
// since settings profiles may be shared among ladders
// of different securities/tick sizes, the ticks per row setting
// may need to be rounded to a number that is a factor of $1.00
public uint? rounded_ticks_per_row =>
TickUtils.fit_ticks_per_row_to_dollars(_security, ticks_per_row);
public MarketSizeDisplayVM size_display { get; } = new MarketSizeDisplayVM();
public SimpleGridSettingsVM mini_ob { get; } = new SimpleGridSettingsVM(OrderBookGridSettingsManager.hard_column_flags);
@@ -327,7 +300,12 @@ namespace mbts.spark {
public IEnumerable order_entry_panel_items {
get {
// Order these items according to their display order in the actual ladder (from top to
// bottom). There are a lot of them, so this is a simple convenience for the user.
yield return _zoom_slider_visbility;
yield return _ask_price;
yield return _mid_price;
yield return _bid_price;
yield return _day_change;
yield return _session_high;
yield return _session_low;
@@ -450,6 +428,12 @@ namespace mbts.spark {
zoom_factor = settings.zoom_factor;
// left-panel (show/hide)
_zoom_slider_visbility.show = settings.zoom_slider_visible;
_bid_price.show = settings.bid_price_visible;
_bid_price.load_from(settings.panel_price_point_settings.bid_price);
_ask_price.show = settings.ask_price_visible;
_ask_price.load_from(settings.panel_price_point_settings.ask_price);
_mid_price.show = settings.mid_price_visible;
_mid_price.load_from(settings.panel_price_point_settings.mid_price);
_day_change.show = settings.day_visible;
_day_change.load_from(settings.panel_price_point_settings.day_change);
_session_high.show = settings.high_visible;
@@ -537,6 +521,9 @@ namespace mbts.spark {
.ToList();
// left-panel price items
clone.panel_price_point_settings = new LadderPanelPricePointSettings {
bid_price = _bid_price.create(),
ask_price = _ask_price.create(),
mid_price = _mid_price.create(),
day_change = _day_change.create(),
open = _open.create(),
session_low = _session_low.create(),
@@ -561,6 +548,9 @@ namespace mbts.spark {
clone.order_entry_panel_initial_width = _order_entry_panel_width;
clone.zoom_factor = zoom_factor;
// left-panel (components)
clone.bid_price_visible = _bid_price.show;
clone.ask_price_visible = _ask_price.show;
clone.mid_price_visible = _mid_price.show;
clone.day_visible = _day_change.show;
clone.high_visible = _session_high.show;
clone.low_visible = _session_low.show;
File diff suppressed because it is too large. Load diff
@@ -14,6 +14,7 @@ using mbts.ui.utility.text;
using mbts.utils;
using Spark.Core.Disposables;
using Spark.Core.Math;
using System;
using System.Collections;
@@ -62,6 +63,7 @@ namespace mbts.spark {
readonly RefValueContainer<IEnumerable<VolumeAtPriceLevelImmutable>> _volume_container = new();
IDisposable _settings_sub, _volume_sub, _tick_sub, _fair_value_lines_sub, _vm_sub;
readonly ThrottledAction _scroll_to_tick_log_throttle = new(TimeSpan.FromSeconds(5));
readonly SingleValuePump<ScrollViewer> _scroll_viewer_source;
ScrollViewer _scroll_viewer {
@@ -452,8 +454,8 @@ namespace mbts.spark {
public bool scroll_to_tick(long tick) {
if (tick > int.MaxValue) {
Log.Ui.error(
$"Unable to scroll to tick {tick} because it exceeds int.MaxValue");
_scroll_to_tick_log_throttle.Execute(() =>
Log.Ui.error($"Unable to scroll to tick {tick} because it exceeds int.MaxValue"));
return false;
}
return scroll_to_tick((int)tick);
@@ -1113,7 +1115,7 @@ namespace mbts.spark {
Log.assert(_price_dirty);
_price_list = new LadderPriceList {
length = _initial_row_count,
security = security
regional_tick = _spec
};
var mid_tick = security.tickdiff(_mkt_break_lines.origin, 0) ?? 0;
if (mid_tick > int.MaxValue) {
@@ -1264,13 +1266,15 @@ namespace mbts.spark {
}
void _refresh_session_low_line() {
if (_settings.session_low_line.show && _mkt_break_lines.low_render_index.HasValue)
_render_session_line(_session_low_vis, _mkt_break_lines.low_render_index.Value, _settings.session_low_line.color);
if (_settings.session_low_line.show) {
_render_session_line(_session_low_vis, _mkt_break_lines.low_render_index ?? -1, _settings.session_low_line.color);
}
}
void _refresh_session_high_line() {
if (_settings.session_high_line.show && _mkt_break_lines.high_render_index.HasValue)
_render_session_line(_session_high_vis, _mkt_break_lines.high_render_index.Value, _settings.session_high_line.color);
if (_settings.session_high_line.show) {
_render_session_line(_session_high_vis, _mkt_break_lines.high_render_index ?? -1, _settings.session_high_line.color);
}
}
void _refresh_last_trade() {
@@ -1361,7 +1365,7 @@ namespace mbts.spark {
return;
if (_price_list is null) {
_price_list = new LadderPriceList {
security = security
regional_tick = _spec
};
}
_price_list.reset(null, null, _initial_row_count);
@@ -1398,7 +1402,10 @@ namespace mbts.spark {
double _get_bid_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.bid_line(best_bid, best_ask, _vm.settlement, _spec);
var v = best_bid
.if_nan(_spec.tickdown(best_ask))
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _normalize_price(double price) =>
@@ -1407,13 +1414,20 @@ namespace mbts.spark {
double _get_ask_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.ask_line(best_bid, best_ask, _vm.settlement, _spec);
var v = _spec.tickdown(best_ask)
.if_nan(best_bid)
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _get_mid_market_break() {
double best_bid = _get_top_price(_bids);
double best_ask = _get_top_price(_asks);
return LadderPriceLineViewAdapter.mid_line(best_bid, best_ask, _vm.settlement, _spec);
var v = TickUtils.mid_tick(_spec, best_bid, best_ask)
.if_nan(best_bid)
.if_nan(_spec?.tickdown(best_ask) ?? double.NaN)
.if_nan(_vm.settlement);
return _spec.round_to_tick(v, RoundingMode.AbsDown);
}
double _get_session_low() => _normalize_price(_get_session_low_raw());
@@ -1445,7 +1459,13 @@ namespace mbts.spark {
_pending_scroll_to_origin |= _settings == null;
_invalidate_spec();
if (_price_list != null) {
_price_list.security = security;
_pending_price_list = null;
if (_price_list.Count > 0) {
var high_price = _price_list.First();
var new_tickdiff = _spec.count_ticks(high_price);
_price_list.high_tick = (long)new_tickdiff;
}
_price_list.regional_tick = _spec;
}
_bid_vis_tup.glyph_context = glyph_context(s.bid_column);
_ask_vis_tup.glyph_context = glyph_context(s.ask_column);
@@ -1530,6 +1550,7 @@ namespace mbts.spark {
// }
scroll_to_pending_target();
visible_columns_changed?.Invoke();
_refresh_all_visuals();
}
// This is designed to be a redundant null check for _fmt_mkt_depth_item_impl.
@@ -1,62 +0,0 @@
using bts.api;
namespace mbts.spark {
using RegionalTickFactors = user.settings.RegionalTickFactors;
class LadderPriceLineViewAdapter {
public static double bid_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (!double.IsNaN(bid)) {
return bid;
}
if (!double.IsNaN(ask)) {
return _try_tick_down(spec, ask);
}
return settlement;
}
}
public static double ask_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (!double.IsNaN(ask)) {
return _try_tick_down(spec, ask);
}
if (!double.IsNaN(bid)) {
return bid;
}
return settlement;
}
}
public static double mid_line(
double bid, double ask, double settlement, RegionalTickFactors spec) {
return TickUtils.normalize_price(spec, impl());
double impl() {
if (double.IsNaN(bid)) {
if (double.IsNaN(ask)) {
return settlement;
}
return _try_tick_down(spec, ask);
}
if (double.IsNaN(ask)) {
return bid;
}
if (spec is not null) {
return TickUtils.mid_tick(spec, bid, ask);
}
return bid;
}
}
static double _try_tick_down(RegionalTickFactors spec, double value) {
if (spec is not null) {
return spec.tickdown(value);
}
return value;
}
}
}
@@ -16,33 +16,34 @@ namespace mbts.spark {
long _length;
long _high_tick;
SecurityImmutable? _security;
RegionalTickFactors _regional_tick_backing;
RegionalTickFactors _regional_tick =>
_regional_tick_backing ??= TickUtils.get_regional_ticks(_security);
public LadderPriceList() { }
public LadderPriceList()
: this(RegionalTickFactors.Default) { }
public LadderPriceList(RegionalTickFactors regional_tick) =>
this.regional_tick = regional_tick;
public LadderPriceList(LadderPriceList other) {
_length = other._length;
_high_tick = other._high_tick;
_security = other._security;
regional_tick = other.regional_tick;
}
public event NotifyCollectionChangedEventHandler CollectionChanged;
public SecurityImmutable? security {
get => _security;
RegionalTickFactors _regional_tick;
public RegionalTickFactors regional_tick {
get => _regional_tick;
set {
if (value == _security) {
return;
if (value is null) {
_regional_tick = RegionalTickFactors.Default;
} else {
_regional_tick = value;
}
_security = value;
_regional_tick_backing = null;
}
}
public ContractSpecificationImmutable spec { get; set; }
public long high_tick {
get => _high_tick;
set => _high_tick = value;
@@ -54,8 +55,8 @@ namespace mbts.spark {
}
public double start {
get => _regional_tick.tickup<double>(0, (uint)high_tick);
set => high_tick = _regional_tick.tickdiff(value, 0) ?? high_tick;
get => regional_tick.tickup<double>(0, (uint)high_tick);
set => high_tick = regional_tick.tickdiff(value, 0) ?? high_tick;
}
public long length {
@@ -80,7 +81,7 @@ namespace mbts.spark {
public bool IsReadOnly => false;
public double this[int idx] {
get => _regional_tick.tick<double>(0, high_tick - idx);
get => regional_tick.tick<double>(0, high_tick - idx);
set => throw new NotSupportedException();
}
@@ -94,7 +95,7 @@ namespace mbts.spark {
GetEnumerator();
public int IndexOf(double item) {
var idx = _regional_tick.tickdiff(start, item) ?? -1;
var idx = regional_tick.tickdiff(start, item) ?? -1;
if (idx < 0 || idx >= length) {
return -1;
}
@@ -209,7 +210,7 @@ namespace mbts.spark {
other != null &&
_high_tick == other._high_tick &&
_length == other._length &&
_regional_tick.safe_equals(other._regional_tick);
regional_tick.safe_equals(other.regional_tick);
public override bool Equals(object obj) =>
Equals(obj as LadderPriceList);
@@ -218,7 +219,7 @@ namespace mbts.spark {
HashCode.Combine(_high_tick, _length);
double _tick_to_price(long tick) =>
_regional_tick.tick<double>(0, tick);
regional_tick.tick<double>(0, tick);
void _add_tick(long tick) {
int idx;
@@ -79,13 +79,6 @@ namespace mbts.spark {
public static int index_of(IList<double> prices, double price, IComparer<double> comparer, bool relative_idx) {
for (int i = 1; i < prices.Count; i++) {
Log.assert(prices[i - 1] > prices[i]);
var c = comparer.Compare(prices[i - 1], prices[i]);
if (c >= 0) {
c = comparer.Compare(prices[i - 1], prices[i]);
} else {
c = comparer.Compare(prices[i - 1], prices[i]);
}
Log.assert(c < 0);
}
var idx = CollectionHelper.binary_search(prices, price, comparer);
if (relative_idx && idx < 0) {
@@ -232,8 +225,9 @@ namespace mbts.spark {
using (var dc = dv.RenderOpen())
using (_draw_with_clip(dc, settings, row_height, prices.Count)) {
//dc.DrawRectangle(background, null, new Rect(0, 0, settings.width, prices.Count * row_height));
if (!prices.within_range(origin_index) || rungs.is_null_or_empty())
if (rungs.is_null_or_empty()) {
return;
}
var foreground = settings.foreground.rgb_brush();
int curr_index = origin_index;
double curr_price = prices[curr_index];
@@ -254,8 +248,8 @@ namespace mbts.spark {
var price = ticks.HasValue ? spec.tickup(0, ticks.Value) : rung.price;
// prices are in descending order, so get diff from curr_price - price
var tick_diff = spec.tickdiff(curr_price, price).assert_value();
checked {
curr_index += (int)tick_diff;
if (!MathUtils.try_increment(ref curr_index, tick_diff)) {
continue;
}
curr_price = price;
if (curr_index >= 0 && curr_index < prices.Count) {
File diff suppressed because it is too large. Load diff
@@ -39,6 +39,9 @@
<cv:EnumCharacterCasingConverter x:Key="casing_converter"/>
<cv:GridLengthConverter x:Key="GridLengthPixelConverter" UnitType="Pixel" />
<cv:ResponsiveTextConverter x:Key="BidPriceTextConverter" LongText="Bid:" ShortText="B:" Threshold="99" />
<cv:ResponsiveTextConverter x:Key="AskPriceTextConverter" LongText="Ask:" ShortText="A:" Threshold="99" />
<cv:ResponsiveTextConverter x:Key="MidPriceTextConverter" LongText="Mid:" ShortText="M:" Threshold="99" />
<cv:ResponsiveTextConverter x:Key="DayTextConverter" LongText="Day:" ShortText="D:" Threshold="99" />
<cv:ResponsiveTextConverter x:Key="HighTextConverter" LongText="High:" ShortText="H:" Threshold="99" />
<cv:ResponsiveTextConverter x:Key="LowTextConverter" LongText="Low:" ShortText="L:" Threshold="99" />
@@ -363,13 +366,103 @@
<Setter Property="Grid.Column" Value="2"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="Margin" Value="0,0,0,2"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Padding" Value="4,1"/>
</Style>
<Style x:Key="LeftPanelPricePointText" TargetType="TextBlock">
<Setter Property="HorizontalAlignment" Value="Right" />
<Setter Property="FontWeight" Value="Bold"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.default_text}"/>
</Style>
<Style x:Key="LeftPanelPricePointButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Setter Property="Grid.Column" Value="2" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="HorizontalAlignment" Value="Stretch" />
<Setter Property="HorizontalContentAlignment" Value="Right" />
<Setter Property="Margin" Value="0,0,0,2" />
<Setter Property="Padding" Value="4,1" />
<Setter Property="Cursor" Value="Hand" />
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Border
x:Name="Border"
Background="{TemplateBinding Background}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="0"
Height="Auto"
Padding="0"
SnapsToDevicePixels="True">
<VisualStateManager.VisualStateGroups>
<VisualStateGroup Name="CommonStates">
<VisualState Name="Normal" />
<VisualState Name="MouseOver">
<Storyboard>
<DoubleAnimation Storyboard.TargetName="HoverRect" Storyboard.TargetProperty="Fill.Opacity" BeginTime="0" Duration="00:00:00.15" To="0.20">
<DoubleAnimation.EasingFunction>
<QuadraticEase />
</DoubleAnimation.EasingFunction>
</DoubleAnimation>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.mouseover_border}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="Pressed">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.pressed_background}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.pressed_border}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState Name="Disabled">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="Background">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.disabled_background}" />
</ObjectAnimationUsingKeyFrames>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.disabled_border}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
<VisualStateGroup Name="FocusStates">
<VisualState Name="Unfocused" />
<VisualState Name="Focused">
<Storyboard>
<ObjectAnimationUsingKeyFrames Storyboard.TargetName="Border" Storyboard.TargetProperty="BorderBrush">
<DiscreteObjectKeyFrame KeyTime="0" Value="{u:BTSBrush UI.Button.focused_border}" />
</ObjectAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<Grid>
<Rectangle Name="HoverRect" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" IsHitTestVisible="False">
<Rectangle.Fill>
<SolidColorBrush Color="White" Opacity="0" />
</Rectangle.Fill>
</Rectangle>
<ContentPresenter
Margin="{TemplateBinding Padding}"
HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
RecognizesAccessKey="True" />
</Grid>
</Border>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<sys:Double x:Key="MaxZoomFactor">1.5</sys:Double>
<sys:Double x:Key="MinZoomFactor">0.5</sys:Double>
</ResourceDictionary>
@@ -434,6 +527,9 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
@@ -441,9 +537,123 @@
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<!-- Day Change (label) -->
<!-- Ask Price (label) -->
<TextBlock
Grid.Row="0"
Text="{Binding left_panel_width, Converter={StaticResource AskPriceTextConverter}}"
Visibility="{Binding
ask_price_style.actual_show_label,
Converter={StaticResource BooleanToVisibilityConverter}}"
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Ask Price (value) -->
<Button
Grid.Row="0"
Visibility="{Binding
ask_price_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Ask"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding ask_price}"
Style="{StaticResource LeftPanelPricePointButton}">
<Button.Background>
<SolidColorBrush Color="{Binding ask_price_style.background_color}" Opacity="1" />
</Button.Background>
<TextBlock
FontFamily="{Binding ask_price_style.font_family}"
FontSize="{Binding ask_price_style.font_size}"
FontWeight="{Binding ask_price_style.font_weight}"
Foreground="{Binding
ask_price_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="ask_price"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Button>
<!-- Mid Price (label) -->
<TextBlock
Grid.Row="1"
Text="{Binding left_panel_width, Converter={StaticResource MidPriceTextConverter}}"
Visibility="{Binding
mid_price_style.actual_show_label,
Converter={StaticResource BooleanToVisibilityConverter}}"
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Mid Price (value) -->
<Button
Grid.Row="1"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding mid_price}"
Visibility="{Binding
mid_price_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Mid"
Style="{StaticResource LeftPanelPricePointButton}">
<Button.Background>
<SolidColorBrush Color="{Binding mid_price_style.background_color}" Opacity="1" />
</Button.Background>
<TextBlock
FontFamily="{Binding mid_price_style.font_family}"
FontSize="{Binding mid_price_style.font_size}"
FontWeight="{Binding mid_price_style.font_weight}"
Foreground="{Binding
mid_price_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="mid_price"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Button>
<!-- Bid Price (label) -->
<TextBlock
Grid.Row="2"
Text="{Binding left_panel_width, Converter={StaticResource BidPriceTextConverter}}"
Visibility="{Binding
bid_price_style.actual_show_label,
Converter={StaticResource BooleanToVisibilityConverter}}"
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Bid Price (value) -->
<Button
Grid.Row="2"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding bid_price}"
Visibility="{Binding
bid_price_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Bid"
Style="{StaticResource LeftPanelPricePointButton}">
<Button.Background>
<SolidColorBrush Color="{Binding bid_price_style.background_color}" Opacity="1" />
</Button.Background>
<TextBlock
FontFamily="{Binding bid_price_style.font_family}"
FontSize="{Binding bid_price_style.font_size}"
FontWeight="{Binding bid_price_style.font_weight}"
Foreground="{Binding
bid_price_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="bid_price"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Button>
<!-- Day Change (label) -->
<TextBlock
Grid.Row="3"
Text="{Binding left_panel_width, Converter={StaticResource DayTextConverter}}"
Visibility="{Binding
day_change_style.actual_show_label,
@@ -452,7 +662,7 @@
<!-- Day Change (value) -->
<Border
Grid.Row="0"
Grid.Row="3"
Background="{Binding
day_change_background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
@@ -479,7 +689,7 @@
<!-- High (label) -->
<TextBlock
Grid.Row="1"
Grid.Row="4"
Text="{Binding left_panel_width, Converter={StaticResource HighTextConverter}}"
Visibility="{Binding
session_high_style.actual_show_label,
@@ -487,15 +697,17 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- High (value) -->
<Border
Grid.Row="1"
<Button
Grid.Row="4"
Background="{Binding
session_high_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding session_high}"
Visibility="{Binding
session_high_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Session High"
Style="{StaticResource LeftPanelPricePointBorder}">
Style="{StaticResource LeftPanelPricePointButton}">
<TextBlock
FontFamily="{Binding session_high_style.font_family}"
FontSize="{Binding session_high_style.font_size}"
@@ -504,24 +716,19 @@
session_high_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<Hyperlink
Command="{Binding go_to_price_cmd}" CommandParameter="{Binding session_high}">
<TextBlock>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="session_high"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Hyperlink>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="session_high"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</Button>
<!-- Low (label) -->
<TextBlock
Grid.Row="2"
Grid.Row="5"
Text="{Binding left_panel_width, Converter={StaticResource LowTextConverter}}"
Visibility="{Binding
session_low_style.actual_show_label,
@@ -529,15 +736,17 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Low (value) -->
<Border
Grid.Row="2"
<Button
Grid.Row="5"
Background="{Binding
session_low_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding session_low}"
Visibility="{Binding
session_low_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Session Low"
Style="{StaticResource LeftPanelPricePointBorder}">
Style="{StaticResource LeftPanelPricePointButton}">
<TextBlock
FontFamily="{Binding session_low_style.font_family}"
FontSize="{Binding session_low_style.font_size}"
@@ -546,24 +755,19 @@
session_low_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<Hyperlink
Command="{Binding go_to_price_cmd}" CommandParameter="{Binding session_low}">
<TextBlock>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="session_low"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Hyperlink>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="session_low"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</Button>
<!-- Open (label) -->
<TextBlock
Grid.Row="3"
Grid.Row="6"
Text="{Binding left_panel_width, Converter={StaticResource OpenTextConverter}}"
Visibility="{Binding
open_style.actual_show_label,
@@ -571,15 +775,17 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Open (value) -->
<Border
Grid.Row="3"
<Button
Grid.Row="6"
Background="{Binding
open_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding open}"
Visibility="{Binding
open_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Open"
Style="{StaticResource LeftPanelPricePointBorder}">
Style="{StaticResource LeftPanelPricePointButton}">
<TextBlock
FontFamily="{Binding open_style.font_family}"
FontSize="{Binding open_style.font_size}"
@@ -587,23 +793,19 @@
Foreground="{Binding
open_style.font_color, Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<Hyperlink Command="{Binding go_to_price_cmd}" CommandParameter="{Binding open}">
<TextBlock>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="open"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Hyperlink>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="open"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</Button>
<!-- Settlement (label) -->
<TextBlock
Grid.Row="4"
Grid.Row="7"
Text="{Binding
left_panel_width, Converter={StaticResource SettlementTextConverter}}"
Visibility="{Binding
@@ -612,15 +814,17 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Settlement (value) -->
<Border
Grid.Row="4"
<Button
Grid.Row="7"
Background="{Binding
settlement_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding settlement}"
Visibility="{Binding
settlement_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Settlement"
Style="{StaticResource LeftPanelPricePointBorder}">
Style="{StaticResource LeftPanelPricePointButton}">
<TextBlock
FontFamily="{Binding settlement_style.font_family}"
FontSize="{Binding settlement_style.font_size}"
@@ -629,23 +833,18 @@
settlement_style.font_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<Hyperlink
Command="{Binding go_to_price_cmd}" CommandParameter="{Binding settlement}">
<TextBlock>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="settlement"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Hyperlink>
<TextBlock.Text>
<MultiBinding Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="settlement"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</Button>
<!-- Theo (label) -->
<TextBlock
Grid.Row="5"
Grid.Row="8"
Text="{Binding left_panel_width, Converter={StaticResource TheoTextConverter}}"
Visibility="{Binding
theo_style.actual_show_label,
@@ -653,15 +852,17 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<!-- Theo (value) -->
<Border
Grid.Row="5"
<Button
Grid.Row="8"
Background="{Binding
theo_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Command="{Binding go_to_price_cmd}"
CommandParameter="{Binding theo}"
Visibility="{Binding
theo_style.show, Converter={StaticResource BooleanToVisibilityConverter}}"
ToolTip="Theo"
Style="{StaticResource LeftPanelPricePointBorder}">
Style="{StaticResource LeftPanelPricePointButton}">
<TextBlock
FontFamily="{Binding theo_style.font_family}"
FontSize="{Binding theo_style.font_size}"
@@ -669,23 +870,19 @@
Foreground="{Binding
theo_style.font_color, Converter={x:Static cv:ColorToBrushConverter.Instance}}"
Style="{StaticResource LeftPanelPricePointText}">
<Hyperlink Command="{Binding go_to_price_cmd}" CommandParameter="{Binding theo}">
<TextBlock>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="theo"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Hyperlink>
<TextBlock.Text>
<MultiBinding
Converter="{StaticResource TickDisplayConverter}" Mode="OneWay">
<Binding Path="theo"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</TextBlock.Text>
</TextBlock>
</Border>
</Button>
<!-- Delta -->
<TextBlock
Grid.Row="6"
Grid.Row="9"
Text="{Binding left_panel_width, Converter={StaticResource DeltaTextConverter}}"
Visibility="{Binding
delta_style.actual_show_label,
@@ -693,7 +890,7 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<Border
Grid.Row="6"
Grid.Row="9"
Background="{Binding
delta_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
@@ -714,7 +911,7 @@
<!-- Vega -->
<TextBlock
Grid.Row="7"
Grid.Row="10"
Text="{Binding left_panel_width, Converter={StaticResource VegaTextConverter}}"
Visibility="{Binding
vega_style.actual_show_label,
@@ -722,7 +919,7 @@
Style="{StaticResource LeftPanelPricePointLabel}" />
<Border
Grid.Row="7"
Grid.Row="10"
Background="{Binding
vega_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
@@ -743,7 +940,7 @@
<!-- Volume (label) -->
<TextBlock
Grid.Column="0"
Grid.Row="8"
Grid.Row="11"
Text="{Binding left_panel_width, Converter={StaticResource VolumeTextConverter}}"
Visibility="{Binding
volume_style.actual_show_label,
@@ -752,7 +949,7 @@
<!-- Volume (price) -->
<Border
Grid.Row="8"
Grid.Row="11"
Background="{Binding
volume_style.background_color,
Converter={x:Static cv:ColorToBrushConverter.Instance}}"
@@ -793,6 +990,7 @@
Margin="2,10,2,2"
ItemsSource="{Binding accounts}"
SelectedItem="{Binding selected_account}"
ToolTip="Account"
Visibility="{Binding
DataContext.show_account,
RelativeSource={RelativeSource AncestorType=UserControl},
@@ -802,6 +1000,7 @@
<ComboBox
DataContext="{Binding order_properties_vm}" ItemsSource="{Binding time_in_forces}"
SelectedItem="{Binding selected_time_in_force}" Margin="2"
ToolTip="Time In Force"
Visibility="{Binding
DataContext.show_tif,
RelativeSource={RelativeSource AncestorType=UserControl},
@@ -824,6 +1023,7 @@
IsOpen="{Binding is_expanded}"
ItemsSource="{Binding algo_definitions_view}"
SelectedItem="{Binding selected_algo_definition}"
ToolTip="Order/Algo Type"
Visibility="{Binding
DataContext.show_order_type,
RelativeSource={RelativeSource AncestorType=UserControl},
@@ -879,6 +1079,7 @@
Increment="{Binding size_calculator.unit_quantity}"
Minimum="0"
TickDisplaySettings="{Binding size_calculator.display_settings}"
ToolTip="Size"
Value="{Binding size_calculator.display_value, Mode=TwoWay}" />
<!-- Qty quick buttons -->
@@ -901,7 +1102,8 @@
RelativeSource={RelativeSource AncestorType=ItemsControl}}"
Content="{Binding}"
Focusable="False"
Foreground="{u:BTSColor UI.Button.normal_foreground}">
Foreground="{u:BTSColor UI.Button.normal_foreground}"
ToolTip="Add to Size">
<Button.CommandParameter>
<MultiBinding
Converter="{x:Static cv:DynamicDoubleMultiplierConverter.Instance}">
@@ -921,6 +1123,7 @@
Margin="2"
HorizontalAlignment="Stretch"
Command="{Binding size_calculator.clear}"
ToolTip="Clear Size"
Visibility="{Binding
show_clear, Converter={StaticResource BooleanToVisibilityConverter}}"
Style="{StaticResource CommonButton}">
@@ -931,6 +1134,7 @@
<CheckBox
Margin="2"
IsChecked="{Binding auto_clear}"
ToolTip="Clear Size after order"
Visibility="{Binding
show_auto_clear, Converter={StaticResource BooleanToVisibilityConverter}}">
Auto Clear
@@ -76,14 +76,8 @@ namespace mbts.spark {
if (show_total_pos) add_part(total_pos_text, " (", ")");
//
if (part_count > 1) {
// This is a complex expression (showing more than 1 value) - wrap it in single quotes.
// Explicitly state which value will be copied to the size input.
sb.Insert(0, "'");
sb.Add("'");
sb.Add(" position\n(click to copy ", primary_pos, " to size)");
} else {
// Only showing 1 value, no need for single quotes,
// nor an explicit statement that indicates which value will be copied to the size input.
sb.Add(" position\n(click to copy to size)");
}
return sb.ToString();
@@ -289,7 +289,8 @@ namespace bts.shell.pnl {
public AccountTuple account => new(account_id, account_name);
public string symbol => security?.pnl_symbol() ?? string.Empty;
public DateTime expiration => security?.earliest_expiration() ?? DateTime.MinValue;
public DateTime expiration =>
security?.normal_expirations()?.MinOrDefault(DateTime.MinValue) ?? DateTime.MinValue;
public double effective_cpp => override_cpp ?? default_cpp;
/// Market/Calc
@@ -18,7 +18,7 @@
<sys:Double x:Key="VerticalSpacing">4.0</sys:Double>
<sys:Double x:Key="ButtonHeight">22.0</sys:Double>
<cv:NullableDoubleConverter x:Key="TickDefaultPriceConverter" DefaultValue="0"/>
<Style TargetType="Button" BasedOn="{StaticResource {x:Type Button}}">
<Style TargetType="Button" BasedOn="{StaticResource DefaultButton}">
<Setter Property="Height" Value="{StaticResource ButtonHeight}"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
</Style>
@@ -53,8 +53,6 @@
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="140"/>
@@ -77,6 +75,7 @@
RegionalTick="{Binding price_tick}"
Focusable="false"
TickDefaultValue="{Binding current_price, Converter={StaticResource TickDefaultPriceConverter}, FallbackValue={u:Double 0}}"
ToolTip="Price"
Value="{Binding price}"
/>
<c:TickUpDownNullableDouble
@@ -88,6 +87,7 @@
Increment="{Binding size_calculator.unit_quantity}"
Minimum="0"
TickDisplaySettings="{Binding size_calculator.display_settings}"
ToolTip="Size"
Value="{Binding size_calculator.display_value}"
/>
</Grid>
@@ -97,13 +97,24 @@
<ColumnDefinition Width="{Binding Source={StaticResource HorizontalSpacing}}"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Command="{Binding set_price_command}" CommandParameter="{Binding bbo.bid}" Foreground="{u:BTSColor MarketData.bid}" FontWeight="Bold">
<Button
Command="{Binding set_price_command}"
CommandParameter="{Binding bbo.bid}"
Foreground="{u:BTSColor MarketData.bid}"
FontWeight="Bold"
ToolTip="Bid Price">
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="bbo.bid"/>
<Binding Path="security.ContractSpec"/>
</MultiBinding>
</Button>
<Button Grid.Column="2" Command="{Binding set_price_command}" CommandParameter="{Binding bbo.ask}" Foreground="{u:BTSColor MarketData.ask}" FontWeight="Bold">
<Button
Grid.Column="2"
Command="{Binding set_price_command}"
CommandParameter="{Binding bbo.ask}"
Foreground="{u:BTSColor MarketData.ask}"
FontWeight="Bold"
ToolTip="Ask Price">
<MultiBinding Converter="{StaticResource TickDisplayConverter}">
<Binding Path="bbo.ask"/>
<Binding Path="security.ContractSpec"/>
@@ -120,7 +131,7 @@
Command="{Binding size_calculator.set_actual_value_command}"
CommandParameter="{Binding bbo.bid_size}"
Foreground="{u:BTSColor MarketData.bid}"
>
ToolTip="Bid Size">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="bbo.bid_size" />
<Binding Path="qty_display" />
@@ -131,20 +142,20 @@
Command="{Binding size_calculator.set_actual_value_command}"
CommandParameter="{Binding bbo.ask_size}"
Foreground="{u:BTSColor MarketData.ask}"
>
ToolTip="Ask Size">
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding Path="bbo.ask_size" />
<Binding Path="qty_display" />
</MultiBinding>
</Button>
</Grid>
<Grid Grid.Row="4" Grid.RowSpan="3">
<Grid Grid.Row="4">
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ItemsControl Margin="-2,-2,-2,0" DataContext="{Binding size_calculator}" ItemsSource="{Binding buttons}" Focusable="False">
<ItemsControl Margin="0,0,-4,-4" DataContext="{Binding size_calculator}" ItemsSource="{Binding buttons}" Focusable="False">
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate>
<UniformGrid Columns="3" Focusable="False"/>
@@ -153,11 +164,11 @@
<ItemsControl.ItemTemplate>
<DataTemplate>
<Button
Margin="2,4,2,0"
Margin="0,0,4,4"
Content="{Binding}"
Focusable="False"
Command="{Binding Path=DataContext.click, RelativeSource={RelativeSource AncestorType=ItemsControl}}"
>
ToolTip="Add to Size">
<Button.CommandParameter>
<MultiBinding Converter="{x:Static cv:TickDisplayConverter.Instance}">
<Binding />
@@ -170,35 +181,35 @@
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Button Grid.Row="2" Command="{Binding size_calculator.clear}">Clear</Button>
<Button
Grid.Row="2"
Command="{Binding size_calculator.clear}"
Content="Clear"
ToolTip="Clear Size" />
</Grid>
<Grid Grid.Row="4" Grid.Column="2" Grid.RowSpan="3">
<Grid Grid.Row="4" Grid.Column="2">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition/>
<RowDefinition/>
<RowDefinition Height="{Binding Source={StaticResource VerticalSpacing}}"/>
<RowDefinition/>
</Grid.RowDefinitions>
<ComboBox
Grid.ColumnSpan="2"
usp:OrderModificationControl.IsDirty="{Binding account_dirty, FallbackValue={u:False}}"
IsEnabled="{Binding can_change_account, FallbackValue={u:True}}"
ItemsSource="{Binding properties_vm.accounts}"
Margin="0,2"
SelectedItem="{Binding properties_vm.selected_account}"
/>
ToolTip="Account" />
<ComboBox
Grid.Row="1"
Grid.ColumnSpan="2"
Grid.Row="2"
usp:OrderModificationControl.IsDirty="{Binding time_in_force_dirty, FallbackValue={u:False}}"
IsEnabled="{Binding can_change_time_in_force, FallbackValue={u:True}}"
ItemsSource="{Binding properties_vm.time_in_forces}"
Margin="0,2"
SelectedItem="{Binding properties_vm.selected_time_in_force}"
/>
ToolTip="Time In Force" />
<uag:OrderDetailsPopupControl
Grid.Row="2"
Margin="0,2"
Grid.Row="4"
DataContext="{Binding properties_vm}"
usp:OrderModificationControl.IsDirty="{Binding DataContext.order_type_dirty, RelativeSource={RelativeSource AncestorType=usp:OrderModificationControl}, FallbackValue={u:False}}"
HasEditableProperties="{Binding can_expand, FallbackValue={u:False}}"
@@ -207,7 +218,7 @@
IsOpen="{Binding is_expanded, FallbackValue={u:False}}"
ItemsSource="{Binding algo_definitions_view}"
SelectedItem="{Binding selected_algo_definition}"
>
ToolTip="Order/Algo Type">
<uag:OrderDetailsPopupControl.Style>
<Style TargetType="uag:OrderDetailsPopupControl" BasedOn="{StaticResource {x:Type uag:OrderDetailsPopupControl}}">
<Style.Triggers>
@@ -128,7 +128,7 @@ namespace mbts.spark {
new PropertyValidation<AccountTuple?>(
a => (a.HasValue && !string.IsNullOrWhiteSpace(a.Value.name) && accounts.Contains(a.Value), "Please select an account"))
});
attach(_accounts, accounts_src.Select(accs => accs.Values.ToList()), inline_account_src);
attach(_accounts, accounts_src.Select(accs => accs.Values.ToListSorted()), inline_account_src);
// time in force
_time_in_force = new SelectorProperty<TimeInForce>(
+1 -1
View File
@@ -398,7 +398,7 @@
$"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 = Math.Round(rounded_qty - iqty, 2) });
return ((uint)iqty, new() { Fraction = Math.Round(rounded_qty - iqty, 6) });
}
private CustomOrderDefinitionImmutable? _create_custom_def_for_stop_and_stop_limit(OrderRecordImmutable order, ref double stop_price) {
@@ -227,7 +227,7 @@ namespace mbts.ui {
public static BTSColor atm_background => BTSCoreColors.gray_dark;
public static BTSColor session_low => 0xff59596b;
public static BTSColor session_low => 0xff8f5924;
public static BTSColor session_high => 0xff239b00;
public static BTSColor session_range_fill => 0x1a000000;
@@ -984,7 +984,7 @@ namespace mbts.ui {
public static BTSColor alternate_column_foreground => UI.foreground_standout;
public static BTSColor bid_line => BTSCoreColors.blue_light_dark_saturated;
public static BTSColor ask_line => BTSCoreColors.red_light_dark_saturated;
public static BTSColor mid_line => 0x40000000;
public static BTSColor mid_line => 0xffa4a4a4;
public static BTSColor default_column_background => 0xff141420;//0xff28283b;
public static BTSColor alternate_column_background => 0xff141420;// 0xff494957;
@@ -5,7 +5,8 @@ using mbts.ui.utility.text;
using ProtoBuf;
using System;
using Spark.Core.Protobuf;
using System.Windows;
using System.Windows.Media;
@@ -13,7 +14,7 @@ using FontFamily = System.Windows.Media.FontFamily;
namespace bts.proto {
[ProtoContract]
class FontParamsProto : IEquatable<FontParamsProto> {
class FontParamsProto : IProtobuf<FontParamsProto> {
[ProtoMember(1)]
public TypefaceProto typeface { get; set; }
[ProtoMember(2)]
@@ -24,6 +25,27 @@ namespace bts.proto {
public string font_family => typeface.font_family;
public int font_weight => typeface.font_weight;
public FontParamsProto With(TypefaceProto? typeface = null, double? font_size = null, uint? font_color = null, bool in_place = false) {
var rv = in_place ? this : Clone();
if (typeface.HasValue) {
rv.typeface = typeface.Value;
}
if (font_size.HasValue) {
rv.font_size = font_size.Value;
}
if (font_color.HasValue) {
rv.font_color = font_color.Value;
}
return rv;
}
public FontParamsProto Clone() =>
new() {
typeface = typeface.Clone(),
font_size = font_size,
font_color = font_color,
};
public bool Equals(FontParamsProto other) =>
other != null &&
typeface == other.typeface &&
@@ -4,14 +4,15 @@ using mbts.ui.utility.text;
using ProtoBuf;
using System;
using Spark.Core.Protobuf;
using System.Windows;
using FontFamily = System.Windows.Media.FontFamily;
namespace bts.proto {
[ProtoContract]
readonly struct TypefaceProto : IEquatable<TypefaceProto> {
readonly struct TypefaceProto : IProtobuf<TypefaceProto> {
static readonly int _type_hash = typeof(TypefaceProto).GetHashCode();
[ProtoMember(1)]
@@ -30,6 +31,9 @@ namespace bts.proto {
font_family ?? this.font_family,
font_weight ?? this.font_weight);
public TypefaceProto Clone() =>
new(font_family.ToString(), font_weight);
public bool Equals(TypefaceProto other) =>
font_family == other.font_family &&
font_weight == other.font_weight;
@@ -20,13 +20,23 @@ namespace mbts.ui {
}
public static class AutoFocusTargetProvider {
public static IAutoFocusTargetProvider<T> TypeProvider<T>(FrameworkElement root, bool focus, bool focus_keyboard, bool release_keyboard, bool capture_mouse, bool release_mouse) where T : FrameworkElement =>
new AnonymousProvider<T>(() => root.descendants_of_type<T>().FirstOrDefault(), focus, focus_keyboard, release_keyboard, capture_mouse, release_mouse);
public static IAutoFocusTargetProvider TypeProvider(Type type, FrameworkElement root, bool focus, bool focus_keyboard, bool release_keybobard, bool capture_mouse, bool release_mouse) =>
public static IAutoFocusTargetProvider TypeProvider(
Type type,
FrameworkElement root,
bool focus = true,
bool focus_keyboard = false,
bool release_keyboard = true,
bool capture_mouse = false,
bool release_mouse = true) =>
new AnonymousProvider<FrameworkElement>(
() => root.visual_children_where(el => type.IsAssignableFrom(el.GetType())).Cast<FrameworkElement>().FirstOrDefault(),
focus, focus_keyboard, release_keybobard, capture_mouse, release_mouse);
() => root.visual_children_where(el => type.IsAssignableFrom(el.GetType()))
.Cast<FrameworkElement>()
.FirstOrDefault(),
focus,
focus_keyboard,
release_keyboard,
capture_mouse,
release_mouse);
private class AnonymousProvider<T> : IAutoFocusTargetProvider<T> where T : FrameworkElement {
readonly Func<T> _get_target;
@@ -3,6 +3,7 @@
x:ClassModifier="internal"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="clr-namespace:mbts.ui"
xmlns:c="clr-namespace:mbts.ui.controls"
>
<UserControl.Resources>
@@ -21,7 +22,7 @@
<GroupBox Header="Font Family" Height="{Binding ActualHeight, ElementName=_panel_right}">
<ListBox
x:Name="_font_family_list_box"
Background="White"
Background="{u:BTSBrush UI.ListBox.normal_background}"
ItemsSource="{Binding FontFamilies, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
SelectedItem="{Binding SelectedFontFamily, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
>
@@ -40,7 +41,7 @@
</Grid.RowDefinitions>
<GroupBox Header="Font Weight">
<ListBox
Background="White"
Background="{u:BTSBrush UI.ListBox.normal_background}"
ItemsSource="{Binding FontWeights, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
SelectedItem="{Binding SelectedFontWeight, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
>
@@ -73,7 +74,7 @@
FontFamily="{Binding SelectedFontFamily, Mode=OneWay, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
FontSize="{Binding SelectedFontSize, Mode=OneWay, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
FontWeight="{Binding SelectedFontWeight, Mode=OneWay, RelativeSource={RelativeSource AncestorType=c:FontPicker}}"
Foreground="{Binding SelectedFontColor, Mode=OneWay, RelativeSource={RelativeSource AncestorType=c:FontPicker}, Converter={StaticResource ColorToBrushConverter}}"
Foreground="{u:BTSBrush UI.default_text}"
TextWrapping="Wrap"
>
<TextBlock.Inlines>
@@ -12,8 +12,12 @@
x:Name="order_type"
Text="{Binding algo_root.order_type, Converter={StaticResource OrderTypeDisplayTextConverter}, StringFormat='{}{0}: ', Mode=OneWay}"
FontWeight="Bold"
/>
<TextBlock x:Name="display_name" Text="{Binding name, Mode=OneWay}" FontWeight="Normal"/>
Foreground="{u:BTSBrush UI.default_text}" />
<TextBlock
x:Name="display_name"
Text="{Binding name, Mode=OneWay}"
FontWeight="Normal"
Foreground="{u:BTSBrush UI.default_text}" />
</StackPanel>
<DataTemplate.Triggers>
<DataTrigger Value="{u:True}">
@@ -87,10 +87,10 @@
</c:TickUpDown>
</ControlTemplate>
<Style TargetType="usp:PriceEntryControl">
<Setter Property="Background" Value="{u:BTSColor UI.input_background}" />
<Setter Property="Background" Value="{u:BTSBrush UI.Button.normal_background}" />
<Setter Property="Foreground" Value="{u:BTSColor UI.input_text}" />
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1" />
<Setter Property="BorderThickness" Value="0" />
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Template" Value="{StaticResource PriceEntryTemplate}"/>
</Style>
@@ -14,7 +14,7 @@
<Style TargetType="{x:Type c:TickUpDown}">
<Setter Property="Background" Value="{StaticResource TextBox.Static.Background.Brush}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="Height" Value="20" />
@@ -75,7 +75,8 @@
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="BorderBrush" Value="{StaticResource TextBox.MouseOver.Border.Brush}"/>
<Setter TargetName="Bd" Property="Background" Value="{u:BTSBrush UI.Button.mouseover_background}"/>
<Setter TargetName="Bd" Property="BorderBrush" Value="{u:BTSBrush UI.Button.mouseover_border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
@@ -133,7 +134,8 @@
</Border>
<ControlTemplate.Triggers>
<Trigger Property="IsMouseOver" Value="True">
<Setter TargetName="Bd" Property="BorderBrush" Value="{StaticResource TextBox.MouseOver.Border.Brush}"/>
<Setter TargetName="Bd" Property="Background" Value="{u:BTSBrush UI.Button.mouseover_background}"/>
<Setter TargetName="Bd" Property="BorderBrush" Value="{u:BTSBrush UI.Button.mouseover_border}"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
@@ -145,7 +147,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -188,7 +190,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -230,7 +232,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -272,7 +274,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -310,7 +312,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -348,7 +350,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -384,7 +386,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -428,7 +430,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -466,7 +468,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -548,7 +550,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -586,7 +588,7 @@
<Setter Property="Background" Value="{u:BTSColor UI.TextBox.default_background}"/>
<Setter Property="Foreground" Value="{u:BTSColor UI.TextBox.default_foreground}"/>
<Setter Property="BorderBrush" Value="{StaticResource TextBox.Static.Border.Brush}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="HorizontalContentAlignment" Value="Stretch"/>
<Setter Property="VerticalContentAlignment" Value="Stretch"/>
<Setter Property="IsTabStop" Value="False"/>
@@ -1,248 +1,264 @@
using bts.utils;
using mbts.utils;
using Spark.Core.Disposables;
using Spark.ViewModel.Commands;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
namespace mbts.ui {
static class Behavior {
#region CloseWindow
public static readonly DependencyProperty CloseWindowProperty = DependencyProperty.RegisterAttached("CloseWindow", typeof(bool), typeof(Behavior),
new PropertyMetadata(false, (d, dpc_args) => {
var button = d as Button;
if (button != null && (bool)dpc_args.NewValue) {
RoutedEventHandler close_window = (sender, e) => {
var window = button.find_ancestor_of_type<Window>();
if (window != null)
window.Close();
};
button.Click += close_window;
IDisposable dispose = Disposable.Create(() => {
button.Click -= close_window;
close_window = null;
});
IDisposable early_dispose = button.ObserveProperty(CloseWindowProperty, (sender, e) => {
if (!GetCloseWindow(button))
Disposable.dispose(ref dispose);
});
DisposeExtensions.attach_to_disposer(button, dispose);
DisposeExtensions.attach_to_disposer(button, early_dispose);
}
}));
public static bool GetCloseWindow(Button obj) { return (bool)obj.GetValue(CloseWindowProperty); }
public static void SetCloseWindow(Button obj, bool value) { obj.SetValue(CloseWindowProperty, value); }
#endregion
#region AnimatedScrollViewerVerticalOffset
static double GetAnimatedScrollViewerVerticalOffset(DependencyObject obj) =>
(double)obj.GetValue(AnimatedScrollViewerVerticalOffsetProperty);
public static void SetAnimatedScrollViewerVerticalOffset(DependencyObject obj, double value) =>
obj.SetValue(AnimatedScrollViewerVerticalOffsetProperty, value);
public static readonly DependencyProperty AnimatedScrollViewerVerticalOffsetProperty =
DependencyProperty.RegisterAttached("AnimatedScrollViewerVerticalOffset", typeof(double), typeof(Behavior), new PropertyMetadata(0.0, scroll_changed));
static void scroll_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
ScrollViewer target = d as ScrollViewer;
if (target != null) {
target.ScrollToVerticalOffset((double)e.NewValue);
}
}
#endregion
#region AutoFocusTargetProvider
public static readonly DependencyProperty AutoFocusTargetProviderProperty = DependencyProperty.RegisterAttached("AutoFocusTargetProvider", typeof(bool),
typeof(Behavior), new PropertyMetadata(OnAutoFocusTargetProviderChanged));
static void OnAutoFocusTargetProviderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.NewValue is IAutoFocusTargetProvider aftp) {
var el = ExceptionAssert.Argument.Is<FrameworkElement>(d, nameof(d));
d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, new AutoFocusTargetProviderLifeDependency(el, aftp));
} else
d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, null);
}
public static bool GetAutoFocusTargetProvider(DependencyObject d) => (bool)d.GetValue(AutoFocusTargetProviderProperty);
public static void SetAutoFocusTargetProvider(DependencyObject d, bool value) => d.SetValue(AutoFocusTargetProviderProperty, value);
#endregion
#region AutoFocusTargetProviderLifeDependency (ReadOnly)
static readonly DependencyPropertyKey AutoFocusTargetProviderLifeDependencyPropertyKey = DependencyProperty.RegisterAttachedReadOnly("AutoFocusTargetProviderLifeDependency",
typeof(FrameworkElementLifeDependency), typeof(Behavior), new PropertyMetadata(FrameworkElementLifeDependencyHelper.DisposeOldInitializeNew));
public static readonly DependencyProperty AutoFocusTargetProviderLifeDependencyProperty = AutoFocusTargetProviderLifeDependencyPropertyKey.DependencyProperty;
public static FrameworkElementLifeDependency GetAutoFocusTargetProviderLifeDependency(DependencyObject d) => d.GetValue(AutoFocusTargetProviderLifeDependencyProperty) as FrameworkElementLifeDependency;
public static void SetAutoFocusTargetProviderLifeDependency(DependencyObject d, FrameworkElementLifeDependency value) => d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, value);
class AutoFocusTargetProviderLifeDependency : FrameworkElementLifeDependency {
readonly IAutoFocusTargetProvider _focus_target_provider;
public AutoFocusTargetProviderLifeDependency(FrameworkElement root, IAutoFocusTargetProvider focus_target_provider) : base(root) =>
_focus_target_provider = focus_target_provider;
protected override void OnLoaded() {
var el = _focus_target_provider.Target;
if (el != null) {
if (_focus_target_provider.Focus)
el.Focus();
if (_focus_target_provider.FocusKeyboard)
Keyboard.Focus(el);
if (_focus_target_provider.CaptureMouse)
el.CaptureMouse();
}
}
protected override void OnUnloaded() {
var el = _focus_target_provider.Target;
if (el != null) {
if (_focus_target_provider.ReleaseKeyboard) {
ReferenceEquals(Keyboard.FocusedElement, el);
Keyboard.ClearFocus();
}
if (_focus_target_provider.ReleaseMouse)
el.ReleaseMouseCapture();
}
}
}
#endregion
#region EatMouseDown
public static readonly DependencyProperty EatMouseDownProperty =
DependencyProperty.RegisterAttached("EatMouseDown", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnEatMouseDownChanged));
static void OnEatMouseDownChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var el = (FrameworkElement)d;
if ((bool)e.NewValue) el.MouseDown += _eat_mouse_down;
else el.MouseDown -= _eat_mouse_down;
}
static void _eat_mouse_down(object sender, MouseButtonEventArgs e) =>
e.Handled = true;
public static bool GetEatMouseDown(DependencyObject d) => (bool)d.GetValue(EatMouseDownProperty);
public static void SetEatMouseDown(DependencyObject d, bool value) => d.SetValue(EatMouseDownProperty, value);
#endregion
#region DisablePaste
public static readonly DependencyProperty DisablePasteProperty = DependencyProperty.RegisterAttached(
"DisablePaste", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnDisablePasteChanged));
static void OnDisablePasteChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if ((bool)e.NewValue)
DataObject.AddPastingHandler(d, _disable_paste_pasting_handler);
else DataObject.RemovePastingHandler(d, _disable_paste_pasting_handler);
}
static void _disable_paste_pasting_handler(object sender, DataObjectPastingEventArgs e) => e.CancelCommand();
public static bool GetDisablePaste(DependencyObject d) => (bool)d.GetValue(DisablePasteProperty);
public static void SetDisablePaste(DependencyObject d, bool value) => d.SetValue(DisablePasteProperty, value);
#endregion
public static readonly DependencyProperty BindingUpdateGroupsProperty =
DependencyProperty.RegisterAttached("BindingUpdateGroups", typeof(BindingUpdateGroupCollection), typeof(Behavior), new PropertyMetadata(null));
public static BindingUpdateGroupCollection GetBindingUpdateGroups(DependencyObject d) => d.GetValue(BindingUpdateGroupsProperty) as BindingUpdateGroupCollection;
public static void SetBindingUpdateGroups(DependencyObject d, BindingUpdateGroupCollection value) => d.SetValue(BindingUpdateGroupsProperty, value);
#region AutoRaiseCanExecuteChanged
public static readonly DependencyProperty AutoRaiseCanExecuteChangedProperty =
DependencyProperty.RegisterAttached("AutoRaiseCanExecuteChanged", typeof(bool), typeof(Behavior),
new PropertyMetadata(false, (d, e) => {
if ((bool)e.NewValue) {
BindingOperations.SetBinding(d, AutoCommandProperty, new Binding(nameof(ButtonBase.Command)) { Source = d, Mode = BindingMode.OneWay });
BindingOperations.SetBinding(d, AutoCommandParameterProperty, new Binding(nameof(ButtonBase.CommandParameter)) { Source = d, Mode = BindingMode.OneWay });
} else {
BindingOperations.ClearBinding(d, AutoCommandProperty);
BindingOperations.ClearBinding(d, AutoCommandParameterProperty);
}
}));
public static bool GetAutoRaiseCanExecuteChanged(DependencyObject d) => (bool)d.GetValue(AutoRaiseCanExecuteChangedProperty);
public static void SetAutoRaiseCanExecuteChanged(DependencyObject d, bool value) => d.SetValue(AutoRaiseCanExecuteChangedProperty, value);
/// Do not bind directly to <see cref="AutoCommandProperty"/> (used internally by <see cref="AutoRaiseCanExecuteChangedProperty"/>
public static readonly DependencyProperty AutoCommandProperty =
DependencyProperty.RegisterAttached("AutoCommand", typeof(ICommand), typeof(Behavior), new PropertyMetadata(null, _try_raise_can_execute));
public static ICommand GetAutoCommand(DependencyObject d) => d.GetValue(AutoCommandProperty) as ICommand;
public static void SetAutoCommand(DependencyObject d, ICommand value) => d.SetValue(AutoCommandProperty, value);
/// Do not bind directly to <see cref="AutoCommandParameterProperty"/> (used internally by <see cref="AutoRaiseCanExecuteChangedProperty"/>
public static readonly DependencyProperty AutoCommandParameterProperty =
DependencyProperty.RegisterAttached("AutoCommandParameter", typeof(object), typeof(Behavior), new PropertyMetadata(null, _try_raise_can_execute));
public static object GetAutoCommandParameter(DependencyObject d) => d.GetValue(AutoCommandParameterProperty);
public static void SetAutoCommandParameter(DependencyObject d, object value) => d.SetValue(AutoCommandParameterProperty, value);
static void _try_raise_can_execute(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
(d.GetValue(ButtonBase.CommandProperty) as IRaiseCanExecuteChangedCommand)?.RaiseCanExecuteChanged();
#endregion
#region FocusOnLoaded
public static readonly DependencyProperty FocusOnLoadedProperty =
DependencyProperty.RegisterAttached("FocusOnLoaded", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnFocusOnLoadedChanged));
static void OnFocusOnLoadedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = (FrameworkElement)d;
if ((bool)e.NewValue) target.Loaded += _target_Loaded;
else target.Loaded -= _target_Loaded;
}
static void _target_Loaded(object sender, RoutedEventArgs e) {
var target = (FrameworkElement)sender;
Keyboard.Focus(target);
}
public static bool GetFocusOnLoaded(DependencyObject d) => (bool)d.GetValue(FocusOnLoadedProperty);
public static void SetFocusOnLoaded(DependencyObject d, bool value) => d.SetValue(FocusOnLoadedProperty, value);
#endregion
#region MirrorLayout
static readonly DependencyProperty[] _layout_props = new[] {
FrameworkElement.HeightProperty,
FrameworkElement.WidthProperty,
FrameworkElement.MarginProperty,
Control.PaddingProperty,
FrameworkElement.HorizontalAlignmentProperty,
Control.HorizontalContentAlignmentProperty,
FrameworkElement.VerticalAlignmentProperty,
Control.VerticalContentAlignmentProperty
};
public static readonly DependencyProperty MirrorLayoutForProperty =
DependencyProperty.RegisterAttached("MirrorLayoutFor", typeof(FrameworkElement), typeof(Behavior),
new PropertyMetadata(OnMirrorLayoutForChanged));
static void OnMirrorLayoutForChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = new LazyCast<FrameworkElement, DependencyObject>(d);
if (e.OldValue is FrameworkElement old_src) {
target.value.clear_bindings(_layout_props);
}
if (e.NewValue is FrameworkElement new_src) {
target.value.bind(FrameworkElement.WidthProperty, new_src, FrameworkElement.ActualWidthProperty);
target.value.bind(FrameworkElement.HeightProperty, new_src, FrameworkElement.ActualHeightProperty);
target.value.bind(FrameworkElement.MarginProperty, new_src, FrameworkElement.MarginProperty);
target.value.bind(FrameworkElement.HorizontalAlignmentProperty, new_src, FrameworkElement.HorizontalAlignmentProperty);
target.value.bind(FrameworkElement.VerticalAlignmentProperty, new_src, FrameworkElement.VerticalAlignmentProperty);
if (target.value is Control && new_src is Control) {
target.value.bind(Control.PaddingProperty, new_src, Control.PaddingProperty);
target.value.bind(Control.HorizontalContentAlignmentProperty, new_src, Control.HorizontalContentAlignmentProperty);
target.value.bind(Control.VerticalContentAlignmentProperty, new_src, Control.VerticalContentAlignmentProperty);
}
}
}
public static FrameworkElement GetMirrorLayoutFor(DependencyObject d) => d.GetValue(MirrorLayoutForProperty) as FrameworkElement;
public static void SetMirrorLayoutFor(DependencyObject d, FrameworkElement value) => d.SetValue(MirrorLayoutForProperty, value);
#endregion
}
}
using bts.utils;
using mbts.utils;
using Spark.Core.Disposables;
using Spark.ViewModel.Commands;
using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Input;
namespace mbts.ui {
static class Behavior {
#region CloseWindow
public static readonly DependencyProperty CloseWindowProperty = DependencyProperty.RegisterAttached("CloseWindow", typeof(bool), typeof(Behavior),
new PropertyMetadata(false, (d, dpc_args) => {
var button = d as Button;
if (button != null && (bool)dpc_args.NewValue) {
RoutedEventHandler close_window = (sender, e) => {
var window = button.find_ancestor_of_type<Window>();
if (window != null)
window.Close();
};
button.Click += close_window;
IDisposable dispose = Disposable.Create(() => {
button.Click -= close_window;
close_window = null;
});
IDisposable early_dispose = button.ObserveProperty(CloseWindowProperty, (sender, e) => {
if (!GetCloseWindow(button))
Disposable.dispose(ref dispose);
});
DisposeExtensions.attach_to_disposer(button, dispose);
DisposeExtensions.attach_to_disposer(button, early_dispose);
}
}));
public static bool GetCloseWindow(Button obj) { return (bool)obj.GetValue(CloseWindowProperty); }
public static void SetCloseWindow(Button obj, bool value) { obj.SetValue(CloseWindowProperty, value); }
#endregion
#region AnimatedScrollViewerVerticalOffset
static double GetAnimatedScrollViewerVerticalOffset(DependencyObject obj) =>
(double)obj.GetValue(AnimatedScrollViewerVerticalOffsetProperty);
public static void SetAnimatedScrollViewerVerticalOffset(DependencyObject obj, double value) =>
obj.SetValue(AnimatedScrollViewerVerticalOffsetProperty, value);
public static readonly DependencyProperty AnimatedScrollViewerVerticalOffsetProperty =
DependencyProperty.RegisterAttached("AnimatedScrollViewerVerticalOffset", typeof(double), typeof(Behavior), new PropertyMetadata(0.0, scroll_changed));
static void scroll_changed(DependencyObject d, DependencyPropertyChangedEventArgs e) {
ScrollViewer target = d as ScrollViewer;
if (target != null) {
target.ScrollToVerticalOffset((double)e.NewValue);
}
}
#endregion
#region AutoFocusTargetProvider
public static readonly DependencyProperty AutoFocusTargetProviderProperty = DependencyProperty.RegisterAttached(
"AutoFocusTargetProvider", typeof(IAutoFocusTargetProvider), typeof(Behavior), new PropertyMetadata(OnAutoFocusTargetProviderChanged));
static void OnAutoFocusTargetProviderChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (e.NewValue is IAutoFocusTargetProvider aftp) {
var el = ExceptionAssert.Argument.Is<FrameworkElement>(d, nameof(d));
d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, new AutoFocusTargetProviderLifeDependency(el, aftp));
} else
d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, null);
}
public static IAutoFocusTargetProvider GetAutoFocusTargetProvider(DependencyObject d) =>
d.GetValue(AutoFocusTargetProviderProperty) as IAutoFocusTargetProvider;
public static void SetAutoFocusTargetProvider(DependencyObject d, IAutoFocusTargetProvider value) =>
d.SetValue(AutoFocusTargetProviderProperty, value);
#endregion
#region AutoFocusTargetProviderLifeDependency (ReadOnly)
static readonly DependencyPropertyKey AutoFocusTargetProviderLifeDependencyPropertyKey = DependencyProperty.RegisterAttachedReadOnly("AutoFocusTargetProviderLifeDependency",
typeof(FrameworkElementLifeDependency), typeof(Behavior), new PropertyMetadata(FrameworkElementLifeDependencyHelper.DisposeOldInitializeNew));
public static readonly DependencyProperty AutoFocusTargetProviderLifeDependencyProperty = AutoFocusTargetProviderLifeDependencyPropertyKey.DependencyProperty;
public static FrameworkElementLifeDependency GetAutoFocusTargetProviderLifeDependency(DependencyObject d) => d.GetValue(AutoFocusTargetProviderLifeDependencyProperty) as FrameworkElementLifeDependency;
public static void SetAutoFocusTargetProviderLifeDependency(DependencyObject d, FrameworkElementLifeDependency value) => d.SetValue(AutoFocusTargetProviderLifeDependencyPropertyKey, value);
class AutoFocusTargetProviderLifeDependency : FrameworkElementLifeDependency {
readonly IAutoFocusTargetProvider _focus_target_provider;
public AutoFocusTargetProviderLifeDependency(FrameworkElement root, IAutoFocusTargetProvider focus_target_provider) : base(root) =>
_focus_target_provider = focus_target_provider;
protected override void OnLoaded() {
var el = _focus_target_provider.Target;
if (el != null) {
if (_focus_target_provider.Focus) {
var fs = FocusManager.GetFocusScope(el);
if (fs is not null) {
FocusManager.SetFocusedElement(fs, el);
if (fs is UIElement fsUiEl) {
fsUiEl.Focus();
} else if (fs is IInputElement fsInputEl) {
Keyboard.Focus(fsInputEl);
} else {
el.Focus();
}
} else {
el.Focus();
}
}
if (_focus_target_provider.FocusKeyboard)
Keyboard.Focus(el);
if (_focus_target_provider.CaptureMouse)
el.CaptureMouse();
}
}
protected override void OnUnloaded() {
var el = _focus_target_provider.Target;
if (el != null) {
if (_focus_target_provider.ReleaseKeyboard) {
ReferenceEquals(Keyboard.FocusedElement, el);
Keyboard.ClearFocus();
}
if (_focus_target_provider.ReleaseMouse)
el.ReleaseMouseCapture();
}
}
}
#endregion
#region EatMouseDown
public static readonly DependencyProperty EatMouseDownProperty =
DependencyProperty.RegisterAttached("EatMouseDown", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnEatMouseDownChanged));
static void OnEatMouseDownChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var el = (FrameworkElement)d;
if ((bool)e.NewValue) el.MouseDown += _eat_mouse_down;
else el.MouseDown -= _eat_mouse_down;
}
static void _eat_mouse_down(object sender, MouseButtonEventArgs e) =>
e.Handled = true;
public static bool GetEatMouseDown(DependencyObject d) => (bool)d.GetValue(EatMouseDownProperty);
public static void SetEatMouseDown(DependencyObject d, bool value) => d.SetValue(EatMouseDownProperty, value);
#endregion
#region DisablePaste
public static readonly DependencyProperty DisablePasteProperty = DependencyProperty.RegisterAttached(
"DisablePaste", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnDisablePasteChanged));
static void OnDisablePasteChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if ((bool)e.NewValue)
DataObject.AddPastingHandler(d, _disable_paste_pasting_handler);
else DataObject.RemovePastingHandler(d, _disable_paste_pasting_handler);
}
static void _disable_paste_pasting_handler(object sender, DataObjectPastingEventArgs e) => e.CancelCommand();
public static bool GetDisablePaste(DependencyObject d) => (bool)d.GetValue(DisablePasteProperty);
public static void SetDisablePaste(DependencyObject d, bool value) => d.SetValue(DisablePasteProperty, value);
#endregion
public static readonly DependencyProperty BindingUpdateGroupsProperty =
DependencyProperty.RegisterAttached("BindingUpdateGroups", typeof(BindingUpdateGroupCollection), typeof(Behavior), new PropertyMetadata(null));
public static BindingUpdateGroupCollection GetBindingUpdateGroups(DependencyObject d) => d.GetValue(BindingUpdateGroupsProperty) as BindingUpdateGroupCollection;
public static void SetBindingUpdateGroups(DependencyObject d, BindingUpdateGroupCollection value) => d.SetValue(BindingUpdateGroupsProperty, value);
#region AutoRaiseCanExecuteChanged
public static readonly DependencyProperty AutoRaiseCanExecuteChangedProperty =
DependencyProperty.RegisterAttached("AutoRaiseCanExecuteChanged", typeof(bool), typeof(Behavior),
new PropertyMetadata(false, (d, e) => {
if ((bool)e.NewValue) {
BindingOperations.SetBinding(d, AutoCommandProperty, new Binding(nameof(ButtonBase.Command)) { Source = d, Mode = BindingMode.OneWay });
BindingOperations.SetBinding(d, AutoCommandParameterProperty, new Binding(nameof(ButtonBase.CommandParameter)) { Source = d, Mode = BindingMode.OneWay });
} else {
BindingOperations.ClearBinding(d, AutoCommandProperty);
BindingOperations.ClearBinding(d, AutoCommandParameterProperty);
}
}));
public static bool GetAutoRaiseCanExecuteChanged(DependencyObject d) => (bool)d.GetValue(AutoRaiseCanExecuteChangedProperty);
public static void SetAutoRaiseCanExecuteChanged(DependencyObject d, bool value) => d.SetValue(AutoRaiseCanExecuteChangedProperty, value);
/// Do not bind directly to <see cref="AutoCommandProperty"/> (used internally by <see cref="AutoRaiseCanExecuteChangedProperty"/>
public static readonly DependencyProperty AutoCommandProperty =
DependencyProperty.RegisterAttached("AutoCommand", typeof(ICommand), typeof(Behavior), new PropertyMetadata(null, _try_raise_can_execute));
public static ICommand GetAutoCommand(DependencyObject d) => d.GetValue(AutoCommandProperty) as ICommand;
public static void SetAutoCommand(DependencyObject d, ICommand value) => d.SetValue(AutoCommandProperty, value);
/// Do not bind directly to <see cref="AutoCommandParameterProperty"/> (used internally by <see cref="AutoRaiseCanExecuteChangedProperty"/>
public static readonly DependencyProperty AutoCommandParameterProperty =
DependencyProperty.RegisterAttached("AutoCommandParameter", typeof(object), typeof(Behavior), new PropertyMetadata(null, _try_raise_can_execute));
public static object GetAutoCommandParameter(DependencyObject d) => d.GetValue(AutoCommandParameterProperty);
public static void SetAutoCommandParameter(DependencyObject d, object value) => d.SetValue(AutoCommandParameterProperty, value);
static void _try_raise_can_execute(DependencyObject d, DependencyPropertyChangedEventArgs e) =>
(d.GetValue(ButtonBase.CommandProperty) as IRaiseCanExecuteChangedCommand)?.RaiseCanExecuteChanged();
#endregion
#region FocusOnLoaded
public static readonly DependencyProperty FocusOnLoadedProperty =
DependencyProperty.RegisterAttached("FocusOnLoaded", typeof(bool), typeof(Behavior), new PropertyMetadata(false, OnFocusOnLoadedChanged));
static void OnFocusOnLoadedChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = (FrameworkElement)d;
if ((bool)e.NewValue) target.Loaded += _target_Loaded;
else target.Loaded -= _target_Loaded;
}
static void _target_Loaded(object sender, RoutedEventArgs e) {
var target = (FrameworkElement)sender;
Keyboard.Focus(target);
}
public static bool GetFocusOnLoaded(DependencyObject d) => (bool)d.GetValue(FocusOnLoadedProperty);
public static void SetFocusOnLoaded(DependencyObject d, bool value) => d.SetValue(FocusOnLoadedProperty, value);
#endregion
#region MirrorLayout
static readonly DependencyProperty[] _layout_props = new[] {
FrameworkElement.HeightProperty,
FrameworkElement.WidthProperty,
FrameworkElement.MarginProperty,
Control.PaddingProperty,
FrameworkElement.HorizontalAlignmentProperty,
Control.HorizontalContentAlignmentProperty,
FrameworkElement.VerticalAlignmentProperty,
Control.VerticalContentAlignmentProperty
};
public static readonly DependencyProperty MirrorLayoutForProperty =
DependencyProperty.RegisterAttached("MirrorLayoutFor", typeof(FrameworkElement), typeof(Behavior),
new PropertyMetadata(OnMirrorLayoutForChanged));
static void OnMirrorLayoutForChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = new LazyCast<FrameworkElement, DependencyObject>(d);
if (e.OldValue is FrameworkElement old_src) {
target.value.clear_bindings(_layout_props);
}
if (e.NewValue is FrameworkElement new_src) {
target.value.bind(FrameworkElement.WidthProperty, new_src, FrameworkElement.ActualWidthProperty);
target.value.bind(FrameworkElement.HeightProperty, new_src, FrameworkElement.ActualHeightProperty);
target.value.bind(FrameworkElement.MarginProperty, new_src, FrameworkElement.MarginProperty);
target.value.bind(FrameworkElement.HorizontalAlignmentProperty, new_src, FrameworkElement.HorizontalAlignmentProperty);
target.value.bind(FrameworkElement.VerticalAlignmentProperty, new_src, FrameworkElement.VerticalAlignmentProperty);
if (target.value is Control && new_src is Control) {
target.value.bind(Control.PaddingProperty, new_src, Control.PaddingProperty);
target.value.bind(Control.HorizontalContentAlignmentProperty, new_src, Control.HorizontalContentAlignmentProperty);
target.value.bind(Control.VerticalContentAlignmentProperty, new_src, Control.VerticalContentAlignmentProperty);
}
}
}
public static FrameworkElement GetMirrorLayoutFor(DependencyObject d) => d.GetValue(MirrorLayoutForProperty) as FrameworkElement;
public static void SetMirrorLayoutFor(DependencyObject d, FrameworkElement value) => d.SetValue(MirrorLayoutForProperty, value);
#endregion
}
}
@@ -557,6 +557,8 @@
</Style.Triggers>
</Style>
<Style x:Key="DefaultButton" TargetType="Button" BasedOn="{StaticResource {x:Type Button}}" />
<Style TargetType="RepeatButton">
<Setter Property="Foreground" Value="{u:BTSBrush UI.Button.normal_foreground}" />
<Setter Property="Background" Value="{u:BTSBrush UI.Button.normal_background}" />
@@ -1,348 +1,371 @@
using bts;
using mbts.ui.native;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
namespace mbts.ui {
public partial class WindowStyle : ResourceDictionary {
// 'Top' is 0 because the window's TitleContent overlaps the top-resize-border.
public static readonly Thickness NegativeResizeBorderThickness = new Thickness(-5, 0, -5, -5);
public static readonly ExecutedRoutedEventHandler
CloseWindowExecutedHandler = WindowCallbackHelper.safe_command_executed_handler(w => w.Close(), "closing"),
HideWindowExecutedHandler = WindowCallbackHelper.safe_command_executed_handler(w => w.Visibility = Visibility.Hidden, "hiding"),
MinimizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = WindowState.Minimized),
MaximizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = w.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized);
#region UnsafeWindow
// UnsafeWindow is described as 'Unsafe' because the window may be on a different dispatcher than the DependencyObject target.
public static readonly DependencyProperty UnsafeWindowProperty =
DependencyProperty.RegisterAttached("UnsafeWindow", typeof(Window), typeof(WindowStyle), new PropertyMetadata(OnUnsafeWindowChanged));
static void OnUnsafeWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is UIElement el)
el.RaiseEvent(new RoutedPropertyChangedEventArgs<Window>(e.OldValue as Window, e.NewValue as Window, UnsafeWindowChangedEvent));
}
public static Window GetUnsafeWindow(DependencyObject d) => d.GetValue(UnsafeWindowProperty) as Window;
public static void SetUnsafeWindow(DependencyObject d, Window value) => d.SetValue(UnsafeWindowProperty, value);
#endregion
#region UnsafeWindowChanged (Event)
internal static readonly RoutedEvent UnsafeWindowChangedEvent = EventManager.RegisterRoutedEvent("UnsafeWindowChanged", RoutingStrategy.Direct, typeof(RoutedPropertyChangedEventHandler<Window>), typeof(WindowStyle));
internal static void AddUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.AddHandler(UnsafeWindowChangedEvent, handler);
internal static void RemoveUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.RemoveHandler(UnsafeWindowChangedEvent, handler);
#endregion
static class WindowCallbackHelper {
public static ExecutedRoutedEventHandler safe_command_executed_handler(Action<Window> action, string action_name) =>
(s, e) => _safe_execute_on_window(s, action, action_name);
public static ExecutedRoutedEventHandler command_executed_handler(Action<Window> action) =>
(s, e) => _execute_on_window(s, action);
public static RoutedEventHandler routed_event_handler(Action<Window> action) =>
(s, e) => _execute_on_window(s, action);
static void _execute_on_window(object sender, Action<Window> action) {
if (_get_host_window(sender) is Window window)
action(window);
}
static void _safe_execute_on_window(object sender, Action<Window> action, string action_name) {
try {
_execute_on_window(sender, action);
} catch (Exception err) {
Log.Ui.warn($"Exception {action_name} window : {err}");
}
}
static Window _get_host_window(object sender) =>
sender is Window w ? w : sender is DependencyObject d ? Window.GetWindow(d) : null;
}
#region Attached properties to control the style b/c the default Window properties are lame
#region Close button
public static bool GetShowCloseButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowCloseButtonProperty);
}
public static void SetShowCloseButton(DependencyObject obj, bool value) {
obj.SetValue(ShowCloseButtonProperty, value);
}
public static readonly DependencyProperty ShowCloseButtonProperty =
DependencyProperty.RegisterAttached("ShowCloseButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(true));
#endregion
#region Minimize Button
public static bool GetShowMinimizeButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowMinimizeButtonProperty);
}
public static void SetShowMinimizeButton(DependencyObject obj, bool value) {
obj.SetValue(ShowMinimizeButtonProperty, value);
}
public static readonly DependencyProperty ShowMinimizeButtonProperty =
DependencyProperty.RegisterAttached("ShowMinimizeButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(true));
#endregion
#region Maximize Button
public static bool GetShowMaximizeButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowMaximizeButtonProperty);
}
public static void SetShowMaximizeButton(DependencyObject obj, bool value) {
obj.SetValue(ShowMaximizeButtonProperty, value);
}
public static readonly DependencyProperty ShowMaximizeButtonProperty =
DependencyProperty.RegisterAttached("ShowMaximizeButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false));
#endregion
#region AllowResize
public static bool GetAllowResize(DependencyObject obj) {
return (bool)obj.GetValue(AllowResizeProperty);
}
public static void SetAllowResize(DependencyObject obj, bool value) {
obj.SetValue(AllowResizeProperty, value);
}
public static readonly DependencyProperty AllowResizeProperty =
DependencyProperty.RegisterAttached("AllowResize", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false, (s, e) => {
var wnd = s as Window;
if (wnd != null) {
if ((bool)e.NewValue == true) {
wnd.ResizeMode = ResizeMode.CanResize;
} else {
wnd.ResizeMode = ResizeMode.NoResize;
}
}
}));
#endregion
#region IsNonClientArea Inherited property
public static bool GetIsNonClientArea(DependencyObject obj) {
return (bool)obj.GetValue(IsNonClientAreaProperty);
}
public static void SetIsNonClientArea(DependencyObject obj, bool value) {
obj.SetValue(IsNonClientAreaProperty, value);
}
public static readonly DependencyProperty IsNonClientAreaProperty =
DependencyProperty.RegisterAttached("IsNonClientArea", typeof(bool), typeof(WindowStyle), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits));
#endregion
#region [Custom]SizeToContent property (some additional logic is needed to avoid ugly black border margins on the edge of the window)
public static readonly DependencyProperty SizeToContentProperty = DependencyProperty.RegisterAttached("SizeToContent", typeof(SizeToContent), typeof(WindowStyle), new PropertyMetadata(SizeToContent.Manual, OnSizeToContentChanged));
private static void OnSizeToContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
SizeToContent old_val = (SizeToContent)e.OldValue;
SizeToContent new_val = (SizeToContent)e.NewValue;
Window w = (Window)d;
if (old_val != SizeToContent.Manual) {
if (new_val == SizeToContent.Manual) w.ContentRendered -= InvalidateVisualOnContentRendered;
} else w.ContentRendered += InvalidateVisualOnContentRendered;
w.SizeToContent = new_val;
}
private static void InvalidateVisualOnContentRendered(object sender, EventArgs e) { ((Window)sender).InvalidateVisual(); }
public static SizeToContent GetSizeToContent(Window w) { return (SizeToContent)w.GetValue(SizeToContentProperty); }
public static void SetSizeToContent(Window w, SizeToContent value) { w.SetValue(SizeToContentProperty, value); }
#endregion
#region TitleContent
public static readonly DependencyProperty TitleContentProperty = DependencyProperty.RegisterAttached("TitleContent", typeof(object), typeof(WindowStyle), new PropertyMetadata(null));
public static object GetTitleContent(DependencyObject d) { return d.GetValue(TitleContentProperty); }
public static void SetTitleContent(DependencyObject d, object value) { d.SetValue(TitleContentProperty, value); }
#endregion
#region TitleContentTemplate
public static readonly DependencyProperty TitleContentTemplateProperty = DependencyProperty.RegisterAttached("TitleContentTemplate", typeof(DataTemplate), typeof(WindowStyle), new PropertyMetadata(null));
public static DataTemplate GetTitleContentTemplate(DependencyObject d) { return d.GetValue(TitleContentTemplateProperty) as DataTemplate; }
public static void SetTitleContentTemplate(DependencyObject d, DataTemplate value) { d.SetValue(TitleContentTemplateProperty, value); }
#endregion
#region DisposeVMOnClose
public static readonly DependencyProperty DisposeVMOnCloseProperty = DependencyProperty.RegisterAttached("DisposeVMOnClose", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false, OnDisposeVMOnCloseChanged));
private static void OnDisposeVMOnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = d as Window;
target?.SetValue(DisposeVMOnCloseHandlerWrapperPropertyKey, (bool)e.NewValue ? new DisposeVMOnCloseHandlerWrapper(target) : null);
}
public static bool GetDisposeVMOnClose(DependencyObject d) { return (bool)d.GetValue(DisposeVMOnCloseProperty); }
public static void SetDisposeVMOnClose(DependencyObject d, bool value) { d.SetValue(DisposeVMOnCloseProperty, value); }
private static readonly DependencyPropertyKey DisposeVMOnCloseHandlerWrapperPropertyKey = DependencyProperty.RegisterAttachedReadOnly("DisposeVMOnCloseHandlerWrapper", typeof(IDisposable), typeof(WindowStyle), new PropertyMetadata(null, FrameworkElementLifeDependencyHelper.DisposeOld));
internal static readonly DependencyProperty DisposeVMOnCloseHandlerWrapperProperty = DisposeVMOnCloseHandlerWrapperPropertyKey.DependencyProperty;
internal static IDisposable GetDisposeVMOnCloseHandlerWrapper(Window w) { return w.GetValue(DisposeVMOnCloseHandlerWrapperProperty) as IDisposable; }
private static void SetDisposeVMOnCloseHandlerWrapper(Window w, IDisposable value) { w.SetValue(DisposeVMOnCloseHandlerWrapperProperty, value); }
private class DisposeVMOnCloseHandlerWrapper : IDisposable {
public DisposeVMOnCloseHandlerWrapper(Window target) { (_target = target).Closed += _target_Closed; }
private readonly Window _target;
private void _target_Closed(object sender, EventArgs e) { (_target.DataContext as IDisposable)?.Dispose(); }
public void Dispose() { _target.Closed -= _target_Closed; }
}
#endregion
#endregion
private void style_loaded(object sender, RoutedEventArgs _) {
if (sender is DependencyObject) {
var window = Window.GetWindow(((DependencyObject)sender));
if (window != null) {
if (WindowStyle.GetAllowResize(window)) {
set_resize_window_events(sender as FrameworkElement, window);
} else {
// Simpler dragmove interaction
var border = (FrameworkElement)sender;
border.MouseLeftButtonDown += (s, e) => {
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
};
}
// Handle Close command automagically
if (window.CommandBindings.Count == 0) {
window.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, CloseWindowExecutedHandler));
window.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, MinimizeWindowExecutedHandler));
window.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, MaximizeWindowExecutedHandler));
}
}
}
}
private static void set_resize_window_events(FrameworkElement border, Window window) {
HookWndProc(window);
Log.assert(border != null);
var restore_on_move = false;
border.MouseLeftButtonDown += (s, e) => {
FrameworkElement fe = e.OriginalSource as FrameworkElement;
if (fe != null && (bool)fe.GetValue(WindowStyle.IsNonClientAreaProperty)) {
if (e.ClickCount == 2) {
toggle_max(window);
} else {
if (window.WindowState == WindowState.Maximized) { restore_on_move = true; }
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
}
}
};
border.MouseLeftButtonUp += (s, e) => restore_on_move = false;
border.MouseMove += (s, e) => {
if (restore_on_move && window.WindowState == WindowState.Maximized && Mouse.LeftButton == MouseButtonState.Pressed) {
window.WindowState = WindowState.Normal;
window.Top = 0;
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
}
};
}
private static void toggle_max(Window window) {
if (window.WindowState == WindowState.Maximized) {
window.WindowState = WindowState.Normal;
} else {
window.WindowState = WindowState.Maximized;
}
}
private static void HookWndProc(Window window) {
HwndSource source = PresentationSource.FromVisual(window) as HwndSource;
if (source != null) {
source.AddHook(new HwndSourceHook(WndProc));
}
}
private static void UnhookWndProc(Window window) {
HwndSource source = PresentationSource.FromVisual(window) as HwndSource;
if (source != null) {
source.RemoveHook(new HwndSourceHook(WndProc));
}
}
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled) {
WM wmsg = (WM)msg;
if (WM.NCHITTEST == wmsg /*|| WM.MOUSEMOVE == wmsg*/) {
Thickness t = new Thickness(6);
// Get the mouse coordinates in screen space
short x = (short)lparam.ToInt32();
short y = (short)(lparam.ToInt32() >> 16);
// Get the window bounds in screen coords
Win32Rect w;
NativeMethods.GetWindowRect(hwnd, out w);
// Assume that mouse position is inside the window
bool left = x < (w.Left + t.Left);
bool right = x > (w.Right - t.Right);
bool top = y < (w.Top + t.Top);
bool bottom = y > (w.Bottom - t.Bottom);
// A B C
// D E
// F G H
HT ret = HT.CLIENT;
if (top) {
if (left) ret = HT.TOPLEFT; // A
else if (right) ret = HT.TOPRIGHT; // C
else ret = HT.TOP; // B
} else if (bottom) {
if (left) ret = HT.BOTTOMLEFT; // F
else if (right) ret = HT.BOTTOMRIGHT; // H
else ret = HT.BOTTOM; // G
} else {
if (left) ret = HT.LEFT; // D
if (right) ret = HT.RIGHT; // E
}
handled = true;
return new IntPtr((int)ret);
} else if (wmsg == WM.NCCALCSIZE) {
handled = true;
} else if (wmsg == WM.NCPAINT) {
handled = true;
} else if (wmsg == WM.NCACTIVATE) {
handled = true;
return NativeMethods.DefWindowProc(hwnd, msg, wparam, new IntPtr(-1));
} else if (wmsg == WM.ERASEBKGND) {
handled = true;
} else if (wmsg == WM.GETMINMAXINFO) {
SetMinMaxInfo(hwnd, lparam);
handled = true;
}
return IntPtr.Zero;
}
private static void SetMinMaxInfo(IntPtr hwnd, IntPtr lparam) {
var mminfo = (MINMAXINFO)Marshal.PtrToStructure(lparam, typeof(MINMAXINFO));
var hmonitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTONNEAREST);
if (hmonitor != IntPtr.Zero) {
MONITORINFO minfo = new MONITORINFO();
minfo.cbSize = Marshal.SizeOf(minfo);
NativeMethods.GetMonitorInfo(hmonitor, ref minfo);
var rc_monitor = minfo.rcMonitor;
var rc_work = minfo.rcWork;
mminfo.ptMaxPosition.x = Math.Abs(rc_work.Left - rc_monitor.Left);
mminfo.ptMaxPosition.y = Math.Abs(rc_work.Top - rc_monitor.Top);
mminfo.ptMaxSize.x = Math.Abs(rc_work.Right - rc_work.Left);
mminfo.ptMaxSize.y = Math.Abs(rc_work.Bottom - rc_work.Top);
Marshal.StructureToPtr(mminfo, lparam, true);
}
}
}
}
using bts;
using mbts.ui.native;
using System;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Input;
using System.Windows.Interop;
namespace mbts.ui {
public partial class WindowStyle : ResourceDictionary {
// 'Top' is 0 because the window's TitleContent overlaps the top-resize-border.
public static readonly Thickness NegativeResizeBorderThickness = new Thickness(-5, 0, -5, -5);
public static readonly ExecutedRoutedEventHandler
CloseWindowExecutedHandler = WindowCallbackHelper.safe_command_executed_handler(w => w.Close(), "closing"),
HideWindowExecutedHandler = WindowCallbackHelper.safe_command_executed_handler(w => w.Visibility = Visibility.Hidden, "hiding"),
MinimizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = WindowState.Minimized),
MaximizeWindowExecutedHandler = WindowCallbackHelper.command_executed_handler(w => w.WindowState = w.WindowState == WindowState.Maximized ? WindowState.Normal : WindowState.Maximized);
#region UnsafeWindow
// UnsafeWindow is described as 'Unsafe' because the window may be on a different dispatcher than the DependencyObject target.
public static readonly DependencyProperty UnsafeWindowProperty =
DependencyProperty.RegisterAttached("UnsafeWindow", typeof(Window), typeof(WindowStyle), new PropertyMetadata(OnUnsafeWindowChanged));
static void OnUnsafeWindowChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is UIElement el)
el.RaiseEvent(new RoutedPropertyChangedEventArgs<Window>(e.OldValue as Window, e.NewValue as Window, UnsafeWindowChangedEvent));
}
public static Window GetUnsafeWindow(DependencyObject d) => d.GetValue(UnsafeWindowProperty) as Window;
public static void SetUnsafeWindow(DependencyObject d, Window value) => d.SetValue(UnsafeWindowProperty, value);
#endregion
#region UnsafeWindowChanged (Event)
internal static readonly RoutedEvent UnsafeWindowChangedEvent = EventManager.RegisterRoutedEvent("UnsafeWindowChanged", RoutingStrategy.Direct, typeof(RoutedPropertyChangedEventHandler<Window>), typeof(WindowStyle));
internal static void AddUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.AddHandler(UnsafeWindowChangedEvent, handler);
internal static void RemoveUnsafeWindowChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<Window> handler) =>
el.RemoveHandler(UnsafeWindowChangedEvent, handler);
#endregion
#region WinFormsHost
public static readonly DependencyProperty WinFormsHostProperty =
DependencyProperty.RegisterAttached("WinFormsHost", typeof(WPFPanel), typeof(WindowStyle), new PropertyMetadata(OnWinFormsHostChanged));
static void OnWinFormsHostChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
if (d is UIElement el)
el.RaiseEvent(new RoutedPropertyChangedEventArgs<WPFPanel>(e.OldValue as WPFPanel, e.NewValue as WPFPanel, WinFormsHostChangedEvent));
}
public static WPFPanel GetWinFormsHost(DependencyObject d) => d.GetValue(WinFormsHostProperty) as WPFPanel;
public static void SetWinFormsHost(DependencyObject d, WPFPanel value) => d.SetValue(WinFormsHostProperty, value);
#endregion
#region WinFormsHostChanged (Event)
internal static readonly RoutedEvent WinFormsHostChangedEvent = EventManager.RegisterRoutedEvent("WinFormsHostChanged", RoutingStrategy.Direct, typeof(RoutedPropertyChangedEventHandler<WPFPanel>), typeof(WindowStyle));
internal static void AddWinFormsHostChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<WPFPanel> handler) =>
el.AddHandler(WinFormsHostChangedEvent, handler);
internal static void RemoveWinFormsHostChangedHandler(UIElement el, RoutedPropertyChangedEventHandler<WPFPanel> handler) =>
el.RemoveHandler(WinFormsHostChangedEvent, handler);
#endregion
static class WindowCallbackHelper {
public static ExecutedRoutedEventHandler safe_command_executed_handler(Action<Window> action, string action_name) =>
(s, e) => _safe_execute_on_window(s, action, action_name);
public static ExecutedRoutedEventHandler command_executed_handler(Action<Window> action) =>
(s, e) => _execute_on_window(s, action);
public static RoutedEventHandler routed_event_handler(Action<Window> action) =>
(s, e) => _execute_on_window(s, action);
static void _execute_on_window(object sender, Action<Window> action) {
if (_get_host_window(sender) is Window window)
action(window);
}
static void _safe_execute_on_window(object sender, Action<Window> action, string action_name) {
try {
_execute_on_window(sender, action);
} catch (Exception err) {
Log.Ui.warn($"Exception {action_name} window : {err}");
}
}
static Window _get_host_window(object sender) =>
sender is Window w ? w : sender is DependencyObject d ? Window.GetWindow(d) : null;
}
#region Attached properties to control the style b/c the default Window properties are lame
#region Close button
public static bool GetShowCloseButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowCloseButtonProperty);
}
public static void SetShowCloseButton(DependencyObject obj, bool value) {
obj.SetValue(ShowCloseButtonProperty, value);
}
public static readonly DependencyProperty ShowCloseButtonProperty =
DependencyProperty.RegisterAttached("ShowCloseButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(true));
#endregion
#region Minimize Button
public static bool GetShowMinimizeButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowMinimizeButtonProperty);
}
public static void SetShowMinimizeButton(DependencyObject obj, bool value) {
obj.SetValue(ShowMinimizeButtonProperty, value);
}
public static readonly DependencyProperty ShowMinimizeButtonProperty =
DependencyProperty.RegisterAttached("ShowMinimizeButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(true));
#endregion
#region Maximize Button
public static bool GetShowMaximizeButton(DependencyObject obj) {
return (bool)obj.GetValue(ShowMaximizeButtonProperty);
}
public static void SetShowMaximizeButton(DependencyObject obj, bool value) {
obj.SetValue(ShowMaximizeButtonProperty, value);
}
public static readonly DependencyProperty ShowMaximizeButtonProperty =
DependencyProperty.RegisterAttached("ShowMaximizeButton", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false));
#endregion
#region AllowResize
public static bool GetAllowResize(DependencyObject obj) {
return (bool)obj.GetValue(AllowResizeProperty);
}
public static void SetAllowResize(DependencyObject obj, bool value) {
obj.SetValue(AllowResizeProperty, value);
}
public static readonly DependencyProperty AllowResizeProperty =
DependencyProperty.RegisterAttached("AllowResize", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false, (s, e) => {
var wnd = s as Window;
if (wnd != null) {
if ((bool)e.NewValue == true) {
wnd.ResizeMode = ResizeMode.CanResize;
} else {
wnd.ResizeMode = ResizeMode.NoResize;
}
}
}));
#endregion
#region IsNonClientArea Inherited property
public static bool GetIsNonClientArea(DependencyObject obj) {
return (bool)obj.GetValue(IsNonClientAreaProperty);
}
public static void SetIsNonClientArea(DependencyObject obj, bool value) {
obj.SetValue(IsNonClientAreaProperty, value);
}
public static readonly DependencyProperty IsNonClientAreaProperty =
DependencyProperty.RegisterAttached("IsNonClientArea", typeof(bool), typeof(WindowStyle), new FrameworkPropertyMetadata(false, FrameworkPropertyMetadataOptions.Inherits));
#endregion
#region [Custom]SizeToContent property (some additional logic is needed to avoid ugly black border margins on the edge of the window)
public static readonly DependencyProperty SizeToContentProperty = DependencyProperty.RegisterAttached("SizeToContent", typeof(SizeToContent), typeof(WindowStyle), new PropertyMetadata(SizeToContent.Manual, OnSizeToContentChanged));
private static void OnSizeToContentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
SizeToContent old_val = (SizeToContent)e.OldValue;
SizeToContent new_val = (SizeToContent)e.NewValue;
Window w = (Window)d;
if (old_val != SizeToContent.Manual) {
if (new_val == SizeToContent.Manual) w.ContentRendered -= InvalidateVisualOnContentRendered;
} else w.ContentRendered += InvalidateVisualOnContentRendered;
w.SizeToContent = new_val;
}
private static void InvalidateVisualOnContentRendered(object sender, EventArgs e) { ((Window)sender).InvalidateVisual(); }
public static SizeToContent GetSizeToContent(Window w) { return (SizeToContent)w.GetValue(SizeToContentProperty); }
public static void SetSizeToContent(Window w, SizeToContent value) { w.SetValue(SizeToContentProperty, value); }
#endregion
#region TitleContent
public static readonly DependencyProperty TitleContentProperty = DependencyProperty.RegisterAttached("TitleContent", typeof(object), typeof(WindowStyle), new PropertyMetadata(null));
public static object GetTitleContent(DependencyObject d) { return d.GetValue(TitleContentProperty); }
public static void SetTitleContent(DependencyObject d, object value) { d.SetValue(TitleContentProperty, value); }
#endregion
#region TitleContentTemplate
public static readonly DependencyProperty TitleContentTemplateProperty = DependencyProperty.RegisterAttached("TitleContentTemplate", typeof(DataTemplate), typeof(WindowStyle), new PropertyMetadata(null));
public static DataTemplate GetTitleContentTemplate(DependencyObject d) { return d.GetValue(TitleContentTemplateProperty) as DataTemplate; }
public static void SetTitleContentTemplate(DependencyObject d, DataTemplate value) { d.SetValue(TitleContentTemplateProperty, value); }
#endregion
#region DisposeVMOnClose
public static readonly DependencyProperty DisposeVMOnCloseProperty = DependencyProperty.RegisterAttached("DisposeVMOnClose", typeof(bool), typeof(WindowStyle), new PropertyMetadata(false, OnDisposeVMOnCloseChanged));
private static void OnDisposeVMOnCloseChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) {
var target = d as Window;
target?.SetValue(DisposeVMOnCloseHandlerWrapperPropertyKey, (bool)e.NewValue ? new DisposeVMOnCloseHandlerWrapper(target) : null);
}
public static bool GetDisposeVMOnClose(DependencyObject d) { return (bool)d.GetValue(DisposeVMOnCloseProperty); }
public static void SetDisposeVMOnClose(DependencyObject d, bool value) { d.SetValue(DisposeVMOnCloseProperty, value); }
private static readonly DependencyPropertyKey DisposeVMOnCloseHandlerWrapperPropertyKey = DependencyProperty.RegisterAttachedReadOnly("DisposeVMOnCloseHandlerWrapper", typeof(IDisposable), typeof(WindowStyle), new PropertyMetadata(null, FrameworkElementLifeDependencyHelper.DisposeOld));
internal static readonly DependencyProperty DisposeVMOnCloseHandlerWrapperProperty = DisposeVMOnCloseHandlerWrapperPropertyKey.DependencyProperty;
internal static IDisposable GetDisposeVMOnCloseHandlerWrapper(Window w) { return w.GetValue(DisposeVMOnCloseHandlerWrapperProperty) as IDisposable; }
private static void SetDisposeVMOnCloseHandlerWrapper(Window w, IDisposable value) { w.SetValue(DisposeVMOnCloseHandlerWrapperProperty, value); }
private class DisposeVMOnCloseHandlerWrapper : IDisposable {
public DisposeVMOnCloseHandlerWrapper(Window target) { (_target = target).Closed += _target_Closed; }
private readonly Window _target;
private void _target_Closed(object sender, EventArgs e) { (_target.DataContext as IDisposable)?.Dispose(); }
public void Dispose() { _target.Closed -= _target_Closed; }
}
#endregion
#endregion
private void style_loaded(object sender, RoutedEventArgs _) {
if (sender is DependencyObject) {
var window = Window.GetWindow(((DependencyObject)sender));
if (window != null) {
if (WindowStyle.GetAllowResize(window)) {
set_resize_window_events(sender as FrameworkElement, window);
} else {
// Simpler dragmove interaction
var border = (FrameworkElement)sender;
border.MouseLeftButtonDown += (s, e) => {
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
};
}
// Handle Close command automagically
if (window.CommandBindings.Count == 0) {
window.CommandBindings.Add(new CommandBinding(SystemCommands.CloseWindowCommand, CloseWindowExecutedHandler));
window.CommandBindings.Add(new CommandBinding(SystemCommands.MinimizeWindowCommand, MinimizeWindowExecutedHandler));
window.CommandBindings.Add(new CommandBinding(SystemCommands.MaximizeWindowCommand, MaximizeWindowExecutedHandler));
}
}
}
}
private static void set_resize_window_events(FrameworkElement border, Window window) {
HookWndProc(window);
Log.assert(border != null);
var restore_on_move = false;
border.MouseLeftButtonDown += (s, e) => {
FrameworkElement fe = e.OriginalSource as FrameworkElement;
if (fe != null && (bool)fe.GetValue(WindowStyle.IsNonClientAreaProperty)) {
if (e.ClickCount == 2) {
toggle_max(window);
} else {
if (window.WindowState == WindowState.Maximized) { restore_on_move = true; }
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
}
}
};
border.MouseLeftButtonUp += (s, e) => restore_on_move = false;
border.MouseMove += (s, e) => {
if (restore_on_move && window.WindowState == WindowState.Maximized && Mouse.LeftButton == MouseButtonState.Pressed) {
window.WindowState = WindowState.Normal;
window.Top = 0;
if (Mouse.LeftButton == MouseButtonState.Pressed) {
window.DragMove();
}
}
};
}
private static void toggle_max(Window window) {
if (window.WindowState == WindowState.Maximized) {
window.WindowState = WindowState.Normal;
} else {
window.WindowState = WindowState.Maximized;
}
}
private static void HookWndProc(Window window) {
HwndSource source = PresentationSource.FromVisual(window) as HwndSource;
if (source != null) {
source.AddHook(new HwndSourceHook(WndProc));
}
}
private static void UnhookWndProc(Window window) {
HwndSource source = PresentationSource.FromVisual(window) as HwndSource;
if (source != null) {
source.RemoveHook(new HwndSourceHook(WndProc));
}
}
private static IntPtr WndProc(IntPtr hwnd, int msg, IntPtr wparam, IntPtr lparam, ref bool handled) {
WM wmsg = (WM)msg;
if (WM.NCHITTEST == wmsg /*|| WM.MOUSEMOVE == wmsg*/) {
Thickness t = new Thickness(6);
// Get the mouse coordinates in screen space
short x = (short)lparam.ToInt32();
short y = (short)(lparam.ToInt32() >> 16);
// Get the window bounds in screen coords
Win32Rect w;
NativeMethods.GetWindowRect(hwnd, out w);
// Assume that mouse position is inside the window
bool left = x < (w.Left + t.Left);
bool right = x > (w.Right - t.Right);
bool top = y < (w.Top + t.Top);
bool bottom = y > (w.Bottom - t.Bottom);
// A B C
// D E
// F G H
HT ret = HT.CLIENT;
if (top) {
if (left) ret = HT.TOPLEFT; // A
else if (right) ret = HT.TOPRIGHT; // C
else ret = HT.TOP; // B
} else if (bottom) {
if (left) ret = HT.BOTTOMLEFT; // F
else if (right) ret = HT.BOTTOMRIGHT; // H
else ret = HT.BOTTOM; // G
} else {
if (left) ret = HT.LEFT; // D
if (right) ret = HT.RIGHT; // E
}
handled = true;
return new IntPtr((int)ret);
} else if (wmsg == WM.NCCALCSIZE) {
handled = true;
} else if (wmsg == WM.NCPAINT) {
handled = true;
} else if (wmsg == WM.NCACTIVATE) {
handled = true;
return NativeMethods.DefWindowProc(hwnd, msg, wparam, new IntPtr(-1));
} else if (wmsg == WM.ERASEBKGND) {
handled = true;
} else if (wmsg == WM.GETMINMAXINFO) {
SetMinMaxInfo(hwnd, lparam);
handled = true;
}
return IntPtr.Zero;
}
private static void SetMinMaxInfo(IntPtr hwnd, IntPtr lparam) {
var mminfo = (MINMAXINFO)Marshal.PtrToStructure(lparam, typeof(MINMAXINFO));
var hmonitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTONNEAREST);
if (hmonitor != IntPtr.Zero) {
MONITORINFO minfo = new MONITORINFO();
minfo.cbSize = Marshal.SizeOf(minfo);
NativeMethods.GetMonitorInfo(hmonitor, ref minfo);
var rc_monitor = minfo.rcMonitor;
var rc_work = minfo.rcWork;
mminfo.ptMaxPosition.x = Math.Abs(rc_work.Left - rc_monitor.Left);
mminfo.ptMaxPosition.y = Math.Abs(rc_work.Top - rc_monitor.Top);
mminfo.ptMaxSize.x = Math.Abs(rc_work.Right - rc_work.Left);
mminfo.ptMaxSize.y = Math.Abs(rc_work.Bottom - rc_work.Top);
Marshal.StructureToPtr(mminfo, lparam, true);
}
}
}
}
@@ -1,241 +1,242 @@
namespace mbts.ui.shell {
using bts;
using Spark.Core;
using Spark.Core.Async;
using Spark.Core.Disposables;
using System;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
public class ShellWindowVM : DisposableViewModelBase {
readonly IWindowManager _window_manager;
readonly Property<bool> _edit_mode;
readonly Property<string> _title;
readonly Property<string> _title_override;
readonly Property<bool> _has_custom_title;
IShellWindow _model;
UIElement _ui;
ShellWindowUI _document;
HwndContentHost _hwnd_host;
FloatingWindow _owner;
ImageSource _icon;
ICommand _close_command;
ICommand _rename_command;
ICommand _unrename_command;
public ShellWindowVM(IShellWindow model, IWindowManager wm, IShellThreadFactory threads, string host = null) {
Log.assert(model != null);
_model = model;
_model.IconChanged += on_icon_changed;
_window_manager = wm;
host_id = (model as ITabAffineWindow)?.tab_group ?? host ?? string.Empty;
// init Dispatcher
var stf = (ShellThreadFactory)threads;
if (IsShared) {
Dispatcher = stf.get_dispatcher((ISharedWindow)model);
} else if (IsSlow) {
Dispatcher = stf.create_dispatcher((ISlowWindow)model);
} else {
Dispatcher = Dispatcher.CurrentDispatcher;
}
_edit_mode = backing(nameof(EditMode), false);
_title_override = backing<string>(nameof(TitleOverride));
_title = backing(
nameof(Title),
_model.observe_title()
.CombineLatest(
_title_override.observe_current(true),
(title, title_override) => (title, title_override))
.Select(t => t.title_override ?? t.title)
.OnDispatcher());
_has_custom_title = backing(
nameof(HasCustomTitle),
_title_override.observe_current(true).Select(t => !t.is_null_or_white_space()).OnDispatcher());
model.on_shell_window_vm(this);
_dispose = Disposable.Create(() => {
_model.IconChanged -= on_icon_changed;
if (IsShared) {
// Shared threads continue running
Dispatcher.Invoke(() => Disposable.dispose(ref _model));
} else if (IsSlow) {
// Terminating the background thread will dispose the model on that thread
Log.Ui.info("Beginning asyncronous dispose of slow window {0} .".fmt(_model.GetType().ToString()));
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
} else {
Disposable.dispose(ref _model);
}
_ui = null;
Disposable.dispose(ref _hwnd_host);
});
void on_icon_changed() {
_icon = null;
RaisePropertyChanged(nameof(Icon));
}
}
public AsyncEvent<(object sender, ShellWindowVM e)> Closing { get; } = new();
public string host_id { get; set; }
public string OwnerName => _model.Owner?.name ?? string.Empty;
public IShellWindow Model => _model;
public Dispatcher Dispatcher { get; }
// title
public string Title => _title.Value;
public string TitleOverride {
get => _title_override.Value;
set {
_title_override.Value = value;
_edit_mode.set(false);
}
}
public bool HasCustomTitle => _has_custom_title.Value;
public ImageSource Icon =>
_icon ??= _model.Icon ?? _model.Owner?.icon;
public bool EditMode => _edit_mode.Value;
public double InitialWidth { get; private set; }
public double InitialHeight { get; private set; }
public UIElement AppContent =>
_ui ??= _create_contents();
public bool IsSlow => _model is ISlowWindow;
public bool IsShared => _model is ISharedWindow;
public bool HasTabAffinity => _model is ITabAffineWindow;
public ICommand rename_command =>
_rename_command ??= new DelegateCommand(_begin_rename);
public ICommand unrename_command =>
_unrename_command ??= new DelegateCommand(() => TitleOverride = string.Empty);
public ICommand CloseCommand =>
_close_command ??= new DelegateCommand(_begin_close);
internal FloatingWindow owner {
get => _owner;
set {
if (Set(ref _owner, value)) {
_try_set_wpf_bus();
}
}
}
public IObservable<string> observe_title() =>
_title.observe_current(true);
void _begin_rename() {
if (string.IsNullOrEmpty(TitleOverride)) {
_title_override.Value = Title;
}
_edit_mode.set(true);
}
async void _begin_close(object sender) {
if (_window_manager is null) {
return;
}
if (!_window_manager.contains(_model)) {
return;
}
await Closing?.InvokeAsync((sender, this));
// Removing the window will cause this object to be Disposed
// Which will terminate the background thread
// Which will dispose the model (on that thread)
await _window_manager.remove(_model);
}
UIElement _create_contents() {
string error_text = null;
Dispatcher.Invoke(() => {
// Executes possibly on background thread
try {
_document = _model.GetContent();
} catch (Exception ex) {
error_text = ex.Message;
Log.Ui.error($"Error getting window contents: {ex}");
}
}, DispatcherPriority.Send);
if (_document == null && string.IsNullOrEmpty(error_text)) {
error_text = $"No content for window {_model.GetType()}";
}
// If there's an error draw a big red X
if (!error_text.is_null_or_empty()) {
_document = new ShellWindowUI(new TextBlock() {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Foreground = Brushes.Red,
Text = error_text
});
_model = new ErrorShellWindow {
Content = _document,
Icon = _model.Icon,
Title = $"Error: {_model.GetType()}"
};
RaisePropertyChanged("Title");
}
Log.assert(_document != null);
return _document.content.Match(on_wpf_element, on_handle_ref);
UIElement on_wpf_element(UIElement element) {
if (IsSlow || IsShared) {
// Create a WPFPanel (a Winforms window), then attach it with the HwndContentHost.
// This gives the document content a separate thread affinity from the shell window,
// and lets the win32 layer handle the thread boundary.
var retval = Dispatcher.Invoke(() => {
var interop_window = new WPFPanel(element);
return new HandleRef(interop_window, interop_window.Handle);
}, DispatcherPriority.Send);
_hwnd_host = new HwndContentHost(retval);
InitialHeight = _hwnd_host.InitialHeight;
InitialWidth = _hwnd_host.InitialWidth;
return _hwnd_host;
}
if (element is FrameworkElement fe) {
InitialHeight = fe.Height;
InitialWidth = fe.Width;
fe.Height = fe.Width = double.NaN;
}
return element;
}
UIElement on_handle_ref(HandleRef handle_ref) {
_hwnd_host = new HwndContentHost(handle_ref);
InitialHeight = _hwnd_host.Height;
InitialWidth = _hwnd_host.Width;
return _hwnd_host;
}
}
void _try_set_wpf_bus() {
if (_owner is null) {
return;
}
_document.content.try_match(on_wpf_element);
void on_wpf_element(UIElement element) =>
element.Dispatcher.InvokeAsync(() =>
ui.WindowStyle.SetUnsafeWindow(element, _owner));
}
}
}
namespace mbts.ui.shell {
using bts;
using Spark.Core;
using Spark.Core.Async;
using Spark.Core.Disposables;
using System;
using System.Reactive.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
public class ShellWindowVM : DisposableViewModelBase {
readonly IWindowManager _window_manager;
readonly Property<bool> _edit_mode;
readonly Property<string> _title;
readonly Property<string> _title_override;
readonly Property<bool> _has_custom_title;
IShellWindow _model;
UIElement _ui;
ShellWindowUI _document;
HwndContentHost _hwnd_host;
FloatingWindow _owner;
ImageSource _icon;
ICommand _close_command;
ICommand _rename_command;
ICommand _unrename_command;
public ShellWindowVM(IShellWindow model, IWindowManager wm, IShellThreadFactory threads, string host = null) {
Log.assert(model != null);
_model = model;
_model.IconChanged += on_icon_changed;
_window_manager = wm;
host_id = (model as ITabAffineWindow)?.tab_group ?? host ?? string.Empty;
// init Dispatcher
var stf = (ShellThreadFactory)threads;
if (IsShared) {
Dispatcher = stf.get_dispatcher((ISharedWindow)model);
} else if (IsSlow) {
Dispatcher = stf.create_dispatcher((ISlowWindow)model);
} else {
Dispatcher = Dispatcher.CurrentDispatcher;
}
_edit_mode = backing(nameof(EditMode), false);
_title_override = backing<string>(nameof(TitleOverride));
_title = backing(
nameof(Title),
_model.observe_title()
.CombineLatest(
_title_override.observe_current(true),
(title, title_override) => (title, title_override))
.Select(t => t.title_override ?? t.title)
.OnDispatcher());
_has_custom_title = backing(
nameof(HasCustomTitle),
_title_override.observe_current(true).Select(t => !t.is_null_or_white_space()).OnDispatcher());
model.on_shell_window_vm(this);
_dispose = Disposable.Create(() => {
_model.IconChanged -= on_icon_changed;
if (IsShared) {
// Shared threads continue running
Dispatcher.Invoke(() => Disposable.dispose(ref _model));
} else if (IsSlow) {
// Terminating the background thread will dispose the model on that thread
Log.Ui.info("Beginning asyncronous dispose of slow window {0} .".fmt(_model.GetType().ToString()));
Dispatcher.BeginInvokeShutdown(DispatcherPriority.Background);
} else {
Disposable.dispose(ref _model);
}
_ui = null;
Disposable.dispose(ref _hwnd_host);
});
void on_icon_changed() {
_icon = null;
RaisePropertyChanged(nameof(Icon));
}
}
public AsyncEvent<(object sender, ShellWindowVM e)> Closing { get; } = new();
public string host_id { get; set; }
public string OwnerName => _model.Owner?.name ?? string.Empty;
public IShellWindow Model => _model;
public Dispatcher Dispatcher { get; }
// title
public string Title => _title.Value;
public string TitleOverride {
get => _title_override.Value;
set {
_title_override.Value = value;
_edit_mode.set(false);
}
}
public bool HasCustomTitle => _has_custom_title.Value;
public ImageSource Icon =>
_icon ??= _model.Icon ?? _model.Owner?.icon;
public bool EditMode => _edit_mode.Value;
public double InitialWidth { get; private set; }
public double InitialHeight { get; private set; }
public UIElement AppContent =>
_ui ??= _create_contents();
public bool IsSlow => _model is ISlowWindow;
public bool IsShared => _model is ISharedWindow;
public bool HasTabAffinity => _model is ITabAffineWindow;
public ICommand rename_command =>
_rename_command ??= new DelegateCommand(_begin_rename);
public ICommand unrename_command =>
_unrename_command ??= new DelegateCommand(() => TitleOverride = string.Empty);
public ICommand CloseCommand =>
_close_command ??= new DelegateCommand(_begin_close);
internal FloatingWindow owner {
get => _owner;
set {
if (Set(ref _owner, value)) {
_try_set_wpf_bus();
}
}
}
public IObservable<string> observe_title() =>
_title.observe_current(true);
void _begin_rename() {
if (string.IsNullOrEmpty(TitleOverride)) {
_title_override.Value = Title;
}
_edit_mode.set(true);
}
async void _begin_close(object sender) {
if (_window_manager is null) {
return;
}
if (!_window_manager.contains(_model)) {
return;
}
await Closing?.InvokeAsync((sender, this));
// Removing the window will cause this object to be Disposed
// Which will terminate the background thread
// Which will dispose the model (on that thread)
await _window_manager.remove(_model);
}
UIElement _create_contents() {
string error_text = null;
Dispatcher.Invoke(() => {
// Executes possibly on background thread
try {
_document = _model.GetContent();
} catch (Exception ex) {
error_text = ex.Message;
Log.Ui.error($"Error getting window contents: {ex}");
}
}, DispatcherPriority.Send);
if (_document == null && string.IsNullOrEmpty(error_text)) {
error_text = $"No content for window {_model.GetType()}";
}
// If there's an error draw a big red X
if (!error_text.is_null_or_empty()) {
_document = new ShellWindowUI(new TextBlock() {
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Center,
Foreground = Brushes.Red,
Text = error_text
});
_model = new ErrorShellWindow {
Content = _document,
Icon = _model.Icon,
Title = $"Error: {_model.GetType()}"
};
RaisePropertyChanged("Title");
}
Log.assert(_document != null);
return _document.content.Match(on_wpf_element, on_handle_ref);
UIElement on_wpf_element(UIElement element) {
if (IsSlow || IsShared) {
// Create a WPFPanel (a Winforms window), then attach it with the HwndContentHost.
// This gives the document content a separate thread affinity from the shell window,
// and lets the win32 layer handle the thread boundary.
var retval = Dispatcher.Invoke(() => {
var interop_window = new WPFPanel(element);
element.SetCurrentValue(ui.WindowStyle.WinFormsHostProperty, interop_window);
return new HandleRef(interop_window, interop_window.Handle);
}, DispatcherPriority.Send);
_hwnd_host = new HwndContentHost(retval);
InitialHeight = _hwnd_host.InitialHeight;
InitialWidth = _hwnd_host.InitialWidth;
return _hwnd_host;
}
if (element is FrameworkElement fe) {
InitialHeight = fe.Height;
InitialWidth = fe.Width;
fe.Height = fe.Width = double.NaN;
}
return element;
}
UIElement on_handle_ref(HandleRef handle_ref) {
_hwnd_host = new HwndContentHost(handle_ref);
InitialHeight = _hwnd_host.Height;
InitialWidth = _hwnd_host.Width;
return _hwnd_host;
}
}
void _try_set_wpf_bus() {
if (_owner is null) {
return;
}
_document.content.try_match(on_wpf_element);
void on_wpf_element(UIElement element) =>
element.Dispatcher.InvokeAsync(() =>
ui.WindowStyle.SetUnsafeWindow(element, _owner));
}
}
}
@@ -63,7 +63,7 @@ namespace mbts {
if (ticks_per_base.is_int()) {
return true;
}
return tick.tick_unit > tick.tick_base && tick.tick_base == 1;
return tick.tick_unit > tick.tick_base && tick.tick_unit_frac().is_int();
}
public static bool is_valid(this RegionalTickFactors regional_tick) =>
@@ -179,10 +179,7 @@ namespace mbts {
if (T.IsInfinity(value)) {
return value.ToString();
}
return tick?.is_valid() ?? false ?
_format_tick(tick, value, settings) :
_format_no_tick(
value, settings.display_multiplier.as_type<double, T>(), settings.show_commas);
return _format_tick(tick, value, settings);
}
public static string format<T>(
+60 -93
View File
@@ -6,6 +6,7 @@ using bts.utils;
using mbts.user.settings;
using Spark.Core;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
@@ -189,52 +190,58 @@ namespace mbts.spark {
public static int compare_tick_fallback_to_double(this ContractSpecificationImmutable contract, double x, double y) =>
tick_equals(contract, x, y) ? 0 : x.CompareTo(y);
public static double round_to_tick(this ContractSpecificationImmutable spec, double value) =>
round_to_tick(spec.ticksize(value), value);
public static double round_to_tick(this ContractSpecificationImmutable spec, double value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick(spec.ticksize(value), value, rounding_mode);
public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value) =>
round_to_tick((decimal)spec.ticksize((double)value), value);
public static decimal round_to_tick(this ContractSpecificationImmutable spec, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick((decimal)spec.ticksize((double)value), value, rounding_mode);
public static double round_to_tick(this RegionalTickFactors rtick, double value) =>
round_to_tick(rtick.ticksize(value), value);
public static double round_to_tick(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick(rtick.ticksize(value), value, rounding_mode);
public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value) =>
round_to_tick((decimal)rtick.ticksize((double)value), value);
public static decimal round_to_tick(this RegionalTickFactors rtick, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) =>
round_to_tick((decimal)rtick.ticksize((double)value), value, rounding_mode);
public static double round_to_tick(double tick_size, double value) {
double intpart = (long)value;
double floatpart = value % 1;
floatpart = ((int)Math.Round(floatpart / tick_size)) * tick_size;
return intpart + floatpart;
public static double round_to_tick(double tick_size, double value, RoundingMode rounding_mode = RoundingMode.Closest) {
double n = rounding_mode switch {
RoundingMode.Closest => Math.Round(value / tick_size),
RoundingMode.Up => Math.Ceiling((value - _precision_const) / tick_size),
RoundingMode.Down => Math.Floor((value + _precision_const) / tick_size),
RoundingMode.AbsUp => value < 0
? Math.Floor((value + _precision_const) / tick_size)
: Math.Ceiling((value - _precision_const) / tick_size),
RoundingMode.AbsDown => value < 0
? Math.Ceiling((value - _precision_const) / tick_size)
: Math.Floor((value + _precision_const) / tick_size),
_ => double.NaN,
};
return n * tick_size;
}
public static decimal round_to_tick(decimal tick_size, decimal value) {
decimal intpart = (long)value;
decimal floatpart = value % 1;
floatpart = ((int)(floatpart / tick_size)) * tick_size;
return intpart + floatpart;
public static decimal round_to_tick(decimal tick_size, decimal value, RoundingMode rounding_mode = RoundingMode.Closest) {
decimal n = rounding_mode switch {
RoundingMode.Closest => Math.Round(value / tick_size),
RoundingMode.Up => Math.Ceiling(value / tick_size),
RoundingMode.Down => Math.Floor(value / tick_size),
RoundingMode.AbsUp => value < 0
? Math.Floor(value / tick_size)
: Math.Ceiling(value / tick_size),
RoundingMode.AbsDown => value < 0
? Math.Ceiling(value / tick_size)
: Math.Floor(value / tick_size),
_ => throw new ArgumentException("Invalid rounding mode", nameof(rounding_mode)),
};
return n * tick_size;
}
public static long? count_ticks(this RegionalTickFactors rtick, double value) {
if (!rtick.is_valid()) {
return null;
}
public static long? count_ticks(this RegionalTickFactors rtick, double value, RoundingMode rounding_mode = RoundingMode.AbsDown) {
var rounded_value = rtick.round_to_tick(value, rounding_mode);
var n = _count_ticks(
rtick.low_tick.tick_unit_frac(),
rtick.low_tick_inclusive_end,
rtick.high_tick.tick_unit_frac(),
0,
value);
var orig_n = n;
// Enforce proper rounding
var rounded_val = rtick.round_to_tick(value);
var half_tick = rtick.get_tick_for(value).tick_unit_frac() / 2;
if (n < 0 && (value - rounded_val) > half_tick) {
++n;
} else if (n > 0 && (rounded_val - value) > half_tick) {
--n;
}
Log.assert(n == orig_n);
rounded_value);
return n;
}
@@ -253,71 +260,19 @@ namespace mbts.spark {
return tick;
}
public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) {
factor = _fit_ticks_per_row_to_dollars(spec, factor) ?? 1;
return new(
public static RegionalTickFactors multiply_tick_size(RegionalTickFactors spec, uint factor) =>
new(
new(spec.low_tick.tick_base, spec.low_tick.tick_unit * factor),
new(spec.high_tick.tick_base, spec.high_tick.tick_unit * factor),
spec.low_tick_inclusive_end);
}
public static double normalize_price(RegionalTickFactors rtick, double price) {
if (!price.is_real()) {
var maybe_ticks = rtick.count_ticks(price);
if (!maybe_ticks.HasValue) {
return price;
}
var ticks = rtick.count_ticks(price);
if (!ticks.HasValue) {
return price;
}
var normalized = rtick.tick(0, ticks.Value);
var tick = price > rtick.low_tick_inclusive_end ? rtick.high_tick : rtick.low_tick;
// Diff should always be < 1/2 tick
Log.assert((normalized - price).abs() < tick.tick_unit_frac() * 0.5);
return normalized;
}
public static uint fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(sec, ticks_per_row) ?? 1;
public static uint fit_ticks_per_row_to_dollars(RegionalTickFactors rtick, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(rtick, ticks_per_row) ?? 1;
static uint? _fit_ticks_per_row_to_dollars(SecurityImmutable sec, uint ticks_per_row) =>
_fit_ticks_per_row_to_dollars(sec.regional_ticks(), ticks_per_row);
static uint? _fit_ticks_per_row_to_dollars(RegionalTickFactors tf, uint ticks_per_row) {
if (ticks_per_row == 0)
return null;
// it is assumed that low tick will be the same as high tick;
// however, best to double check - return null if this isn't the case (let the caller decide what to do).
if (!tf.low_tick.Equals(tf.high_tick) || !tf.is_valid() || tf.low_tick.is_integer())
return null;
var ticks_per_dollar = (uint)(tf.low_tick.tick_base / tf.low_tick.tick_unit);
// if ticks_per_row is greater than ticks_per_dollar, round to a multiple of ticks_per_dollar
if (ticks_per_row > ticks_per_dollar) {
if (ticks_per_dollar == 0) {
return null;
}
return (uint)(ticks_per_dollar * Math.Floor((double)(ticks_per_row / ticks_per_dollar)));
} else if (ticks_per_row == ticks_per_dollar) {
return ticks_per_row;
} else {
uint max_decrease_adj = ticks_per_row;
uint max_increase_adj = ticks_per_dollar - ticks_per_row - 1;
for (uint adj = 0; adj < Math.Max(max_decrease_adj, max_increase_adj); adj++) {
if (adj < max_decrease_adj) {
var result = ticks_per_row - adj;
if (ticks_per_dollar % result == 0)
return result;
}
if (adj < max_increase_adj) {
var result = ticks_per_row + adj;
if (ticks_per_dollar % result == 0)
return result;
}
}
}
return null;
var ticks = maybe_ticks.Value;
return rtick.tick(0, (long)ticks);
}
static long? _count_ticks(
@@ -367,8 +322,20 @@ namespace mbts.spark {
static long count_single_tick_sz(
double tick_sz, double from, double to) {
var from_n = (long)MathUtils.round_fractional_units(from, tick_sz);
var to_n = (long)MathUtils.round_fractional_units(to, tick_sz);
from = round_to_tick(tick_sz, from, RoundingMode.AbsDown);
to = round_to_tick(tick_sz, to, RoundingMode.AbsDown);
if (from < 0) {
from -= _precision_const;
} else {
from += _precision_const;
}
if (to < 0) {
to -= _precision_const;
} else {
to += _precision_const;
}
var from_n = (long)(from / tick_sz);
var to_n = (long)(to / tick_sz);
return to_n - from_n;
}
}
@@ -1,5 +1,6 @@
namespace bts.api {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection.Metadata.Ecma335;
@@ -36,6 +37,15 @@ namespace bts.api {
};
}
public static IEnumerable<DateTime> normal_expirations(this SecurityImmutable security) =>
security.ContractCase switch {
Security.ContractOneofCase.Future => new[] { security.Future.expiration_date() },
Security.ContractOneofCase.Option => new[] { security.Option.expiration_date() },
Security.ContractOneofCase.Spread => security.Spread.Legs.SelectMany(l => l.Security.normal_expirations()),
Security.ContractOneofCase.Synthetic => security.Synthetic.Legs.SelectMany(l => l.Security.normal_expirations()),
_ => Enumerable.Empty<DateTime>()
};
public static ProductImmutable product(this SecurityImmutable security) =>
new(new() {
Exchange = security.Exchange,
@@ -59,13 +69,7 @@ namespace bts.api {
new((int)future.ExpirationYear, (int)future.ExpirationMonth, (int)future.ExpirationDay);
internal static DateTime earliest_expiration(this SecurityImmutable security) =>
security.ContractCase switch {
Security.ContractOneofCase.Synthetic => security.Synthetic.Legs.First().Security.earliest_expiration(),
Security.ContractOneofCase.Spread => security.Spread.Legs.First().Security.earliest_expiration(),
Security.ContractOneofCase.Future => security.Future.expiration_date(),
Security.ContractOneofCase.Option => security.Option.expiration_date(),
_ => throw new NotImplementedException(),
};
security.normal_expirations().Min();
public static double strike(this SecurityImmutable security) =>
security.HasOption ? security.Option.Strike : double.NaN;
@@ -105,13 +109,13 @@ namespace bts.api {
Security.ExchangeDataOneofCase.Deribit => security.Deribit.SecurityDesc,
Security.ExchangeDataOneofCase.Ftx => security.Ftx.SecurityDesc,
Security.ExchangeDataOneofCase.Binance => security.Binance.SecurityDesc,
Security.ExchangeDataOneofCase.BinanceCoinFutures => security.BinanceCoinFutures.SecurityDesc,
Security.ExchangeDataOneofCase.BinanceUs => security.BinanceUs.SecurityDesc,
Security.ExchangeDataOneofCase.BinanceUsdsFutures => security.BinanceUsdsFutures.SecurityDesc,
Security.ExchangeDataOneofCase.Coinbase => security.Coinbase.SecurityDesc,
Security.ExchangeDataOneofCase.Okx => security.Okx.SecurityDesc,
Security.ExchangeDataOneofCase.Cboe => security.Cboe.SecurityDesc,
Security.ExchangeDataOneofCase.Taifex => security.Taifex.SecurityDesc,
Security.ExchangeDataOneofCase.Twse => security.Twse.SecurityDesc,
_ => throw new NotImplementedException("security_desc not implemented for exchange")
};
@@ -152,14 +156,14 @@ namespace bts.api {
domain.Venue.Deribit => Venue.Deribit,
domain.Venue.Ftx => Venue.Ftx,
domain.Venue.Binance => Venue.Binance,
domain.Venue.BinanceCoinFutures => Venue.BinanceCoinFutures,
domain.Venue.BinanceUs => Venue.BinanceUs,
domain.Venue.BinanceUsdsFutures => Venue.BinanceUsdsFutures,
domain.Venue.Glbx => Venue.Glbx,
domain.Venue.Coinbase => Venue.Coinbase,
domain.Venue.Okx => Venue.Okx,
domain.Venue.Cboe => Venue.Cboe,
domain.Venue.Cboe => Venue.Cboe,
domain.Venue.Taifex => Venue.Taifex,
domain.Venue.Twse => Venue.Twse,
domain.Venue.Unspecified => Venue.Unset,
@@ -173,6 +177,7 @@ namespace bts.api {
Venue.Deribit => domain.Venue.Deribit,
Venue.Ftx => domain.Venue.Ftx,
Venue.Binance => domain.Venue.Binance,
Venue.BinanceCoinFutures => domain.Venue.BinanceCoinFutures,
Venue.BinanceUs => domain.Venue.BinanceUs,
Venue.BinanceUsdsFutures => domain.Venue.BinanceUsdsFutures,
Venue.Coinbase => domain.Venue.Coinbase,
@@ -180,7 +185,6 @@ namespace bts.api {
Venue.Okx => domain.Venue.Okx,
Venue.Cboe => domain.Venue.Cboe,
Venue.Taifex => domain.Venue.Taifex,
Venue.Twse => domain.Venue.Twse,
Venue.Unset => domain.Venue.Unspecified,
_ => throw new NotImplementedException(),
@@ -162,7 +162,7 @@
return leg.signed_quantity() switch {
1.0 => sec_str,
-1.0 => $"-{sec_str}",
_ => ""
_ => $"{leg.signed_quantity()}{sec_str}",
};
}
@@ -172,7 +172,7 @@
return leg.signed_quantity() switch {
1.0 => $"+{sec_str}",
-1.0 => $"-{sec_str}",
_ => $"{leg.signed_quantity():+0;-0}{sec_str}",
_ => $"{leg.signed_quantity():+0.######;-0.######}{sec_str}",
};
}
}
@@ -640,6 +640,9 @@ namespace System.Collections.Generic {
public static List<T> ToListSorted<T, TKey>(this IEnumerable<T> enumerable, Func<T, TKey> key_selector, IComparer<TKey> key_comparer) =>
enumerable.ToListSorted(key_comparer.wrap(key_selector));
public static List<T> ToListSorted<T>(this IEnumerable<T> enumerable) where T : IComparable<T> =>
enumerable.ToListSorted(Comparer<T>.Default);
public static List<T> ToListSorted<T>(this IEnumerable<T> enumerable, IComparer<T> comparer) {
var list = new List<T>(enumerable);
list.Sort(comparer);
@@ -0,0 +1,17 @@
#nullable enable
namespace Spark.Core.Math;
public enum RoundingMode {
None,
// Round to the closest integer (up if decimal part is >= 0.5, otherwise down)
Closest,
// Round up
Up,
// Round down
Down,
// Round positive numbers up, and negative numbers down
AbsUp,
// Round positive numbers down, and negative numbers up
AbsDown
}
+31
View File
@@ -0,0 +1,31 @@
#nullable enable
namespace bts;
using System;
public class ThrottledAction {
readonly TimeSpan interval;
readonly bool measureEndToNextStart;
DateTime lastInvokedTime = DateTime.MinValue;
public ThrottledAction(TimeSpan interval, bool measureEndToNextStart = true) {
this.interval = interval;
this.measureEndToNextStart = measureEndToNextStart;
}
public bool Execute(Action action) {
var now = DateTime.Now;
var elapsed = now - lastInvokedTime;
if (elapsed < interval) {
return false;
}
if (measureEndToNextStart) {
action();
lastInvokedTime = DateTime.Now;
} else {
lastInvokedTime = now;
action();
}
return true;
}
}
+30 -4
View File
@@ -50,6 +50,30 @@ namespace bts.utils {
public static bool is_nan<T>(T value) where T : INumber<T> =>
NormalNumericOps<T>.is_nan(value);
public static bool can_increment<T>(T value, T addend) where T : INumber<T>, IMinMaxValue<T> {
if (value > T.Zero != addend > T.Zero) {
return true;
}
if (value > T.Zero) {
return addend < T.MaxValue - value;
}
if (value < T.Zero) {
return addend > T.MinValue - value;
}
return true;
}
public static bool try_increment<T>(ref T value, T addend) where T : INumber<T>, IMinMaxValue<T> {
if (can_increment(value, addend)) {
value += addend;
return true;
}
return false;
}
public static bool try_increment(ref int value, long addend) =>
addend <= int.MaxValue && addend >= int.MinValue && try_increment(ref value, (int)addend);
public static float gcd(IEnumerable<float> nums) =>
gcd<float, NumericCastConverter>(nums);
@@ -449,10 +473,12 @@ namespace bts.utils {
}
static bool try_mk_floating_point_type([NotNullWhen(true)] out Type type) {
try {
type = typeof(IFloatingPoint<>).MakeGenericType(typeof(T));
return type.IsAssignableFrom(typeof(T));
} catch { }
if (typeof(T).GetInterfaces().Any(iface => iface.IsGenericType && iface.GetGenericTypeDefinition().Equals(typeof(IFloatingPoint<>)))) {
try {
type = typeof(IFloatingPoint<>).MakeGenericType(typeof(T));
return type.IsAssignableFrom(typeof(T));
} catch { }
}
type = null;
return false;
}
+3 -31
View File
@@ -6,6 +6,8 @@ using mbts;
using mbts.spark;
using mbts.user.settings;
using Spark.Core.Math;
using System;
using System.Collections.Generic;
using System.Linq;
@@ -159,7 +161,7 @@ namespace bts.tests.security {
var price_break = tick.low_tick_inclusive_end;
foreach (var p in prices) {
var expected_ticks_from_zero = TickTestHelper.count_ticks(tick, p);
var actual_ticks_from_zero = TickUtils.count_ticks(tick, p);
var actual_ticks_from_zero = TickUtils.count_ticks(tick, p, RoundingMode.Closest);
Assert.That(expected_ticks_from_zero == actual_ticks_from_zero,
$"Expected ticks from zero to be '{expected_ticks_from_zero}', actually '{actual_ticks_from_zero}' " +
$"(low/high/pricebreak: {tick.low_tick}/{tick.high_tick}/{price_break}, price: {p}).");
@@ -177,24 +179,6 @@ namespace bts.tests.security {
}
}
void _test_tick_increment(ContractSpecificationImmutable spec, double from, double to) {
if (!from.is_real() || !to.is_real())
return;
var (min, max) = MathUtils.get_outliers(from, to);
if (spec.PriceBreak.is_real()) {
if (min >= spec.PriceBreak) {
//_test_single_tick(spec.HighTick, min, max);
} else if (max <= spec.PriceBreak) {
_test_tick_increment(spec, spec.LowTick, min, max);
} else {
//if (round_ticks(spec.LowTick, min, out var ))
_test_tick_increment_across_break(spec, min, max);
}
} else {
_test_tick_increment(spec, spec.LowTick, min, max);
}
}
void _test_tick_increment(RegionalTickFactors tick, double from, double to) {
if (!from.is_real() || !to.is_real())
return;
@@ -260,18 +244,6 @@ namespace bts.tests.security {
Assert.That(MathUtils.marginal_equals(batch_tick_down_result, rounded_min, TickUtils.precision_const<double>()));
}
void _test_tick_increment(ContractSpecificationImmutable spec, double tick_size, double min, double max) {
// min round/partial tick
Assert.That(TickTestHelper.round_ticks(tick_size, min, out var rounded_min, out var rounded_min_ticks));
var min_partial_tick = TickTestHelper.check_partial_tick(spec, min, rounded_min, true);
// max round/partial tick
Assert.That(TickTestHelper.round_ticks(tick_size, max, out var rounded_max, out var rounded_max_ticks));
var max_partial_tick = TickTestHelper.check_partial_tick(spec, max, rounded_max, false);
var full_ticks = rounded_max_ticks - rounded_min_ticks;
Assert.That(MathUtils.marginal_equals(rounded_max, spec.tickup(min, full_ticks + min_partial_tick), TickUtils.precision_const<double>()));
Assert.That(MathUtils.marginal_equals(rounded_min, spec.tickup(max, -(full_ticks + max_partial_tick)), TickUtils.precision_const<double>()));
}
void _test_tick_increment(RegionalTickFactors tick, double tick_size, double min, double max) {
// min round/partial tick
Assert.That(TickTestHelper.round_ticks(tick_size, min, out var rounded_min, out var rounded_min_ticks));
+1 -1
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.10)
project(data_files)
include(${CMAKE_SOURCE_DIR}/cmake/safe_dep_glob.cmake)
+1 -1
View File
@@ -1,4 +1,4 @@
cmake_minimum_required(VERSION 3.5)
cmake_minimum_required(VERSION 3.10)
project(libspark)
set(CMAKE_SHARED_LIBRARY_PREFIX "")
include(GNUInstallDirs)
-1
View File
@@ -27,5 +27,4 @@ enum Venue {
VENUE_OKX = 15;
VENUE_TAIFEX = 16;
VENUE_CBOE = 17;
VENUE_TWSE = 18;
}
@@ -0,0 +1,34 @@
syntax = "proto3";
import "lib/api/domain/SecurityCriteria.proto";
import "lib/api/core/RegexFormatting.proto";
package bts.api.md;
option csharp_namespace = "bts.api.md";
option cc_enable_arenas = true;
message BinanceCoinFuturesMarketDataConfig {
uint32 num_depth_levels = 1;
uint32 depth_throttle_ms = 2;
bts.api.domain.SecurityCriteria security_criteria = 3;
// Market data isn't subscribed for securities listed here (even if they are
// included by 'security_criteria'). There are some securities that don't
// fit into our system just yet, such as 'BTCBIDR', which trades in prices
// larger than our cpp 'domain::Price' class supports.
repeated string excluded_securities = 4;
// The list of instruments at Binance is obtained via an 'exchangeInfo' http
// rest request. In the corresponding response, each instrument has a 'pair'
// field, which is analgous to a security desc in our system (a unique
// human-readable string representation of the security). For some
// instruments, the string representation used in the market depth request is
// slightly different.
//
// 'depth_symbol_mappings' is a list of regex find/replace patterns to
// apply (to the 'pair' field) when subscribing to depth.
repeated bts.api.core.RegexFormatting security_desc_formattings = 5;
string url_rest_base = 6;
string url_ws_base = 7;
}
@@ -1,7 +1,6 @@
syntax = "proto3";
import "lib/api/domain/SecurityCriteria.proto";
import "lib/api/core/RegexFormatting.proto";
package bts.api.md;
@@ -9,6 +8,13 @@ option csharp_namespace = "bts.api.md";
option cc_enable_arenas = true;
message BinanceUsdsFuturesMarketDataConfig {
message Subscription {
string symbol = 1;
string pair = 2;
string contract_type = 3;
string base_asset = 4;
string quote_asset = 5;
}
uint32 num_depth_levels = 1;
uint32 depth_throttle_ms = 2;
bts.api.domain.SecurityCriteria security_criteria = 3;
@@ -17,17 +23,7 @@ message BinanceUsdsFuturesMarketDataConfig {
// fit into our system just yet, such as 'BTCBIDR', which trades in prices
// larger than our cpp 'domain::Price' class supports.
repeated string excluded_securities = 4;
// The list of instruments at Binance is obtained via an 'exchangeInfo' http
// rest request. In the corresponding response, each instrument has a 'pair'
// field, which is analgous to a security desc in our system (a unique
// human-readable string representation of the security). For some
// instruments, the string representation used in the market depth request is
// slightly different.
//
// 'depth_symbol_mappings' is a list of regex find/replace patterns to
// apply (to the 'pair' field) when subscribing to depth.
repeated bts.api.core.RegexFormatting security_desc_formattings = 5;
repeated Subscription subscriptions = 8;
string url_rest_base = 6;
string url_ws_base = 7;
+2 -2
View File
@@ -2,6 +2,7 @@ syntax = "proto3";
import "lib/api/md/FTXMarketDataConfig.proto";
import "lib/api/md/BinanceMarketDataConfig.proto";
import "lib/api/md/BinanceCoinFuturesMarketDataConfig.proto";
import "lib/api/md/BinanceUsMarketDataConfig.proto";
import "lib/api/md/CoinbaseMarketDataConfig.proto";
import "lib/api/md/BinanceUsdsFuturesMarketDataConfig.proto";
@@ -12,7 +13,6 @@ import "lib/api/md/EmumbaDeribitMarketDataConfig.proto";
import "lib/api/md/OkxMarketDataConfig.proto";
import "lib/api/md/GlbxMarketDataConfig.proto";
import "lib/api/md/TaifexMarketDataConfig.proto";
import "lib/api/md/TwseMarketDataConfig.proto";
import "lib/api/md/CboeMarketDataConfig.proto";
option csharp_namespace = "bts.api.md";
@@ -22,6 +22,7 @@ package bts.api.md;
message MarketDataConfig {
repeated FTXMarketDataConfig ftx = 1;
repeated BinanceMarketDataConfig binance = 2;
repeated BinanceCoinFuturesMarketDataConfig binance_coin_futures = 11;
repeated BinanceUsdsFuturesMarketDataConfig binance_usds_futures = 3;
repeated BinanceUsMarketDataConfig binance_us = 4;
repeated DeribitMarketDataConfig deribit = 5;
@@ -30,7 +31,6 @@ message MarketDataConfig {
repeated GlbxMarketDataConfig glbx = 8;
repeated CboeMarketDataConfig cboe = 9;
repeated TaifexMarketDataConfig taifex =10;
repeated TwseMarketDataConfig twse =11;
// Add an entry here for all the exchanges that need their market data to be recorded
repeated EmumbaDeribitMarketDataConfig emumba_deribit = 100;
-2
View File
@@ -23,8 +23,6 @@ std::set<bts::api::Venue> MarketDataConfigUtils::get_live_exchanges(
rv.insert(bts::api::VENUE_GLBX);
if (cfg.taifex_size()>0)
rv.insert(bts::api::VENUE_TAIFEX);
if (cfg.twse_size()>0)
rv.insert(bts::api::VENUE_TWSE);
if (cfg.cboe_size()>0)
rv.insert(bts::api::VENUE_CBOE);
return rv;
-19
View File
@@ -1,19 +0,0 @@
syntax = "proto3";
import "lib/api/domain/SecurityCriteria.proto";
package bts.api.md;
option csharp_namespace = "bts.api.md";
message TwseConnectionDetails{
string live_data_ip = 30;
}
message TwseMarketDataConfig {
uint32 unique_check_value = 1;
bool read_from_file = 20;
string realtime_data_file_name = 22;
TwseConnectionDetails connection_details = 30;
bts.api.domain.SecurityCriteria security_criteria = 3;
}
@@ -66,13 +66,13 @@ bool AdminServiceUtils::has_exchange(
case api::Venue::VENUE_DERIBIT: // TODO
case api::Venue::VENUE_FTX:
case api::Venue::VENUE_BINANCE:
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
case api::Venue::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
case api::Venue::VENUE_OKX:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_TAIFEX:
case api::Venue::VENUE_CBOECFE:
case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
@@ -186,9 +186,9 @@ AdminServiceUtils::resolve_connection(
case api::Venue::VENUE_FTX:
case api::Venue::VENUE_OKX:
case api::Venue::VENUE_BINANCE:
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
case api::Venue::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_TAIFEX:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_BINANCE_USDS_FUTURES: {
@@ -456,13 +456,13 @@ std::string AdminServiceUtils::find_account_exchange_account(
case api::Venue::VENUE_DERIBIT: // TODO
case api::Venue::VENUE_FTX: // TODO
case api::Venue::VENUE_BINANCE: // TODO
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
case api::Venue::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
case api::Venue::VENUE_OKX:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_TAIFEX:
case api::Venue::VENUE_CBOECFE:
case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
@@ -583,6 +583,21 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record(
out_result.set_is_success(true);
return rv;
}
case api::VENUE_OKX: {
rv.set_session("okx_1");
rv.set_account(account_ptr->name());
rv.set_operator_id(user_ptr->name());
// AdminServiceUtils::ExchangeSubAccountResolver resolver;
// auto sub_acc_ptr = resolver.find_entry(&sec, account_ptr->name(), true);
// if (!sub_acc_ptr) {
// out_result.set_is_success(false);
// out_result.set_error_text("Could not resolve sub account");
// return rv;
// }
// rv.set_account_code(sub_acc_ptr->exchange_subaccount());
out_result.set_is_success(true);
return rv;
}
case api::Venue::VENUE_DERIBIT: {
rv.set_session("deribit_1");
rv.set_account(account_ptr->name());
@@ -752,15 +767,20 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record(
out_result.set_is_success(true);
return rv;
}
case api::VENUE_BINANCE_USDS_FUTURES: {
rv.set_session("binance_usds_futures_1");
rv.set_account(account_ptr->name());
rv.set_account(user_ptr->name());
out_result.set_is_success(true);
return rv;
}
case api::VENUE_FTX: // TODO
case api::VENUE_BINANCE: // TODO
case api::VENUE_BINANCE_COIN_FUTURES:
case api::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::VENUE_BINANCE_USDS_FUTURES:
case api::VENUE_OKX:
case api::Venue::VENUE_UNSET:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_CBOECFE:
case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
case api::Venue::Venue_INT_MAX_SENTINEL_DO_NOT_USE_:
@@ -1149,6 +1169,7 @@ std::string AdminServiceUtils::find_user_exchange_id(
case api::Venue::VENUE_DERIBIT: // TODO
case api::Venue::VENUE_FTX: // TODO
case api::Venue::VENUE_BINANCE: // TODO
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
case api::Venue::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
@@ -1156,7 +1177,6 @@ std::string AdminServiceUtils::find_user_exchange_id(
case api::Venue::VENUE_UNSET:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_TAIFEX:
case api::Venue::VENUE_CBOECFE:
case api::Venue::Venue_INT_MIN_SENTINEL_DO_NOT_USE_:
@@ -1185,6 +1205,7 @@ std::string AdminServiceUtils::find_user_company_id(
case api::Venue::VENUE_DERIBIT:
case api::Venue::VENUE_FTX: // TODO
case api::Venue::VENUE_BINANCE: // TODO
case api::Venue::VENUE_BINANCE_COIN_FUTURES:
case api::Venue::VENUE_BINANCE_US:
case api::Venue::VENUE_COINBASE:
case api::Venue::VENUE_BINANCE_USDS_FUTURES:
@@ -1195,7 +1216,6 @@ std::string AdminServiceUtils::find_user_company_id(
case api::Venue::VENUE_UNSET:
case api::Venue::VENUE_BTS:
case api::Venue::VENUE_CBOE:
case api::Venue::VENUE_TWSE:
case api::Venue::VENUE_TAIFEX:
case api::Venue::VENUE_CBOECFE:
@@ -41,6 +41,18 @@ class AdminServiceUtils {
}
return nullptr;
}
bts::config::toggles::ExchangeSubAccountUnit const *find_entry(
const std::string &account, bool is_internal_account) {
for (const auto &esa : exch_sub_accounts.accounts()) {
const auto &a = is_internal_account ? esa.bts_account_name()
: esa.exchange_subaccount();
if (a == account) {
return &esa;
}
}
return nullptr;
}
};
////////////////////////////////////////////
// connection accessors ////////////////////
@@ -74,11 +74,6 @@ function(get_cpp_sources dest)
expression/ParserExceptions.cpp
expression/Value.cpp
expression/tests/expression_parser_tests.cpp
io/http/CurlHandle.cpp
io/http/HTTPClient.cpp
io/http/HTTPHeaders.cpp
io/http/HTTPRequest.cpp
io/http/HTTPResponse.cpp
logging/LoggerHub.cpp
logging/Sink.cpp
logging/logging.cpp
@@ -4,6 +4,7 @@ SecurityMetadataCollection {
scope {
clauses {
symbols: "BTC"
symbols: "ETH"
security_types: SECURITY_TYPE_FUTURE
security_types: SECURITY_TYPE_SPREAD
venues: VENUE_BINANCE
@@ -13,11 +14,11 @@ SecurityMetadataCollection {
value {
quantity_display {
tick_factors {
tick_base: 1
tick_unit: 10
tick_base: 1000
tick_unit: 1
}
display_multiplier: NaN
show_decimal_part: false
show_decimal_part: true
pad_with_leading_zeros: true
show_zero_integer: true
nan_text: ""
@@ -4028,6 +4028,10 @@ JetFIX {
name: "deribit_1"
venue: VENUE_DERIBIT
}
connection {
name: "okx_1"
venue: VENUE_OKX
}
# CME EXECUTION NEEDS TO BE UPDATED, probably below
# connection {
# name: "onixs_sim"
+8 -21
View File
@@ -20,12 +20,9 @@ SymbolLists {
symbol: "ETH"
}
list {
key: "TWSE"
symbol: "2330"
symbol: "2317"
symbol: "2454"
symbol: "2603"
symbol: "2615"
key: "BINANCE_COIN_FUTURES"
symbol: "BTC"
symbol: "ETH"
}
list {
key: "TAIFEX"
@@ -67,11 +64,6 @@ Symbols {
future: @SymbolLists.list[GLBX].symbol
spread: @SymbolLists.list[GLBX].symbol
}
venues{
name: "VENUE_TWSE"
future: @SymbolLists[TWSE].symbol
option: @SymbolLists[TWSE].symbol
}
venues{
name: "VENUE_TAIFEX"
future: @SymbolLists[TAIFEX].symbol
@@ -104,11 +96,6 @@ Symbols {
future: @SymbolLists.list[ICE].symbol
spread: @SymbolLists.list[ICE].symbol
}
venues{
name: "VENUE_TWSE"
future: @SymbolLists[TWSE].symbol
option: @SymbolLists[TWSE].symbol
}
venues{
name: "VENUE_TAIFEX"
future: @SymbolLists[TAIFEX].symbol
@@ -143,11 +130,6 @@ Symbols {
option: @SymbolLists.list[DERIBIT].symbol
spread: @SymbolLists.list[DERIBIT].symbol
}
venues{
name: "VENUE_TWSE"
future: @SymbolLists.list[TWSE].symbol
option: @SymbolLists.list[TWSE].symbol
}
venues{
name: "VENUE_TAIFEX"
future: @SymbolLists.list[TAIFEX].symbol
@@ -163,6 +145,11 @@ Symbols {
spot: @SymbolLists.list[BINANCE].symbol
spread: @SymbolLists.list[BINANCE].symbol
}
venues {
name: "VENUE_BINANCE_COIN_FUTURES"
future: @SymbolLists.list[BINANCE_COIN_FUTURES].symbol
spread: @SymbolLists.list[BINANCE_COIN_FUTURES].symbol
}
venues {
name: "VENUE_BINANCE_US"
spot: @SymbolLists.list[BINANCE_US].symbol
@@ -13,6 +13,19 @@ MarketDataConfig {
}
}
binance_coin_futures {
num_depth_levels: 5
url_rest_base: "https://testnet.binancefuture.com"
url_ws_base: "wss://dstream.binance.com"
security_criteria {
clauses {
security_types: SECURITY_TYPE_FUTURE
symbols: "BTC"
symbols: "ETH"
}
}
}
binance_us {
num_depth_levels: 5
url_rest_base: "https://api.binance.us"
@@ -13,6 +13,19 @@ MarketDataConfig {
}
}
binance_coin_futures {
num_depth_levels: 5
url_rest_base: "https://dapi.binance.com"
url_ws_base: "wss://dstream.binance.com"
security_criteria {
clauses {
security_types: SECURITY_TYPE_FUTURE
symbols: "BTC"
symbols: "ETH"
}
}
}
binance_usds_futures {
num_depth_levels: 5
url_rest_base: "https://dapi.binance.com"
+7
View File
@@ -0,0 +1,7 @@
#pragma once
#define BTS_LOCK_GUARD(lockable) \
std::lock_guard<decltype(lockable)> __lock_guard { lockable }
#define BTS_LOCK_GUARD_AS(lockable, name) \
std::lock_guard<decltype(lockable)> __lock_guard_##name { lockable }
+18
View File
@@ -28,6 +28,9 @@ class TimeSpan {
static constexpr TimeSpan from_micros(std::int64_t value);
static constexpr TimeSpan from_millis(std::int64_t value);
static constexpr TimeSpan from_seconds(std::int64_t value);
static constexpr TimeSpan from_minutes(std::int64_t value);
static constexpr TimeSpan from_hours(std::int64_t value);
static constexpr TimeSpan from_days(std::int64_t value);
static TimeSpan from_posix_duration(boost::posix_time::time_duration t);
static TimeSpan from_iso_string(const std::string &iso_string);
@@ -85,6 +88,21 @@ constexpr TimeSpan TimeSpan::from_seconds(std::int64_t value) {
return TimeSpan{value * nanos_per_second};
}
constexpr TimeSpan TimeSpan::from_minutes(std::int64_t value) {
constexpr const auto nanos_per_minute = 60'000'000'000;
return TimeSpan{value * nanos_per_minute};
}
constexpr TimeSpan TimeSpan::from_hours(std::int64_t value) {
constexpr const auto nanos_per_hour = 3'600'000'000'000;
return TimeSpan{value * nanos_per_hour};
}
constexpr TimeSpan TimeSpan::from_days(std::int64_t value) {
constexpr const auto nanos_per_day = 86'400'000'000'000;
return TimeSpan{value * nanos_per_day};
}
constexpr std::int64_t TimeSpan::nanos() const { return ticks_; }
constexpr std::int64_t TimeSpan::micros() const { return ticks_ / 1'000; }
+13 -3
View File
@@ -5,12 +5,19 @@
namespace bts::core {
using std::uint32_t;
using std::uint8_t;
static bool is_valid_ymd(uint32_t year, uint32_t month, uint32_t day) {
static bool is_valid_ymd(uint32_t year, uint8_t month, uint8_t day) {
return year >= 1970 && month >= 1 && month <= 12 && day >= 1 && day <= 31;
}
TimeStamp::TimeStamp(uint32_t year, uint32_t month, uint32_t day) {
TimeStamp::TimeStamp(
uint32_t year,
uint8_t month,
uint8_t day,
uint8_t hour,
uint8_t minute,
uint8_t second) {
bts_assert_msgf(
is_valid_ymd(year, month, day), "Invalid timestamp {}/{}/{} (y/m/d)",
year, month, day);
@@ -18,6 +25,9 @@ TimeStamp::TimeStamp(uint32_t year, uint32_t month, uint32_t day) {
date.tm_year = year - 1900;
date.tm_mon = month - 1;
date.tm_mday = day;
date.tm_hour = hour;
date.tm_min = minute;
date.tm_sec = second;
auto time = std::chrono::system_clock::from_time_t(mktime(&date));
auto duration = time.time_since_epoch();
value_ =
@@ -25,7 +35,7 @@ TimeStamp::TimeStamp(uint32_t year, uint32_t month, uint32_t day) {
}
bool TimeStamp::from_ymd(
std::uint32_t year, std::uint32_t month, std::uint32_t day, TimeStamp *result) {
uint32_t year, uint8_t month, uint8_t day, TimeStamp *result) {
if (!is_valid_ymd(year, month, day)) {
return false;
}
+103 -9
View File
@@ -8,7 +8,6 @@
#include <boost/date_time/posix_time/posix_time_duration.hpp>
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/time.hpp>
#include <chrono>
#include <cstdint>
#include <fmt/format.h>
#include <limits>
@@ -16,6 +15,9 @@
namespace bts::core {
#define VALID_YMD(year, month, day) \
(year >= 1970 && month >= 1 && month <= 12 && day >= 1 && day <= 31)
/**
* @brief Represents time as nano-seconds since the unix epoch (Jan 1, 1970)
*/
@@ -23,8 +25,14 @@ struct TimeStamp {
public:
constexpr TimeStamp() = default;
explicit constexpr TimeStamp(std::uint64_t value);
// constructs a TimeStamp from a UTC date
explicit TimeStamp(uint32_t year, uint32_t month, uint32_t day);
TimeStamp(std::uint32_t year, std::uint8_t month, std::uint8_t day);
TimeStamp(
std::uint32_t year,
std::uint8_t month,
std::uint8_t day,
std::uint8_t hour,
std::uint8_t minute,
std::uint8_t second);
static constexpr TimeStamp min();
static constexpr TimeStamp max();
@@ -36,10 +44,33 @@ struct TimeStamp {
static constexpr TimeStamp from_seconds(std::int64_t value);
static TimeStamp from_ptime(boost::posix_time::ptime t);
static TimeStamp from_iso_string(const std::string &iso_string);
// Constructs a TimeStamp from a UTC date
static TimeStamp from_ymd(
std::uint32_t year, std::uint8_t month, std::uint8_t day);
static bool from_ymd(
std::uint32_t year,
std::uint32_t month,
std::uint32_t day,
std::uint8_t month,
std::uint8_t day,
TimeStamp *result);
static TimeStamp from_ymdhms(
std::uint32_t year,
std::uint8_t month,
std::uint8_t day,
std::uint8_t hour,
std::uint8_t minute,
std::uint8_t second);
// Constructs a TimeStamp from a UTC date
static bool from_ymdhms(
std::uint32_t year,
std::uint8_t month,
std::uint8_t day,
std::uint8_t hour,
std::uint8_t minute,
std::uint8_t second,
TimeStamp *result);
constexpr std::uint64_t nanos() const;
@@ -50,8 +81,11 @@ struct TimeStamp {
constexpr double total_millis() const;
constexpr double total_seconds() const;
constexpr std::int64_t to_int64();
inline void to_date(uint32_t &year, uint32_t &month, uint32_t &day);
constexpr std::int64_t to_int64() const;
std::int64_t to_date_int() const;
void to_date(uint32_t &year, uint32_t &month, uint32_t &day) const;
// Gets a TimeStamp representing this date at midnight.
TimeStamp date() const;
constexpr boost::posix_time::ptime to_ptime() const;
std::string to_iso_string() const;
// current epoch ns
@@ -82,7 +116,9 @@ constexpr bool operator>=(TimeStamp lhs, TimeStamp rhs) noexcept;
constexpr TimeSpan operator-(TimeStamp lhs, TimeStamp rhs) noexcept;
constexpr TimeStamp operator-(TimeStamp lhs, TimeSpan rhs) noexcept;
TimeStamp &operator-=(TimeStamp &lhs, TimeSpan rhs) noexcept;
constexpr TimeStamp operator+(TimeStamp lhs, TimeSpan rhs) noexcept;
TimeStamp &operator+=(TimeStamp &lhs, TimeSpan rhs) noexcept;
std::ostream &operator<<(std::ostream &out, const TimeStamp &ts) noexcept;
@@ -92,6 +128,10 @@ std::ostream &operator<<(std::ostream &out, const TimeStamp &ts) noexcept;
constexpr TimeStamp::TimeStamp(std::uint64_t value) : value_(value) {}
inline TimeStamp::TimeStamp(
std::uint32_t year, std::uint8_t month, std::uint8_t day)
: TimeStamp(year, month, day, 0, 0, 0) {}
constexpr TimeStamp TimeStamp::min() { return TimeStamp{0}; }
constexpr TimeStamp TimeStamp::max() {
@@ -144,13 +184,21 @@ constexpr double TimeStamp::total_seconds() const {
return static_cast<double>(value_) / 1000'000'000;
}
constexpr std::int64_t TimeStamp::to_int64() {
constexpr std::int64_t TimeStamp::to_int64() const {
bts_assert(
value_ <=
static_cast<std::int64_t>(std::numeric_limits<std::int64_t>::max()));
return static_cast<std::int64_t>(value_);
}
void TimeStamp::to_date(uint32_t &year, uint32_t &month, uint32_t &day) {
inline std::int64_t TimeStamp::to_date_int() const {
std::uint32_t y, m, d;
to_date(y, m, d);
return y << 6 | m << 4 | d;
}
inline void TimeStamp::to_date(
uint32_t &year, uint32_t &month, uint32_t &day) const {
std::uint64_t epoch_secs = value_ / (1000 * 1000 * 1000);
time_t ts_tt(epoch_secs);
struct tm *ptm = gmtime(&ts_tt);
@@ -159,6 +207,12 @@ void TimeStamp::to_date(uint32_t &year, uint32_t &month, uint32_t &day) {
day = ptm->tm_mday;
}
inline TimeStamp TimeStamp::date() const {
std::uint32_t y, m, d;
to_date(y, m, d);
return from_ymd(y, m, d);
}
constexpr boost::posix_time::ptime TimeStamp::to_ptime() const {
constexpr const auto nanos_per_sec = 1'000'000'000;
constexpr const auto nanos_per_micro = 1'000;
@@ -170,6 +224,36 @@ constexpr boost::posix_time::ptime TimeStamp::to_ptime() const {
boost::posix_time::microseconds(nanos_rem / nanos_per_micro);
}
inline TimeStamp TimeStamp::from_ymd(
std::uint32_t year, std::uint8_t month, std::uint8_t day) {
return {year, month, day, 0, 0, 0};
}
inline TimeStamp TimeStamp::from_ymdhms(
std::uint32_t year,
std::uint8_t month,
std::uint8_t day,
std::uint8_t hour,
std::uint8_t minute,
std::uint8_t second) {
return {year, month, day, hour, minute, second};
}
inline bool TimeStamp::from_ymdhms(
std::uint32_t year,
std::uint8_t month,
std::uint8_t day,
std::uint8_t hour,
std::uint8_t minute,
std::uint8_t second,
TimeStamp *result) {
if (!VALID_YMD(year, month, day)) {
return false;
}
*result = TimeStamp{year, month, day, hour, minute, second};
return true;
}
constexpr bool operator==(TimeStamp lhs, TimeStamp rhs) noexcept {
return lhs.nanos() == rhs.nanos();
}
@@ -202,10 +286,20 @@ constexpr TimeStamp operator-(TimeStamp lhs, TimeSpan rhs) noexcept {
return TimeStamp{lhs.nanos() - rhs.nanos()};
}
inline TimeStamp &operator-=(TimeStamp &lhs, TimeSpan rhs) noexcept {
lhs = lhs - rhs;
return lhs;
}
constexpr TimeStamp operator+(TimeStamp lhs, TimeSpan rhs) noexcept {
return TimeStamp{lhs.nanos() + rhs.nanos()};
}
inline TimeStamp &operator+=(TimeStamp &lhs, TimeSpan rhs) noexcept {
lhs = lhs + rhs;
return lhs;
}
} // namespace bts::core
FMT_IMPL(bts::core::TimeStamp, t, "{}", t.to_iso_string());
-8
View File
@@ -43,8 +43,6 @@ class BookT {
void reset_merged_quantity();
void reset_n_orders();
template <class Container>
void apply_changes(Side side, const Container &changes);
/**
* Removes price levels of the non-dominant side that cross the dominant
@@ -203,12 +201,6 @@ bool BookT<BS>::is_sorted() const {
return Side::forboth([&](Side s) { return operator[](s).is_sorted(s); });
}
template <class BS>
template <class Container>
void BookT<BS>::apply_changes(Side side, const Container &changes) {
_books[static_cast<std::size_t>(side.value)].apply_changes(side, changes);
}
template <class BS>
void from_json(const nlohmann::json &j, BookT<BS> &book) {
io::JsonReader jr{&j};
Loaded 100 of 385 files, more files were not shown because too many files have changed in this diff. Show more