Compare commits

...
Author SHA1 Message Date
Adeel Khan 6c1fe0f561 Fix: Taifex Time Conversion 2025-03-26 18:49:17 +00:00
Adeel Khan a0eaf60eec FIX: Taifex Crash Fixed, Added Diag Logs 2025-03-26 18:48:27 +00:00
Adeel Khan f2080d558a ADD: TBBO & Symbol wise Naming in Recorder 2025-03-26 18:25:28 +00:00
Adeel Khan 06bfe9c29f ADD: TWSE Code Complete 2025-03-26 18:20:39 +00:00
Adeel Khan 022546a6c1 Revert "Diag: Pushing changes prior to 6th March Crash"
This reverts commit 344d180557.
2025-03-26 17:59:59 +00:00
Adeel Khan 344d180557 Diag: Pushing changes prior to 6th March Crash 2025-03-06 05:56:01 +00:00
Adeel Khan a485f8139c ADD: TWSE to WebApp 2024-12-26 21:53:35 -05:00
Adeel Khan f50066f4d2 ADD: TWSE throughout Sparkd 2024-12-26 21:53:35 -05:00
Taha 277c3056c4 Merge branch 'development' of bitbucket.org:bluetradesys/spark into development 2024-12-09 15:37:50 -05:00
Taha 5eb95e69cb Cleaning up some streams,new prompt etc 2024-12-09 15:37:45 -05:00
John Colvin 058e11eadc fix build: Fix install path for sparkd 2024-12-05 18:31:36 +00:00
John Colvin 6ff52e7107 fix build: Add onixs libs again
Taha accidentally reverted externals
2024-12-04 16:56:46 +00:00
John Colvin ee4c28ed41 Port ws client over from cme-websocket-connector
Need this to implement execution at crypto exchanges (beginning with
Binance and OKX)
2024-12-04 16:56:46 +00:00
Mohammad Arham 50d26f0060 Merge branch 'development' of bitbucket.org:bluetradesys/spark into development 2024-12-03 09:52:09 -05:00
Mohammad Arham 36378e6074 Add:: Recording md to sql 2024-12-03 14:51:32 +00:00
John Colvin 8cde8ee6e1 build: Add script to publish the api server
This will build the app as a self-contained executable here:
build/Release/bin/net7.0/linux-x64/publish
2024-11-28 16:35:21 +00:00
John Colvin 4f8fad444e fix build: Add missing csproj deps to Spark.Api.Server.sln 2024-11-28 16:35:20 +00:00
John Colvin 832c645a30 build: Map cmake install dir to associated preset
Cpp bins are now installed to "install/<cmake_preset>/bin". For example,
"install/sparkd-release-gcc/bin", "install/spark-api-server-linux/bin", etc.
2024-11-28 16:35:20 +00:00
John Colvin 691343d9b6 feat: Add datastreams to spark api server 2024-11-28 06:14:00 +00:00
Taha 461cbad338 Adding FakeBBO stream 2024-11-27 13:36:14 -05:00
Taha fecbcbb6b6 Merge branch 'development' of bitbucket.org:bluetradesys/spark into development 2024-11-26 22:33:31 -05:00
Taha aab8e83543 Some rewrite of streams that fetch bars, and making the other business streams thin wrapper over stream primitives 2024-11-26 22:33:26 -05:00
Mohammad Arham 420b46741e ADD: Config for sql writer in mdrecorder 2024-11-24 19:14:45 +00:00
Mohammad Arham e8f65f95bd Wrapped proto write in function in mdrecorder 2024-11-24 19:13:36 +00:00
93 changed files with 5490 additions and 752 deletions

No files matched your search

+6 -4
View File
@@ -1,5 +1,6 @@
cmake_minimum_required(VERSION 3.12)
project(spark)
include(GNUInstallDirs)
set(CMAKE_CXX_STANDARD 20)
if(WIN32)
@@ -49,8 +50,6 @@ else()
# make sparkd look for libspark.so in its directory
set(CMAKE_BUILD_WITH_INSTALL_RPATH TRUE)
set(CMAKE_INSTALL_RPATH ".")
set(CMAKE_INSTALL_PREFIX "${CMAKE_SOURCE_DIR}/install")
set(SPARK_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}/$<CONFIG>")
if(BUILD_SPARKD)
# Note: All macros that begin w/ 'CCAPI' are ccapi's macros (defined and/or
@@ -147,11 +146,14 @@ else()
install(
DIRECTORY "${CMAKE_BINARY_DIR}/server/plugins"
DESTINATION "${SPARK_INSTALL_PREFIX}/bin")
DESTINATION "${CMAKE_INSTALL_BINDIR}")
install(
FILES
"${SPARK_LIB}/libACE-5.7.5.so"
"${SPARK_LIB}/libOnixS.IceImpactMulticastPriceFeedHandlerCpp.so.3.16.0.0"
DESTINATION "${SPARK_INSTALL_PREFIX}/bin")
"${SPARK_LIB}/libonixs-fix-engine.so.4.10.1"
"${SPARK_LIB}/libonixs-fix-engine.so.4"
"${SPARK_LIB}/libonixs-fix-engine.so"
DESTINATION "${CMAKE_INSTALL_BINDIR}")
endif()
endif()
+1 -1
View File
@@ -61,7 +61,7 @@
},
"CMAKE_CXX_STANDARD": "20",
"CMAKE_INSTALL_RPATH": ".",
"CMAKE_INSTALL_PREFIX": "${sourceDir}/install/${presetName}/sparkd",
"CMAKE_INSTALL_PREFIX": "${sourceDir}/install/${presetName}",
"CMAKE_EXE_LINKER_FLAGS": "-Wno-undef",
"EXTERNALS_ROOT": "${sourceDir}/externals/linux",
"BUILD_SDK": {
+139
View File
@@ -14,6 +14,34 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "spark_test", "src\client\sp
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Spark.Console", "src\client\Spark.Console\Spark.Console.csproj", "{89D666E6-B500-498F-B026-4D167F68ADFC}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "src", "src", "{267F81EF-A8AB-49FD-9F56-D7EC3C1F7C7C}"
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "DataStreamSuite", "DataStreamSuite", "{C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataStreamCore", "src\DataStreamSuite\DataStreamCore\DataStreamCore.csproj", "{EF26A475-6101-4C9C-A717-D60BB92A2302}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SharedStreams", "src\DataStreamSuite\SharedStreams\SharedStreams.csproj", "{911B08A3-515A-441D-84C8-8A43740B5FC1}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PubSub", "src\DataStreamSuite\PubSub\PubSub.csproj", "{14140310-2233-430A-821B-F3058A25234B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaseUtilities", "src\DataStreamSuite\BaseUtilities\BaseUtilities.csproj", "{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExpressionCore", "src\DataStreamSuite\ExpressionCore\ExpressionCore.csproj", "{6F22DB96-6EAB-4034-99D9-287021C36F01}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArithmeticExpressions", "src\DataStreamSuite\ArithmeticExpressions\ArithmeticExpressions.csproj", "{A5C33956-A41F-49B3-A41D-1082CBA59D02}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataStreamExpressions", "src\DataStreamSuite\DataStreamExpressions\DataStreamExpressions.csproj", "{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bts.ColumnSortExpressions", "src\DataStreamSuite\Bts.ColumnSortExpressions\Bts.ColumnSortExpressions.csproj", "{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ColumnMapExpressions", "src\DataStreamSuite\ColumnMapExpressions\ColumnMapExpressions.csproj", "{B945A183-2174-4ACB-B289-8A5C546656FE}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BooleanExpressions", "src\DataStreamSuite\BooleanExpressions\BooleanExpressions.csproj", "{9F6D7DE8-185B-4C1D-B809-3314D092DF28}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Bts.ColumnExpressions", "src\DataStreamSuite\Bts.ColumnExpressions\Bts.ColumnExpressions.csproj", "{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataStream", "src\DataStreamSuite\DataStream\DataStream.csproj", "{39AEA075-6457-46C0-8821-1158BE6EFA57}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
@@ -70,6 +98,102 @@ Global
{89D666E6-B500-498F-B026-4D167F68ADFC}.Release|x64.Build.0 = Release|x64
{89D666E6-B500-498F-B026-4D167F68ADFC}.RelWithDebInfo|x64.ActiveCfg = Debug|x64
{89D666E6-B500-498F-B026-4D167F68ADFC}.RelWithDebInfo|x64.Build.0 = Debug|x64
{EF26A475-6101-4C9C-A717-D60BB92A2302}.Debug|x64.ActiveCfg = Debug|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.Debug|x64.Build.0 = Debug|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.Release|x64.ActiveCfg = Release|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.Release|x64.Build.0 = Release|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{EF26A475-6101-4C9C-A717-D60BB92A2302}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.Debug|x64.ActiveCfg = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.Debug|x64.Build.0 = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.Release|x64.ActiveCfg = Release|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.Release|x64.Build.0 = Release|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{911B08A3-515A-441D-84C8-8A43740B5FC1}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.Debug|x64.ActiveCfg = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.Debug|x64.Build.0 = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.Release|x64.ActiveCfg = Release|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.Release|x64.Build.0 = Release|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{14140310-2233-430A-821B-F3058A25234B}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.Debug|x64.ActiveCfg = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.Debug|x64.Build.0 = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.Release|x64.ActiveCfg = Release|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.Release|x64.Build.0 = Release|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.Debug|x64.ActiveCfg = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.Debug|x64.Build.0 = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.Release|x64.ActiveCfg = Release|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.Release|x64.Build.0 = Release|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{6F22DB96-6EAB-4034-99D9-287021C36F01}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.Debug|x64.ActiveCfg = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.Debug|x64.Build.0 = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.Release|x64.ActiveCfg = Release|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.Release|x64.Build.0 = Release|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{A5C33956-A41F-49B3-A41D-1082CBA59D02}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.Debug|x64.ActiveCfg = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.Debug|x64.Build.0 = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.Release|x64.ActiveCfg = Release|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.Release|x64.Build.0 = Release|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.Debug|x64.ActiveCfg = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.Debug|x64.Build.0 = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.Release|x64.ActiveCfg = Release|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.Release|x64.Build.0 = Release|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.Debug|x64.ActiveCfg = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.Debug|x64.Build.0 = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.Release|x64.ActiveCfg = Release|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.Release|x64.Build.0 = Release|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{B945A183-2174-4ACB-B289-8A5C546656FE}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.Debug|x64.ActiveCfg = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.Debug|x64.Build.0 = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.Release|x64.ActiveCfg = Release|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.Release|x64.Build.0 = Release|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{39AEA075-6457-46C0-8821-1158BE6EFA57}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.Debug|x64.ActiveCfg = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.Debug|x64.Build.0 = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.Release|x64.ActiveCfg = Release|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.Release|x64.Build.0 = Release|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{9F6D7DE8-185B-4C1D-B809-3314D092DF28}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.Debug|x64.ActiveCfg = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.Debug|x64.Build.0 = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.MinSizeRel|x64.ActiveCfg = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.MinSizeRel|x64.Build.0 = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.Release|x64.ActiveCfg = Release|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.Release|x64.Build.0 = Release|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.RelWithDebInfo|x64.ActiveCfg = Debug|Any CPU
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B}.RelWithDebInfo|x64.Build.0 = Debug|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
@@ -80,4 +204,19 @@ Global
GlobalSection(Performance) = preSolution
HasPerformanceSessions = true
EndGlobalSection
GlobalSection(NestedProjects) = preSolution
{C09ED521-D2DF-40BC-A76F-EB3CB870B2F6} = {267F81EF-A8AB-49FD-9F56-D7EC3C1F7C7C}
{EF26A475-6101-4C9C-A717-D60BB92A2302} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{911B08A3-515A-441D-84C8-8A43740B5FC1} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{14140310-2233-430A-821B-F3058A25234B} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{43146EA8-6FCC-46B8-88B0-42F9BB5E6E0A} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{6F22DB96-6EAB-4034-99D9-287021C36F01} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{A5C33956-A41F-49B3-A41D-1082CBA59D02} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{2FE745C3-1EDF-4421-8CD7-A63EE0C1AE43} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{FDA791E0-2B91-4AD5-B91D-CF920A4C4E38} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{B945A183-2174-4ACB-B289-8A5C546656FE} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{39AEA075-6457-46C0-8821-1158BE6EFA57} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{9F6D7DE8-185B-4C1D-B809-3314D092DF28} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
{6BD3F6D8-B6FC-44E8-B8FE-06352F638B9B} = {C09ED521-D2DF-40BC-A76F-EB3CB870B2F6}
EndGlobalSection
EndGlobal
@@ -23,6 +23,7 @@
<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,6 +4,8 @@ namespace bts.SilverPine {
using System;
public class NullFilterStream : ViewStream {
public NullFilterStream(ViewStream parent_str, string col_name)
: this(parent_str, col_name, true) { }
public NullFilterStream(ViewStream parent_str, string col_name, bool filter_out_doublenans = false) {
ViewStream rs = new FilterStream(parent_str,
r => {
@@ -0,0 +1,126 @@
namespace bts.SilverPine {
using BCG;
using System;
using System.Collections.Generic;
using System.Linq;
//using MathNet.Numerics.Statistics;
public enum MultiRowOp {
Mean,
Median,
Mode,
Range,
StdDev,
Max,
Min,
First,
Last,
Sum,
EdgeDiff,
EdgeDiffPercentage,
//IsEdgeDiff,
}
public class MultiRowOpHelper {
public readonly List<Tuple<string, MultiRowOp>> operations;
public static MultiRowOpHelper parse(string text) {
// text is inp_col: op, inp_col: op, inp_col:op
List<Tuple<string, MultiRowOp>> rv = new List<Tuple<string, MultiRowOp>>();
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);
rv.Add(Tuple.Create(inp_col, op));
}
return new MultiRowOpHelper(rv);
}
public MultiRowOpHelper(List<Tuple<string, MultiRowOp>> operations_) {
operations = operations_;
}
public static IBlueRow group_by(List<IBlueRow> rows, MultiRowOpHelper parameters) {
if (rows.Count() == 0) {
return null;
}
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>>();
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);
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>(rows, in_col_name);
double comp_res = compute_op(col_vals, op);
or.setValue(out_col_name, comp_res);
}
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) {
switch (op) {
case MultiRowOp.Max:
return col_vals.Max<double>();
case MultiRowOp.Min:
return col_vals.Min<double>();
case MultiRowOp.Mean:
return col_vals.Sum() / col_vals.Count();
case MultiRowOp.Sum:
return col_vals.Sum();
case MultiRowOp.First:
return col_vals.First();
case MultiRowOp.Last:
return col_vals.Last();
case MultiRowOp.StdDev:
return MathNet.Numerics.Statistics.Statistics.StandardDeviation(col_vals);
default:
// TODO
Log.assert(false);
return Double.NaN;
}
}
}
}
@@ -0,0 +1,20 @@
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);
}
}
}
@@ -2,10 +2,13 @@
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text.Json;
using bts;
using bts.SilverPine;
namespace BCG {
[DataStreamUserRespresentation("AggregateStream")]
public class NonIncGroupByStream : ViewStream {
private class DelNonIncGroupByEvaluator : INonIncGroupByEvaluator {
Func<string[]> _groupby_cols_func;
@@ -43,13 +46,34 @@ namespace BCG {
_main_stream = main_stream;
_groupby_func = groupby_func;
_groupby_cols = _groupby_func.get_group_by_cols();
_row_hasher = new BlueRowHasher(_groupby_cols.Length);
_row_hasher = new BlueRowHasher(_groupby_cols == null ? 0 : _groupby_cols.Length);
}
public NonIncGroupByStream(ViewStream main_stream, Func<string[]> groupby_cols_func,
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);
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);
return new IBlueRow[] { rv }.ToList();
};
ViewStream rs = new NonIncGroupByStream(parent_str, groupby_cols_func, evaluate_func);
mySetRealSource(rs);
}
public NonIncGroupByStream(ViewStream parent_str, string standard_group_by_text) :
this(parent_str, String.Empty, standard_group_by_text) {
}
protected override void myOnFirstSubscriber() { _main_stream.onChange += _main_stream_onchange; }
@@ -79,7 +103,9 @@ namespace BCG {
Log.DataFlow.info(
$"Time to evaluate {grouped_rows.Count} groups {_timer.ElapsedMilliseconds}ms, ratio {_n_expensive_fires}/{_n_total_fires}");
}
myFireEvent(new DataPacket(total_state, total_state, myLastValue == null ? new BlueTable(total_state.schema) : (myLastValue as DataPacket).newRows));
// TODO,
if (total_state != null)
myFireEvent(new DataPacket(total_state, total_state, myLastValue == null ? new BlueTable(total_state.schema) : (myLastValue as DataPacket).newRows));
}
}
}
@@ -1,10 +1,12 @@
using bts;
using bts.collections;
using mbts;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Security.Cryptography;
namespace BCG {
@@ -35,6 +37,38 @@ namespace BCG {
_is_tag_along = _join_spec.join_col_names.Length == 0;
}
private bool _filled_missing_data = false;
private void _fill_missing_data(DataPacket dp) {
if (_filled_missing_data)
return;
Func<string[], bool> null_or_empty = (str_arr) => {
if (str_arr == null || str_arr.Length == 0)
return true;
foreach (string s in str_arr) {
if (!String.IsNullOrEmpty(s)) {
return false;
}
}
return true;
};
Func<string[], string[]> remove_bad_cols = (col_names) => {
HashSet<string> schema_col_map = new HashSet<string>(dp.schema.columnNames);
List<string> cols_list = new List<string>(col_names);
cols_list.RemoveWhere(c => !schema_col_map.Contains(c));
return cols_list.ToArray();
};
if (null_or_empty(_join_spec.data_col_names)) {
_join_spec.data_col_names = dp.schema.columnNames;
}
_join_spec.data_col_names = remove_bad_cols(_join_spec.data_col_names);
if (null_or_empty(_join_spec.data_col_names)) {
_join_spec.data_col_names = dp.schema.columnNames;
}
if (null_or_empty(_join_spec.projected_col_names)) {
_join_spec.projected_col_names = _join_spec.data_col_names;
}
}
public void init() {
_join_spec.stream.onChange += _on_stream_cb;
}
@@ -43,6 +77,7 @@ namespace BCG {
Log.Gen.info($"NonIncJoinBookkeeper._on_stream_cb dp_obj: {dp_obj}");
var timer = Stopwatch.StartNew();
DataPacket dp = (DataPacket)dp_obj;
_fill_missing_data(dp);
if (_schema == null) {
_schema = dp.schema;
_join_col_indices = BlueDataUtility.get_column_indices(_schema, _join_spec.join_col_names);
@@ -7,11 +7,12 @@ using System.Threading.Tasks;
using mbts;
namespace BCG {
// this a collection of data, theres no joining logic in here
public class NonIncJoinSpec {
public ViewStream stream;
// join col names are the names on which the streams are joined (for equality),
// data col names are the names in the original stream
// projected col naes are their new names, ie if its x:l_x, then x is in the
// projected col names are their new names, ie if its x:l_x, then x is in the
// data_col_names and l_x in projected cols
public string[] join_col_names, data_col_names, projected_col_names;
@@ -69,4 +69,6 @@ namespace bts {
myFireEvent(dp_out);
}
}
}
@@ -13,9 +13,8 @@ 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;
@@ -0,0 +1,14 @@
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)
{
}
}
}
@@ -0,0 +1,10 @@
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) {
}
}
}
@@ -1,9 +1,8 @@
using Google.Protobuf.WellKnownTypes;
using System;
using BCG.Utilities.General;
namespace BCG {
using BCG;
namespace bts.SilverPine {
// Keeps adding changing rows to the stream, hence preserving the history
// and creating a time series, for example this can be used to make bbo updates
// into a time series of prices/qty
@@ -108,6 +108,7 @@ namespace bts {
}
[DataStreamUserRespresentation("Project")]
public class NewProjectStream : ViewStream, IStreamMapper {
private ViewStream _stream;
@@ -9,161 +9,16 @@ using BCG;
using System.Linq;
using System.Data.Entity;
using System.Collections.Generic;
using System.Data.SQLite;
namespace bts.SilverPine {
public class DataRowWrapperRow : IBlueRow {
private readonly DataRow _row;
private readonly IBlueTableSchema _schema;
private readonly int _id;
public DataRowWrapperRow(IBlueTableSchema schema, DataRow row, int id) {
_row = row;
_id = id;
_schema = schema;
}
public virtual IBlueTableSchema schema { get { return _schema; } }
public virtual object this[string col_name] {
get {
ColumnInfo ci = _schema[col_name];
return this[ci.colNo];
}
}
public virtual object this[int index] {
get {
if (_schema[index].colName == "id")
return _id;
return _row[index];
}
}
public virtual int Count { get { return _row.ItemArray.Length; } }
public virtual bool IsSynchronized { get { return false; } }
public virtual object SyncRoot { get { return this; } }
public virtual void CopyTo(Array array, int index) { _row.ItemArray.CopyTo(array, index); }
public virtual bool IsFixedSize { get { return true; } }
virtual public bool IsReadOnly { get { return true; } }
/// <summary>
/// The key can either be the string corrsponding to the column name or
/// the order of the column
/// </summary>
public virtual object this[object key] {
get {
if (key is string)
return this[(string)key];
else if (key is int)
return this[(int)key];
throw new BlueDataException("Wrong type while indexing the row");
}
set { throw new NotSupportedException("The IBlueRow is readonly"); }
}
public virtual ICollection Keys { get { return _schema.columnNames; } }
public virtual ICollection Values { get { return _row.ItemArray; } }
public virtual void Add(object key, object value) { throw new NotSupportedException("The IBlueRow is readonly"); }
public virtual void Clear() { throw new NotSupportedException("The IBlueRow is readonly"); }
public virtual bool Contains(object key) { return _schema[(string)key] != null; }
public IDictionaryEnumerator GetEnumerator() { return new BlueRowDictionaryEnumerator(this); }
IEnumerator IEnumerable.GetEnumerator() { return new BlueRowEnumerator(this); }
public virtual void Remove(object key) { throw new NotSupportedException("The IBlueRow is readonly"); }
}
public class DataTableWrapperTable : IBlueRowCollection {
public class DataTableWrapperTableEnumerator : IEnumerator {
private IEnumerator _enumerator;
private IBlueTableSchema _schema;
private int _id = 0;
public DataTableWrapperTableEnumerator(DataTable table) {
_enumerator = table.Rows.GetEnumerator();
_schema = BlueDataUtility.getSchema(table);
}
public object Current {
get {
DataRow r = _enumerator.Current as DataRow;
return new DataRowWrapperRow(_schema, r, _id);
}
}
public bool MoveNext() {
_id++;
return _enumerator.MoveNext();
}
public void Reset() {
_id = 0;
_enumerator.Reset();
}
}
private readonly DataTable _table;
private IBlueTableSchema _schema;
private IEnumerator _enumerator;
public DataTableWrapperTable(DataTable table) {
_table = table;
_schema = BlueDataUtility.getSchema(_table);
_enumerator = new DataTableWrapperTableEnumerator(table);
}
public virtual IBlueRow this[int id] {
get {
// its assumed the rows index == id
DataRow dr = _table.Rows[id];
return new DataRowWrapperRow(_schema, dr, id);
}
set {
}
}
public virtual IBlueTableSchema schema { get { return _schema; } }
public virtual bool containsID(int id) { return id < _table.Rows.Count; }
// private List<IBlueRow> _rows() {
// List<IBlueRow> rv = new List<IBlueRow>();
// int id = 0;
// foreach (DataRow r in _table.Rows) {
// rv.Add(new DataRowWrapperRow(r, id++));
// }
// return rv;
// }
public virtual IEnumerator GetEnumerator() {
// var rows = _rows();
// return rows.GetEnumerator();
return _enumerator;
}
public virtual bool IsSynchronized { get { return false; } }
public virtual object SyncRoot { get { return this; } }
public virtual void CopyTo(Array array, int index) {
Log.assert(false);
//_rows().CopyTo(array as IBlueRow[], index);
}
public virtual int Count {
get { return _table.Rows.Count; }
}
}
public static class SQLiteHelper {
public static DataTable ExecuteSelectQuery(string connection_string, string query) {
public static string location = "C:\\Users\\m_tah\\development\\data\\";
public static string db_name = "stream_data.db";
public static DataTable execute_select_query(string connection_string, string query) {
// Create a new DataTable to store the results
DataTable dataTable = new DataTable();
@@ -183,48 +38,85 @@ namespace bts.SilverPine {
Console.WriteLine("An error occurred: " + ex.Message);
}
}
// Return the populated DataTable
return dataTable;
}
}
[DataStreamUserRespresentation("SQLite")]
public class SQLiteStream : ViewStream {
private readonly string _connection_string, _query;
private Stopwatch _stopwatch = new Stopwatch();
public SQLiteStream(string connection_string, string query) {
_connection_string = connection_string;
_query = query;
public static List<Dictionary<string, object>> ExecuteBulkRead(string connectionString, string query) {
var result = new List<Dictionary<string, object>>();
using (var connection = new SQLiteConnection(connectionString)) {
connection.Open();
// Begin a transaction to optimize read speed
using (var transaction = connection.BeginTransaction())
using (var command = new SQLiteCommand(query, connection, transaction))
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++) {
string columnName = reader.GetName(i);
object columnValue = reader.IsDBNull(i) ? null : reader.GetValue(i);
row[columnName] = columnValue;
}
result.Add(row);
}
// Commit the transaction
transaction.Commit();
}
}
return result;
}
public static List<Dictionary<string, object>> get_table(string connectionString, string query) {
var result = new List<Dictionary<string, object>>();
private void _read_from_sqlite_nd_fire() {
_stopwatch.Start();
DataTable dt = SQLiteHelper.ExecuteSelectQuery(_connection_string, _query);
_stopwatch.Stop();
Log.Gen.info($"SQLiteStream._read_from_sqlite_and_fire time to read db: {_stopwatch.ElapsedMilliseconds} msecs");
_stopwatch.Start();
IBlueRowCollection rows = BCG.BlueDataUtility.toIBlueRowCollection(dt);
//IBlueRowCollection rows = new DataTableWrapperTable(dt);
_stopwatch.Stop();
Log.Gen.info($"SQLiteStream._read_from_sqlite_and_fire time to load into IBlueRowCollection: {_stopwatch.ElapsedMilliseconds} msecs");
DataPacket dp = BlueDataUtility.build_dp_inc(rows, myLastValue as DataPacket);
myFireEvent(dp);
using (var connection = new SQLiteConnection(connectionString)) {
try {
connection.Open();
using (var command = new SQLiteCommand(query, connection))
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++) {
string columnName = reader.GetName(i);
object columnValue = reader.IsDBNull(i) ? null : reader.GetValue(i);
row[columnName] = columnValue;
}
result.Add(row);
}
}
} catch (Exception ex) {
Console.WriteLine("An error occurred: " + ex.Message);
}
}
return result;
}
protected override void myOnFirstSubscriber() {
_read_from_sqlite_nd_fire();
public static IEnumerable<Dictionary<string, object>> get_table_2(string connectionString, string query) {
using (var connection = new SQLiteConnection(connectionString)) {
connection.Open();
using (var command = new SQLiteCommand(query, connection))
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new Dictionary<string, object>();
for (int i = 0; i < reader.FieldCount; i++) {
string columnName = reader.GetName(i);
object columnValue = reader.IsDBNull(i) ? null : reader.GetValue(i);
row[columnName] = columnValue;
}
yield return row;
}
}
}
}
protected override void myOnLastSubscriber() {
// this value will be cleared by the base class
// but in this particular stream this behaviour
// is not usefull since any new subscribers
// would force the query to be recreated
//myLastDP = myLastValue;
}
}
}
@@ -0,0 +1,73 @@
namespace bts.SilverPine {
using System;
using System.Data;
using System.Data.SQLite;
using System.Diagnostics;
using System.Collections;
using BCG;
[DataStreamUserRespresentation("SQLite")]
public class SQLiteStream : ViewStream {
private readonly string _connection_string, _query;
private Stopwatch _stopwatch = new Stopwatch();
private SQLiteStream(string connection_string, string query, bool noop) {
_connection_string = connection_string;
_query = query;
}
public SQLiteStream(string db_name, string query)
:
this($"Data Source={SQLiteHelper.location}{db_name};Version=3", query, true) { }
public SQLiteStream(string query)
:
this(SQLiteHelper.db_name, query) {
}
private void _read_from_sqlite_and_fire() {
_stopwatch.Start();
DataTable dt = SQLiteHelper.execute_select_query(_connection_string, _query);
_stopwatch.Stop();
Log.Gen.info($"SQLiteStream.ExecuteSelectQuery time to read db: {_stopwatch.ElapsedMilliseconds} msecs");
_stopwatch.Restart();
#region perf measures
// SQLiteHelper.get_table(_connection_string, _query);
// _stopwatch.Stop();
// Log.Gen.info($"SQLiteStream.get_table time to read db: {_stopwatch.ElapsedMilliseconds} msecs");
// _stopwatch.Restart();
// SQLiteHelper.ExecuteBulkRead(_connection_string, _query);
// _stopwatch.Stop();
// Log.Gen.info($"SQLiteStream.ExecuteBulkRead time to read db: {_stopwatch.ElapsedMilliseconds} msecs");
// _stopwatch.Restart();
// SQLiteHelper.get_table_2(_connection_string, _query);
// _stopwatch.Stop();
// Log.Gen.info($"SQLiteStream.get_table_2 time to read db: {_stopwatch.ElapsedMilliseconds} msecs");
// _stopwatch.Restart();
#endregion
IBlueRowCollection rows = BCG.BlueDataUtility.toIBlueRowCollection(dt);
//IBlueRowCollection rows = new DataTableWrapperTable(dt);
_stopwatch.Stop();
Log.Gen.info($"SQLiteStream._read_from_sqlite_and_fire time to load into IBlueRowCollection: {_stopwatch.ElapsedMilliseconds} msecs");
DataPacket dp = BlueDataUtility.build_dp_inc(rows, myLastValue as DataPacket);
myFireEvent(dp);
}
protected override void myOnFirstSubscriber() {
_read_from_sqlite_and_fire();
}
protected override void myOnLastSubscriber() {
// this value will be cleared by the base class
// but in this particular stream this behaviour
// is not usefull since any new subscribers
// would force the query to be recreated
//myLastDP = myLastValue;
}
}
}
@@ -80,7 +80,7 @@ namespace BCG {
public IBlueRow map(IBlueRow row) {
MutableBlueRow rv = new MutableBlueRow(getOutputSchema(row.schema), row);
rv.setValue(myConversionColName, mapDateTime(row[myConversionColName], myConversion));
rv.setValue(myConversionColName, mapDateTime(row.get_datetime(myConversionColName), myConversion));
return rv;
//return BlueDataUtility.getNewReplacedRow(row, mapDateTime(row[myConversionColName], myConversion), myConversionColName);
}
@@ -10,9 +10,11 @@ namespace bts.SilverPine {
Func<IBlueTableSchema, IBlueTableSchema> get_schema = (s) => {
IBlueTableSchema rv = s.add_column(System.TypeCode.DateTime, $"{inp_col}_date");
rv = rv.add_column(System.TypeCode.String, $"{inp_col}_day");
rv = rv.add_column(System.TypeCode.String, $"{inp_col}_month");
rv = rv.add_column(System.TypeCode.String, $"{inp_col}_hour");
rv = rv.add_column(System.TypeCode.String, $"{inp_col}_min");
rv = rv.add_column(System.TypeCode.Int32, $"{inp_col}_day_of_month");
rv = rv.add_column(System.TypeCode.Int32, $"{inp_col}_month");
rv = rv.add_column(System.TypeCode.Int32, $"{inp_col}_hour");
rv = rv.add_column(System.TypeCode.Int32, $"{inp_col}_min");
rv = rv.add_column(System.TypeCode.Int32, $"{inp_col}_seconds_of_day");
return rv;
};
ViewStream rs = new MapStream(parent_stream,
@@ -23,9 +25,11 @@ namespace bts.SilverPine {
MutableBlueRow rv = new MutableBlueRow(s, r);
rv.setValue($"{inp_col}_date", dt.Date);
rv.setValue($"{inp_col}_day", dt.DayOfWeek.ToString());
rv.setValue($"{inp_col}_month", dt.Date.Month.ToString());
rv.setValue($"{inp_col}_day_of_month", dt.Day);
rv.setValue($"{inp_col}_month", dt.Date.Month);
rv.setValue($"{inp_col}_hour", dt.Hour);
rv.setValue($"{inp_col}_min", dt.Minute);
rv.setValue($"{inp_col}_seconds_of_day", (dt - dt.Date).TotalSeconds);
return rv;
});
mySetRealSource(rs);
@@ -39,7 +39,7 @@ namespace bts.SilverPine {
mySetRealSource(rs);
}
// for each row, does a row[new_ol_name] = row[col1] - rows[row_ffset][col2]
// for each row, does a row[new_col_name] = row[col1] - rows[row_ffset][col2]
// we should generlize this for any math operation
public ColumnDifferenceStream(ViewStream parent_stream, string sort_col_name, int row_offset, string col1, string col2, string diff_col_name, double optional_perc_diff_filter = 0.0) {
// use GlobalMapStream
@@ -91,19 +91,32 @@ namespace bts.SilverPine {
DataPacket dp = dp_obj as DataPacket;
List<IBlueRow> rows = dp.newRows.to_list();
var f1_rows = rows.Where(r => _f1(r));
Log.assert(f1_rows.Count() == 1);
//Log.assert(f1_rows.Count() == 1);
var f2_rows = rows.Where(r => _f2(r));
Log.assert(f2_rows.Count() == 1);
IBlueRow f1_r = f1_rows.ElementAt(0);
IBlueRow f2_r = f2_rows.ElementAt(0);
double diff = f1_r.get<double>(_c1) - f2_r.get<double>(_c2);
IBlueTableSchema out_schema = f1_r.schema.add_columns(Tuple.Create(typeof(double), "diff"));
BlueTable out_table = new BlueTable(out_schema);
MutableBlueRow out_row = new MutableBlueRow(out_schema, f1_r);
out_row.setValue("diff", diff);
out_table.addRow(out_row);
DataPacket dp_out = BlueDataUtility.build_dp(out_table, myLastValue as DataPacket);
myFireEvent(dp_out);
//Log.assert(f2_rows.Count() == 1);
if (f1_rows != null && f1_rows.Count() > 0 && f2_rows != null && f2_rows.Count() > 0) {
IBlueRow f1_r = f1_rows.ElementAt(0);
IBlueRow f2_r = f2_rows.ElementAt(0);
double diff = f1_r.get<double>(_c1) - f2_r.get<double>(_c2);
IBlueTableSchema out_schema = f1_r.schema.add_columns(Tuple.Create(typeof(double), "diff"));
BlueTable out_table = new BlueTable(out_schema);
MutableBlueRow out_row = new MutableBlueRow(out_schema, f1_r);
out_row.setValue("diff", diff);
out_table.addRow(out_row);
DataPacket dp_out = BlueDataUtility.build_dp(out_table, myLastValue as DataPacket);
myFireEvent(dp_out);
} else {
IBlueRow f1_r = rows.ElementAt(0);
IBlueRow f2_r = rows.ElementAt(0);
double diff = Double.NaN;
IBlueTableSchema out_schema = f1_r.schema.add_columns(Tuple.Create(typeof(double), "diff"));
BlueTable out_table = new BlueTable(out_schema);
MutableBlueRow out_row = new MutableBlueRow(out_schema, f1_r);
out_row.setValue("diff", diff);
out_table.addRow(out_row);
DataPacket dp_out = BlueDataUtility.build_dp(out_table, myLastValue as DataPacket);
myFireEvent(dp_out);
}
}
}
@@ -1,18 +1,15 @@
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;
}
@@ -21,10 +18,8 @@ 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
@@ -52,20 +47,17 @@ 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."); }
}
@@ -74,8 +66,7 @@ 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);
}
@@ -90,8 +81,7 @@ 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
}
@@ -106,8 +96,7 @@ 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");
@@ -116,20 +105,17 @@ 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);
@@ -139,8 +125,7 @@ namespace BCG
}
}
public void clear()
{
public void clear() {
myRows.clear();
myIDMap.Clear();
}
@@ -151,7 +136,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
@@ -169,7 +154,7 @@ namespace BCG
#region IEnumerable Members
public System.Collections.IEnumerator GetEnumerator() {return myRows.GetEnumerator();}
public System.Collections.IEnumerator GetEnumerator() { return myRows.GetEnumerator(); }
#endregion
}
@@ -179,8 +164,8 @@ namespace BCG
/// to append (or remove) more streams at
/// runtime
/// </summary>
public class MutableAppendStream : ViewStream
{
[DataStreamUserRespresentation("UnionStream")]
public class MutableAppendStream : ViewStream {
private bool mySubscriptionActive = false;
private MutableAppendTable myTable;
private int myMovingIndex;
@@ -188,22 +173,17 @@ 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)
@@ -212,8 +192,7 @@ 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
@@ -225,19 +204,14 @@ 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));
@@ -250,15 +224,13 @@ 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);
@@ -266,20 +238,17 @@ 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);
}
@@ -18,6 +18,7 @@ using System.Text.Json.Nodes;
using Newtonsoft.Json;
using BCG;
using System.Runtime.CompilerServices;
using bts;
namespace bts {
@@ -207,6 +208,10 @@ namespace BCG {
return rv;
}
public static bool contains_column(this IBlueTableSchema input_schema, string col) {
return input_schema.columnNames.Contains(col);
}
public static IBlueTableSchema add_columns(this IBlueTableSchema input_schema, params Tuple<Type, string>[] cols) {
List<ColumnInfo> cis = new List<ColumnInfo>(input_schema.columnInfo);
foreach (Tuple<Type, string> c in cols)
@@ -1719,8 +1724,10 @@ namespace BCG {
public static int[] get_column_indices(IBlueTableSchema schema, string[] col_names) {
List<int> rv = new List<int>();
foreach (string c in col_names)
foreach (string c in col_names) {
Log.assert(schema.contains_column(c), $"Could not find col: {c} in table: {schema.tableName}");
rv.Add(schema[c].colNo);
}
return rv.ToArray();
}
@@ -2207,23 +2214,53 @@ namespace BCG {
try {
if (v == null || v == DBNull.Value)
return error_val;
else {
if (v is DateTime)
return (DateTime)v;
else if (v is string) {
DateTime rv_dt = error_val;
DateTime.TryParse((string)v, out rv_dt);
if (v is DateTime) {
return (DateTime)v;
} else if (v is string) {
DateTime rv_dt;
// Try parsing the string as a DateTime
if (DateTime.TryParse((string)v,
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.RoundtripKind,
out rv_dt)) {
return rv_dt;
} else {
double oa_date = (double)Convert.ChangeType(v, typeof(Double));
return DateTime.FromOADate(oa_date);
return error_val; // Return the error value if parsing fails
}
} else {
// Assume the input can be converted to a double and use FromOADate
double oa_date = (double)Convert.ChangeType(v, typeof(Double));
return DateTime.FromOADate(oa_date);
}
} catch {
return error_val;
}
}
// private static DateTime _get_datetime_value(object v, DateTime error_val) {
// try {
// if (v == null || v == DBNull.Value)
// return error_val;
// else {
// if (v is DateTime)
// return (DateTime)v;
// else if (v is string) {
// DateTime rv_dt = error_val;
// DateTime.TryParse((string)v, out rv_dt);
// return rv_dt;
// } else {
// double oa_date = (double)Convert.ChangeType(v, typeof(Double));
// return DateTime.FromOADate(oa_date);
// }
// }
// } catch {
// return error_val;
// }
// }
#endregion
#region CSV methods
@@ -47,6 +47,11 @@ namespace BCG {
/// </summary>
/// <param name="assemblyName"></param>
public void loadAssembly(string assemblyName) {
Func<Type, bool> is_silverpine_only = (t) => {
if (!assemblyName.Contains("SharedStreams.dll"))
return true;
return t.Namespace == "bts.SilverPine";
};
bts.Log.Gen.info($"PrimitiveManager.loadAssembly assemblyName: {assemblyName}");
if (myAssemblyNames.Contains(assemblyName))
return;
@@ -56,7 +61,7 @@ namespace BCG {
Assembly.LoadFrom(assemblyName);
foreach (Type type in loadedAssembly.GetTypes())
if (!type.IsInterface
if (!type.IsInterface && is_silverpine_only(type)
&& !type.IsAbstract
&& type.IsSubclassOf(typeof(ViewStream))
&& type.IsPublic) {
@@ -1,60 +1,62 @@
"user": "bts",
"pubsub": {
"milliseconds_between_sub_info_updates": 1000,
"milliseconds_between_time_slice_updates": 5000,
"milliseconds_between_no_buffer_space_retries": 100,
"retries_on_no_buffer_space": 1,
"do_it_all_seconds_between_logs": 0,
"heartbeat_interval": 15000,
"missing_heartbeats_before_gc": 50,
"use_managed_sockets": true,
"state_update_period": 5000,
"statistics_update_period": 5000,
"disposed_connection_check_period": 1000,
"message_processing_warning_threshold": 1000,
"server_port": 12345,
"publisher_routes": [
{
"name": "default",
"server_address": "bts-cloud://192.168.1.80:12345",
"tag": ".*"
}
],
"subscriber_routes": [
{
"name": "default",
"server_address": "bts-cloud://192.168.1.80:12345",
"tag": ".*"
}
],
"max_packet_size": 500000000,
"blue_comm_must_die": true,
"crushable_tags": [],
"tag_type_to_assembly_map": [
{
"handler_class": "BCG.PubSubServerTagHandler",
"assembly": "DataStreamCore.dll"
}
],
"server_queue": "PubSubQueue",
"port_range": {
"first": 30400,
"last": 31700
},
"bind_to_random_port": false,
"debug_tags": "^NOTAGS$",
"latency_report_threshold_ms": 1500,
"use_substations": false,
"use_dynamic_clients": false,
"is_substation": false,
"internally_publish_sub_info": true,
"use_managed_clients_in_native_code": false,
"compressed_tags": "^NOTAGS$",
"tags_to_report_compression_ratio": "^NOTAGS$",
"disable_msmq": false,
"use_prepublished_server_state": false,
"ip_translation": null,
"gc_activation_threshold": 0,
"wait_period_after_gc": 1000
}
{
"user": "bts",
"sparkd": "http://192.168.1.80:8000/config",
"pubsub": {
"milliseconds_between_sub_info_updates": 1000,
"milliseconds_between_time_slice_updates": 5000,
"milliseconds_between_no_buffer_space_retries": 100,
"retries_on_no_buffer_space": 1,
"do_it_all_seconds_between_logs": 0,
"heartbeat_interval": 15000,
"missing_heartbeats_before_gc": 50,
"use_managed_sockets": true,
"state_update_period": 5000,
"statistics_update_period": 5000,
"disposed_connection_check_period": 1000,
"message_processing_warning_threshold": 1000,
"server_port": 12345,
"publisher_routes": [
{
"name": "default",
"server_address": "bts-cloud://192.168.1.80:12345",
"tag": ".*"
}
],
"subscriber_routes": [
{
"name": "default",
"server_address": "bts-cloud://192.168.1.80:12345",
"tag": ".*"
}
],
"max_packet_size": 500000000,
"blue_comm_must_die": true,
"crushable_tags": [],
"tag_type_to_assembly_map": [
{
"handler_class": "BCG.PubSubServerTagHandler",
"assembly": "DataStreamCore.dll"
}
],
"server_queue": "PubSubQueue",
"port_range": {
"first": 30400,
"last": 31700
},
"bind_to_random_port": false,
"debug_tags": "^NOTAGS$",
"latency_report_threshold_ms": 1500,
"use_substations": false,
"use_dynamic_clients": false,
"is_substation": false,
"internally_publish_sub_info": true,
"use_managed_clients_in_native_code": false,
"compressed_tags": "^NOTAGS$",
"tags_to_report_compression_ratio": "^NOTAGS$",
"disable_msmq": false,
"use_prepublished_server_state": false,
"ip_translation": null,
"gc_activation_threshold": 0,
"wait_period_after_gc": 1000
}
}
@@ -9,8 +9,90 @@ namespace bts.SilverPine {
using ZstdSharp.Unsafe;
public static class ContractUtils {
public class FutureTradableContract {
public string symbol;
public DateTime expiration;
public Exchange exchange;
public string contract_text;
}
public class FutureSpreadContract {
public List<Tuple<double, bts.SilverPine.ContractUtils.FutureTradableContract>> legs;
public string symbol {
get {
return legs == null || legs.Count == 0 ? String.Empty : legs.ElementAt(0).Item2.symbol;
}
}
public string contract_text;
}
public class FutureContinousContract {
public string symbol;
public Exchange exchange;
}
// this is for all future conytracts belonging to a symbol
public class FutureWildcardContract {
public string symbol;
public Exchange exchange;
}
public class FutureContract {
public FutureWildcardContract wildcard_contract = null;
public FutureTradableContract future_tradable_contract = null;
public FutureSpreadContract spread_tradable_contract = null;
public FutureContinousContract continous_constract = null;
public FutureContract(string txt) {
wildcard_contract = parse_wildcard_contract(txt);
if (wildcard_contract != null)
return;
FutureTradableContract fc = parse_future_contract(txt);
if (fc != null) {
future_tradable_contract = fc;
return;
}
FutureSpreadContract sc = parse_future_spread_contract(txt);
if (sc != null) {
spread_tradable_contract = sc;
return;
}
// this is not totally true, since ParseFutureSpreadContract does not
// parse ICS spreads
continous_constract = new FutureContinousContract() { symbol = txt };
}
public bool is_continous_contract => continous_constract != null;
public string symbol() {
if (wildcard_contract != null)
return wildcard_contract.symbol;
if (continous_constract != null) {
return continous_constract.symbol;
} else if (future_tradable_contract != null) {
return future_tradable_contract.symbol;
} else if (spread_tradable_contract != null) {
return spread_tradable_contract.symbol;
}
Log.assert(false);
return String.Empty;
}
public string contract_text {
get {
if (future_tradable_contract != null)
return future_tradable_contract.contract_text;
if (spread_tradable_contract != null)
return spread_tradable_contract.contract_text;
return null;
}
}
}
#region Parsing
public static FutureContract ParseFutureContract(string contract_txt, Exchange exchange = Exchange.CME) {
public static FutureWildcardContract parse_wildcard_contract(string contract_txt, Exchange exchange = Exchange.CME) {
if (contract_txt.EndsWith("*")) {
contract_txt = contract_txt.Replace("*", String.Empty);
return new FutureWildcardContract() {
symbol = contract_txt,
exchange = exchange
};
}
return null;
}
public static FutureTradableContract parse_future_contract(string contract_txt, Exchange exchange = Exchange.CME) {
// Validate the future string length
if (!contract_txt.All(c => Char.IsLetterOrDigit(c)))
return null;
@@ -56,23 +138,24 @@ namespace bts.SilverPine {
// Create the FutureContract instance and set its properties
DateTime expiration = new DateTime(year, month, 1);
var futureContract = new FutureContract {
var futureContract = new FutureTradableContract {
symbol = symbol,
expiration = expiration,
exchange = exchange
exchange = exchange,
contract_text = contract_txt
};
return futureContract;
}
// Method to parse a futures spread, e.g. "CLX4-CLZ4"
public static FutureSpreadContract ParseFutureSpreadContract(string spreadString, Exchange exchange = Exchange.CME) {
public static FutureSpreadContract parse_future_spread_contract(string contract_txt, Exchange exchange = Exchange.CME) {
// Split the string by '-' to handle each leg
var spreadParts = spreadString.Split('-');
var spreadParts = contract_txt.Split('-');
if (spreadParts.Length < 2) {
return null; // Not a valid spread format
}
var spreadContract = new FutureSpreadContract { legs = new List<Tuple<double, FutureContract>>() };
var spreadContract = new FutureSpreadContract { legs = new List<Tuple<double, FutureTradableContract>>() };
foreach (var part in spreadParts) {
// Split each leg by '*', assuming the format is weight*future or just future
@@ -92,33 +175,32 @@ namespace bts.SilverPine {
}
// Parse the future contract
var futureContract = ParseFutureContract(futurePart, exchange);
var futureContract = parse_future_contract(futurePart, exchange);
if (futureContract == null) {
return null; // Failed to parse the future part
}
// Add the leg to the spread contract
spreadContract.legs.Add(new Tuple<double, FutureContract>(weight, futureContract));
spreadContract.legs.Add(new Tuple<double, FutureTradableContract>(weight, futureContract));
}
return spreadContract;
}
public static ContractType DetermineFutureOrSpread(string contract) {
if (contract.Contains("-")) {
return ContractType.FutureSpread;
} else {
return ContractType.Future;
}
}
// public static ContractType DetermineFutureOrSpread(string contract) {
// if (contract.Contains("-")) {
// return ContractType.FutureSpread;
// } else {
// return ContractType.Future;
// }
// }
#endregion
public static ContractType get_type(string contract_txt) {
FutureContract fc = ParseFutureContract(contract_txt);
FutureTradableContract fc = parse_future_contract(contract_txt);
if (fc != null) {
return ContractType.Future;
}
FutureSpreadContract sc = ParseFutureSpreadContract(contract_txt);
FutureSpreadContract sc = parse_future_spread_contract(contract_txt);
if (sc != null) {
return ContractType.FutureSpread;
}
@@ -133,11 +215,11 @@ namespace bts.SilverPine {
}
public static Tuple<ContractCategory, string> get_symbol_category(string symbol) {
ContractUtils.FutureContract fc = ParseFutureContract(symbol);
ContractUtils.FutureTradableContract fc = parse_future_contract(symbol);
if (fc != null) {
return Tuple.Create(ContractCategory.FutureString, fc.symbol);
}
var sc = ParseFutureSpreadContract(symbol);
var sc = parse_future_spread_contract(symbol);
if (sc != null) {
return Tuple.Create(ContractCategory.FutureString, sc.symbol);
}
@@ -165,18 +247,6 @@ namespace bts.SilverPine {
public enum Exchange {
CME
}
public class FutureContract {
public string symbol;
public DateTime expiration;
public Exchange exchange;
}
public class FutureSpreadContract {
public List<Tuple<double, bts.SilverPine.ContractUtils.FutureContract>> legs;
public string symbol {
get {
return legs == null || legs.Count == 0 ? String.Empty : legs.ElementAt(0).Item2.symbol;
}
}
}
}
}
@@ -1,35 +1,105 @@
namespace BCG {
namespace bts.SilverPine {
using BCG.Utilities.General;
using bts.api;
using bts.api.domain;
using bts.api.synthetic;
using bts.md;
using bts.spark;
using bts.utils;
using mbts;
using mbts.co2;
using mbts.config;
using mbts.spark;
using mbts.ui;
using Spark.Core.Data;
using Spark.Core.Disposables;
using BCG;
using Spark.Core.Reactive;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reactive.Linq;
using bts.api.core;
using Spark.Api.MarketData;
using SecurityKey = System.UInt32;
using System.Data;
using System.Reflection.Metadata;
using System.Data.Entity.Infrastructure;
public class FakeBBOStream : ViewStream, IWorker {
private string _symbol;
public BlueTable _table = new BlueTable(BBOStream._bbo_schema);
private DateTime _last_fired_time = DateTime.MinValue;
private TimeSpan _period = TimeSpan.FromMilliseconds(333);
private double _start_price;
private double _inc;
private int _total_count = 5;
private Random _rnd = new Random(DateTime.Now.Millisecond);
private string[] _months = new string[]{
"F","G", "H", "J","K", "M", "N","Q","U","V","X","Z"
};
private ViewStreamDatabase _vsd;
public FakeBBOStream(string contract_type, string exchange, string symbol, double start_price, double inc)
:
this(contract_type, exchange, symbol, start_price, inc, ViewStreamDatabase.instance) { }
public FakeBBOStream(string contract_type, string exchange, string symbol, double start_price, double inc, ViewStreamDatabase vsd) {
_symbol = symbol;
_start_price = start_price;
_inc = inc;
_vsd = vsd;
Log.assert(contract_type.ToLower() == "future");
}
protected override void myOnFirstSubscriber() {
_vsd.addWorker(this);
}
protected override void myOnLastSubscriber() {
_vsd.removeWorker(this);
}
private bool _random_truefase() {
int r = _rnd.Next(0, 100);
return r % 2 == 0;
}
private IBlueRow _perturb_row(IBlueRow er) {
MutableBlueRow rv = new MutableBlueRow(er);
double bid_price = rv.get<double>("bid_price");
bid_price += _inc;
double ask_price = bid_price + _inc;
rv.setValue("bid_price", bid_price);
rv.setValue("ask_price", ask_price);
return rv;
}
public void doWork() {
if (DateTime.Now - _last_fired_time < _period)
return;
_last_fired_time = DateTime.Now;
if (_table.Count == 0) {
// first fire_symbol
string year_code = DateTime.Now.Year.ToString().Last().ToString();
for (int i = 0; i < _total_count; i++) {
string month_code = _months[i % _months.Length];
string sec = $"{_symbol}{month_code}{year_code}";
double bid_price = _start_price + _rnd.Next(-10, 10) * _inc;
double ask_price = bid_price + _inc;
BlueRow nr = new BlueRow(_table.schema, _table.Count, _table.Count, sec,
bid_price, _rnd.Next(1, 10),
ask_price, _rnd.Next(1, 10));
_table.addRow(nr);
var dp = BlueDataUtility.build_dp(new BlueTable(_table), myLastValue as DataPacket);
myFireEvent(dp);
}
} else {
BlueTable deleted_rows = new BlueTable(_table.schema);
BlueTable added_rows = new BlueTable(_table.schema);
// go through all rows, select some at random, add them to deleted, get
// the replaced one and add it to added, updates table state and fire
for (int i = 0; i < _table.Count; i++) {
if (_random_truefase()) {
IBlueRow er = _table[i];
IBlueRow nr = _perturb_row(er);
_table.deleteRow(er);
_table.addRow(nr);
}
}
var dp = BlueDataUtility.build_dp_inc(new BlueTable(_table), myLastValue as DataPacket, true);
myFireEvent(dp);
}
}
}
[DataStreamUserRespresentation("bbo")]
public class BBOStream : ViewStream, IWorker {
@@ -39,7 +109,7 @@ namespace BCG {
private int _id = 0;
IReadOnlyDictionary<SecurityKey, BookTuple> _cached_state = null;
MarketDataClient _md_client;
private readonly IBlueTableSchema _bbo_schema = BlueDataUtility.form_schema("bbo",
internal static IBlueTableSchema _bbo_schema = BlueDataUtility.form_schema("bbo",
Tuple.Create("id", TypeCode.Int32),
Tuple.Create("sec_key", TypeCode.UInt32),
Tuple.Create("sec", TypeCode.String),
@@ -54,9 +124,11 @@ namespace BCG {
}
public BBOStream(ViewStreamDatabase vsd) {
bts.Log.Gen.info("BBOStream.cons");
_vsd = vsd;
_md_client = new MarketDataClient(new MDSource(TimeSpan.FromSeconds(0.5)));
// bts.Log.Gen.info("BBOStream.cons");
// _vsd = vsd;
// _md_client = new MarketDataClient(new MDSource(TimeSpan.FromSeconds(0.5)));
FakeBBOStream rs = new FakeBBOStream("Future", "CME", "ES", 5000, 0.25, vsd);
mySetRealSource(rs);
}
protected override void myOnFirstSubscriber() {
@@ -0,0 +1,254 @@
namespace bts.SilverPine {
using BCG;
using System.Runtime.CompilerServices;
using ZstdSharp.Unsafe;
public class DateTimeRange {
public readonly DateTime range_beg;
public readonly DateTime range_end;
public DateTimeRange(DateTime range_beg_, DateTime range_end_) {
range_beg = range_beg_;
range_end = range_end_;
}
public static DateTimeRange parse(string range_beg_, string range_end_) {
DateTime range_beg = String.IsNullOrEmpty(range_beg_) ? DateTime.MinValue : DateTime.Parse(range_beg_);
DateTime range_end = String.IsNullOrEmpty(range_end_) ? DateTime.MaxValue : DateTime.Parse(range_end_);
return new DateTimeRange(range_beg, range_end);
}
}
public class FutureBarsLoader {
public static string get_db_table_name(BarSize bar_size, string symbol, bool is_continous) {
switch (bar_size) {
case BarSize.ONE_DAY: {
if (is_continous) {
return $"bars_future_{symbol}_continous_1day";
} else
return $"bars_future_{symbol}_all_1day";
}
case BarSize.ONE_MIN: {
if (is_continous) {
return $"bars_future_{symbol}_continous_1min";
} else
return $"bars_future_{symbol}_all_1min";
}
}
Log.assert(false);
return null;
}
}
public enum BarSize {
ONE_DAY = 0,
ONE_MIN
}
[DataStreamUserRespresentation("FuturesHistorical1DayBars")]
public class FuturesHistorical1DayBarsStream : ViewStream {
// this gets the raw bars for a symbol (perhaps make it into a raw bars stream?)
public FuturesHistorical1DayBarsStream(string symbol) :
this(symbol, DateTime.MinValue, DateTime.MaxValue) { }
// creates the non raw stream (ie for tradable contract, or continous contract)
public FuturesHistorical1DayBarsStream(string future_contract, DateTime range_beg, DateTime range_end)
: this(new ContractUtils.FutureContract(future_contract), new DateTimeRange(range_beg, range_end)) { }
// this creates a tradable contracts bars streams or continous contracts stream. if get_all_rows is true,
// it gets the raw table with all contracts for that symbol
public FuturesHistorical1DayBarsStream(ContractUtils.FutureContract future_contract,
DateTimeRange dt_range) {
DateTime beg = dt_range.range_beg;//.ToUniversalTime(),
DateTime end = dt_range.range_end;//.ToUniversalTime();
beg = beg.Date;
end = end.Date.Add(new TimeSpan(23, 59, 59));
// this returns rows from beg and end inclusive
Func<string, SQLiteStream> get_sqlite_str = (table_name) => {
string range_beg_iso8601 = beg.ToString("yyyy-MM-ddTHH:mm:ss"),
range_end_iso8601 = end.ToString("yyyy-MM-ddTHH:mm:ss");
string sql_str = $"select * from {table_name} where ts_event >= '{range_beg_iso8601}' AND ts_event <= '{range_end_iso8601}'";
return new SQLiteStream(SQLiteHelper.db_name, sql_str);
};
string symbol = future_contract.symbol();
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
}
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
}
if (future_contract.is_continous_contract) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, symbol, true);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
mySetRealSource(rs);
return;
} else {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_DAY, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
//rs = new DateStandardizationStream(rs, "ts_event", DateConversion.ChopTime);
//TODO: filter it
rs = new FilterStream(rs, $"symbol = '{future_contract.contract_text}'");
mySetRealSource(rs);
}
}
}
[DataStreamUserRespresentation("FuturesHistorical1MinBars")]
public class FuturesHistorical1MinuteBarsStream : ViewStream {
// same as the above but for one min
// this gets the raw bars for a symbol
public FuturesHistorical1MinuteBarsStream(string symbol) :
this(symbol, DateTime.MinValue, DateTime.MaxValue) { }
// creates the non raw stream (ie for tradable contract, or continous contract)
public FuturesHistorical1MinuteBarsStream(string future_contract, DateTime range_beg, DateTime range_end)
: this(new ContractUtils.FutureContract(future_contract), new DateTimeRange(range_beg, range_end)) { }
// this creates a tradable contracts bars streams or continous contracts stream. if get_all_rows is true,
// it gets the raw table with all contracts for that symbol
public FuturesHistorical1MinuteBarsStream(ContractUtils.FutureContract future_contract,
DateTimeRange dt_range) {
Func<string, SQLiteStream> get_sqlite_str = (table_name) => {
string range_beg_iso8601 = dt_range.range_beg.ToString("yyyy-MM-ddTHH:mm:ss"),
range_end_iso8601 = dt_range.range_end.ToString("yyyy-MM-ddTHH:mm:ss");
//string sql_str = $"select * from {table_name} where DATE(ts_event) >= '{range_beg_iso8601}' AND DATE(ts_event) <= '{range_end_iso8601}'";
string sql_str = $"select * from {table_name} where ts_event >= '{range_beg_iso8601}' AND ts_event <= '{range_end_iso8601}'";
return new SQLiteStream(SQLiteHelper.db_name, sql_str);
};
string symbol = future_contract.symbol();
if (future_contract.wildcard_contract != null) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
mySetRealSource(rs);
return;
}
if (future_contract.is_continous_contract) {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, symbol, true);
ViewStream rs = get_sqlite_str(table_name);
mySetRealSource(rs);
return;
} else {
string table_name = FutureBarsLoader.get_db_table_name(BarSize.ONE_MIN, future_contract.symbol(), false);
ViewStream rs = get_sqlite_str(table_name);
// TODO: filter
rs = new FilterStream(rs, $"symbol = '{future_contract.contract_text}'");
mySetRealSource(rs);
}
}
}
[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;
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)
:
this(new ContractUtils.FutureContract(fut_contract), Enum.Parse<BarSize>(bar_size, true),
new DateTimeRange(dt_range_beg, dt_range_end)) { }
public FutureHistoricalBarsStream(ContractUtils.FutureContract fut_contract, BarSize bar_size,
DateTimeRange dt_range) {
switch (bar_size) {
case BarSize.ONE_DAY: {
ViewStream rs = new FuturesHistorical1DayBarsStream(fut_contract, dt_range);
mySetRealSource(rs);
break;
}
case BarSize.ONE_MIN: {
ViewStream rs = new FuturesHistorical1MinuteBarsStream(fut_contract, dt_range);
mySetRealSource(rs);
break;
}
}
}
}
[DataStreamUserRespresentation("FuturePriceDiff")]
public class FutureHistoricalBarsPriceDiffStream : ViewStream {
public FutureHistoricalBarsPriceDiffStream(string future_contract, string dt1, string dt2)
:
this(new ContractUtils.FutureContract(future_contract), DateTime.Parse(dt1), DateTime.Parse(dt2), "close", ViewStreamDatabase.instance) {
}
public FutureHistoricalBarsPriceDiffStream(string future_contract, DateTime dt1, DateTime dt2)
:
this(new ContractUtils.FutureContract(future_contract), dt1, dt2, "close", ViewStreamDatabase.instance) {
}
public FutureHistoricalBarsPriceDiffStream(string future_contract, DateTime dt1, DateTime dt2, string col)
:
this(new ContractUtils.FutureContract(future_contract), dt1, dt2, col, ViewStreamDatabase.instance) {
}
public FutureHistoricalBarsPriceDiffStream(ContractUtils.FutureContract fc, DateTime dt1, DateTime dt2, string col, ViewStreamDatabase vsd) {
BarSize bsize = dt2 - dt1 >= TimeSpan.FromDays(1.0) ? BarSize.ONE_DAY : BarSize.ONE_MIN;
ViewStream rs = new FutureHistoricalBarsStream(fc, BarSize.ONE_DAY, new DateTimeRange(dt1, dt2));
rs = new ColumnDifferenceStream(rs, r => {
DateTime r_dt = r.get_datetime("ts_event");
var rv = dt1.Equals(r_dt);
return rv;
},
//r => dt2.Equals(r.get_datetime("ts_event")), col, col);
r => {
DateTime r_dt = r.get_datetime("ts_event");
var rv = dt2.Equals(r_dt);
return rv;
}, col, col);
rs = new NewProjectStream(rs, "diff !");
mySetRealSource(rs);
}
}
// takes the contract name and expands it into multuiple columns corresponding to the contracts.
// the contract columns are a union, of all properties with some of them empty
public class ContractExpanderStream : ViewStream {
private static IBlueTableSchema map_schema(IBlueTableSchema schema) {
return schema.add_column(TypeCode.String, "contract_type");
}
public ContractExpanderStream(ViewStream parent_str, string contract_col_name) {
ViewStream rs = new MapStream(parent_str, (schema) => map_schema(schema),
r => {
string contract = r.get<string>(contract_col_name);
var ct = ContractUtils.get_type(contract);
MutableBlueRow rv = new MutableBlueRow(map_schema(r.schema), r);
rv.setValue("contract_type", ct.ToString());
return rv;
});
mySetRealSource(rs);
}
}
}
@@ -0,0 +1,53 @@
using BCG;
namespace bts.SilverPine {
/*
----------------------------------------------------------------------
*Expression*
----------------------------------------------------------------------
//r=FutureHistoricalBars("ES*", "02/01/2024 09:30 AM", "02/01/2024 09:30 PM")
r=FutureHistoricalBars("ES*","One_Day", 02/01/2024, 02/01/2025)
r=contractExpander(r,"symbol")
r=filter(r,"contract_type='FutureSpread'")
r=aggregate(r,"symbol","volume:Sum","ts_event")
r=aggregate(r,"volume_sum:Max")
r=newProject(r,"volume_sum_max:volume symbol !")
----------------------------------------------------------------------
*Schema*
----------------------------------------------------------------------
symbol System.String
id System.Int32
volume System.Double
*/
[DataStreamUserRespresentation("VolumeAgg")]
public class VolumeAggregationStream : ViewStream {
public VolumeAggregationStream(string future_contract, string contract_type, DateTime range_beg, DateTime range_end)
: this(future_contract, contract_type, range_beg, range_end, ViewStreamDatabase.instance) { }
public VolumeAggregationStream(string future_contract, string contract_type, string range_beg, string range_end)
:
this(future_contract, contract_type, DateTime.Parse(range_beg), DateTime.Parse(range_end), ViewStreamDatabase.instance) { }
public VolumeAggregationStream(string future_contract, string contract_type, DateTime range_beg, DateTime range_end, ViewStreamDatabase db) {
future_contract = future_contract.EndsWith("*") ? future_contract : future_contract + "*";
ViewStream r;
r = new FutureHistoricalBarsStream(future_contract,
range_beg.ToString(), range_end.ToString());
r = new ContractExpanderStream(r, "symbol");
r = new FilterStream(r, $"contract_type='{contract_type}'");
r = new NonIncGroupByStream(r, "symbol", "volume:Sum", "ts_event");
r = new NonIncGroupByStream(r, "volume_sum:Max");
r = new NewProjectStream(r, "volume_sum_max:volume symbol !");
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) {
}
}
}
@@ -1,68 +1,117 @@
// namespace bts.SilverPine {
// using bts;
// using BCG;
// using MongoDB.Driver.Linq;
// using System.ComponentModel.DataAnnotations;
// using ZstdSharp.Unsafe;
// [DataStreamUserRespresentation("VWAP")]
// public class VWAPStream : ViewStream {
// // returns the VWAP stream for each contract
// private static ViewStream build_vwap_stream(string symbol, DateTime begin_dt, DateTime end_dt) {
// var ohlcv_params = OHLCVStream.get_params(begin_dt, end_dt);
// ViewStream ohlc_str = new OHLCVStream(symbol, ohlcv_params);
// // stream is grouped per contract and then vwap is calculated per contract
// GlobalMapStream rs = new GlobalMapStream(ohlc_str, "ts_event", "contract",
// (rows, idx) => {
// Log.Gen.info($"VWAPStream.GlobalMapStream delegate n_rows: {rows.Count} idx: {idx}");
// IBlueRow ir = rows.ElementAt((int)idx);
// var sel_rows = rows.Skip((int)idx).Where(r => r.get_datetime("ts_event") >= end_dt && r.get_datetime("ts_event") <= begin_dt);
// var volumeprices = sel_rows.Select(r => Tuple.Create(r.get<int>("volume"), r.get<double>("close"))).ToList();
// double vwap = IndicatorCalc.calculate_VWAP(volumeprices);
// IBlueTableSchema schema = ir.schema.add_columns(Tuple.Create(typeof(double), "vwap"));
// MutableBlueRow nr = new MutableBlueRow(schema, ir);
// //vwap = -313.987;
// nr.setValue("vwap", vwap);
// return nr;
// });
// return rs;
// }
// // the args want dt1 > dt2, if its nto we, swap them
// static void swap_if_necessary(ref DateTime dt1, ref DateTime dt2) {
// if (dt1 < dt2) {
// DateTime aux = dt1;
// dt1 = dt2;
// dt2 = aux;
// }
// }
// // this assumes the ohlc_str has diff contracts
// public VWAPStream(string symbol_or_contract, DateTime begin_dt, DateTime end_dt) {
// swap_if_necessary(ref begin_dt, ref end_dt);
// Tuple<ContractUtils.ContractCategory, string> ccat_sym_contr = ContractUtils.get_symbol_category(symbol_or_contract);
// string symbol = String.Empty;
// symbol = ccat_sym_contr.Item2;
// var ohlcv_params = OHLCVStream.get_params(begin_dt, end_dt);
// ViewStream vwap_str = build_vwap_stream(symbol, begin_dt, end_dt);
// // vwap_str now has vwap for all contracts. if the arg was a symbol, we need to filter it for the active contract,
// // whihc we do with FutureActivesContractStream. If the arg was a contract we'll simply filter it
// ViewStream rs = vwap_str;
// switch (ccat_sym_contr.Item1) {
// case ContractUtils.ContractCategory.FutureString:
// case ContractUtils.ContractCategory.SpreadString:
// rs = new FilterStream(vwap_str, r => r.get<string>("contract").CompareTo(ccat_sym_contr.Item2) == 0);
// break;
// case ContractUtils.ContractCategory.Symbol:
// rs = new FuturesActiveContractStream(vwap_str);
// break;
// }
// rs = new FilterStream(rs, r => r.get_datetime("ts_event").CompareTo(begin_dt) == 0);
// rs = new NewProjectStream(rs, "! vwap");
// mySetRealSource(rs);
// }
// public VWAPStream(string symbol_or_contract, string begin_dt, string end_dt)
// :
// this(symbol_or_contract, DateTime.Parse(begin_dt), DateTime.Parse(end_dt)) { }
// }
// }
using System;
using BCG;
using bts.api;
namespace bts.SilverPine {
using bts;
using BCG;
using MongoDB.Driver.Linq;
using System.ComponentModel.DataAnnotations;
using ZstdSharp.Unsafe;
/*
----------------------------------------------------------------------
*Expression*
----------------------------------------------------------------------
//nl("Find Settlement price of the SP500 future in the first week of 2023.")
r=FutureHistoricalBars("ES", "One_Day", "1/1/2024", "2/1/2024")
r=math(r, "vprice = volume * close")
r=aggregate(r, "vprice:Sum, volume:Sum")
r=math(r, "vwap = vprice_sum / volume_sum")
r=newProject(r, "vwap !")
----------------------------------------------------------------------
*Schema*
----------------------------------------------------------------------
id System.Int32
vwap System.Double
*/
[DataStreamUserRespresentation("VWAP")]
public class VWAPStream : ViewStream {
// returns the VWAP stream for each contract
private static ViewStream build_vwap_stream(string symbol, DateTime begin_dt, DateTime end_dt) {
var ohlcv_params = OHLCVStream.get_params(begin_dt, end_dt);
ViewStream ohlc_str = new OHLCVStream(symbol, ohlcv_params);
// stream is grouped per contract and then vwap is calculated per contract
GlobalMapStream rs = new GlobalMapStream(ohlc_str, "ts_event", "contract",
(rows, idx) => {
Log.Gen.info($"VWAPStream.GlobalMapStream delegate n_rows: {rows.Count} idx: {idx}");
IBlueRow ir = rows.ElementAt((int)idx);
var sel_rows = rows.Skip((int)idx).Where(r => r.get_datetime("ts_event") >= end_dt && r.get_datetime("ts_event") <= begin_dt);
var volumeprices = sel_rows.Select(r => Tuple.Create(r.get<int>("volume"), r.get<double>("close"))).ToList();
double vwap = IndicatorCalc.calculate_VWAP(volumeprices);
IBlueTableSchema schema = ir.schema.add_columns(Tuple.Create(typeof(double), "vwap"));
MutableBlueRow nr = new MutableBlueRow(schema, ir);
//vwap = -313.987;
nr.setValue("vwap", vwap);
return nr;
});
return rs;
}
// the args want dt1 > dt2, if its nto we, swap them
static void swap_if_necessary(ref DateTime dt1, ref DateTime dt2) {
if (dt1 < dt2) {
DateTime aux = dt1;
dt1 = dt2;
dt2 = aux;
}
}
// this assumes the ohlc_str has diff contracts
public VWAPStream(string symbol_or_contract, DateTime begin_dt, DateTime end_dt) {
swap_if_necessary(ref begin_dt, ref end_dt);
Tuple<ContractUtils.ContractCategory, string> ccat_sym_contr = ContractUtils.get_symbol_category(symbol_or_contract);
string symbol = String.Empty;
symbol = ccat_sym_contr.Item2;
var ohlcv_params = OHLCVStream.get_params(begin_dt, end_dt);
ViewStream vwap_str = build_vwap_stream(symbol, begin_dt, end_dt);
// vwap_str now has vwap for all contracts. if the arg was a symbol, we need to filter it for the active contract,
// whihc we do with FutureActivesContractStream. If the arg was a contract we'll simply filter it
ViewStream rs = vwap_str;
switch (ccat_sym_contr.Item1) {
case ContractUtils.ContractCategory.FutureString:
case ContractUtils.ContractCategory.SpreadString:
rs = new FilterStream(vwap_str, r => r.get<string>("contract").CompareTo(ccat_sym_contr.Item2) == 0);
break;
case ContractUtils.ContractCategory.Symbol:
rs = new FuturesActiveContractStream(vwap_str);
break;
}
rs = new FilterStream(rs, r => r.get_datetime("ts_event").CompareTo(begin_dt) == 0);
rs = new NewProjectStream(rs, "! vwap");
mySetRealSource(rs);
}
public VWAPStream(string symbol_or_contract, string begin_dt, string end_dt)
public VWAPStream(string symbol_or_contract, DateTime beg_dt, DateTime end_dt)
:
this(symbol_or_contract, DateTime.Parse(begin_dt), DateTime.Parse(end_dt)) { }
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
r = new MathStream(r,
"vprice = volume * close");
r = new NonIncGroupByStream(r,
"vprice:Sum, volume:Sum");
r = new MathStream(r,
"vwap = vprice_sum / volume_sum");
r = new NewProjectStream(r,
"vwap !");
mySetRealSource(r);
}
}
}
}
@@ -75,4 +75,31 @@ namespace bts.SilverPine {
mySetRealSource(rs);
}
}
}
namespace bts.SilverPine {
using BCG;
using bts.api;
using Newtonsoft.Json.Serialization;
[DataStreamUserRespresentation("FuturesContinousContract")]
public class FuturesContinousContractStream : ViewStream {
// 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");
mySetRealSource(r);
}
}
}
@@ -2,15 +2,14 @@ namespace bts.SilverPine {
using bts;
using BCG;
// 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
// 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
[DataStreamUserRespresentation("FuturesRoll")]
public class FuturesRollStream : ViewStream {
public FuturesRollStream(string future_symbol) {
//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 !");
ViewStream rs = new FuturesContinousContractStream(future_symbol);
rs = new ColumnEvolutionStream(rs, "ts_event", "symbol");
rs = new NewProjectStream(rs, "symbol ts_event:roll_date !");
mySetRealSource(rs);
}
}
@@ -2,6 +2,93 @@ namespace bts.SilverPine {
using bts;
using BCG;
using MongoDB.Driver;
// OHLCV request breakdown
// symbol_or_contract (if symbol, get continous, otherwise get raw and filter it)
// bar_size (one min, one day)
// live/historic
// time range
// internal code oranization only
public class OHLCV_1min_stream : ViewStream {
public OHLCV_1min_stream(string symbol_or_contract, string range_beg, string range_end) :
this(symbol_or_contract, DateTime.Parse(range_beg), DateTime.Parse(range_end)) { }
public OHLCV_1min_stream(string symbol_or_contract, DateTime range_beg, DateTime range_end) {
Func<string, bool, SQLiteStream> get_sqlite_str = (symbol, is_continous_contracts) => {
string table_name = is_continous_contracts ? $"ohlcv_1min_{symbol}_continous" : $"{symbol}_ohlcv_1min";
string db_str = $"Data Source={SQLiteHelper.location}{SQLiteHelper.db_name};Version=3";
string range_beg_iso8601 = range_beg.ToString("yyyy-MM-ddTHH:mm:ss"),
range_end_iso8601 = range_end.ToString("yyyy-MM-ddTHH:mm:ss");
string sql_str = $"select * from {table_name} where DATE(ts_event) >= '{range_beg_iso8601}' AND DATE(ts_event) <= '{range_end_iso8601}'";
return new SQLiteStream(db_str, sql_str);
};
Tuple<ContractUtils.ContractCategory, string> tup = ContractUtils.get_symbol_category(symbol_or_contract);
var contract_cat = tup.Item1;
switch (contract_cat) {
case ContractUtils.ContractCategory.Symbol: {
ViewStream res = get_sqlite_str(tup.Item2, true);
mySetRealSource(res);
// this creates the continous stream for 1 min bars, but we store it in the DB, so we just read it from it
// ViewStream ohlcv_1min = get_sqlite_str(tup.Item2, false);
// // the following is whats written to the DB in the _contionous table
// ohlcv_1min = new DateTimeExpanstionStream(ohlcv_1min, "ts_event");
// ViewStream active_contr_str = new FuturesActiveContractStream(tup.Item2);
// ViewStream res = new NonIncJoinStream(ohlcv_1min, "ts_event_date symbol", "ts_event ts_event_date symbol open high low close volume",
// active_contr_str, "ts_event contract", "ts_event:date contract:continous_contract");
// res = new NullFilterStream(res, "continous_contract", true);
// res = new NewProjectStream(res, "ts_event date continous_contract open high low close volume !");
// mySetRealSource(res);
break;
}
default: {
ViewStream sql_str = get_sqlite_str(tup.Item2, false);
ViewStream rs = new FilterStream(sql_str, $"symbol='{symbol_or_contract}'");
// filter here
mySetRealSource(rs);
break;
}
}
}
}
// this is to make bigger bars form smaller bars. Right now the assumption it only works
// with symbols vs contracts, and the 1min <= aggregation_period < 1day
[DataStreamUserRespresentation("OHLCVAggregated")]
public class OHLCVAggregatedStream : ViewStream {
public OHLCVAggregatedStream(string symbol, string agregation_period, string range_beg, string range_end) :
this(symbol, TimeBasedFilter.parse_duration(agregation_period), DateTime.Parse(range_beg), DateTime.Parse(range_end)) {
}
public OHLCVAggregatedStream(string symbol, TimeSpan aggregation_period, DateTime range_beg, DateTime range_end) {
Tuple<ContractUtils.ContractCategory, string> tup = ContractUtils.get_symbol_category(symbol);
Log.assert(tup.Item1 == ContractUtils.ContractCategory.Symbol);
if (aggregation_period < TimeSpan.FromDays(1.0) &&
aggregation_period > TimeSpan.FromMinutes(1.0)) {
ViewStream r = new OHLCV_1min_stream(symbol, range_beg, range_end);
r = new DateTimeExpanstionStream(r,
"ts_event");
double tot_secs = aggregation_period.TotalSeconds;
r = new MathStream(r,
$"bucket = Floor(ts_event_seconds_of_day / {tot_secs})");
r = new NonIncGroupByStream(r,
"bucket",
// column:operation
"open:first, high:max, low:min, close:last, volume:sum",
"ts_event");
r = new SortStream(r,
"-ts_event");
mySetRealSource(r);
} else {
// fix it later
Log.assert(false);
}
}
}
[DataStreamUserRespresentation("OHLCV")]
// This stream retreives the OHLCV table as is, and fires it as-is.
// The only logic here is as follows:
@@ -80,12 +167,13 @@ namespace bts.SilverPine {
switch (ohlcv_params.type) {
case OHLCVType.LIVE:
case OHLCVType.LIVE_AND_HISTORIC:
// TODO
Log.assert(false);
break;
case OHLCVType.HISTORIC:
// TODO: assuming 1 day only for historic
string table_name = get_table_from_barsize(ohlcv_params.bar_size, symbol);// $"{symbol}_OHLCV_1DAY";
//string table_name = $"{symbol}_{ohlcv_params.bar_size}";
//string table_name = $"{symbol}_{ohlcv_params.bar_size}";
string db_str = $"Data Source={_location}{_db_name};Version=3";
string sql_str = $"select * from {table_name}";
// "Data Source=C:\\Users\\m_tah\\development\\data\\stream_data.db;Version=3;"
@@ -111,6 +199,11 @@ namespace bts.SilverPine {
:
this(symbol, Enum.Parse<OHLCVBarSize>(bar_size)) { }
// aggregates the bars
public OHLCVStream(string symbol, TimeSpan agregation_period) {
}
}
@@ -2,50 +2,23 @@ namespace bts.SilverPine {
using BCG;
using bts;
using DnsClient.Protocol;
using MongoDB.Driver;
// used directly in blueorb
[DataStreamUserRespresentation("Settlement")]
public class SettlementPriceStream : ViewStream {
public SettlementPriceStream(string future_name, string date_txt)
: this(future_name, date_txt, String.Empty) { }
// 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 symbol_or_contract, DateTime begin_dt)
: this(symbol_or_contract, begin_dt, DateTime.MinValue) { }
public SettlementPriceStream(string future_contract, DateTime begin_dt)
: this(future_contract, begin_dt, begin_dt) { }
public SettlementPriceStream(string symbol_or_contract, DateTime begin_dt, DateTime end_dt) {
// DateTime begin_dt = DateTime.Parse(begin_dt_txt);
// DateTime end_dt = String.IsNullOrEmpty(end_dt_txt) ? DateTime.MinValue : DateTime.Parse(end_dt_txt);
Tuple<ContractUtils.ContractCategory, string> ccat_sym_contr = ContractUtils.get_symbol_category(symbol_or_contract);
ContractUtils.ContractCategory contr_cat = ccat_sym_contr.Item1;
string symbol = ccat_sym_contr.Item2;
ViewStream settl_str = new OHLCVStream(symbol);
// TODO: close != settlement, get settlement from somewhere
ViewStream rs = new NewProjectStream(settl_str, "close:settlement");
switch (contr_cat) {
case ContractUtils.ContractCategory.FutureString:
case ContractUtils.ContractCategory.SpreadString:
rs = new FilterStream(settl_str, r => r.get<string>("contract").CompareTo(symbol_or_contract) == 0);
break;
case ContractUtils.ContractCategory.Symbol:
rs = new FuturesActiveContractStream(settl_str);
break;
}
if (DateTime.MinValue.Equals(end_dt)) {
rs = new FilterStream(rs, r => r.get_datetime("ts_event").CompareTo(begin_dt) == 0);
}
rs = new FilterStream(rs, r => {
DateTime dt = r.get_datetime("ts_event");
return dt <= begin_dt && dt >= end_dt;
});
rs = new MathStream(rs, "settlement = close * 1.0");
rs = new NewProjectStream(rs, " ! ts_event:date settlement");
public SettlementPriceStream(string future_contract, DateTime begin_dt, DateTime end_dt) {
ContractUtils.FutureContract fc = new ContractUtils.FutureContract(future_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);
}
@@ -0,0 +1,276 @@
# **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,9 +2,13 @@
"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 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",
"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.",
"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)"
@@ -41,70 +45,82 @@
},
{
"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, datetime1, datetime2). 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 argument is where the VWAP has to be calculated (also the beginning of the time window), and the third argument is datetime specifying the end of the time window. So, for example, a 20-day VWAP on 9/30/2023, the first argument will be 9/30/2023, and the third argument will be 9/10/2023 (20 days prior). This will also have datetimes expressed as Today, Yesterday, Last Friday, Last Sunday, etc. For the purpose of this few-shot prompts, let's assume today is 10/11/2024.",
"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. ",
"prompt": "What was the VWAP for SP 500 Future over the past 30 days?",
"examples": [
{
"natural_language": "Find the 20 day VWAP of the SP future on 04/22/2023.",
"dsl": "VWAP(\"ES\", 4/22/2023, 4/02/2023)"
"dsl": "VWAP(\"ES\", 4/02/2023, 4/22/2023)"
},
{
"natural_language": "Find Yesterday's 10 day VWAP of the Crude Oil Future.",
"dsl": "VWAP(\"CL\", 10/10/2024, 10/1/2024)"
"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 today's 30-day VWAP of the 10 year treasury future.",
"dsl": "VWAP(\"ZN\", 10/11/2024, 9/11/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 the 10 hour VWAP of the Natural Gas future from yesterday at 5:00 PM.",
"dsl": "VWAP(\"NG\", 9/27/2024 17:00:00, 9/27/2024 7:00:00)"
"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": "Price Diff",
"description": "This is a few shot learning example for an NL to DSL. The DSL function in question is OHLCVPriceDiff (symbol_or_contract, datetime1, datetime2). 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 and third arguments are dates, that the function finds the difference of prices at. Assume today is 10/15/2024",
"prompt": "What is the difference in SP 500 Future from July 10th to July 14th?",
"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?)",
"examples": [
{
"natural_language": "What is the difference in ZN price from July 10th to July 14th?",
"dsl": "OHLCVPriceDiff(\"ZN\", 7/14/2024, 7/10/2024)"
"dsl": "FuturePriceDiff(\"ZN\", 7/10/2024, 7/14/2024)"
},
{
"natural_language": "What is the price difference in SP Future price from Sept 10th and Sept 5th?",
"dsl": "OHLCVPriceDiff(\"ES\", 9/10/2024, 9/5/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 Natural Gas Dec Future price from Aug 30th and Aug 20th?",
"dsl": "OHLCVPriceDiff(\"NGZ4\", 8/30/2024, 8/20/2024)"
"dsl": "FuturePriceDiff(\"NGZ4\", 8/20/2024, 8/30/2024)"
},
{
"natural_language": "What is the price move in SP 500 Future from Aug 30th 2023 to October 10th 2023",
"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",
"dsl": "FuturePriceDiff(\"ES\", 1/1/2023, 3/31/2023)"
}
]
},
{
"category": "Absolute Volume",
"description": "this is a few shot learning example for an NL to DSL. The DSL function in question is AbsVolume(symbol, ContractType, 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. For this prompt, assume today is 10/11/2024 ",
"prompt": "Which SP 500 Future traded the most between 7/14/2024 and 7/10/2024",
"category": "Contract 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",
"examples": [
{
"natural_language": "Which SP Future traded the most between 7/14/2024 and 7/10/2024",
"dsl": "AbsVolume(\"ES\", \"Future\", 7/14/2024, 7/10/2024)"
"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)"
},
{
"natural_language": "Which Gold Spread traded the most between Today and Sept 20th",
"dsl": "AbsVolume(\"GC\", \"FutureSpread\", 10/1/2024, 9/20/2024)"
"natural_language": "Which Gold Spread traded the most in the first month of this year",
"dsl": "VolumeAgg(\"GC\", \"FutureSpread\", 1/1/2024, 1/31/2024)"
},
{
"natural_language": "Which 10 year Spread traded the highest volume last week?",
"dsl": "AbsVolume(\"ZN\", \"FutureSpread\", 9/27/2024, 9/23/2024)"
"natural_language": "Which 10 year Spread traded the highest volume last week to now?(in this example(only) we are assuming today is 11/26/2024)",
"dsl": "VolumeAgg(\"ZN\", \"FutureSpread\", 11/19/2024, 11/26/2024)"
},
{
"natural_language": "Which Corn Spread traded the most today?",
"dsl": "AbsVolume(\"ZC\", \"FutureSpread\", 10/1/2024, 10/1/2024)"
},
{
"natural_language": "Which Gold Future traded the most today?",
"dsl": "AbsVolume(\"GC\", \"Future\", 9/30/2024, 9/30/2024)"
"natural_language": "Which Corn Spread traded the most today (in this example(only) we are assuming today is 11/26/2024)?",
"dsl": "VolumeAgg(\"ZC\", \"FutureSpread\", 11/26/2024, 11/26/2024)"
}
]
},
@@ -114,8 +130,8 @@
"prompt": "When does the roll typically occur In SP 500?",
"examples": [
{
"natural_language": "When does the roll typically occur In CL?",
"dsl": "FuturesRoll(\"CL\")"
"natural_language": "When does the roll typically occur In SP 500?",
"dsl": "FuturesRoll(\"ES\")"
},
{
"natural_language": "When does the roll typically occur for 10 year treasury?",
@@ -159,8 +175,8 @@
]
},
{
"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 ",
"category": "Open Interest",
"description": "This is a few shot learning example for an NL to DSL.",
"prompt": "When does the most open interest typically shift from one contract to another in SP 500 Future?",
"examples": [
{
@@ -218,6 +234,17 @@
"dsl": "r=standardDeviation(\"ZN\", \"30d\")\nr=math(r, \"abs_daily_change = Abs(close - open) comp = std_dev * 2.0\")\nr=filter(r,\"abs_daily_change >= comp\")"
}
]
},
{
"category": "Price Movement",
"description": "This is a few shot learning example for an NL to DSL. In the NL prompt the user is asking for the average price movement for e-minis (aka ES aka SP Futures aka SP 500 Futures)) on Wednesday between 9:30 am and 9:40 AM? the multiline DSL is as follows (along with the explaination in comments before each line, dont include the comments in the asnwer): //following line gets the 1 min ohlcv bars of ES \n r=OHLCV_1min_stream(\"ES\")\n //this passes it to the filter stream, which filters the rows for Wednesday, and time bw 9:30 and 9:40.\nr=filter(r,\"ts_event_day = 'Wednesday' and ts_event_hour = 9 and ts_event_min >= 30 and ts_event_min < 40\")\n// this aggregates it using the date as the agregation key, it find the max of the column called high, and the low of the column called min, to find the max and the min prices in that time window\nr=aggregate(r, \"ts_event_date\", \"high: max, low: min\")\n/// this then passes the previous result to the math stream operator which calculates the move, which is the difference between high_max and low_min (columns that were added from the previous aggregate)\nr=math(r,\"move = high_max - low_min\")\n// At the end we compute the mean of the move column, notice this is the total mean, so we are not providing an aggregation col to agregate\nr=aggregate(r, \"move:mean\")\n// we project out every col by the ! operator and call rename move_mean as average_vol\nr=newProject(r,\"move_mean:average_move !\")",
"prompt": "What is the average price movement for SP Futures (ES) on Wednesday between 9:30 am and 9:40 AM ?",
"examples": [
{
"natural_language": "What is the average price movement for SP Futures (ES) on Wednesday between 9:30 am and 9:40 AM?",
"dsl": "r=OHLCV_1min_stream(\"ES\")\nr=filter(r,\"ts_event_day = 'Wednesday' and ts_event_hour = 9 and ts_event_min >= 30 and ts_event_min < 40\")\nr=aggregate(r, \"ts_event_date\", \"high: max, low: min\")\nr=math(r,\"move = high_max - low_min\")\nr=aggregate(r, \"move:mean\")\nr=newProject(r,\"move_mean:average_move !\")"
}
]
}
]
}
@@ -1,4 +1,4 @@
namespace sbts.SilverPine {
namespace bts.SilverPine {
using BCG;
using bts;
+1 -1
View File
@@ -105,4 +105,4 @@ add_custom_command(
add_custom_target(admin_web_app_bundle ALL DEPENDS ${CMAKE_CURRENT_BINARY_DIR}/bundle.js)
install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" DESTINATION "${SPARK_INSTALL_PREFIX}/bin")
install(DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}" DESTINATION "${CMAKE_INSTALL_BINDIR}")
+6 -1
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.SIM; |]
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 securityTypes = [| SecurityType.SPOT; SecurityType.FUTURE; SecurityType.OPTION; SecurityType.SPREAD; |]
@@ -74,6 +74,11 @@ type TaifexExchangeField =
| Origin of CustomerOrFirm
| ClearingAccount of string
type TwseExchangeField =
| CTI of CTICode
| Origin of CustomerOrFirm
| ClearingAccount of string
type SIMExchangeField =
| CTI of CTICode
| Origin of CustomerOrFirm
@@ -800,6 +800,7 @@ 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
@@ -1,41 +0,0 @@
// using System;
// using System.Collections.Generic;
// using System.Linq;
// using System.Text;
// namespace BCG
// {
// public class DateTimeFormatter
// {
// private delegate string MyFormatDateTime (DateTime v);
// public enum ExpirationShortForms
// {
// DayMonthYearDiff2000,
// MonthYearDiff2000
// }
// public enum DateTimeFormats { Regular, ShortDate, DayMonthYearDiff2000, MonthYearDiff2000 }
// private static Dictionary<string, MyFormatDateTime> _local_formats = null;
// private static void _init()
// {
// if (_local_formats == null)
// {
// _local_formats = new Dictionary<string, MyFormatDateTime>();
// _local_formats.Add(DateTimeFormats.Regular.ToString(), v => v.ToString());
// _local_formats.Add(DateTimeFormats.ShortDate.ToString(), v => v.ToShortDateString());
// _local_formats.Add(DateTimeFormats.DayMonthYearDiff2000.ToString(),
// (DateTime v) => { return String.Format("{0} {1}{2}", v.Day, BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); });
// _local_formats.Add(DateTimeFormats.MonthYearDiff2000.ToString(),
// (DateTime v) => { return String.Format("{0}{1}", BCG.Utilities.Dates.DateCode.getMonthSymbol(v.Month), v.Year - 2000); });
// }
// }
// public static string format(DateTime val, string format)
// {
// _init ();
// MyFormatDateTime f = null;
// if (_local_formats.TryGetValue(format, out f))
// return f(val);
// else
// return val.ToString(format);
// }
// }
// }
@@ -111,6 +111,7 @@ namespace bts.api {
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")
};
@@ -158,6 +159,7 @@ namespace bts.api {
domain.Venue.Okx => Venue.Okx,
domain.Venue.Cboe => Venue.Cboe,
domain.Venue.Taifex => Venue.Taifex,
domain.Venue.Twse => Venue.Twse,
domain.Venue.Unspecified => Venue.Unset,
@@ -178,6 +180,7 @@ 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(),
@@ -0,0 +1,61 @@
{
"user": "bts",
"pubsub": {
"milliseconds_between_sub_info_updates": 1000,
"milliseconds_between_time_slice_updates": 5000,
"milliseconds_between_no_buffer_space_retries": 100,
"retries_on_no_buffer_space": 1,
"do_it_all_seconds_between_logs": 0,
"heartbeat_interval": 15000,
"missing_heartbeats_before_gc": 50,
"use_managed_sockets": true,
"state_update_period": 5000,
"statistics_update_period": 5000,
"disposed_connection_check_period": 1000,
"message_processing_warning_threshold": 1000,
"server_port": 12345,
"publisher_routes": [
{
"name": "default",
"server_address": "bts-cloud://localhost:12345",
"tag": ".*"
}
],
"subscriber_routes": [
{
"name": "default",
"server_address": "bts-cloud://localhost:12345",
"tag": ".*"
}
],
"max_packet_size": 500000000,
"blue_comm_must_die": true,
"crushable_tags": [],
"tag_type_to_assembly_map": [
{
"handler_class": "BCG.PubSubServerTagHandler",
"assembly": "DataStreamCore.dll"
}
],
"server_queue": "PubSubQueue",
"port_range": {
"first": 30400,
"last": 31700
},
"bind_to_random_port": false,
"debug_tags": "^NOTAGS$",
"latency_report_threshold_ms": 1500,
"use_substations": false,
"use_dynamic_clients": false,
"is_substation": false,
"internally_publish_sub_info": true,
"use_managed_clients_in_native_code": false,
"compressed_tags": "^NOTAGS$",
"tags_to_report_compression_ratio": "^NOTAGS$",
"disable_msmq": false,
"use_prepublished_server_state": false,
"ip_translation": null,
"gc_activation_threshold": 0,
"wait_period_after_gc": 1000
}
}
+18 -1
View File
@@ -1,4 +1,7 @@
namespace spark_api_server {
using BCG;
using Bts.PubSub;
using Bts.Websocket;
using bts;
@@ -29,8 +32,11 @@
static async Task<int> _run(RunOptions opts) {
Console.WriteLine("Starting spark_api_server... ");
opts.MergeWithConfigFile();
opts.MergeWith(RunOptions.Default());
Log.notnull(opts.user);
Log.notnull(opts.password);
PubSubConfig.SetGlobalConfig(Log.notnull(opts.PubSub));
var service_ctx = ServiceContext.create(opts.sparkd);
await service_ctx.login(opts.user, opts.password);
@@ -67,6 +73,14 @@
}
});
var vsdTask = Task.Run(() => {
Log.Gen.info("Starting ViewStreamDatabase work loop");
var cancellationToken = cancellationTokenSource.Token;
while (!cancellationToken.IsCancellationRequested) {
ViewStreamDatabase.instance.doWork();
Thread.Sleep(100);
}
}, cancellationTokenSource.Token);
// var task = Task.Run(() => {
// while (!cancellationTokenSource.IsCancellationRequested) {
// // Do something that can be interrupted
@@ -76,8 +90,11 @@
// Console.WriteLine("Press any key to stop the server...");
// Console.ReadKey();
// cancellationTokenSource.Cancel();
await Task.WhenAny(listen);
await Task.WhenAny(listen, vsdTask);
//UPTILL HERE
// These tasks aren't designed to finish naturally. If the code reaches here, it means one
// of them threw an exception. Cancel the other task to exit (somewhat) gracefully.
cancellationTokenSource.Cancel();
return (int)errors;
}
}
+46
View File
@@ -1,6 +1,13 @@
namespace Spark.Api.Server {
using Bts.PubSub;
using CommandLine;
using System;
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
[Verb("run")]
public class RunOptions {
[Option("user", Default = CommonOptionMetadata.DEFAULT_USER)]
@@ -14,5 +21,44 @@ namespace Spark.Api.Server {
MetaValue = CommonOptionMetadata.SPARKD_META_VALUE,
HelpText = CommonOptionMetadata.SPARKD_HELP_TEXT)]
public string? sparkd { get; set; }
[JsonPropertyName("pubsub")]
public PubSubConfig? PubSub { get; set; }
[JsonIgnore]
[Option(
"config",
MetaValue = "PATH",
HelpText = "Path to json file representing these options (RunOptions)")]
public string? ConfigFile { get; set; }
public static RunOptions Default() =>
new() {
PubSub = PubSubConfig.Default(),
};
public void MergeWith(RunOptions other) {
sparkd ??= other.sparkd;
PubSub ??= other.PubSub;
ConfigFile ??= other.ConfigFile;
}
/// <summary>
/// Merges options with those defined in `ConfigFile` (does not overwrite
/// non-null existing values).
/// </summary>
/// <exception cref="InvalidOperationException">
/// JsonSerializer.Deserialize returns null
/// </exception>
public void MergeWithConfigFile() {
if (ConfigFile is null) {
return;
}
var cfgString = File.ReadAllText(ConfigFile);
var parsedCfg = JsonSerializer.Deserialize<RunOptions>(cfgString) ??
throw new InvalidOperationException($"Failed to parse json from {ConfigFile}");
MergeWith(parsedCfg);
ConfigFile = null;
}
}
}
@@ -1,14 +1,21 @@
namespace bts.websocket_core {
using BCG;
using bts.api;
using bts.api.orderman;
using bts.md;
using Bts.DataStream;
using Bts.DataStreamCore;
using Bts.DataStreamExpressions;
using mbts.spark;
using Newtonsoft.Json.Linq;
using Spark.Api.MarketData;
using Spark.Api.Orders;
using Spark.Core.Collections;
using System;
using System.Diagnostics.CodeAnalysis;
@@ -22,6 +29,7 @@ namespace bts.websocket_core {
PRICE_STATS,
PRICE_TICKERS,
FILLS,
DATA_STREAM,
UNKNOWN = 0
}
public bool Valid { get; set; } = true;
@@ -91,6 +99,47 @@ namespace bts.websocket_core {
hdlr.SendMessage(WebsocketJsonParsers.to_json<OrderRecordTupleWithRoot, uint>(upd)));
};
}
private static Action<WebsocketSubscriptionHandler> GetDataStreamSubscriber(ViewStream vs, string subId) {
return Subscribe;
void Subscribe(WebsocketSubscriptionHandler hdlr) {
// Declare dictionaries here to reduce allocations in the callback. Use a lock
// to be safe (callbacks are likely single-threaded, this is just insurance).
var syncRoot = new object();
var removedRows = new Dictionary<int, object>();
var changedRows = new Dictionary<int, object>();
var addedRows = new Dictionary<int, object>();
hdlr.dis = vs.AsObservable().Subscribe(OnData);
void OnData(DataPacket dp) {
lock (syncRoot) {
removedRows.Clear();
changedRows.Clear();
addedRows.Clear();
foreach (IBlueRow r in dp.deletedRows) {
var id = r.Id();
removedRows[id] = r;
}
foreach (IBlueRow r in dp.addedRows) {
var id = r.Id();
if (removedRows.Remove(id)) {
changedRows.Add(id, r);
} else {
addedRows.Add(id, r);
}
}
hdlr.SendMessage(new {
added = addedRows.Values,
changed = changedRows.Values,
removed = removedRows.Values,
});
}
}
}
}
private static Action<WebsocketSubscriptionHandler> GetFillsSubscriber(FillsSubscriptionFilter cri) {
return (WebsocketSubscriptionHandler hdlr) => {
hdlr.dis = hdlr._OrdersClient.fills(cri).Subscribe(
@@ -149,6 +198,39 @@ namespace bts.websocket_core {
return true;
}
static bool TryGetDataStream(
WebsocketRequest req,
[NotNullWhen(true)] out ViewStream? stream,
[NotNullWhen(false)] out string error
) {
stream = null;
error = "";
var query = (req.parameters?["query"] as JValue)?.Value<string>();
if (query is null) {
error = "'params.query' field not found (expected a string)";
return false;
}
var exp = DataStreamExpressionsInterpreter.Evaluate(query);
if (exp is null) {
error = "'params.query' expression has invalid syntax";
return false;
}
Exception? exception = null;
try {
stream = exp.getView(new Dictionary<string, StatementExpression>(0));
} catch (Exception ex) {
exception = ex;
}
if (stream is null) {
error = "Failed to create ViewStream from 'params.query' expression (check for typos in arguments/typenames)";
if (exception is not null) {
error += ". " + exception.Message;
}
return false;
}
return true;
}
static bool TryGetFilter(WebsocketRequest req, [NotNullWhen(true)] out SecurityCriteria? cri, out string message) {
cri = null;
if (req.parameters?["filter"] is not JObject filter) {
@@ -183,10 +265,13 @@ namespace bts.websocket_core {
}
public static bool TryCreate(
WebsocketRequest req, MarketDataClient md, OrdersClient oc,
WebsocketRequest req,
MarketDataClient md,
OrdersClient oc,
Action<Object> sm,
[NotNullWhen(true)] out WebsocketSubscriptionHandler? hdlr,
out string status) {
out string status
) {
hdlr = null;
if (
@@ -247,6 +332,14 @@ namespace bts.websocket_core {
sub = GetOrdersSubscriber(filter);
break;
}
case SUBSCRIPTION_TYPE.DATA_STREAM: {
// TODO: make this nullable
if (!TryGetDataStream(req, out var filter, out status)) {
return false;
}
sub = GetDataStreamSubscriber(filter, id.Value.Val);
break;
}
default: {
status = "Incorrect subscription type";
return false;
@@ -19,13 +19,15 @@
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="System.Net.WebSockets" Version="4.3.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="Microsoft.AspNetCore.Cors" Version="2.2.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\spark_core\spark_core.csproj" />
<ProjectReference Include="..\spark_api\spark_api.csproj" />
<ProjectReference Include="..\..\DataStreamSuite\DataStream\DataStream.csproj" />
<ProjectReference Include="..\..\DataStreamSuite\SharedStreams\SharedStreams.csproj" />
</ItemGroup>
<ItemGroup>
+2 -3
View File
@@ -1,6 +1,7 @@
cmake_minimum_required(VERSION 3.5)
project(libspark)
set(CMAKE_SHARED_LIBRARY_PREFIX "")
include(GNUInstallDirs)
include(${CMAKE_SOURCE_DIR}/cmake/safe_dep_glob.cmake)
include(${CMAKE_SOURCE_DIR}/cmake/Protobuf.cmake)
include(${CMAKE_CURRENT_SOURCE_DIR}/cmake/GenerateDefaultConfig.cmake)
@@ -71,9 +72,7 @@ if (DEFINED DOTNET_WINDOWS_BINARY_DIR)
"Copy ${PROJECT_NAME} bins to Dotnet Windows build dir")
endif()
if(BUILD_SPARKD)
install(TARGETS ${PROJECT_NAME} DESTINATION "${SPARK_INSTALL_PREFIX}/bin")
endif()
install(TARGETS ${PROJECT_NAME} DESTINATION "${CMAKE_INSTALL_BINDIR}")
if(WIN32)
include(${CMAKE_SOURCE_DIR}/cmake/vs_filters.cmake)
+1
View File
@@ -27,4 +27,5 @@ enum Venue {
VENUE_OKX = 15;
VENUE_TAIFEX = 16;
VENUE_CBOE = 17;
VENUE_TWSE = 18;
}
+2
View File
@@ -12,6 +12,7 @@ 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";
@@ -29,6 +30,7 @@ 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,6 +23,8 @@ 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;
@@ -9,7 +9,9 @@ option cc_enable_arenas = true;
// Config to control the recording of the market data for an exchange.
// This config is part of MarketDataConfig.proto
message MarketDataRecordingConfig {
uint32 num_of_seconds_to_run = 10;
uint32 num_of_seconds_to_run_file_writer=12;
uint32 num_of_seconds_to_run_db_writer=13;
bts.api.Venue venue = 20;
uint32 n_book_levels = 30;
uint32 batch_size = 40;
}
+19
View File
@@ -0,0 +1,19 @@
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;
}
@@ -72,6 +72,7 @@ bool AdminServiceUtils::has_exchange(
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_:
@@ -187,6 +188,7 @@ AdminServiceUtils::resolve_connection(
case api::Venue::VENUE_BINANCE:
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: {
@@ -460,6 +462,7 @@ std::string AdminServiceUtils::find_account_exchange_account(
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_:
@@ -757,6 +760,7 @@ bts::api::orderman::RoutingRecord AdminServiceUtils::get_routing_record(
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_:
@@ -1152,6 +1156,7 @@ 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_:
@@ -1190,6 +1195,7 @@ 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:
@@ -19,6 +19,14 @@ SymbolLists {
symbol: "BTC"
symbol: "ETH"
}
list {
key: "TWSE"
symbol: "2330"
symbol: "2317"
symbol: "2454"
symbol: "2603"
symbol: "2615"
}
list {
key: "TAIFEX"
symbol: "QFFH"
@@ -59,6 +67,11 @@ 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
@@ -91,6 +104,11 @@ 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
@@ -125,6 +143,11 @@ 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
+10
View File
@@ -53,6 +53,8 @@ constexpr bool operator<(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr bool operator<=(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr bool operator>(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr bool operator>=(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan operator-(TimeSpan lhs, TimeSpan rhs) noexcept;
constexpr TimeSpan operator+(TimeSpan lhs, TimeSpan rhs) noexcept;
std::ostream &operator<<(std::ostream &out, const TimeSpan &ts) noexcept;
@@ -130,6 +132,14 @@ constexpr bool operator>=(TimeSpan lhs, TimeSpan rhs) noexcept {
return lhs.nanos() >= rhs.nanos();
}
constexpr TimeSpan operator-(TimeSpan lhs, TimeSpan rhs) noexcept {
return TimeSpan{lhs.nanos() - rhs.nanos()};
}
constexpr TimeSpan operator+(TimeSpan lhs, TimeSpan rhs) noexcept {
return TimeSpan{lhs.nanos() + rhs.nanos()};
}
} // namespace bts::core
FMT_IMPL(bts::core::TimeSpan, t, "{}", t.to_iso_string());
+7
View File
@@ -25,6 +25,8 @@ api::domain::Venue DomainSecurityUtils::convert(bts::api::Venue venue) {
return DOMAIN_VENUE(DERIBIT);
case bts::api::Venue::VENUE_CBOE:
return DOMAIN_VENUE(CBOE);
case bts::api::Venue::VENUE_TWSE:
return DOMAIN_VENUE(TWSE);
case bts::api::Venue::VENUE_TAIFEX:
return DOMAIN_VENUE(TAIFEX);
case bts::api::Venue::VENUE_BTS:
@@ -59,6 +61,8 @@ bts::api::Venue DomainSecurityUtils::convert(api::domain::Venue venue) {
return api::Venue::VENUE_DERIBIT;
case DOMAIN_VENUE(CBOE):
return api::Venue::VENUE_CBOE;
case DOMAIN_VENUE(TWSE):
return api::Venue::VENUE_TWSE;
case DOMAIN_VENUE(TAIFEX):
return api::Venue::VENUE_TAIFEX;
case DOMAIN_VENUE(FTX):
@@ -171,6 +175,9 @@ bool DomainSecurityUtils::get_security_desc(
case bts::api::Security::ExchangeDataCase::kCboe:
desc = security.cboe().security_desc();
break;
case bts::api::Security::ExchangeDataCase::kTwse:
desc = security.twse().security_desc();
break;
case bts::api::Security::ExchangeDataCase::kTaifex:
desc = security.taifex().security_desc();
break;
+2
View File
@@ -276,6 +276,8 @@ inline const std::string &descriptor(
return sec.coinbase().security_desc();
case api::Security::kOkx:
return sec.okx().security_desc();
case api::Security::kTwse:
return sec.twse().security_desc();
case api::Security::kTaifex:
return sec.taifex().security_desc();
default: {
+7
View File
@@ -20,6 +20,7 @@ enum Venue {
VENUE_COINBASE = 450;
VENUE_OKX = 460;
VENUE_TAIFEX = 500;
VENUE_TWSE = 600;
}
enum SecurityType {
@@ -87,6 +88,11 @@ message CBOEExchangeData {
int32 class_key = 30;
string source = 40;
}
message TWSEExchangeData {
int64 exchange_id = 10;
int32 class_key = 30;
string security_desc = 20;
}
message TAIFEXExchangeData {
int64 exchange_id = 10;
int32 class_key = 30;
@@ -233,6 +239,7 @@ message Security {
CoinbaseExchangeData coinbase = 290;
OkxExchangeData okx = 300;
TAIFEXExchangeData taifex = 400;
TWSEExchangeData twse = 500;
}
}
message SecurityList {
+383
View File
@@ -0,0 +1,383 @@
#include "websocket_client.h"
#include "lib/core/TimeSpan.h"
#include "lib/core/TimeStamp.h"
#include "lib/io/websocket/websocket_client_state.h"
#include "lib/io/websocket/websocket_close_status.h"
#include "lib/io/websocket/websocket_error_code.h"
#include "lib/io/websocket/websocketpp_exception_formatter.h"
#include "lib/logging/logging.h"
#include "lib/utils/formatters/exception_formatter.h"
#include <atomic>
#include <exception>
#include <fmt/format.h>
#include <mutex>
#include <nlohmann/json.hpp>
#include <optional>
#include <stdexcept>
#include <string>
#include <thread>
#include <websocketpp/close.hpp>
#include <websocketpp/common/connection_hdl.hpp>
#include <websocketpp/common/memory.hpp>
#include <websocketpp/common/system_error.hpp>
#include <websocketpp/common/thread.hpp>
#include <websocketpp/config/asio_client.hpp>
#include <websocketpp/config/core_client.hpp>
#include <websocketpp/roles/client_endpoint.hpp>
namespace bts::websocket {
struct WebsocketClientSnapshot {
int client_id;
WebsocketClientState state;
int version;
};
} // namespace bts::websocket
FMT_IMPL(
bts::websocket::WebsocketClientSnapshot,
t,
"id: {}; state: {}; version: {}",
t.client_id,
t.state,
t.version);
namespace bts::websocket {
using namespace std::chrono_literals;
using bts::core::TimeSpan;
using bts::core::TimeStamp;
using nlohmann::json;
using std::lock_guard;
using std::map;
using std::mutex;
using std::optional;
using std::size_t;
using std::string;
using std::thread;
using std::uint32_t;
using websocketpp::config::asio_tls_client;
using WebsocketppClient =
websocketpp::client<websocketpp::config::asio_tls_client>;
using ConnectionHdl = websocketpp::connection_hdl;
using ConnectionPtr = WebsocketppClient::connection_ptr;
using MessageTypePtr = websocketpp::config::core_client::message_type::ptr;
using SslContext = boost::asio::ssl::context;
using State = WebsocketClientState;
// ws endpoint http://markets.api.uat.cmegroup.com/marketdatastream/v1
#define _ASSERT_MSGF(condition, ...) \
bts_assert_msgf(condition, "WebsocketClient::" __VA_ARGS__)
#define DIAG(...) LOG(Gen, Diag, __VA_ARGS__)
#define DIAG_FN(...) LOG(Gen, Diag, "WebsocketClient::" __VA_ARGS__)
#define INFO(...) LOG(Gen, Info, __VA_ARGS__)
#define INFO_FN(...) LOG(Gen, Info, "WebsocketClient::" __VA_ARGS__)
#define WARN(...) LOG(Gen, Warn, __VA_ARGS__)
#define WARN_FN(...) LOG(Gen, Warn, "WebsocketClient::" __VA_ARGS__)
#define ERROR(...) LOG(Gen, Error, __VA_ARGS__)
#define ERROR_FN(...) LOG(Gen, Error, "WebsocketClient::" __VA_ARGS__)
struct WebsocketClient::PImpl {
string url;
WebsocketppClient client;
uint32_t timeout_secs;
WebsocketppClient::connection_ptr con;
optional<MessageHandler> message_handler;
size_t sub_id_counter{0};
string server_name;
optional<thread> io_thread;
int client_id{client_id_counter++};
mutex instance_mx;
State state;
int version = 0;
~PImpl() {
if (io_thread) {
io_thread->join();
}
}
int set_state(State state) {
if (this->state == state) {
return version;
}
version++;
INFO(
"State changing from {} -> {}. id: {}; version: {}", this->state,
state, client_id, version);
this->state = state;
return version;
}
constexpr WebsocketClientSnapshot snapshot() const {
return {client_id, state, version};
}
void close(websocketpp::close::status::value code, std::string reason) {
lock_guard<mutex> lock{instance_mx};
INFO_FN(
"close. {}; code: {}; reason: {}", snapshot(),
WebsocketCloseStatus{code}, reason);
switch (state.value) {
case State::OPENING:
WARN_FN(
"close. Cannot close while websocket is still opening. {}",
snapshot());
// Wait until we get the 'open' callback, then initiate the close
set_state(State::WAITING_TO_CLOSE);
return;
case State::OPEN:
set_state(State::CLOSING);
break;
default:
return;
}
websocketpp::lib::error_code ec;
client.close(con->get_handle(), code, reason, ec);
if (ec) {
ERROR_FN(
"close. {}; code: {}; reason: {}; error: {}", snapshot(),
WebsocketCloseStatus{code}, reason, ec);
}
}
websocketpp::lib::error_code send_text(const string &text) {
INFO_FN("send_text. {}; text: {}", snapshot(), text);
websocketpp::lib::error_code ec;
client.send(con, text, websocketpp::frame::opcode::value::TEXT, ec);
if (ec) {
ERROR_FN("send_text. {}; text: {}; err: {}", snapshot(), text, ec);
}
return ec;
}
/**
* Connects to the websocket server
*/
void connect(const map<string, string> &headers) {
connect_in_background(headers);
// Wait for connect
if (timeout_secs > 0) {
wait_for_connect(TimeSpan::from_seconds(timeout_secs));
}
}
/**
* Connects to the websocket server in the background.
*
* @note Doesn't block while waiting for the connection to be established
*/
void connect_in_background(const map<string, string> &headers) {
lock_guard<mutex> lock{instance_mx};
INFO_FN("connect_no_timeout. {}", snapshot());
switch (state.value) {
case State::IDLE:
break;
default:
WARN_FN("connect_no_timeout. Unexpected state. {}", snapshot());
return;
}
set_state(State::OPENING);
try {
init_logging();
init_handlers();
// Get connection
websocketpp::lib::error_code ec;
con = client.get_connection(url, ec);
if (ec) {
ERROR_FN("connect_no_timeout. {}; err: {}", snapshot(), ec);
return;
}
// Add headers
for (const auto &[k, v] : headers) {
con->append_header(k, v);
}
// Connect
client.connect(con);
bts_assert_msgf(
!io_thread, "Websocket io_thread already instantiated. {}",
snapshot());
io_thread = std::thread{[this]() {
INFO("Websocket io thread begin. {}", snapshot());
try {
client.run();
} catch (const websocketpp::exception &ex) {
ERROR_FN(
"io_thread. Websocket io threw websocketpp::exception. {}; "
"err: {}",
snapshot(), ex);
} catch (const std::exception &ex) {
ERROR_FN(
"io_thread. Websocket io threw std::exception. {}; err: {}",
snapshot(), ex);
} catch (...) {
bts_assert_msgf(
false,
"io_thread. Websocket io threw unknown exception. Could "
"this have been thrown by a callback delegate? {}",
snapshot());
}
INFO("Websocket 'run' thread end. {}", snapshot());
}};
} catch (const std::exception &ex) {
ERROR_FN(
"connect_no_timeout. Failed to connect. {}; err: {}", snapshot(),
ex);
set_state(State::IDLE);
// Don't wait for connect
return;
}
}
void wait_for_connect(const TimeSpan timeout) {
INFO_FN("wait_for_connect. {}; timeout: {}", snapshot(), timeout);
const auto start = TimeStamp::now();
while (state == State::OPENING) {
const auto elapsed = TimeStamp::now() - start;
const auto rem = timeout - elapsed;
if (rem < TimeSpan::zero()) {
throw std::runtime_error{fmt::format(
"Timed out waiting for connection after {} secs. {}",
elapsed.total_seconds(), snapshot())};
}
WARN_FN(
"wait_for_connect. Still waiting. {}; timeout: {}; rem: {}",
snapshot(), timeout, rem);
std::this_thread::sleep_for(std::chrono::seconds(1));
}
}
private:
static std::atomic<int> client_id_counter;
auto on_tls_init(ConnectionHdl /*hdl*/) {
INFO_FN("on_tls_init. state: {}; version: {}", state, version);
auto result =
websocketpp::lib::make_shared<SslContext>(SslContext::sslv23_client);
result->set_verify_mode(boost::asio::ssl::verify_none);
return result;
}
void init_handlers() {
INFO_FN("init_handlers. state: {}; version: {}", state, version);
bts_assert(!io_thread);
client.init_asio();
client.set_message_handler(
[this](auto hdl, auto msg) { on_message(hdl, msg); });
client.set_open_handler([this](auto hdl) { on_open(hdl); });
client.set_tls_init_handler(
[this](auto hdl) { return on_tls_init(hdl); });
client.set_close_handler([this](auto hdl) { on_close(hdl); });
client.set_fail_handler([this](auto hdl) {
const auto ec = client.get_con_from_hdl(hdl)->get_ec();
ERROR_FN("fail_handler. {}; err: {}", snapshot(), ec.message());
});
}
void init_logging() {
INFO_FN("init_logging. {}", snapshot());
client.set_access_channels(websocketpp::log::alevel::all);
client.clear_access_channels(websocketpp::log::alevel::frame_payload);
client.set_error_channels(websocketpp::log::elevel::all);
}
void on_open(ConnectionHdl hdl) {
lock_guard<mutex> lock{instance_mx};
INFO_FN("on_open. {}", snapshot());
const auto ec = client.get_con_from_hdl(hdl)->get_ec();
if (ec) {
ERROR_FN("on_open. {}; err: {}", snapshot(), ec.message());
}
switch (state.value) {
case State::OPENING:
break;
default:
WARN_FN("on_open. Unexpected state. {}", snapshot());
return;
}
set_state(State::OPEN);
}
void on_message(ConnectionHdl /*hdl*/, MessageTypePtr msg) {
DIAG("on_message. {}", snapshot());
const auto &payload = msg->get_payload();
if (message_handler) {
(*message_handler)(payload);
return;
}
ERROR_FN(
"on_message. Message handler is null. {}; payload: \n{}", snapshot(),
payload);
}
void on_close(ConnectionHdl hdl) {
lock_guard<mutex> lock{instance_mx};
INFO_FN("on_close. {}", snapshot());
switch (state.value) {
case State::CLOSING:
break;
default:
WARN_FN("on_close. Unexpected state. {}", snapshot());
break;
}
set_state(State::IDLE);
const auto con = client.get_con_from_hdl(hdl);
const auto ec = con->get_ec();
if (ec) {
ERROR_FN(
"on_close. {}; local_code: {}; "
"local_reason: {}; remote_code: {}; remote_reason: {}; err: {}",
snapshot(), con->get_local_close_code(),
con->get_local_close_reason(), con->get_remote_close_code(),
con->get_remote_close_reason(), ec.message());
}
}
};
WebsocketClient::WebsocketClient(std::string url, std::uint32_t timeout_secs)
: me_(std::make_unique<PImpl>()) {
me_->url = std::move(url);
me_->timeout_secs = timeout_secs;
}
WebsocketClient::~WebsocketClient() {
me_->close(websocketpp::close::status::going_away, "");
}
std::atomic<int> WebsocketClient::PImpl::client_id_counter = 0;
WebsocketClient::MessageHandler &WebsocketClient::message_handler() {
if (!me_->message_handler) {
me_->message_handler.emplace();
}
return *me_->message_handler;
}
void WebsocketClient::connect(
const std::map<std::string, std::string> &headers) {
me_->connect(headers);
}
websocketpp::lib::error_code WebsocketClient::send_text(const string &text) {
return me_->send_text(text);
}
void WebsocketClient::disconnect() {
me_->close(
websocketpp::close::status::going_away,
"WebsocketClient::disconnect was called");
}
bool WebsocketClient::is_connected() const {
lock_guard<mutex> lock{me_->instance_mx};
return me_->state == State::OPEN;
}
} // namespace bts::websocket
+32
View File
@@ -0,0 +1,32 @@
#pragma once
#include "lib/utils/Delegate.h"
#include <memory>
#include <string>
#include <websocketpp/config/core_client.hpp>
#include <websocketpp/message_buffer/message.hpp>
namespace bts::websocket {
class WebsocketClientConfig;
class WebsocketClient {
public:
WebsocketClient(std::string url, std::uint32_t timeout_secs = 20);
~WebsocketClient();
using MessageHandler = bts::core::Delegate<void(const std::string &)>;
void connect(const std::map<std::string, std::string> &headers = {});
void disconnect();
bool is_connected() const;
MessageHandler &message_handler();
websocketpp::lib::error_code send_text(const std::string &text);
private:
struct PImpl;
std::unique_ptr<PImpl> me_;
};
} // namespace bts::websocket
@@ -0,0 +1,25 @@
#pragma once
#include "lib/core/EnumMacros.h"
#include "lib/core/FMT_IMPL.h"
#include <nlohmann/json.hpp>
namespace bts::websocket {
// clang-format off
#define FOR_ALL_VALUES(op) \
op(WebsocketClientState, IDLE) \
op(WebsocketClientState, OPENING) \
op(WebsocketClientState, OPEN) \
op(WebsocketClientState, WAITING_TO_CLOSE) \
op(WebsocketClientState, CLOSING)
// clang-format on
ENUM_CLASS_DEF(WebsocketClientState, FOR_ALL_VALUES);
#undef FOR_ALL_VALUES
} // namespace bts::websocket
FMT_IMPL(bts::websocket::WebsocketClientState, s, "{}", s.name());
@@ -0,0 +1,24 @@
#pragma once
#include "lib/core/FMT_IMPL.h"
#include "lib/utils/ValueWrapper.h"
#include <websocketpp/close.hpp>
namespace bts::websocket {
/**
* Simple wrapper to provide a means implement a custom formatter for
* `websocketpp::close::status::value` (an alias for a primitive numeric type)
*/
using WebsocketCloseStatus = utils::ValueWrapper<
struct WebsocketCloseStatusTag,
websocketpp::close::status::value>;
} // namespace bts::websocket
FMT_IMPL(
bts::websocket::WebsocketCloseStatus,
s,
"{}",
websocketpp::close::status::get_string(*s));
@@ -0,0 +1,7 @@
#pragma once
#include "lib/core/FMT_IMPL.h"
#include <websocketpp/common/system_error.hpp>
FMT_IMPL(websocketpp::lib::error_code, ec, "{}", ec.message());
@@ -0,0 +1,7 @@
#pragma once
#include "lib/core/FMT_IMPL.h"
#include <websocketpp/error.hpp>
FMT_IMPL(websocketpp::exception, e, "{}", std::string{e.what()});
+162 -4
View File
@@ -22,6 +22,7 @@
#include "lib/domain/TradeRecord.h"
#include "lib/domain_model/Security.pb.h"
#include "lib/domain_model/common.h"
#include "lib/io/JsonDumper.h"
#include "lib/logging/logging.h"
#include "lib/md/GeneralSecurityIndex.h"
#include "lib/md/IMarketDataListener.h"
@@ -128,8 +129,19 @@ bool update_incremental(const IMarketDataListener::BookOp &op) {
case IMarketDataListener::BookOpType::Add:
{
int insert_position = 0;
for (size_t i = 0; i < book_side.size(); i++){//not sure how to access book
if(book_side[i].price != 0 && book_side[i].price > op.price ){
for (size_t i = 0; i < book_side.size();
i++) { //not sure how to access book
if (book_side[i].price == op.price) {
IMarketDataListener::BookOp new_op;
new_op.id = op.id;
new_op.op_type = IMarketDataListener::BookOpType::MODIFY;
new_op.price = op.price;
new_op.quantity = op.quantity;
new_op.side = op.side;
return update_incremental(new_op);
}
if (book_side[i].price != 0 && book_side[i].price > op.price) {
//book_side is the book we have ?
//op.price is what we received ?
insert_position++;
@@ -183,6 +195,16 @@ bool update_incremental(const IMarketDataListener::BookOp &op) {
case IMarketDataListener::BookOpType::Add:{
int insert_position = 0;
for (int i = 0; i < fmin(book_side.size(),5); i++) {
if (book_side[i].price == op.price) {
IMarketDataListener::BookOp new_op;
new_op.id = op.id;
new_op.op_type = IMarketDataListener::BookOpType::MODIFY;
new_op.price = op.price;
new_op.quantity = op.quantity;
new_op.side = op.side;
return update_incremental(new_op);
}
if (book_side[i].price != 0 && book_side[i].price < op.price) {
insert_position++;
continue;
@@ -471,21 +493,157 @@ void GeneralMarketDataListener::on_book_increment(
bts_assert(book_ptr != nullptr);
_on_book(*book_ptr);
}
co2::AggressorSide try_fill_agg_side(
const domain::Price &trade_price,
const co2::AggressorSide &current_side,
const domain::Book *book,
const domain::SecurityID &id) {
if (current_side != co2::AGGRESSOR_SIDE_NONE)
return current_side;
if (!book) {
LOG(md, Info,
"No book found for sec_id: {}. Processing trade with aggressor "
"side set to NONE.",
id);
return current_side;
}
// Access ask-side and bid-side levels
auto book_ask_side = book->asks();
auto book_bid_side = book->bids();
if (book_ask_side.is_populated() &&
trade_price >=
book_ask_side[0]
.price) //this means the trade happened on the ask side
{
LOG(md, Info, "Trade Price: {}, Book_Ask[0] Price: {}", trade_price,
book_ask_side[0].price);
return co2::AGGRESSOR_SIDE_BUY;
}
if (book_bid_side.is_populated() &&
trade_price <=
book_bid_side[0]
.price) //this means the trade happened on the bid side
{
LOG(md, Info, "Trade Price: {}, Book_Ask[0] Price: {}", trade_price,
book_bid_side[0].price);
return co2::AGGRESSOR_SIDE_SELL;
}
std::string book_str =
"Bids: " + bts::io::JsonDumper::dump(book_bid_side, 2) +
"\nAsks: " + bts::io::JsonDumper::dump(book_ask_side, 2);
LOG(md, Info,
"Could not determine Aggressor, Trade Price: {}, Current Book: {}",
trade_price, book_str);
return co2::AGGRESSOR_SIDE_NONE;
}
void GeneralMarketDataListener::on_trades(
const std::vector<domain::TradeRecord const *> &trades) {
for (auto tp : trades) {
auto handle = _find_handle(tp->sec_id);
std::ostringstream log_stream;
// Log the important fields from the TradeRecord pointer
log_stream << "TradePointer - sec_id: " << tp->sec_id
<< ", agg_side: " << tp->agg_side
<< ", trade_price: " << tp->trade_price
<< ", trade_quantity: " << tp->trade_quantity.value()
<< ", time_stamp: " << tp->time_stamp.millis();
// Log the trade data
LOG(md, Diag, "logging tp {}", log_stream.str());
auto handle =
_find_handle(tp->sec_id); // might be the reason behind missing trades
auto aggressor_side = convert_agg_side(tp->agg_side);
// Log the initial aggressor_side
LOG(md, Diag, "Initial aggressor side for sec_id: {} is: {}", tp->sec_id,
static_cast<int>(aggressor_side));
if (handle == nullptr) {
LOG(md, Info, "No handle found for sec_id: {}", tp->sec_id);
continue;
}
aggressor_side = try_fill_agg_side(
tp->trade_price, aggressor_side,
me->inc_book_data.get_const_book(tp->sec_id), tp->sec_id);
auto trade_ts = datetime::ll_from_unix_epoch_ms(tp->time_stamp.millis());
// Process the trade even if aggressor_side is NONE
if (handle != nullptr) {
handle->handle.add_trade(
utils::TimeStamp::now(),
PriceSize(
convert_price(tp->trade_price), tp->trade_quantity.value()),
trade_ts, convert_agg_side(tp->agg_side), 0, false);
trade_ts, aggressor_side, 0, false);
LOG(md, Diag, "Trade processed for sec_id: {}", tp->sec_id);
}
}
}
//Needed for diag for trade gaps
// void GeneralMarketDataListener::on_trades(
// const std::vector<domain::TradeRecord const *> &trades) {
// for (auto tp : trades) {
// for (auto tp : trades) {
// std::ostringstream log_stream;
// // Log the important fields from the TradeRecord pointer
// log_stream << "TradePointer - sec_id: " << tp->sec_id
// << ", agg_side: " << tp->agg_side
// << ", trade_price: " << tp->trade_price
// << ", trade_quantity: " << tp->trade_quantity.value()
// << ", time_stamp: " << tp->time_stamp.millis();
// // Log the trade data
// LOG(md, Info, "logging tp {}",log_stream.str());}
// auto handle =
// _find_handle(tp->sec_id); //might be the reason behind missing trades
// auto aggressor_side = convert_agg_side(tp->agg_side);
// if (aggressor_side == co2::AggressorSide::AGGRESSOR_SIDE_NONE) {
// auto book = me->inc_book_data.get_const_book(tp->sec_id);
// // Check if the book is empty
// if (!book) {
// LOG(md, Info, "book pointer log");
// LOG(md, Info, "Processing trade with sec_id: {}", tp->sec_id);
// aggressor_side =
// co2::AggressorSide::AGGRESSOR_SIDE_NONE; // Reset aggressor side
// continue; // Skip processing this trade
// }else {
// LOG(md, Info, "Book found for sec_id: {} with size: {}", tp->sec_id, book->size());
// }
// // Access ask-side and bid-side levels
// auto book_ask_side = book->asks();
// auto book_bid_side = book->bids();
// if (!book_ask_side.is_populated() || !book_bid_side.is_populated()) {
// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_NONE; // Reset
// continue; // Skip processing this trade
// }
// // Determine aggressor side based on trade price
// if (tp->trade_price <= book_ask_side[0].price) {
// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_BUY;
// } else if (tp->trade_price >= book_bid_side[0].price) {
// aggressor_side = co2::AggressorSide::AGGRESSOR_SIDE_SELL;
// }
// }
// // // Check if ask and bid sides are populated
// // }
// auto trade_ts = datetime::ll_from_unix_epoch_ms(tp->time_stamp.millis());
// if (handle != nullptr) {
// handle->handle.add_trade(
// utils::TimeStamp::now(),
// PriceSize(
// convert_price(tp->trade_price), tp->trade_quantity.value()),
// trade_ts, aggressor_side, 0, false);
// }
// }
// }
void GeneralMarketDataListener::on_rfqs(
const std::vector<domain::RFQ const *> &) {}
+14 -3
View File
@@ -146,6 +146,10 @@ void convert_security(const FixedSecurity &source, Security *presult) {
dest.mutable_okx()->set_security_desc(source.security_desc());
dest.mutable_okx()->set_exchange_id(source.numeric_id);
break;
case Venue::VENUE_TWSE:
dest.mutable_twse()->set_security_desc(source.security_desc());
dest.mutable_twse()->set_exchange_id(source.numeric_id);
break;
case Venue::VENUE_TAIFEX:
dest.mutable_taifex()->set_security_desc(source.security_desc());
dest.mutable_taifex()->set_exchange_id(source.numeric_id);
@@ -256,6 +260,8 @@ uint64_t exchange_id(const Security &security) {
return security.binance_usds_futures().exchange_id();
case Security::ExchangeDataCase::kOkx:
return security.okx().exchange_id();
case Security::ExchangeDataCase::kTwse:
return security.twse().exchange_id();
case Security::ExchangeDataCase::kTaifex:
return security.taifex().exchange_id();
// Debatable whether this should be an error or not.
@@ -289,10 +295,15 @@ void convert_security(
dest.security_desc(src.cboe().security_desc());
dest.cboe_class_key = src.cboe().class_key();
break;
case Security::ExchangeDataCase::kTwse:
dest.numeric_id = src.twse().exchange_id();
dest.security_desc(src.twse().security_desc());
// dest.cboe_class_key = src.twse().class_key();
break;
case Security::ExchangeDataCase::kTaifex:
dest.numeric_id = src.deribit().exchange_id();
dest.security_desc(src.deribit().security_desc());
dest.cboe_class_key = src.taifex().class_key();
dest.numeric_id = src.taifex().exchange_id();
dest.security_desc(src.taifex().security_desc());
// dest.cboe_class_key = src.taifex().class_key();
break;
case Security::ExchangeDataCase::kCfe:
dest.cboe_class_key = src.cfe().class_key();
+17
View File
@@ -142,6 +142,21 @@ message TradeMessage {
AggressorSide aggressor_side = 9;
bool from_spread = 10;
}
enum BboTradeEventType {
BBO_TRADE_UNKNOWN = 0;
//BOOK_UPDATE = 1;
TRADE = 2;
}
message BboTradeRecord {
BboTradeEventType event_type = 1;
// Book at time of trade
TotalBook book = 2;
// Include trade details only for TRADE events.
TradeMessage trade = 3;
}
message QuoteRequestMessage {
enum Side {
UNDEFINED = 0;
@@ -182,6 +197,7 @@ message TotalBook{
// Message written to the file, for replay
message RecordedMDMessage{
uint32 sec_key = 10;
string subset = 11;
int64 timestamp = 20;
oneof MDRecord {
bts.api.Security security = 100;
@@ -189,6 +205,7 @@ message RecordedMDMessage{
TradeMessage trade = 300;
QuoteRequestMessage rfq = 400;
MiscMessage misc = 500;
BboTradeRecord bbo_trade = 600;
}
}
+3
View File
@@ -194,6 +194,9 @@ struct MDConsumerGroup {
case api::VENUE_CBOE:
this->mic = "CBOE";
break;
case api::VENUE_TWSE:
this->mic = "TWSE";
break;
case api::VENUE_TAIFEX:
this->mic = "TAIFEX";
break;
@@ -0,0 +1,18 @@
#pragma once
#include <exception>
#include <fmt/format.h>
#include <string>
template <>
struct fmt::formatter<std::exception> {
constexpr auto parse(fmt::format_parse_context &ctx) -> decltype(ctx.end()) {
return ctx.end();
}
template <typename FormatContext>
auto format(const std::exception &e, FormatContext &ctx) const
-> decltype(ctx.out()) {
return fmt ::format_to(ctx.out(), "{}", std ::string{e.what()});
}
};
+1 -1
View File
@@ -101,4 +101,4 @@ add_custom_command(
COMMAND ln -fs ${CMAKE_BINARY_DIR}/src/lib/libspark.so ${CMAKE_CURRENT_BINARY_DIR}
COMMAND ln ARGS -sf ${EXTERNALS_ROOT}/../src/emumba/sparkd.lic ${CMAKE_BINARY_DIR}/src/server/sparkd)
install(TARGETS sparkd DESTINATION "${SPARK_INSTALL_PREFIX}/bin")
install(TARGETS sparkd DESTINATION "${CMAKE_INSTALL_BINDIR}")
@@ -20,7 +20,8 @@ EnumOptionNames<api::Venue> VenueOption::names() {
NAME_PAIR(api::VENUE_COINBASE),
NAME_PAIR(api::VENUE_BINANCE_USDS_FUTURES),
NAME_PAIR(api::VENUE_CBOE),
NAME_PAIR(api::VENUE_TAIFEX)};
NAME_PAIR(api::VENUE_TAIFEX),
NAME_PAIR(api::VENUE_TWSE)};
}
std::string VenueOption::name(api::Venue venue) {
@@ -49,6 +50,8 @@ std::string VenueOption::name(api::Venue venue) {
return "binance_usds_futures";
case api::VENUE_CBOE:
return "cboe";
case api::VENUE_TWSE:
return "twse";
case api::VENUE_TAIFEX:
return "taifex";
default:
+33 -1
View File
@@ -36,6 +36,7 @@
#include "server/sparkd/md/platforms/mdp3_onixs/MDP3Main.h"
#include "server/sparkd/md/recording/MDReplayer.h"
#include "server/sparkd/md/taifex/TaifexDataGateway.h"
#include "server/sparkd/md/twse/TwseDataGateway.h"
#include <bits/stdint-uintn.h>
#include <boost/filesystem.hpp>
@@ -139,8 +140,9 @@ void MarketDataGateway::run() {
bts_assert(me_->md_config.emumba_deribit().size() == 1);
_start_emumba_deribit(me_->md_config.emumba_deribit().at(0));
}
start_glbx(me_->md_config);
start_glbx(me_->md_config);
start_taifex(me_->md_config);
start_twse(me_->md_config);
start_cboe(me_->md_config);
_start_replays(me_->md_config);
while (true) {
@@ -377,6 +379,36 @@ void MarketDataGateway::_start_replays(
os::get_thread_id(), os::get_thread_name());
}
void MarketDataGateway::start_twse(const bts::api::md::MarketDataConfig &cfg) {
// twse
// int counter = 0;
// LOG(md, Info, "In start, mdgtway.cpp");
// for (const auto &twse : cfg.twse()) {
// counter++;
// auto p = me_->venue_listeners.emplace_back(
// std::make_shared<VenueListenerData>(bts::api::VENUE_TWSE));
// std::string tid_name = "twse" + std::to_string(counter);
// bts::threading::make_thread(tid_name, [&]() {
// bts::md::twse::TwseDataGateway::run(
// twse, p->listener, me_->sec_id_store);
// }).detach();
// }
for (const auto &twse : cfg.twse()) {
auto p = me_->venue_listeners.emplace_back(
std::make_shared<VenueListenerData>(bts::api::VENUE_TWSE));
// Capture `p->listener` and `me_->sec_id_store` by value
auto listener = p->listener;
auto sec_id_store = me_->sec_id_store;
std::string tid_name = "twse";
bts::threading::make_thread(tid_name, [listener, sec_id_store, twse]() {
bts::md::twse::TwseDataGateway::run(
twse, listener, sec_id_store);
}).detach();
}
}
void MarketDataGateway::start_taifex(const bts::api::md::MarketDataConfig &cfg) {
// taifex
for (const auto &taifex : cfg.taifex()) {
+1
View File
@@ -39,6 +39,7 @@ class MarketDataGateway {
void start_glbx(const bts::api::md::MarketDataConfig &cfg);
void start_cboe(const bts::api::md::MarketDataConfig &cfg);
void start_taifex(const bts::api::md::MarketDataConfig &cfg);
void start_twse(const bts::api::md::MarketDataConfig &cfg);
};
} // namespace bts::md
+457
View File
@@ -0,0 +1,457 @@
#ifndef DBWRITERS_H
#define DBWRITERS_H
#include "lib/config/config.h"
#include "lib/config/protos/system_config.pb.h"
#include "lib/logging/logging.h"
#include "lib/md/IntPrice.h"
#include "lib/md/protos/co2.pb.h"
#include "lib/utils/PBUtils.h"
#include <SQLiteCpp/Database.h>
#include <SQLiteCpp/Transaction.h>
#include <fstream>
#include <iostream>
#include <string>
#include <vector>
namespace bts::md::recording {
// Class containing static DB write functions
class DbWriters {
public:
using DataToRecord = co2::RecordedMDMessage;
// Writes data to the console (for testing/debugging)
static void writeToLOG(const std::vector<DataToRecord> &data) {
LOG(md, Info, "Writting {} entries to log", data.size());
for (auto rec_msg : data) {
LOG(md, Info, "{}", bts::utils::pb::to_string(rec_msg));
}
}
// to check subset values for each record
static void dumpSubsets(const std::vector<DataToRecord>& data) {
for (const auto &r : data) {
LOG(md, Info, "Record subset: '{}'", r.subset());
}
}
// Writes data to an SQL database
static std::unique_ptr<SQLite::Database> open_db(
const std::string &db_name = "recorded_md.sqlite") {
// Directory location on disk
auto db_dir = config::get<config::SystemConfig>().data_path() +
"databases/recorded_md/";
auto db_path = db_dir + db_name;
if (!boost::filesystem::exists(db_dir)) {
boost::filesystem::create_directories(db_dir);
}
// Create table if it does not exist
auto db = std::make_unique<SQLite::Database>(
db_path, SQLite::OPEN_READWRITE | SQLite::OPEN_CREATE);
db->setBusyTimeout(9999);
db->exec("PRAGMA journal_mode=WAL");
db->exec("PRAGMA syncronous=0");
db->exec("CREATE TABLE IF NOT EXISTS books("
"ts TEXT NOT NULL, key INTEGER NOT NULL, "
"bid_price_1 float, bid_qty_1 float, ask_price_1 float, "
"ask_qty_1 float, "
"bid_price_2 float, bid_qty_2 float, ask_price_2 float, "
"ask_qty_2 float, "
"bid_price_3 float, bid_qty_3 float, ask_price_3 float, "
"ask_qty_3 float, "
"bid_price_4 float, bid_qty_4 float, ask_price_4 float, "
"ask_qty_4 float, "
"bid_price_5 float, bid_qty_5 float, ask_price_5 float, "
"ask_qty_5 float, "
"bid_price_6 float, bid_qty_6 float, ask_price_6 float, "
"ask_qty_6 float, "
"bid_price_7 float, bid_qty_7 float, ask_price_7 float, "
"ask_qty_7 float, "
"bid_price_8 float, bid_qty_8 float, ask_price_8 float, "
"ask_qty_8 float, "
"bid_price_9 float, bid_qty_9 float, ask_price_9 float, "
"ask_qty_9 float, "
"bid_price_10 float, bid_qty_10 float, ask_price_10 float, "
"ask_qty_10 float);");
db->exec("CREATE TABLE IF NOT EXISTS trades ("
"ts TEXT NOT NULL, key INTEGER NOT NULL, price float NOT NULL, "
"quantity float NOT NULL, total_volume );");
db->exec("CREATE TABLE IF NOT EXISTS tbbo ("
"ts TEXT, key INTEGER, price float, "
"quantity float, total_volume float, book_ts TEXT, "
"book_key INTEGER, "
"bid_price_1 float, bid_qty_1 float, ask_price_1 float, "
"ask_qty_1 float);");
return db;
}
// Helper function to join vector values into a single string
static std::string join(
const std::vector<std::string> &vec, const std::string &delimiter) {
std::ostringstream oss;
for (size_t i = 0; i < vec.size(); ++i) {
oss << vec[i];
if (i != vec.size() - 1) {
oss << delimiter;
}
}
return oss.str();
}
static void writeToSQL(const std::vector<DataToRecord> &data) {
LOG(md, Info, "Writting {} entries to sql", data.size());
dumpSubsets(data);
// Open the database.
std::unique_ptr<SQLite::Database> db = open_db();
try {
// Group records by the subset field.
std::map<std::string, std::vector<DataToRecord>> subsets;
for (const auto &r : data) {
std::string subset = r.subset(); // subset field from the proto
if (!subsets.count(subset)) {
subsets[subset] = std::vector<DataToRecord>();
}
subsets[subset].push_back(r);
}
// Begin a transaction for bulk insert.
SQLite::Transaction transaction(*db);
// Process each group.
for (const auto &pair : subsets) {
const std::string &tableName = pair.first; // dynamic table name from subset
const auto &records = pair.second;
// First, determine the table schema based on record type and create the table if needed.
std::string createTableQuery;
if (!records.empty() && records.front().has_total_book()) {
createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
"ts TEXT NOT NULL, key INTEGER NOT NULL, "
"bid_price_1 float, bid_qty_1 float, ask_price_1 float, ask_qty_1 float, "
"bid_price_2 float, bid_qty_2 float, ask_price_2 float, ask_qty_2 float, "
"bid_price_3 float, bid_qty_3 float, ask_price_3 float, ask_qty_3 float, "
"bid_price_4 float, bid_qty_4 float, ask_price_4 float, ask_qty_4 float, "
"bid_price_5 float, bid_qty_5 float, ask_price_5 float, ask_qty_5 float, "
"bid_price_6 float, bid_qty_6 float, ask_price_6 float, ask_qty_6 float, "
"bid_price_7 float, bid_qty_7 float, ask_price_7 float, ask_qty_7 float, "
"bid_price_8 float, bid_qty_8 float, ask_price_8 float, ask_qty_8 float, "
"bid_price_9 float, bid_qty_9 float, ask_price_9 float, ask_qty_9 float, "
"bid_price_10 float, bid_qty_10 float, ask_price_10 float, ask_qty_10 float)";
} else if (!records.empty() && records.front().has_trade()) {
createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
"ts TEXT , key INTEGER , price float , "
"quantity float , total_volume float)";
} else if (!records.empty() && records.front().has_bbo_trade()) {
createTableQuery = "CREATE TABLE IF NOT EXISTS " + tableName + " ("
"ts TEXT, key INTEGER, price float , "
"quantity float, total_volume float, book_ts TEXT, "
"book_key INTEGER, "
"bid_price_1 float, bid_qty_1 float, ask_price_1 float, ask_qty_1 float)";
} else {
continue;
}
// Execute the CREATE TABLE query.
{
SQLite::Statement createStmt(*db, createTableQuery);
createStmt.exec();
}
// Now build the INSERT query.
std::string insertQuery;
if (!records.empty() && records.front().has_total_book()) {
insertQuery = "INSERT OR REPLACE INTO " + tableName +
" (ts, key, bid_price_1, bid_qty_1, ask_price_1, ask_qty_1, "
"bid_price_2, bid_qty_2, ask_price_2, ask_qty_2, "
"bid_price_3, bid_qty_3, ask_price_3, ask_qty_3, "
"bid_price_4, bid_qty_4, ask_price_4, ask_qty_4, "
"bid_price_5, bid_qty_5, ask_price_5, ask_qty_5, "
"bid_price_6, bid_qty_6, ask_price_6, ask_qty_6, "
"bid_price_7, bid_qty_7, ask_price_7, ask_qty_7, "
"bid_price_8, bid_qty_8, ask_price_8, ask_qty_8, "
"bid_price_9, bid_qty_9, ask_price_9, ask_qty_9, "
"bid_price_10, bid_qty_10, ask_price_10, ask_qty_10)";
} else if (!records.empty() && records.front().has_trade()) {
insertQuery = "INSERT OR REPLACE INTO " + tableName +
" (ts, key, price, quantity, total_volume)";
} else if (!records.empty() && records.front().has_bbo_trade()) {
insertQuery = "INSERT OR REPLACE INTO " + tableName +
" (ts, key, price, quantity, total_volume, book_ts, book_key, "
"bid_price_1, bid_qty_1, ask_price_1, ask_qty_1)";
}
// Build value tuples.
std::vector<std::string> valueStrings;
for (const auto &entry : records) {
std::string tuple;
if (entry.has_total_book()) {
auto book = entry.total_book();
tuple = "(" + std::to_string(entry.timestamp()) + ", " +
std::to_string(entry.sec_key());
const auto &asks = book.direct_book().asks();
const auto &bids = book.direct_book().bids();
for (int i = 0; i < 10; ++i) {
// Process asks.
if (i < asks.size()) {
IntPrice p(asks.at(i).mantissa(), asks.at(i).exponent());
tuple += ", " + std::to_string(p.price()) + ", " +
std::to_string(asks.at(i).size());
} else {
tuple += ", NULL, NULL";
}
// Process bids.
if (i < bids.size()) {
IntPrice p(bids.at(i).mantissa(), bids.at(i).exponent());
tuple += ", " + std::to_string(p.price()) + ", " +
std::to_string(bids.at(i).size());
} else {
tuple += ", NULL, NULL";
}
}
tuple += ")";
} else if (entry.has_trade()) {
const auto &trade = entry.trade();
IntPrice p(trade.mantissa(), trade.exponent());
tuple = "(" + std::to_string(entry.timestamp()) + ", " +
std::to_string(entry.sec_key()) + ", " +
std::to_string(p.price()) + ", " +
std::to_string(trade.size()) + ", " +
std::to_string(trade.total_volume()) + ")";
} else if (entry.has_bbo_trade()) {
const auto &bbo_trade = entry.bbo_trade();
const auto &trade = bbo_trade.trade();
IntPrice p(trade.mantissa(), trade.exponent());
tuple = "("
+ std::to_string(trade.time()) + ", "
+ std::to_string(trade.key()) + ", "
+ std::to_string(p.price()) + ", "
+ std::to_string(trade.size()) + ", "
+ std::to_string(trade.total_volume()) + ", "
+ std::to_string(entry.timestamp()) + ", "
+ std::to_string(entry.sec_key());
const auto &asks = bbo_trade.book().direct_book().asks();
const auto &bids = bbo_trade.book().direct_book().bids();
// Process top ask (level 1)
if (!asks.empty()) {
IntPrice askPrice(asks[0].mantissa(), asks[0].exponent());
tuple += ", " + std::to_string(askPrice.price()) + ", "
+ std::to_string(asks[0].size());
} else {
tuple += ", NULL, NULL";
}
// Process top bid (level 1)
if (!bids.empty()) {
IntPrice bidPrice(bids[0].mantissa(), bids[0].exponent());
tuple += ", " + std::to_string(bidPrice.price()) + ", "
+ std::to_string(bids[0].size());
} else {
tuple += ", NULL, NULL";
}
tuple += ")";
}
valueStrings.push_back(tuple);
}
std::string fullQuery = insertQuery + " VALUES " + join(valueStrings, ", ") + ";";
// Replace any occurrence of "nan" with "NULL".
auto replaceNanWithNull = [](std::string &input) {
const std::string target = "nan";
const std::string replacement = "NULL";
size_t pos = 0;
while ((pos = input.find(target, pos)) != std::string::npos) {
input.replace(pos, target.length(), replacement);
pos += replacement.length();
}
};
replaceNanWithNull(fullQuery);
LOG(md, Diag, "EXECUTING QUERY '{}'", fullQuery);
SQLite::Statement q(*db, fullQuery);
q.exec();
}
transaction.commit();
} catch (const SQLite::Exception &e) {
LOG(md, Warn, "Error writing to books db (retry pending): {}",
std::string(e.what()));
}
}
/*old writeToSQL
static void writeToSQL(const std::vector<DataToRecord> &data) {
LOG(md, Info, "Writting {} entries to sql", data.size());
std::unique_ptr<SQLite::Database> db = open_db();
try {
auto db = open_db();
std::string insert_book =
"INSERT OR REPLACE INTO books (ts, key, "
"bid_price_1, bid_qty_1, ask_price_1, ask_qty_1, "
"bid_price_2, bid_qty_2, ask_price_2, ask_qty_2, "
"bid_price_3, bid_qty_3, ask_price_3, ask_qty_3, "
"bid_price_4, bid_qty_4, ask_price_4, ask_qty_4, "
"bid_price_5, bid_qty_5, ask_price_5, ask_qty_5, "
"bid_price_6, bid_qty_6, ask_price_6, ask_qty_6, "
"bid_price_7, bid_qty_7, ask_price_7, ask_qty_7, "
"bid_price_8, bid_qty_8, ask_price_8, ask_qty_8, "
"bid_price_9, bid_qty_9, ask_price_9, ask_qty_9, "
"bid_price_10, bid_qty_10, ask_price_10, ask_qty_10)";
std::string insert_trade = "INSERT OR REPLACE INTO trades (ts, key, "
"price, quantity, total_volume)";
std::string insert_tbbo = "INSERT OR REPLACE INTO tbbo (ts, key, "
"price, quantity, total_volume, "
"book_ts, book_key, bid_price_1, bid_qty_1, "
"ask_price_1, ask_qty_1)";
SQLite::Transaction transaction(*db);
auto replaceNanWithNull = [](std::string &input) {
const std::string target = "nan";
const std::string replacement = "NULL";
size_t pos = 0;
while ((pos = input.find(target, pos)) != std::string::npos) {
input.replace(pos, target.length(), replacement);
pos += replacement.length(); // Move past the replacement
}
};
// Collect data for bulk insert
std::vector<std::string> book_values;
std::vector<std::string> trade_values;
std::vector<std::string> tbbo_values;
for (const auto &entry : data) {
if (entry.has_total_book()) {
auto book = entry.total_book();
std::string &book_value = book_values.emplace_back();
book_value = "(" + std::to_string(entry.timestamp()) + ", " +
std::to_string(entry.sec_key());
const auto &asks = book.direct_book().asks();
const auto &bids = book.direct_book().bids();
for (int i = 0; i < 10; ++i) {
// Process asks
if (i < asks.size()) {
IntPrice p(asks.at(i).mantissa(), asks.at(i).exponent());
book_value += ", " + std::to_string(p.price()) + ", " +
std::to_string(asks.at(i).size());
} else {
book_value += ", NULL, NULL";
}
// Process bids
if (i < bids.size()) {
IntPrice p(bids.at(i).mantissa(), bids.at(i).exponent());
book_value += ", " + std::to_string(p.price()) + ", " +
std::to_string(bids.at(i).size());
} else {
book_value += ", NULL, NULL";
}
}
book_value += ")";
}
if (entry.has_trade()) {
const auto &trade = entry.trade();
IntPrice p(trade.mantissa(), trade.exponent());
trade_values.push_back(
"(" + std::to_string(entry.timestamp()) + ", " +
std::to_string(entry.sec_key()) + ", " +
std::to_string(p.price()) + ", " +
std::to_string(trade.size()) + ", " +
std::to_string(trade.total_volume()) + ")");
}
if (entry.has_bbo_trade()) {
const auto &bbo_trade = entry.bbo_trade();
IntPrice p(bbo_trade.trade().mantissa(), bbo_trade.trade().exponent());
std::string tbbo_value =
"(" + std::to_string(entry.timestamp()) + ", " +
std::to_string(entry.sec_key()) + ", " +
std::to_string(p.price()) +", " +
std::to_string(bbo_trade.trade().size()) + ", " +
std::to_string(bbo_trade.trade().total_volume());
const auto &asks = bbo_trade.book().direct_book().asks();
const auto &bids = bbo_trade.book().direct_book().bids();
if (!asks.empty()) {
IntPrice askPrice(asks.begin()->mantissa(), asks.begin()->exponent());
tbbo_value += ", " + std::to_string(askPrice.price()) + ", " +
std::to_string(asks.size());
} else {
tbbo_value += ", NULL, NULL";
}
if (!bids.empty()) {
IntPrice bidPrice(
bids.begin()->mantissa(), bids.begin()->exponent());
tbbo_value += ", " + std::to_string(bidPrice.price()) + ", " +
std::to_string(bids.size());
} else {
tbbo_value += ", NULL, NULL";
}
tbbo_value += ")";
tbbo_values.push_back(tbbo_value);
}
}
// Construct the full bulk insert query for books
if (!book_values.empty()) {
std::string book_query =
insert_book + " VALUES " + join(book_values, ", ") + ";";
replaceNanWithNull(book_query);
LOG(md, Diag, "EXECUTING QUERY '{}'", book_query);
SQLite::Statement q(*db, book_query);
q.exec();
}
// Construct the full bulk insert query for trades
if (!trade_values.empty()) {
std::string trade_query =
insert_trade + " VALUES " + join(trade_values, ", ") + ";";
replaceNanWithNull(trade_query);
LOG(md, Diag, "EXECUTING QUERY '{}'", trade_query);
SQLite::Statement q(*db, trade_query);
q.exec();
;
}
if (!tbbo_values.empty()) {
std::string tbbo_query =
insert_tbbo + " VALUES " + join(tbbo_values, ", ") + ";";
replaceNanWithNull(tbbo_query);
LOG(md, Diag, "EXECUTING QUERY '{}'", tbbo_query);
SQLite::Statement q(*db, tbbo_query);
q.exec();
;
}
transaction.commit();
} catch (const SQLite::Exception &e) {
LOG(md, Warn, "Error writing to books db (retry pending): {}",
std::string(e.what()));
}
}
*/
// Writes data to a file
static void writeProtoToFile(
const std::vector<DataToRecord> &data,
const std::string &fileName = "recorded_pb") {
LOG(md, Info, "Writting {} entries to file {}");
std::ofstream outFile(fileName, std::ios::app);
if (!outFile) {
LOG(md, Error, "Error: Unable to open file {}", fileName);
return;
}
for (auto rec_msg : data) {
bts::utils::pb::writebuf(outFile, rec_msg);
}
outFile.close();
}
};
} // namespace bts::md::recording
#endif // DBWRITERS_H
@@ -0,0 +1,63 @@
#include <tbb/concurrent_queue.h>
#include <tbb/task_group.h>
#include <atomic>
#include <thread>
#include <chrono>
#include "lib/utils/bts_assert.h"
#include "MDBatchWriter.h"
namespace bts::md::recording {
MDBatchWriter::MDBatchWriter(size_t buffer_size, std::vector<DBWriteFunction> writer_functions)
: writer_functions(std::move(writer_functions)),
buffer_size_(buffer_size),
stop_thread_(false) {
bts_assert_msgf(this->writer_functions.size()!=0,"DB write function cannot be null size {}",this->writer_functions.size());
consumer_thread_ = std::thread(&MDBatchWriter::consumeData, this);
}
MDBatchWriter::~MDBatchWriter() {
stop_thread_ = true;
consumer_thread_.join(); // Wait for the consumer thread to finish
}
void MDBatchWriter::addData(const DataToRecord& data) {
buffer_.push(data); // Thread-safe with tbb::concurrent_queue
}
void MDBatchWriter::_write(std::vector<DataToRecord> &data_to_write){
for(auto &writer:writer_functions){
writer(data_to_write);
}
}
void MDBatchWriter::consumeData() {
while (!stop_thread_) {
std::vector<DataToRecord> data_to_write;
DataToRecord item;
// Collect a batch of data from the queue
while (data_to_write.size() < buffer_size_ && buffer_.try_pop(item)) {
data_to_write.push_back(std::move(item));
}
if (!data_to_write.empty()) {
_write(data_to_write);
}
// Sleep briefly to avoid busy-waiting
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
// Flush remaining data on exit
flushRemainingData();
}
void MDBatchWriter::flushRemainingData() {
std::vector<DataToRecord> data_to_write;
DataToRecord item;
while (buffer_.try_pop(item)) {
data_to_write.push_back(std::move(item));
}
if (!data_to_write.empty()) {
_write(data_to_write);
}
}
}
@@ -0,0 +1,30 @@
#include <tbb/concurrent_queue.h>
#include <tbb/task_group.h>
#include <functional>
#include <atomic>
#include <thread>
#include <vector>
#include "lib/md/protos/co2.pb.h"
namespace bts::md::recording {
class MDBatchWriter {
public:
using DataToRecord = co2::RecordedMDMessage;
using DBWriteFunction = std::function<void(const std::vector<DataToRecord>&)>;
std::vector<DBWriteFunction> writer_functions;
MDBatchWriter(size_t buffer_size,std::vector<DBWriteFunction> writer_functions);
~MDBatchWriter();
void addData(const DataToRecord& data);
private:
size_t buffer_size_;
tbb::concurrent_queue<DataToRecord> buffer_;
std::atomic<bool> stop_thread_;
std::thread consumer_thread_;
void _write(std::vector<DataToRecord> &data_to_write);
void consumeData();
void flushRemainingData();
};
}
+140 -16
View File
@@ -19,7 +19,9 @@
#include "lib/utils/bts_assert.h"
#include "lib/utils/datetime.h"
#include "lib/utils/thread_manager.h"
#include "MDBatchWriter.h"
#include "DbWriters.h"
#include <algorithm>
#include <array>
#include <boost/filesystem.hpp>
#include <chrono>
@@ -27,6 +29,8 @@
#include <memory>
#include <string>
#include <thread>
#include <vector>
#include <cmath>
namespace bts::md::recording {
@@ -95,11 +99,13 @@ void copy_misc(IntPrice settlement, MiscData &misc, co2::MiscMessage *pmisc) {
// each security is represented here
struct MDRecordingSecEntry {
SecurityKey key;
std::string subset_string; // New: computed base subset (e.g. "taifex_future_tx")
MDConsumerHandle handle;
TimeStamp direct_book_ts = {};
TimeStamp implied_book_ts = {};
TimeStamp trade_ts = {};
TimeStamp misc_ts = {};
co2::TotalBook last_total_book;
MDRecordingSecEntry(SecurityKey key, MDConsumerHandle handle)
: key(key), handle(handle) {}
};
@@ -108,8 +114,11 @@ struct MDRecordingSecEntry {
struct MDRecordingSettings {
const uint32_t n_book_levels = 10;
const uint64_t total_runtime_ns = 300000000000; // 5 mins
const uint64_t file_runtime_ns = total_runtime_ns; // 5 mins
const uint64_t db_runtime_ns = total_runtime_ns; // 5 mins
const uint64_t thread_sleep_time_ns = 100000; // 100 usecs
const uint64_t security_scan_period_ns = 1000000000; // 1 sec
const uint64_t security_scan_period_ns = 1000000000; // 1 sec
const size_t batch_size = 10;
};
// So we dont have to create multiple bids/asks
@@ -137,6 +146,8 @@ struct MDRecorder::PImpl {
uintptr_t mdc_id = 0;
bts::md::MDClient &md_client;
std::map<SecurityKey, MDRecordingSecEntry> handles;
MDBatchWriter batch_writer{settings.batch_size,std::vector<bts::md::recording::MDBatchWriter::DBWriteFunction>{DbWriters::writeToSQL}};
uint64_t start_ns;
PImpl(
bts::api::Venue venue,
bts::md::MDClient &md_client,
@@ -144,10 +155,14 @@ struct MDRecorder::PImpl {
: venue(venue),
settings(MDRecordingSettings{
recording_config.n_book_levels(),
static_cast<uint64_t>(recording_config.num_of_seconds_to_run()) *
static_cast<uint64_t>(std::max(recording_config.num_of_seconds_to_run_db_writer(),recording_config.num_of_seconds_to_run_file_writer())) *
1000 * 1000 * 1000,
100000, 1000000000}),
md_client(md_client) {}
static_cast<uint64_t>(recording_config.num_of_seconds_to_run_file_writer()) *
1000 * 1000 * 1000,
static_cast<uint64_t>(recording_config.num_of_seconds_to_run_db_writer()) *
1000 * 1000 * 1000,
100000, 1000000000,recording_config.batch_size()}),
md_client(md_client),start_ns(bts::core::TimeStamp::now_ns()) {}
};
MDRecorder::MDRecorder(
@@ -167,8 +182,8 @@ MDRecorder::~MDRecorder() {}
// this is the main thread that keeps polling the shared memory for
// total_runtime_secs
void MDRecorder::_poll_md() {
uint64_t start_ns = bts::core::TimeStamp::now_ns();
uint64_t last_sec_scan_time = 0;
me->start_ns = bts::core::TimeStamp::now_ns();
uint64_t i = 0;
LOG(md, Info, "MDRecorder::_poll_md venue: {} starting loop",
bts::api::Venue_Name(me->venue));
@@ -186,6 +201,7 @@ void MDRecorder::_poll_md() {
MDRecordingSecEntry &md_entry = kv.second;
if (me->settings.n_book_levels > 0)
_poll_books(md_entry);
_poll_bbotrade(md_entry); // Added this to poll tbbo
_poll_trades(md_entry);
_poll_misc(md_entry);
}
@@ -193,11 +209,11 @@ void MDRecorder::_poll_md() {
last_sec_scan_time = now_ns;
_scan_securities();
}
if (now_ns - start_ns > me->settings.total_runtime_ns) {
if (now_ns - me->start_ns > me->settings.total_runtime_ns) {
LOG(md, Info,
"MDRecorder::_poll_md exiting recording, iters: {} diff_ns: {} "
"total_ns: {}",
i, now_ns - start_ns, me->settings.total_runtime_ns);
i, now_ns - me->start_ns, me->settings.total_runtime_ns);
break;
}
std::this_thread::sleep_for(
@@ -209,6 +225,37 @@ void MDRecorder::_poll_md() {
bts::api::Venue_Name(me->venue));
}
std::string computeBaseSubsetString(const bts::api::Security &sec) {
std::string exchange_str = bts::api::Venue_Name(sec.exchange());
std::string instrument_type;
if (sec.has_future()) {
instrument_type = "future";
} else if (sec.has_option()) {
instrument_type = "option";
} else if (sec.has_spot()) {
instrument_type = "spot";
} else if (sec.has_spread()) {
instrument_type = "spread";
} else if (sec.has_synthetic()) {
instrument_type = "synthetic";
} else {
instrument_type = "unset";
}
//might need to add toLowerCase for exact match to sheet requirement
std::string symbol = sec.symbol();
// Convert instrument_type and symbol to lowercase
std::transform(exchange_str.begin(), exchange_str.end(), exchange_str.begin(), ::tolower);
std::transform(instrument_type.begin(), instrument_type.end(), instrument_type.begin(), ::tolower);
std::transform(symbol.begin(), symbol.end(), symbol.begin(), ::tolower);
// This base string does not include the event prefix (like "book", "tradebbo", etc.)
return exchange_str + "_" + instrument_type + "_" + symbol;
}
void MDRecorder::_scan_securities() {
auto secs = me->md_client.current_consumer().get_securities();
uint32_t n_secs_added = 0;
@@ -221,22 +268,41 @@ void MDRecorder::_scan_securities() {
LOG(md, Info,
"MDRecorder::_scan_securities adding sec: {}, n_secs: {}", key,
me->handles.size());
me->handles.emplace(
// Compute the base subset string from the security details.
std::string baseSubset = computeBaseSubsetString(*s);
// Create a new MDRecordingSecEntry and assign the computed subset_string.
MDRecordingSecEntry entry(key, me->md_client.current_consumer().get_handle(key.value()));
entry.subset_string = baseSubset;
// Insert the entry with the computed subset_string.
me->handles.emplace(key, std::move(entry));
/*me->handles.emplace(
key, MDRecordingSecEntry(
key, me->md_client.current_consumer().get_handle(
key.value())));
key.value())));*/
bts::co2::RecordedMDMessage rec_msg;
rec_msg.set_sec_key(key.value());
rec_msg.set_timestamp(bts::core::TimeStamp::now_ns());
rec_msg.mutable_security()->CopyFrom(*s);
bts::utils::pb::writebuf(me->file, rec_msg);
rec_msg.set_subset(baseSubset);
_write_pb_to_file(rec_msg);
n_secs_added++;
}
}
LOG(md, Info, "MDRecorder::_scan_securities n_secs_added: {} n_secs: {}",
n_secs_added, secs.size());
}
void MDRecorder::_write_pb_to_file(const bts::co2::RecordedMDMessage &rec_msg){
if (!core::TimeStamp::now_ns() - me->start_ns > me->settings.file_runtime_ns)
bts::utils::pb::writebuf(me->file, rec_msg);
}
void MDRecorder::_write_pb_to_db(const bts::co2::RecordedMDMessage &rec_msg){
if (!core::TimeStamp::now_ns() - me->start_ns > me->settings.db_runtime_ns)
me->batch_writer.addData(rec_msg);
}
void MDRecorder::_poll_books(MDRecordingSecEntry &md_entry) {
TimeStamp ts;
bool md_change = false;
@@ -269,9 +335,14 @@ void MDRecorder::_poll_books(MDRecordingSecEntry &md_entry) {
if (md_change) {
co2::RecordedMDMessage rec_msg;
rec_msg.set_sec_key(md_entry.key.value());
//for tbbo consistency
std::string eventSubset = "book_" + md_entry.subset_string;
rec_msg.set_subset(eventSubset);
//--------
rec_msg.set_timestamp(bts::core::TimeStamp::now_ns());
rec_msg.mutable_total_book()->CopyFrom(book);
bts::utils::pb::writebuf(me->file, rec_msg);
_write_pb_to_file(rec_msg);
_write_pb_to_db(rec_msg);
}
}
@@ -295,12 +366,65 @@ void MDRecorder::_poll_trades(MDRecordingSecEntry &md_entry) {
// aggressor?
co2::RecordedMDMessage rec_msg;
rec_msg.set_sec_key(md_entry.key.value());
//for tbbo consistency
std::string eventSubset = "trade_" + md_entry.subset_string;
rec_msg.set_subset(eventSubset);
//-----
rec_msg.set_timestamp(bts::core::TimeStamp::now_ns());
rec_msg.mutable_trade()->CopyFrom(tm);
bts::utils::pb::writebuf(me->file, rec_msg);
_write_pb_to_file(rec_msg);
_write_pb_to_db(rec_msg);
}
}
void MDRecorder::_poll_bbotrade(MDRecordingSecEntry &md_entry) {
// === Always Update Book Snapshot ===
TimeStamp book_ts;
co2::TotalBook book;
me->reusables.clean_books();
md_entry.handle.get_direct_book(book_ts, me->settings.n_book_levels,
me->reusables.bids, me->reusables.asks);
// Update book snapshot even if timestamp hasn't changed (for TBBO accuracy)
co2::BookMessage *direct_book = book.mutable_direct_book();
copy_book(me->reusables.bids, true, me->settings.n_book_levels, *direct_book);
copy_book(me->reusables.asks, false, me->settings.n_book_levels, *direct_book);
md_entry.last_total_book.CopyFrom(book); // Always update
md_entry.direct_book_ts = book_ts; // Track timestamp
// === Trade Handling ===
TimeStamp trade_ts;
PriceSize t_ps;
datetime::LLDateTime trade_time;
size_t total_volume;
int from_spread;
md_entry.handle.get_last_trade(trade_ts, t_ps, trade_time, &total_volume, &from_spread);
if (trade_ts > md_entry.trade_ts) {
md_entry.trade_ts = trade_ts;
co2::RecordedMDMessage rec_msg;
rec_msg.set_sec_key(md_entry.key.value());
rec_msg.set_timestamp(trade_time);
rec_msg.set_subset("tradebbo_" + md_entry.subset_string);
auto* bboTrade = rec_msg.mutable_bbo_trade();
bboTrade->set_event_type(co2::TRADE);
// Directly populate the trade (no need for TradeMessage intermediary)
auto* trade = bboTrade->mutable_trade();
trade->set_key(md_entry.key.value());
trade->set_time(trade_time);
trade->set_mantissa(t_ps.mantissa());
trade->set_exponent(t_ps.exponent());
trade->set_size(t_ps.direct_size());
trade->set_total_volume(total_volume);
// Attach the freshly updated book snapshot
bboTrade->mutable_book()->CopyFrom(md_entry.last_total_book);
_write_pb_to_file(rec_msg);
_write_pb_to_db(rec_msg);
}
}
void MDRecorder::_poll_misc(MDRecordingSecEntry &md_entry) {
auto misc_data = md_entry.handle.misc();
if (misc_data.misc_timestamp > md_entry.misc_ts) {
@@ -311,7 +435,7 @@ void MDRecorder::_poll_misc(MDRecordingSecEntry &md_entry) {
rec_msg.set_sec_key(md_entry.key.value());
rec_msg.set_timestamp(bts::core::TimeStamp::now_ns());
rec_msg.mutable_misc()->CopyFrom(misc_msg);
bts::utils::pb::writebuf(me->file, rec_msg);
_write_pb_to_file(rec_msg);
}
}
@@ -367,4 +491,4 @@ bool MDRecorder::is_md_recording_file(
file_name.find(search_txt) != std::string::npos;
}
} // namespace bts::md::recording
} // namespace bts::md::recording
@@ -30,7 +30,10 @@ class MDRecorder {
void _scan_securities();
void _poll_books(MDRecordingSecEntry &md_entry);
void _poll_trades(MDRecordingSecEntry &md_entry);
void _poll_bbotrade(MDRecordingSecEntry &md_entry);
void _poll_misc(MDRecordingSecEntry &md_entry);
void _write_pb_to_file(const bts::co2::RecordedMDMessage &rec_msg);
void _write_pb_to_db(const bts::co2::RecordedMDMessage &rec_msg);
bool _active() const;
public:
+254 -12
View File
@@ -10,6 +10,10 @@
#include "lib/utils/bts_chrono.h"
#include "lib/utils/overloaded.h"
#include "lib/utils/thread_manager.h"
#include <chrono>
#include <dirent.h>
#include <dirent.h> // For opendir, readdir, closedir
#include <iostream> // For logging
#include <memory>
#include <optional>
#include <ostream>
@@ -98,6 +102,31 @@ void handleReferenceDataUnparsedMessage(
auto parsed = getParsedReferenceMessage(buffer, position, Header);
if (!parsed.has_value())
return;
///adding temp code to write to preload reference file
// std::set<std::string> I010_seen; // Temporary sets for this run
// std::set<std::string> I011_seen;
// bool seen = true;
// std::visit(
// overloaded{
// [&](const TaifexMessages::I010Data &i010) {
// if (!I010_seen.contains(i010.prod_id) &&
// TaifexUtils::sec_filter(i010.prod_id)) {
// seen = false;
// I010_seen.insert(i010.prod_id);
// }
// },
// [&](const TaifexMessages::I011Data &i011) {
// if (!I011_seen.contains(i011.kind_id) &&
// TaifexUtils::sec_filter(i011.kind_id)) {
// seen = false;
// I011_seen.insert(i011.kind_id);
// }
// }},
// parsed.value());
// if (!seen) {
// writeBufferWithSeparator(buffer, Header.Body_Length + MSG_HEADER_SIZE + MSG_FOOTER_SIZE, position);
// }
/////temp code end
handleReferenceDataParsedMessage(
parsed.value(), listener, sec_id_store, security_details);
}
@@ -329,6 +358,7 @@ void writeBufferWithSeparator(
unsigned long position = 0) {
auto filename = config::get<bts::config::SystemConfig>().data_path() +
"taifex_default_reference";
// "taifex_default_reference_new_secs";
std::ofstream outputFile(
filename, std::ios::binary | std::ios::app); // Open file in append mode
if (!outputFile) {
@@ -359,6 +389,7 @@ void HandleReferenceFeed(
LoadReferenceFromFile(
config::get<bts::config::SystemConfig>().data_path() +
"taifex_default_reference",
// "taifex_default_reference_new_secs",
snapshot_buffered_messages, I010_seen, I011_seen);
// bool file_done =
UNPROCESSED_MSG buffer(FEED_BUFFER_SIZE);
@@ -445,6 +476,116 @@ void HandleLiveBufferFeed(
}
stop_live_buffer_thread = true;
}
//runOnBinary with debuggin code to find md gaps
// bool runOnBinaryFile(
// const std::string &file_name,
// std::shared_ptr<bts::md::IMarketDataListener> listener,
// std::shared_ptr<persistence::IDGenerator> sec_id_store,
// std::shared_ptr<TaifexSecurityDetailsMapper> security_details,
// TaifexDataGateway::DATA_TYPE data_type,
// unsigned long& out_total_processed, // Output: messages processed this run
// int& out_gap_count) { // Output: gaps found this run
// const size_t BUFFER_SIZE = 1024 * 1024;
// std::ifstream file(file_name, std::ios::binary);
// if (!file) {
// LOG(md, Error, "File not found: {}", file_name);
// return false;
// }
// // MODIFICATION 1: Open a file to log gaps, in append mode to collect across all files
// std::ofstream gap_file("/home/bts/sparkdata/data/gaps_report.txt", std::ios::app);
// if (!gap_file) {
// LOG(md, Error, "Failed to open gaps_report.txt for writing");
// }
// UNPROCESSED_MSG buffer(BUFFER_SIZE + 1024);
// UNPROCESSED_MSG prev_data(1024);
// bool start = true;
// size_t prev_data_len = 0;
// unsigned long last_seq_num = 0;
// int last_channel_id = -1;
// unsigned long total_processed = 0;
// static int gap_count = 0;
// int initial_gap_count = gap_count; // Store starting point for this run
// while (file.read(reinterpret_cast<char *>(buffer.data() + prev_data_len), BUFFER_SIZE)) {
// size_t bytes_read = file.gcount();
// if (bytes_read < BUFFER_SIZE) {
// break;
// }
// if (!start) {
// std::memcpy(buffer.data(), prev_data.data(), prev_data_len);
// }
// size_t position = 0;
// while (position < (BUFFER_SIZE + prev_data_len - MSG_HEADER_SIZE)) {
// auto Header = TaifexMessages::Header_Fields(buffer, position);
// size_t message_length = Header.Body_Length + MSG_HEADER_SIZE + MSG_FOOTER_SIZE;
// if ((BUFFER_SIZE + prev_data_len - position) >= message_length) {
// if (!Header.valid) {
// LOG(md, Error, "Invalid header at position {}", position);
// position += message_length;
// continue;
// }
// switch (data_type) {
// case TaifexDataGateway::DATA_TYPE::LIVE:
// LOG(md, Info, "Processed LIVE sequence: {}", Header.Channel_Seq);
// total_processed++;
// if (Header.Channel_Seq != last_seq_num + 1 && last_seq_num != 0) {
// gap_count++;
// LOG(md, Warn, "Gap #{} in recorded LIVE data: {} to {}",
// gap_count, last_seq_num, Header.Channel_Seq);
// LOG(md, Warn, "header.channel_seq {}", Header.Channel_Seq);
// LOG(md, Warn, "header.channel_id {}", Header.Channel_Id);
// LOG(md, Warn, "last_seq_number {}", last_seq_num);
// LOG(md, Warn, "last channel id {}", last_channel_id);
// if (gap_file) {
// gap_file << "File: " << file_name << "\n";
// gap_file << "Gap #" << gap_count << ": " << last_seq_num
// << " to " << Header.Channel_Seq << "\n";
// gap_file << " header.channel_seq: " << Header.Channel_Seq << "\n";
// gap_file << " header.channel_id: " << Header.Channel_Id << "\n";
// gap_file << " last_seq_number: " << last_seq_num << "\n";
// gap_file << " last channel id: " << last_channel_id << "\n\n";
// }
// }
// last_seq_num = Header.Channel_Seq;
// last_channel_id = Header.Channel_Id;
// handleLiveDataUnparsedMessage(
// buffer, position, Header, listener, security_details);
// break;
// case TaifexDataGateway::DATA_TYPE::REFERENCE:
// handleReferenceDataUnparsedMessage(
// buffer, position, Header, listener, sec_id_store, security_details);
// break;
// case TaifexDataGateway::DATA_TYPE::REFRESH:
// handleRefreshDataUnparsedMessage(buffer, position, Header);
// break;
// default:
// bts_assert(false);
// }
// position += message_length;
// } else {
// break;
// }
// }
// prev_data_len = BUFFER_SIZE + prev_data_len - position;
// if (prev_data_len > 0) {
// std::memcpy(prev_data.data(), buffer.data() + position, prev_data_len);
// }
// start = false;
// }
// // Set output parameters
// out_total_processed = total_processed;
// out_gap_count = gap_count - initial_gap_count; // Gaps for this run only
// LOG(md, Info, "Finished processing {}: last_seq_num {}, total_processed {}, total_gaps {}",
// file_name, last_seq_num, total_processed, out_gap_count);
// return true;
// }
bool runOnBinaryFile(
const std::string &file_name,
std::shared_ptr<bts::md::IMarketDataListener> listener,
@@ -463,6 +604,13 @@ bool runOnBinaryFile(
UNPROCESSED_MSG prev_data(1024); // Stores leftover data
bool start = true;
size_t prev_data_len = 0; // Length of leftover data
//changes to check for gaps in live data
unsigned long last_seq_num = 0; // Track sequence for LIVE data
int last_channel_id = -1;
static int gap_count = 0;
unsigned long total_processed = 0;
while (file.read(
reinterpret_cast<char *>(buffer.data() + prev_data_len), BUFFER_SIZE)) {
size_t bytes_read = file.gcount();
@@ -485,6 +633,25 @@ bool runOnBinaryFile(
// Handle the parsed message
switch (data_type) {
case TaifexDataGateway::DATA_TYPE::LIVE:
LOG(md, Info, "Processed LIVE sequence: {}", Header.Channel_Seq);
total_processed++;
//adding sequence number check
if (Header.Channel_Seq != last_seq_num + 1 &&
last_seq_num != 0) {
gap_count++;
LOG(md, Warn, "Gap #{} in recorded LIVE data: {} to {}",
gap_count, last_seq_num, Header.Channel_Seq);
LOG(md, Warn, "Gap in recorded LIVE data: {} to {}",
last_seq_num, Header.Channel_Seq);
LOG(md, Warn, "header.channel_seq {}", Header.Channel_Seq);
LOG(md, Warn, "header.channel_id {}", Header.Channel_Id);
LOG(md, Warn, "last_seq_number {}", last_seq_num);
LOG(md, Warn, "last channel id {}", last_channel_id);
}
last_seq_num = Header.Channel_Seq;
last_channel_id = Header.Channel_Id;
handleLiveDataUnparsedMessage(
buffer, position, Header, listener, security_details);
break;
@@ -514,6 +681,8 @@ bool runOnBinaryFile(
start = false; // Only move leftover data on subsequent iterations
}
LOG(md, Info, "Finished processing {}: last_seq_num {}, total_processed {}, total_gaps {}",
file_name, last_seq_num, total_processed, gap_count);
return true;
}
@@ -575,7 +744,7 @@ void runLive(
live_buffered_messages.clear();
TaifexUtils::close_sockets(sockets);
last_seq_num = 0;
bts_assert(reset_counter < 5);
bts_assert(reset_counter < 5000);
state = LIVE_DATA_STATES::WAITING_FOR_REFRESH_DATA;
break;
@@ -653,8 +822,13 @@ void runLive(
snapshot_buffered_messages.unsafe_size());
bts_assert(stop_refresh_thread);
while (!snapshot_buffered_messages.empty() ||
!products_waiting.empty()) {
int max_iterations = 100; // Arbitrary limit
int iteration_count = 0;
while ((!snapshot_buffered_messages.empty() ||
!products_waiting.empty()) &&
iteration_count < max_iterations) {
iteration_count++;
SNAPSHOT_BUFFER_MSG msg;
if (!snapshot_buffered_messages.try_pop(msg)) {
continue;
@@ -675,8 +849,6 @@ void runLive(
std::visit(
overloaded{
[&](const TaifexMessages::I010Data &data) {
// std::string s = "looking for: '"+TaifexUtils::remove_spaces(data.prod_id)+"', in"+print(products_waiting);
// LOG(md, Error, "{}",s);
if (products_waiting.contains(
TaifexUtils::remove_spaces(
data.prod_id))) {
@@ -707,11 +879,26 @@ void runLive(
}},
*msg);
}
if (iteration_count >= max_iterations) {
LOG(md, Error,
"Exceeded maximum iterations in REFRESH_DATA_DONE. Either "
"snapshot_buffered_messages or "
"products waiting are not empty.");
// Handle unresolved data or cleanup if necessary
if (!products_waiting.empty()) {
LOG(md, Error, "Unresolved products: {}",
print(products_waiting));
}
if (!snapshot_buffered_messages.empty()) {
LOG(md, Error, "Unprocessed buffered messages: {}",
snapshot_buffered_messages.unsafe_size());
}
}
stop_reference_thread = true;
state = LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE;
break;
// stop reference data
// apply all refresh data
}
case LIVE_DATA_STATES::WAITING_TO_SYNC_LIVE: {
LOG(md, Info, "State: WAITING_TO_SYNC_LIVE");
@@ -772,10 +959,10 @@ void runLive(
}
if (Header.Channel_Seq != last_seq_num + 1) {
LOG(md, Error, "Header.Channel_Seq != last_seq_num+1");
LOG(md, Info, "header.channel_seq {}", Header.Channel_Seq);
LOG(md, Info, "header.channel_id {}", Header.Channel_Id);
LOG(md, Info, "last_seq_number {}", last_seq_num);
LOG(md, Info, "last channel id {}", last_channel_id);
LOG(md, Error, "header.channel_seq {}", Header.Channel_Seq);
LOG(md, Error, "header.channel_id {}", Header.Channel_Id);
LOG(md, Error, "last_seq_number {}", last_seq_num);
LOG(md, Error, "last channel id {}", last_channel_id);
state = LIVE_DATA_STATES::START;
break;
}
@@ -793,7 +980,57 @@ void runLive(
};
}
}
//const std::string &filename,
// void bts::md::taifex::TaifexDataGateway::run(
// const api::md::TaifexMarketDataConfig &config,
// std::shared_ptr<IMarketDataListener> listner,
// std::shared_ptr<persistence::IDGenerator> sec_id_store) {
// std::shared_ptr<TaifexSecurityDetailsMapper> sec_details =
// std::make_shared<TaifexSecurityDetailsMapper>();
// if (config.read_from_file()) {
// bts_assert(!config.ref_data_file_name().empty());
// bts_assert(!config.realtime_data_file_name().empty());
// std::string base_path = config::get<bts::config::SystemConfig>().data_path();
// // Hardcode all realtime_data_20250317_* files (1 to 108)
// std::vector<std::string> realtime_files;
// for (int i = 1; i <= 108; ++i) {
// realtime_files.push_back(base_path + "real_time_data_20250317_" + std::to_string(i));
// }
// unsigned long total_files_processed = 0;
// unsigned long grand_total_processed = 0;
// int grand_total_gaps = 0;
// for (const auto& file_name : realtime_files) {
// LOG(md, Info, "Processing file: {}", file_name);
// unsigned long file_total_processed = 0;
// int file_gap_count = 0;
// bool success = runOnBinaryFile(
// file_name, listner, sec_id_store, sec_details, LIVE,
// file_total_processed, file_gap_count);
// if (success) {
// total_files_processed++;
// grand_total_processed += file_total_processed;
// grand_total_gaps += file_gap_count;
// } else {
// LOG(md, Warn, "Failed to process file: {}", file_name);
// }
// }
// LOG(md, Info, "Processed {} files, total messages processed {}, total gaps {}",
// total_files_processed, grand_total_processed, grand_total_gaps);
// while (1) {
// sleep_for(10s);
// }
// } else {
// runLive(listner, sec_id_store, sec_details);
// }
// }
// }
// const std::string &filename,
void bts::md::taifex::TaifexDataGateway::run(
const api::md::TaifexMarketDataConfig &config,
std::shared_ptr<IMarketDataListener> listner,
@@ -807,6 +1044,8 @@ void bts::md::taifex::TaifexDataGateway::run(
config.ref_data_file_name(); //"reference_data_20240806_1";
std::string realtime_file_name =
config.realtime_data_file_name(); //"real_time_data_20240806_274";
// std::string refresh_file_name = "refresh_data_20250317_1";
// config.refresh_data_file_name();
std::string base_path =
config::get<bts::config::SystemConfig>().data_path();
runOnBinaryFile(
@@ -815,6 +1054,9 @@ void bts::md::taifex::TaifexDataGateway::run(
runOnBinaryFile(
base_path + realtime_file_name, listner, sec_id_store, sec_details,
LIVE);
// runOnBinaryFile(
// base_path + refresh_file_name, listner, sec_id_store, sec_details,
// REFRESH);
while (1) { //confirm with taha
sleep_for(10s);
}
@@ -2,6 +2,7 @@
#include "TaifexMessages.h"
#include "TaifexSecurityDetailsMapper.h"
#include "lib/core/TimeStamp.h"
#include "lib/domain/AggressorSide.h"
#include "lib/domain/Security.h"
#include "lib/domain/TradeRecord.h"
#include "lib/logging/logging.h"
@@ -9,8 +10,6 @@
#include "lib/persistence/IDGenerator.h"
#include "lib/utils/bts_assert.h"
#include <cassert>
#include "lib/config/protos/taifex_reference_data.pb.h"
#include "lib/config/config.h"
namespace bts::md::taifex {
class TaifexDataProcessors {
@@ -72,7 +71,6 @@ class TaifexDataProcessors {
listener->on_book(book);
return true;
}
static void processBookIncrements(
const TaifexMessages::I081Data &msg,
const std::shared_ptr<bts::md::IMarketDataListener> &listener,
@@ -85,7 +83,7 @@ class TaifexDataProcessors {
LOG(md,Error,"sec_id or dec_loc not found for: {}",msg.prod_id);
}
return;
}
}
for (const auto &entry : msg.entries) {
IMarketDataListener::BookOp inc;
inc.id = *sec_id;
@@ -127,19 +125,65 @@ class TaifexDataProcessors {
for (const auto &trade_record : msg.trades) {
auto &record = trades.emplace_back();
record.sec_id = *sec_id;
// record.time_stamp = bts::core::TimeStamp::from_iso_string(
// TaifexUtils::convertToISO(msg.match_time, "datetime_no_timezone"));
record.time_stamp = bts::core::TimeStamp::from_iso_string(
TaifexUtils::convertToISO(msg.match_time, "datetime_no_timezone"));
record.trade_quantity = bts::domain::Quantity(trade_record.match_qty);
record.trade_price = bts::domain::Price(
trade_record.match_price * std::pow(10, 9 - *dec_loc));
// TODO: Set the aggressor side (record.agg_side)
}
std::ostringstream oss;
oss << "Trades: [";
for (const auto &trade : trades) {
oss << "{Sec ID: " << trade.sec_id
<< ", Timestamp: " << trade.time_stamp
<< ", Quantity: " << trade.trade_quantity.value()
<< ", Price: " << trade.trade_price
<< ", Aggressor Side: "
<< ((trade.agg_side == domain::AggressorSide::Buy) ? "Buy" : "Sell")
<< "}, ";
}
std::string trade_log = oss.str();
if (!trades.empty()) {
trade_log.pop_back(); // Remove trailing comma
trade_log.pop_back(); // Remove trailing space
}
trade_log += "]";
// Log the string
LOG(md, Diag, "{}", trade_log);
std::vector<const domain::TradeRecord *> trade_ptrs;
trade_ptrs.reserve(trades.size());
for (const auto &trade : trades) {
trade_ptrs.push_back(&trade);
}
std::ostringstream ptr_oss;
ptr_oss << "Trade Pointers: [";
for (const auto *trade_ptr : trade_ptrs) {
if (trade_ptr) { // Ensure the pointer is not null
ptr_oss << "{Sec ID: " << trade_ptr->sec_id
<< ", Timestamp: " << trade_ptr->time_stamp
<< ", Quantity: " << trade_ptr->trade_quantity.value()
<< ", Price: " << trade_ptr->trade_price
<< ", Aggressor Side: "
<< ((trade_ptr->agg_side == domain::AggressorSide::Buy) ? "Buy" : "Sell")
<< "}, ";
}
}
std::string ptr_log = ptr_oss.str();
if (!trade_ptrs.empty()) {
ptr_log.pop_back(); // Remove trailing comma
ptr_log.pop_back(); // Remove trailing space
}
ptr_log += "]";
// Log the string
LOG(md, Diag, "Sending to Listner {}", ptr_log);
// for (const auto *trade_ptr : trade_ptrs) {
// if (trade_ptr != nullptr) {
// LOG(md, Error, "Trade Quantity: {}, Trade Price: {}",
+47 -12
View File
@@ -3,6 +3,7 @@
#include "lib/utils/bts_assert.h"
#include "lib/utils/helper_macros.h"
#include <bitset>
#include <boost/algorithm/string.hpp> // Include the correct header for trim functions
#include <cassert>
#include <cstdint>
#include <string>
@@ -355,24 +356,33 @@ class TaifexMessages {
}
// do we need this?
size_t current_position = offset;
// Extract Product ID
prod_id =
TaifexUtils::extractString(buffer, current_position, PROD_ID_SIZE);
LOG(md, Diag, "FIND TRADE GAP: In constructor, Prod ID: {}", prod_id);
// Extract Sequence Number
sequence_number = TaifexUtils::extractBCD_STOUL(
buffer, current_position, SEQ_NUMBER_SIZE);
LOG(md, Diag, "Sequence Number: {}", sequence_number);
// Extract Calculated Flag
std::string calculated_flag_str = TaifexUtils::extractString(
buffer, current_position, CALCULATED_FLAG);
calculated_flag = (calculated_flag_str[0] == '1');
LOG(md, Diag, "Calculated Flag: {}", calculated_flag);
// Extract Match Time
match_time = TaifexUtils::time_decodePackBCD(
buffer.data() + current_position, MATCH_TIME);
//match_time = TaifexUtils::convertToISO(match_time);
//match_time = sanitizeISOString(match_time);
; // extractBCD(buffer, current_position, MATCH_TIME);
match_time = TaifexUtils::convertToISOFormat(match_time);
boost::trim(match_time);
LOG(md, Diag, "Match Time (ISO format): {}", match_time);
current_position += MATCH_TIME;
// Extract the first trade
trades.push_back(
trade(buffer, current_position, FIRST_MATCH_QTY_SIZE));
current_position += TRADE_SIZE + 2;
@@ -388,21 +398,32 @@ class TaifexMessages {
auto [new_message, trades_count] =
getFirstBitAndRemainingValue(match_display_item);
// assert(new_message);
LOG(md, Diag,
"Match Display Item: 0x{:02X}, New Message: {}, Trades Count: {}",
match_display_item, new_message, trades_count);
// Extract additional trades
for (int i = 0; i < trades_count; i++) {
trades.push_back(trade(buffer, current_position));
current_position += TRADE_SIZE;
}
// match quantity
// Extract Match Total Quantity
match_total_qty = TaifexUtils::extractBCD_STRING(
buffer, current_position, MATCH_TOTAL_QTY_SIZE);
// match buy count
LOG(md, Diag, "Match Total Quantity: {}", match_total_qty);
// Extract Match Buy Count
match_buy_count = TaifexUtils::extractBCD_STRING(
buffer, current_position, MATCH_BUY_COUNT_SIZE);
// match sell count
LOG(md, Diag, "Match Buy Count: {}", match_buy_count);
// Extract Match Sell Count
match_sell_count = TaifexUtils::extractBCD_STRING(
buffer, current_position, MATCH_SELL_COUNT_SIZE);
// std::cout << "trades count: " << trades_count << std::endl;
LOG(md, Diag, "Match Sell Count: {}", match_sell_count);
// Ensure the message ends with the expected bytes (0x0D 0x0A)
assert(
buffer[current_position + 1] == 0x0D &&
buffer[current_position + 2] == 0x0A);
@@ -467,10 +488,24 @@ class TaifexMessages {
// Convert month code to month number
static int getMonthFromCode(char code) {
if (code >= 'A' && code <= 'L')
return code - 'A' +
1; // 'A' corresponds to 1 (January), 'B' to 2, ..., 'L' to 12 (December)
throw std::runtime_error("Invalid month code");
if (code >= 'A' && code <= 'L') {
int month = code - 'A' + 1;//'A' corresponds to first January, 'B' to February etc.
//for logging
std::string str_month = std::to_string(month);
LOG(md, Diag, "Returned value of getMonthFromCode: {}",
std::to_string(month));
return month;
} else {
//for logging
std::string str_code =
std::string(1, code); // Convert char to string
LOG(md, Error,
"Invalid Month Code, Returning default: 0, Received char: "
"{}",
str_code);
return 0;
}
}
// Method to parse Product ID and initialize ProductInfo
+72 -88
View File
@@ -270,110 +270,94 @@ class TaifexUtils {
return result;
}
static std::string convertToISOFormat(const std::string& input) {
if (input.length() != 12) {
throw std::invalid_argument("Input must be exactly 12 characters (hhmmssxxxxxx).");
}
static std::string convertToISO(
const std::string &match_time,
const std::string &format = "datetime_no_timezone") {
if (match_time.length() != 12) {
throw std::invalid_argument(
"in function convertToISO: match_time must be exactly 12 "
"characters "
"long: -> " +
match_time);
}
// Extract components from the input
std::string hours = input.substr(0, 2);
std::string minutes = input.substr(2, 2);
std::string seconds = input.substr(4, 2);
std::string microseconds = input.substr(6, 6);
try {
// Extract time components
std::string hours = match_time.substr(0, 2);
std::string minutes = match_time.substr(2, 2);
std::string seconds = match_time.substr(4, 2);
// Validate the time components
int hh = std::stoi(hours);
int mm = std::stoi(minutes);
int ss = std::stoi(seconds);
// Validate and sanitize time components
int h = std::abs(std::stoi(hours)) % 24;
int m = std::abs(std::stoi(minutes)) % 60;
int s = std::abs(std::stoi(seconds)) % 60;
if (hh < 0 || hh > 23 || mm < 0 || mm > 59 || ss < 0 || ss > 59) {
throw std::invalid_argument("Invalid time values in input.");
}
// Get the current date dynamically
std::string current_date = getCurrentDate();
// Construct the ISO 8601 time string
std::string isoTime = hours + ":" + minutes + ":" + seconds + "." + microseconds;
return isoTime;
}
// Construct the desired ISO format
std::ostringstream iso_stream;
if (format == "datetime_with_timezone") {
// Full date-time with time zone: "YYYY-MM-DDTHH:MM:SS+02:00" (for simplicity using UTC "Z")
static std::string convertToISO(const std::string &match_time, const std::string &format = "datetime_no_timezone") {
// Ensure match_time is not longer than 15 characters
if (match_time.length() > 15) {
throw std::invalid_argument(
"in function convertToISO: match_time must not be longer than 15 characters: -> " + match_time);
}
// If match_time is shorter than 12 characters, append '0's to the end (for microseconds)
std::string adjusted_match_time = match_time;
while (adjusted_match_time.length() < 12) {
adjusted_match_time += '0'; // Append '0' for microseconds
}
// Remove non-numeric characters (e.g., ":" and ".")
adjusted_match_time.erase(std::remove_if(adjusted_match_time.begin(), adjusted_match_time.end(),
[](char c) { return !std::isdigit(c); }),
adjusted_match_time.end());
// Validate time components
try {
if (adjusted_match_time.length() != 12) {
throw std::invalid_argument("Invalid length for time format: " + match_time);
}
std::string hours = adjusted_match_time.substr(0, 2);
std::string minutes = adjusted_match_time.substr(2, 2);
std::string seconds = adjusted_match_time.substr(4, 2);
std::string microseconds = adjusted_match_time.substr(6, 6); // Ensure this is 6 digits
// Now safely convert to integers
int h = std::abs(std::stoi(hours)) % 24;
int m = std::abs(std::stoi(minutes)) % 60;
int s = std::abs(std::stoi(seconds)) % 60;
// Get the current date dynamically
std::string current_date = getCurrentDate();
// Construct the desired ISO format
std::ostringstream iso_stream;
if (format == "datetime_with_timezone") {
iso_stream << current_date << "T" << std::setfill('0')
<< std::setw(2) << h << ":" << std::setfill('0')
<< std::setw(2) << m << ":" << std::setfill('0')
<< std::setw(2) << s << "Z"; // Assuming UTC for now
} else if (format == "datetime_no_timezone") {
// Date-time without time zone: "YYYY-MM-DDTHH:MM:SS"
<< std::setw(2) << s << "." << microseconds << "Z"; // Assuming UTC for now
} else if (format == "datetime_no_timezone") {
iso_stream << current_date << "T" << std::setfill('0')
<< std::setw(2) << h << ":" << std::setfill('0')
<< std::setw(2) << m << ":" << std::setfill('0')
<< std::setw(2) << s;
} else if (format == "date_only") {
// Date only: "YYYY-MM-DD"
<< std::setw(2) << s << "." << microseconds;
} else if (format == "date_only") {
iso_stream << current_date;
} else {
} else {
throw std::invalid_argument(
"Unknown format specified for convertToISO: " + format);
}
}
return iso_stream.str();
} catch (const std::exception &e) {
std::cerr << "Error in convertToISO: " << e.what() << std::endl;
throw;
}
}
return iso_stream.str();
} catch (const std::exception &e) {
std::cerr << "Error in convertToISO: " << e.what() << std::endl;
throw;
}
}
static std::string sanitizeISOString(const std::string &isoString) {
std::string result = isoString;
// Remove any whitespace
result.erase(
std::remove_if(result.begin(), result.end(), ::isspace),
result.end());
// Ensure it's at least 20 characters long (e.g., YYYY-MM-DDTHH:MM:SS)
if (result.size() != 20) {
if (result.size() < 20) {
// If it's too short, pad with zeros at the end (assuming it's missing time components)
result.append(20 - result.size(), '0');
} else {
// If it's too long, truncate to 20 characters
result = result.substr(0, 20);
}
}
// Check for and correct any time zone issues or missing Z (UTC indicator)
size_t posT = result.find('T');
if (posT != std::string::npos) {
size_t posZ = result.find('Z', posT);
if (posZ == std::string::npos) {
size_t posMinus = result.find('-', posT);
size_t posPlus = result.find('+', posT);
if (posMinus != std::string::npos && posMinus > posT) {
// Check if it's "-0" or "-00" or "-000", etc.
if (std::all_of(
result.begin() + posMinus + 1, result.end(),
[](char c) { return c == '0'; })) {
result = result.substr(0, posMinus) + "Z";
}
} else if (posPlus != std::string::npos && posPlus > posT) {
// Check if it's "+0" or "+00" or "+000", etc.
if (std::all_of(
result.begin() + posPlus + 1, result.end(),
[](char c) { return c == '0'; })) {
result = result.substr(0, posPlus) + "Z";
}
} else {
// If there's no timezone indicator, assume UTC and add 'Z'
result += "Z";
}
}
}
return result;
}
static std::string time_decodePackBCD(
const unsigned char *data, size_t length) {
@@ -0,0 +1,663 @@
#include "TwseDataGateway.h"
#include "TwseMessages.h"
#include "lib/api/domain/SecurityType.pb.h"
#include "lib/domain/Security.h"
#include "lib/domain/TradeRecord.h"
#include "lib/logging/logging.h"
#include "lib/md/IMarketDataListener.h"
#include "lib/persistence/IDGenerator.h"
#include "lib/utils/helper_macros.h"
#include <c++/11/bits/fs_fwd.h>
#include <lib/utils/bts_assert.h>
namespace bts::md::twse {
using UNPROCESSED_DATA = std::vector<unsigned char>;
bool runOnBinaryFile(
const std::string &file_name,
std::set<std::string> &securities_set,
const std::unordered_set<std::string> required_securities,
const std::string &twse_securities_path,
std::shared_ptr<bts::md::IMarketDataListener> &listener,
std::shared_ptr<persistence::IDGenerator> &sec_id_store) {
LOG(md, Diag, "In runOnBinaryFile");
LOG(md, Diag, "The path: {}", file_name);
LOG(md, Diag, "Absolute path: {}",
boost::filesystem::absolute(file_name).string());
std::ifstream file(file_name, std::ios::binary);
if (!file) {
LOG(md, Error, "File not found: {}", file_name);
bts_assert(false);
}
size_t BUFFER_SIZE = 20000;
[[maybe_unused]] size_t counter = 0;
UNPROCESSED_DATA buffer(BUFFER_SIZE);
while (file.read((reinterpret_cast<char *>(buffer.data())), BUFFER_SIZE)) {
size_t position = 0;
[[maybe_unused]] size_t format_counter = 0;
std::cout << std::dec << std::endl;
while (position < BUFFER_SIZE && buffer[position] != 0x1B) {
++position;
}
if (position >= BUFFER_SIZE) {
LOG(md, Error, "Escape code (0x0B) not found in buffer");
break;
}
while (position < BUFFER_SIZE - 10) {
LOG(md, Diag, "Esc Code in Hexadecimal: 0x{:02X}, format counter: {}",
static_cast<int>(buffer[position]), format_counter);
std::cout << std::dec;
LOG(md, Diag, "Position: {}", position);
format_counter++;
position++;
auto Header = TwseMessages::Header_Fields(buffer, position);
std::ostringstream oss;
oss << Header;
std::string headerStr = oss.str();
// LOG(md, Diag, "Header: {}", headerStr);
//std::cout << "Header: \n" << Header;
if (Header.transmission_format_code == 06) {
LOG(md, Diag, "We're in Case 06");
auto format_6 = TwseMessages::Format_6(buffer, position);
std::ostringstream oss;
oss << format_6;
std::string format6Str = oss.str();
LOG(md, Diag, "Format 6: {}", format6Str);
if(format_6.stock_code == "0050"){
LOG(md, Diag, "0050 book!: {}", format6Str);
}
domain::Book book;
auto &bids = book.bids();
auto &asks = book.asks();
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT,
format_6.stock_code)};
// std::vector<bts::domain::TradeRecord> trades;
book.set_security_id(sec_id);
for (unsigned long i = 0; i < format_6.bids.size(); ++i) {
const auto &entry = format_6.bids[i];
auto price = bts::domain::Price::from_double(entry.first / 100.0);
bts::domain::Quantity quantity(entry.second);
bids[i].price =
price; //checck if the indexing starts from 1 or 0
bids[i].total_quantity = quantity;
}
// Similarly for asks
for (unsigned int i = 0; i < format_6.asks.size(); ++i) {
const auto &entry = format_6.asks[i];
auto price = bts::domain::Price::from_double(entry.first / 100.0);
bts::domain::Quantity quantity(entry.second);
asks[i].price = price;
asks[i].total_quantity = quantity;
}
std::vector<bts::domain::TradeRecord> trades;
// First, add the real-time quote if present
for (const auto &quote : format_6.quotes) {
auto &record = trades.emplace_back();
record.sec_id = sec_id;
// record.time_stamp = bts::core::TimeStamp::from_iso_string(
// format_6.matching_time);
record.time_stamp = bts::core::TimeStamp::from_iso_string(
TwseUtils::convertToISO(format_6.matching_time));
record.trade_quantity =
bts::domain::Quantity(quote.volume_field);
record.trade_price = bts::domain::Price(
stod(quote.price_field) * std::pow(10, 9 - 4));
}
std::vector<const domain::TradeRecord *> trade_ptrs;
trade_ptrs.reserve(trades.size());
for (const auto &trade : trades) {
trade_ptrs.push_back(&trade);
}
std::ostringstream ptr_oss;
ptr_oss << "Trade Pointers: [";
for (const auto *trade_ptr : trade_ptrs) {
if (trade_ptr) { // Ensure the pointer is not null
ptr_oss << "{Sec ID: " << trade_ptr->sec_id
<< ", Timestamp: " << trade_ptr->time_stamp
<< ", Quantity: " << trade_ptr->trade_quantity.value()
<< ", Price: " << trade_ptr->trade_price
<< ", Aggressor Side: "
<< ((trade_ptr->agg_side ==
domain::AggressorSide::Buy)
? "Buy"
: "Sell")
<< "}, ";
}
}
// std::string ptr_log = ptr_oss.str();
if (!trade_ptrs.empty()) {
// ptr_log.pop_back(); // Remove trailing comma
// ptr_log.pop_back(); // Remove trailing space
}
// ptr_log += "]";
// Log the string
// LOG(md, Info, "TWSE Sending to Listner {}", ptr_log);
listener->on_book(book);
listener->on_trades(trade_ptrs);
position = position + Header.information_length - 10;
} else if (Header.transmission_format_code == 01) {
LOG(md, Diag, "We're in Case 01");
// Parse Format 1 message
auto format_1 = TwseMessages::Format_1(buffer, position);
// Convert Format_1 to string for logging
std::ostringstream oss;
oss << format_1;
std::string format1Str = oss.str();
LOG(md, Diag, "Format 1: {}", format1Str);
// Extract security ID
const auto id = format_1.sec_code;
const auto symbol = id;
// LOG(md, Info, "Extracted security ID: {}, Symbol: {}", id, symbol);
const std::string trimmed_id = TwseUtils::trim(id);
if (required_securities.find(trimmed_id) ==
required_securities.end()) {
LOG(md, Diag, "Security {} not in required list. Skipping.",
trimmed_id);
continue;
}
if (securities_set.find(trimmed_id) != securities_set.end()) {
LOG(md, Diag, "Security {} already processed. Skipping.", id);
} else {
securities_set.insert(trimmed_id);
// Generate or retrieve SecurityID
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT,
id)};
// LOG(md, Info, "SecurityID in store: {}", sec_id);
// Populate security details
bts::domain::Security sec;
sec.security_common.venue = bts::api::domain::VENUE_TWSE;
sec.security_common.id = sec_id;
sec.security_common.exchange_sec_id = id;
sec.security_common.desc = id;
sec.security_common.symbol = symbol;
sec.security_common.asset = id;
sec.security_common.group = id;
auto get_min_inc = [](const std::string &id) {
// LOG(md, Info, "Getting minimum increment for ID: {}", id);
UNUSED(id);
return 0.1;
};
// Set minimum increments
sec.security_common.min_price_increment = get_min_inc(id);
sec.security_common.min_quantity = get_min_inc(id);
sec.security_common.min_quantity_increment = get_min_inc(id);
LOG(md, Info, "Set minimum increments for security.");
sec.security_common.cash_per_point = stod(format_1.trading_unit);
sec.security_common.currency = format_1.trading_currency_code;
// LOG(md, Info, "Set cash per point: {}, Currency: {}",
// sec.security_common.cash_per_point,
// sec.security_common.currency);
// Serialize Security to JSON
nlohmann::json j;
to_json(j, sec);
std::string json_str = j.dump() + "\n";
// Write JSON to file
std::ofstream outfile(twse_securities_path, std::ios::app);
if (outfile.is_open()) {
outfile << json_str;
outfile.close();
// LOG(md, Info, "Security data written to file.");
} else {
// LOG(md, Info, "Failed to open securities file for writing.");
}
LOG(md, Diag, "securities_set size: {}", securities_set.size());
// Notify listener
std::vector<const domain::Security *> const_security_list;
const_security_list.push_back(&sec);
listener->on_securities(const_security_list);
}
// Update position
position = position + Header.information_length - 10;
} else {
LOG(md, Diag, "Unknown Format");
auto payload_length = Header.information_length;
position += payload_length - 10;
}
}
return true;
}
return false;
}
int runLive(
[[maybe_unused]] std::set<std::string> &securities_set,
[[maybe_unused]] const std::unordered_set<std::string> required_securities,
[[maybe_unused]] const std::string &twse_securities_path,
std::shared_ptr<bts::md::IMarketDataListener> &listener,
std::shared_ptr<persistence::IDGenerator> &sec_id_store) {
LOG(md, Diag, "In runLive");
//live connection
const std::string multicastIp = "224.0.100.100";
const int port = 10000;
const std::string interfaceIp = "10.102.167.131";
// Create a UDP socket
int sock = socket(AF_INET, SOCK_DGRAM, 0);
if (sock < 0) {
LOG(md, Error, "Socket creation failed");
//perror("socket creation failed");
return EXIT_FAILURE;
}
LOG(md, Diag, "Socket created successfully");
int reuse = 1;
if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse)) < 0) {
LOG(md, Error, "Failed to set SO_REUSEADDR on socket");
// perror("setsockopt(SO_REUSEADDR) failed");
close(sock);
return EXIT_FAILURE;
}
LOG(md, Diag, "Socket option SO_REUSEADDR set successfully");
struct sockaddr_in localAddr = {};
localAddr.sin_family = AF_INET;
localAddr.sin_port = htons(port);
localAddr.sin_addr.s_addr = INADDR_ANY;
if (bind(sock, (struct sockaddr *)&localAddr, sizeof(localAddr)) < 0) {
LOG(md, Error, "Socket bind failed");
// perror("bind failed");
close(sock);
return EXIT_FAILURE;
}
LOG(md, Diag, "Socket bound successfully to port");
// Join multicast group
struct ip_mreq mreq;
mreq.imr_multiaddr.s_addr = inet_addr(multicastIp.c_str());
mreq.imr_interface.s_addr = inet_addr(interfaceIp.c_str());
if (setsockopt(sock, IPPROTO_IP, IP_ADD_MEMBERSHIP, &mreq, sizeof(mreq)) <
0) {
LOG(md, Error, "Failed to join multicast group");
// perror("setsockopt(IP_ADD_MEMBERSHIP) failed");
close(sock);
return EXIT_FAILURE;
}
LOG(md, Diag, "Joined multicast group successfully");
const size_t BUFFER_SIZE = 1024 * 1024;
std::vector<unsigned char> buffer(BUFFER_SIZE);
LOG(md, Diag, "Entering data reception loop");
while (true) {
struct sockaddr_in srcAddr;
socklen_t addrLen = sizeof(srcAddr);
size_t bytesRead = recvfrom(
sock, buffer.data(), BUFFER_SIZE, 0, (struct sockaddr *)&srcAddr,
&addrLen);
if (bytesRead < 0) {
std::string err = strerror(errno);
LOG(md, Error, "recvfrom failed: {}", err);
break;
}
// LOG(md, Info, "Received {} bytes from {}:{}", bytesRead,
// inet_ntoa(srcAddr.sin_addr), ntohs(srcAddr.sin_port));
// Parse received data
size_t position = 0;
size_t format_counter = 0;
while (position < bytesRead && buffer[position] != 0x1B) {
++position; // Search for escape code (0x1B)
}
if (position >= bytesRead) {
// std::cerr << "Escape code (0x1B) not found in buffer" << std::endl;
continue;
}
while (position < bytesRead - 10) {
std::ostringstream sink;
sink << "Escape Code in Hexadecimal: 0x" << std::hex
<< std::setw(2) << std::setfill('0')
<< static_cast<int>(buffer[position]) << " for format #"
<< format_counter << std::endl;
++format_counter;
++position;
auto Header = TwseMessages::Header_Fields(buffer, position);
std::ostringstream oss;
oss << Header;
std::string headerStr = oss.str();
LOG(md, Diag, "Header: {}", headerStr);
if (Header.transmission_format_code == 6) {
LOG(md, Info, "Book Message --> Case 06");
LOG(md, Diag, "Book-->Case 06");
auto format_6 = TwseMessages::Format_6(buffer, position);
std::ostringstream oss;
oss << format_6;
std::string format6Str = oss.str();
LOG(md, Diag, "Format 6: {}", format6Str);
if(format_6.stock_code == "0050"){
// LOG(md, Diag, "0050 book!: {}", format6Str);
}
domain::Book book;
auto &bids = book.bids();
auto &asks = book.asks();
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT,
format_6.stock_code)};
// std::vector<bts::domain::TradeRecord> trades;
book.set_security_id(sec_id);
for (unsigned long i = 0; i < format_6.bids.size(); ++i) {
const auto &entry = format_6.bids[i];
auto price = bts::domain::Price::from_double(entry.first / 100.0);
bts::domain::Quantity quantity(entry.second);
bids[i].price =
price; //checck if the indexing starts from 1 or 0
bids[i].total_quantity = quantity;
}
// Similarly for asks
for (unsigned int i = 0; i < format_6.asks.size(); ++i) {
const auto &entry = format_6.asks[i];
auto price = bts::domain::Price::from_double(entry.first / 100.0);
bts::domain::Quantity quantity(entry.second);
asks[i].price = price;
asks[i].total_quantity = quantity;
}
std::vector<bts::domain::TradeRecord> trades;
// First, add the real-time quote if present
for (const auto &quote : format_6.quotes) {
auto &record = trades.emplace_back();
record.sec_id = sec_id;
// record.time_stamp = bts::core::TimeStamp::from_iso_string(
// format_6.matching_time);
record.time_stamp = bts::core::TimeStamp::from_iso_string(
TwseUtils::convertToISO(format_6.matching_time));
record.trade_quantity =
bts::domain::Quantity(quote.volume_field);
record.trade_price = bts::domain::Price(
stod(quote.price_field) * std::pow(10, 9 - 4));
}
std::vector<const domain::TradeRecord *> trade_ptrs;
trade_ptrs.reserve(trades.size());
for (const auto &trade : trades) {
trade_ptrs.push_back(&trade);
}
std::ostringstream ptr_oss;
ptr_oss << "Trade Pointers: [";
for (const auto *trade_ptr : trade_ptrs) {
if (trade_ptr) { // Ensure the pointer is not null
ptr_oss << "{Sec ID: " << trade_ptr->sec_id
<< ", Timestamp: " << trade_ptr->time_stamp
<< ", Quantity: " << trade_ptr->trade_quantity.value()
<< ", Price: " << trade_ptr->trade_price
<< ", Aggressor Side: "
<< ((trade_ptr->agg_side == domain::AggressorSide::Buy) ? "Buy" : "Sell")
<< "}, ";
}
}
std::string ptr_log = ptr_oss.str();
if (!trade_ptrs.empty()) {
ptr_log.pop_back(); // Remove trailing comma
ptr_log.pop_back(); // Remove trailing space
}
ptr_log += "]";
// Log the string
LOG(md, Diag, "TWSE Sending to Listner {}", ptr_log);
listener->on_book(book);
listener->on_trades(trade_ptrs);
position += Header.information_length - 10;
} else if (Header.transmission_format_code == 1) {
LOG(md, Info, "Case 01 --> Securities Message");
LOG(md, Diag, "We're in Case 01");
// Parse Format 1 message
auto format_1 = TwseMessages::Format_1(buffer, position);
// Convert Format_1 to string for logging
std::ostringstream oss;
oss << format_1;
std::string format1Str = oss.str();
LOG(md, Diag, "Format 1: {}", format1Str);
// Extract security ID
const auto id = format_1.sec_code;
const auto symbol = id;
LOG(md, Diag, "Extracted security ID: {}, Symbol: {}", id, symbol);
const std::string trimmed_id = TwseUtils::trim(id);
if (required_securities.find(trimmed_id) ==
required_securities.end()) {
LOG(md, Diag, "Security {} not in required list. Skipping.",
trimmed_id);
continue;
}
if (securities_set.find(trimmed_id) != securities_set.end()) {
LOG(md, Diag, "Security {} already processed. Skipping.", id);
} else {
securities_set.insert(trimmed_id);
// Generate or retrieve SecurityID
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT,
id)};
// LOG(md, Info, "SecurityID in store: {}", sec_id);
// Populate security details
bts::domain::Security sec;
sec.security_common.venue = bts::api::domain::VENUE_TWSE;
sec.security_common.id = sec_id;
sec.security_common.exchange_sec_id = id;
sec.security_common.desc = id;
sec.security_common.symbol = symbol;
sec.security_common.asset = id;
sec.security_common.group = id;
// Helper function for minimum increment
auto get_min_inc = [](const std::string &id) {
// LOG(md, Info, "Getting minimum increment for ID: {}", id);
UNUSED(id);
return 0.1;
};
// Populate other fields
sec.security_common.min_price_increment = get_min_inc(id);
sec.security_common.min_quantity = get_min_inc(id);
sec.security_common.min_quantity_increment = get_min_inc(id);
// LOG(md, Info, "Set minimum increments for security.");
sec.security_common.cash_per_point = stod(format_1.trading_unit);
sec.security_common.currency = format_1.trading_currency_code;
// LOG(md, Info, "Set cash per point: {}, Currency: {}",
// sec.security_common.cash_per_point,
// sec.security_common.currency);
// Serialize Security to JSON
nlohmann::json j;
to_json(j, sec);
std::string json_str = j.dump() + "\n";
// Write JSON to file
std::ofstream outfile(twse_securities_path, std::ios::app);
if (outfile.is_open()) {
outfile << json_str;
outfile.close();
// LOG(md, Info, "Security data written to file.");
} else {
// LOG(md, Info, "Failed to open securities file for writing.");
}
std::vector<const domain::Security *> const_security_list;
const_security_list.push_back(&sec);
listener->on_securities(const_security_list);
}
position += Header.information_length - 10;
} else {
LOG(md, Diag, "Unknown Format");
auto payload_length = Header.information_length;
position += payload_length - 10;
}
}
}
close(sock);
return 0;
}
void loadSecurities(
const std::string &filePath,
std::set<std::string> &securitiesSet,
std::shared_ptr<persistence::IDGenerator> sec_id_store,
std::vector<std::shared_ptr<bts::domain::Security>> &securitiesVector,
std::shared_ptr<IMarketDataListener> listener) {
std::ifstream infile(filePath);
if (!infile.is_open()) {
LOG(md, Error, "Failed to open securities file for reading: {}",
filePath);
return;
}
std::string line;
while (std::getline(infile, line)) {
try {
nlohmann::json j = nlohmann::json::parse(line);
std::shared_ptr<bts::domain::Security> sec =
std::make_shared<bts::domain::Security>();
from_json(j, *sec);
const std::string id = sec->security_common.exchange_sec_id;
if (securitiesSet.find(id) == securitiesSet.end()) {
// Generate or retrieve SecurityID
bts::domain::SecurityID sec_id{sec_id_store->get_or_add(
api::domain::VENUE_TWSE, api::domain::SECURITY_TYPE_SPOT, id)};
sec->security_common.id = sec_id;
securitiesSet.insert(id);
securitiesVector.push_back(sec);
LOG(md, Diag, "Loaded security: {}", id);
} else {
LOG(md, Diag, "Duplicate security ID: {}", id);
}
} catch (const nlohmann::json::parse_error &e) {
std::string err = e.what();
LOG(md, Error, "JSON parse error: {}", err);
} catch (const std::exception &e) {
std::string err = e.what();
LOG(md, Error, "Error loading security: {}", err);
}
}
infile.close();
// Notify listener about the loaded securities
if (!securitiesVector.empty()) {
std::vector<const bts::domain::Security *> securitiesToNotify;
for (const auto &sec : securitiesVector) {
securitiesToNotify.push_back(sec.get());
}
listener->on_securities(securitiesToNotify);
}
}
void bts::md::twse::TwseDataGateway::run(
[[maybe_unused]] const api::md::TwseMarketDataConfig &config,
[[maybe_unused]] std::shared_ptr<IMarketDataListener> listner,
[[maybe_unused]] std::shared_ptr<persistence::IDGenerator> sec_id_store) {
LOG(md, Diag, "In run, twsedatagateway.cpp");
std::string twse_securities_path =
"/home/bts/sparkdata/data/twse_load_securities.jsonl";
std::string sec_path = "/home/bts/sparkdata/data/1st_ip_securities_20250116_4";
std::string book_path =
"/home/bts/sparkdata/data/1st_ip_securities_20250116_27";
std::set<std::string> securities_set;
LOG(md, Diag, "securities_set size: {}", securities_set.size());
// const std::unordered_set<std::string> required_securities = {
// "0050", "2317", "2454", "2603", "2615", "00631L", "00633L",
// "00634R", "00637L", "00638R", "00653L", "00654R", "00675L", "00676R",
// "00637L", "006204", "00929", "00919", "006208"};
const std::unordered_set<std::string> required_securities = {
"0050", "2317", "2454", "2603", "2615", "00631L", "00633L",
"00634R", "00637L", "00638R", "00653L", "00654R", "00675L", "00676R",
"00637L", "006204", "00929", "00919", "006208",/*
"6239", "0050", "00703", "00706L", "00707R", "00961", "01001T", "2613",
"0056", "0055", "6239", "00703", "00706L", "00707R", "00961", "01001T",
"2613", "0056", "0055", "00657K", "00690", "00708L", "00712", "00715L",
"00919", "00934", "00938", "00943", "00952", "00685L",*/"054276", "054277", "054278"
};
std::vector<std::shared_ptr<bts::domain::Security>> securities_vector;
loadSecurities(
twse_securities_path, securities_set, sec_id_store, securities_vector,
listner);
bool run_on_live = true;
if (run_on_live) {
runLive(
securities_set, required_securities, twse_securities_path, listner,
sec_id_store);
} else {
runOnBinaryFile(
sec_path, securities_set, required_securities, twse_securities_path,
listner, sec_id_store);
runOnBinaryFile(
book_path, securities_set, required_securities, twse_securities_path,
listner, sec_id_store);
}
}
} // namespace bts::md::twse
@@ -0,0 +1,27 @@
#include "lib/api/md/TwseMarketDataConfig.pb.h"
#include <memory> // Add this line for std::shared_ptr
namespace bts::persistence {
class IDGenerator;
}
namespace bts::md {
class IMarketDataListener;
}
namespace bts::md::twse {
class TwseDataGateway {
public:
static void run(const api::md::TwseMarketDataConfig &config,
std::shared_ptr<IMarketDataListener> listner,
std::shared_ptr<persistence::IDGenerator> sec_id_store);
// (void)config;
// (void)listener;
// (void)sec_id_store;
// // Dummy implementation
};
} // namespace bts::md::twse
@@ -0,0 +1,37 @@
// TwseDataProcessors.h
#ifndef TWSE_DATA_PROCESSORS_H
#define TWSE_DATA_PROCESSORS_H
#include "TwseMessages.h"
#include "lib/domain/Security.h"
#include "lib/md/IMarketDataListener.h"
namespace bts::md::twse {
class TwseDataProcessors {
public:
// TwseMessages::Format_1 format_1;
// static bool processBookMessage(
// const TwseMessages::Format_6 &format_6,
// const TwseMessages::Format_1 &format_1,
// std::shared_ptr<bts::md::IMarketDataListener> listener) {
// auto sec_id = format_1.sec_code;
// if (!sec_id)
// return false;
// domain::Book book;
// auto &bids = book.bids();
// auto &asks = book.asks();
// book.set_security_id(sec_id.value());
// for(const auto &quote : format_6.quotes){
// bts::domain::Price price(quote.price_field);
// bts::domain::Quantity quantity(quote.volume_field);
// }
// listener -> on_book(book);
// return true;
// }
};
} // namespace bts::md::twse
#endif // TWSE_DATA_PROCESSORS_H
+430
View File
@@ -0,0 +1,430 @@
// TwseMessages.h
#include "TwseUtils.h"
#include "lib/logging/logging.h"
#include <bitset>
#include <cstdint>
#include <ostream>
#include <vector>
#ifndef TWSE_MESSAGES_H
#define TWSE_MESSAGES_H
namespace bts::md::twse {
class TwseMessages {
public:
struct Header_Fields {
size_t information_length;
size_t business_type;
size_t transmission_format_code;
size_t transmission_format_version;
size_t transmission_sn;
static const size_t HEADER_SIZE =
9; // Total size of header including all fields
Header_Fields(const std::vector<unsigned char> &buffer, size_t &offset) {
information_length =
stoull(TwseUtils::decodePackBCD(&buffer[offset], 2));
business_type =
stoull(TwseUtils::decodePackBCD(&buffer[offset + 2], 1));
transmission_format_code =
stoull(TwseUtils::decodePackBCD(&buffer[offset + 3], 1));
transmission_format_version =
stoull(TwseUtils::decodePackBCD(&buffer[offset + 4], 1));
transmission_sn =
stoull(TwseUtils::decodePackBCD(&buffer[offset + 5], 4));
// move offset past header
offset += HEADER_SIZE;
}
friend std::ostream &operator<<(
std::ostream &os, const Header_Fields &hf) {
// std::cout<<std::dec;
os << "Information Length: " << hf.information_length << "\n"
<< "Business Type: " << hf.business_type << "\n"
<< "Transmission Format Code: " << hf.transmission_format_code
<< "\n"
<< "Transmission Format Version: " << hf.transmission_format_version
<< "\n"
<< "Transmission S/N: " << hf.transmission_sn << "\n";
return os;
}
};
struct Format_6 {
std::string stock_code;
std::string matching_time;
uint8_t disclosed_item_remarks;
uint8_t rise_fall_remarks;
uint8_t status_remarks;
unsigned long accumalative_trading_volume;
std::vector<std::pair<double, uint32_t>> bids;
std::vector<std::pair<double, uint32_t>> asks;
struct RealTimeQuotes {
std::string price_field;
uint32_t volume_field;
RealTimeQuotes(
const std::vector<unsigned char> &buffer,
const size_t &offset = 0) {
price_field = TwseUtils::decodePackBCD(&buffer[offset], 5);
volume_field =
stoul(TwseUtils::decodePackBCD(&buffer[offset + 5], 4));
//offset = offset + 9;
}
friend std::ostream &operator<<(
std::ostream &os,
const Format_6::RealTimeQuotes &real_time_quotes) {
os << "\n Price Field: " << real_time_quotes.price_field << "\n"
<< "Volume Field: " << real_time_quotes.volume_field << "\n";
return os;
}
};
std::vector<RealTimeQuotes> quotes;
// std::vector<RealTimeQuotes> quotes;
friend std::ostream &operator<<(
std::ostream &os, const Format_6 &format) {
os << "\nStock Code: ." << format.stock_code << ".\n"
<< "Matching Time: " << format.matching_time << "\n"
<< "Disclosed Item Remarks (Binary): "
<< std::bitset<8>(format.disclosed_item_remarks)
<< " (Decimal: " << static_cast<int>(format.disclosed_item_remarks)
<< ")\n"
<< "Rise/Fall Remarks (Binary): "
<< std::bitset<8>(format.rise_fall_remarks)
<< " (Decimal: " << static_cast<int>(format.rise_fall_remarks)
<< ")\n"
<< "Status Remarks (Binary): "
<< std::bitset<8>(format.status_remarks)
<< " (Decimal: " << static_cast<int>(format.status_remarks) << ")\n"
<< "Accumulative Trading Volume: "
<< format.accumalative_trading_volume << "\n";
os << "Real Time Quotes:\n";
for (const auto &quote : format.quotes) {
os << quote;
}
os << "Bids: \n";
for (const auto &bid : format.bids) {
os << "Price = " << bid.first << " Quantity = " << bid.second
<< "\n";
}
os << "\nAsks: \n";
for (const auto &ask : format.asks) {
os << "Price = " << ask.first << " Quantity = " << ask.second
<< "\n";
}
// os << "Quotes:\n";
// for (const auto &real_time_quotes : format.quotes) {
// os << real_time_quotes;
// }
return os;
}
Format_6(
const std::vector<unsigned char> &buffer, const size_t &offset = 0) {
size_t position = offset;
stock_code = std::string(
buffer.begin() + position, buffer.begin() + position + 6);
stock_code = TwseUtils::trim(stock_code);
position += 6;
matching_time = TwseUtils::decodePackBCD(&buffer[position], 6);
position += 6;
disclosed_item_remarks = buffer[position];
position += 1;
rise_fall_remarks = buffer[position];
position += 1;
status_remarks = buffer[position];
position += 1;
accumalative_trading_volume =
stoul(TwseUtils::decodePackBCD(&buffer[position], 4));
position += 4;
if (disclosed_item_remarks & 0x80) { // If Bit 7 is 1
LOG(md, Diag, "Price Field and Volume Field present");
// std::cin.ignore();
auto rtq = RealTimeQuotes(buffer, position);
quotes.push_back(rtq);
} else {
LOG(md, Diag, "No Price Field and Volume Field");
}
LOG(md, Diag, "Purchasing Price and Volumes");
std::cout << std::dec;
// Read Purchase Price and Volume
uint8_t purchasing_count =
(disclosed_item_remarks >> 4) & 0x07; // Get bits 6-4
for (uint8_t i = 0; i < purchasing_count; ++i) {
std::string purchase_price =
TwseUtils::decodePackBCD(&buffer[position], 5); // Price Field
double bid_price =
std::stod(TwseUtils::decodePackBCD(&buffer[position], 5));
position += 5; // Move to the volume field
std::string volume_field =
TwseUtils::decodePackBCD(&buffer[position], 4); // Volume Field
uint32_t bid_volume =
stoul(TwseUtils::decodePackBCD(&buffer[position], 4));
position += 4; // Move to the next price field
LOG(md, Info, "Purchase Price {}: {} Volume {}: {}", i + 1,
purchase_price, i + 1, volume_field);
bids.emplace_back(bid_price, bid_volume);
}
// Read Sell Price and Volume if applicable
uint8_t selling_count =
(disclosed_item_remarks >> 1) & 0x07; // Get bits 3-1
for (uint8_t i = 0; i < selling_count; ++i) {
std::string sell_price = TwseUtils::decodePackBCD(
&buffer[position], 5); // Price Field: 5 bytes
double ask_price =
std::stod(sell_price); // Use the 5-byte decoded value
position += 5; // Move to the volume field
std::string volume_field = TwseUtils::decodePackBCD(
&buffer[position], 4); // Volume Field: 4 bytes
uint32_t ask_volume =
stoul(volume_field); // Use the 4-byte decoded value
position += 4; // Move to the next price field
LOG(md, Info, "Sell Price {}: {} Volume {}: {}", i + 1, sell_price,
i + 1, volume_field);
asks.emplace_back(ask_price, ask_volume);
}
}
};
struct Format_1 {
std::string sec_code;
std::string stock_abbreviation;
std::string industry_category;
std::string stock_category; //can be blank
std::string stock_entries; //can be blank
std::string stock_anomaly_code;
std::string board_code;
std::string today_currency_price;
std::string trading_currency_code;
std::string rise_stop_price;
std::string fall_stop_price;
std::string non_10_face_value_indicator;
std::string abnormal_recommendation_indicator;
std::string abnormal_securities_indicator;
std::string day_trading_indicator;
std::string exemption_unchanged_market_margin_sale_indicator;
std::string exemption_unchanged_market_securities_lending_sale_indicator;
std::string matching_cycle_seconds;
std::string warrant_id;
std::string
exercise_strike_price; // This will need to be decoded from PACK BCD
std::string
prev_business_day_exercise_volume; // This will also need PACK BCD decoding
std::string prev_business_day_cancellation_volume; // PACK BCD format
std::string issuing_balance_volume; // PACK BCD format
std::string strike_ratio; // PACK BCD format
std::string upper_limit_price; // PACK BCD format
std::string lower_limit_price; // PACK BCD format
std::string maturity_date;
std::string foreign_stock_id;
std::string trading_unit; // PACK BCD format
std::string trading_currency_code_foreign_stock;
std::string market_information_note;
Format_1(
const std::vector<unsigned char> &buffer, const size_t &offset = 0) {
size_t position = offset;
sec_code = std::string(
buffer.begin() + position, buffer.begin() + position + 6);
sec_code = TwseUtils::trim(sec_code);
position += 6;
stock_abbreviation = std::string(
buffer.begin() + position, buffer.begin() + position + 16);
position += 16;
industry_category = std::string(
buffer.begin() + position, buffer.begin() + position + 2);
// std::cout << "Industry Category (Hex): ";
// for (char c : industry_category_str) {
// std::cout << std::setw(2) << std::setfill('0') << std::hex <<
// (int)(unsigned char)c << " ";
// }
// std::cout << std::endl;
// Convert the ASCII string to an integer
position += 2;
//hex values show pointing at the right place
stock_category = std::string(
buffer.begin() + position, buffer.begin() + position + 2);
// std::cout << "Stock Category (String): " << stock_category << std::endl;
// std::cout << "Stock Category (ASCII Values): ";
// for (char c : stock_category) {
// std::cout << (int)(unsigned char)c << " "; // Prints the ASCII value of each character
// }
// std::cout << std::endl;
// std::cout << "Stock Category (Hex): ";
// for (char c : stock_category) {
// std::cout << std::setw(2) << std::setfill('0') << std::hex <<
// (int)(unsigned char)c << " ";
// }
// std::cout << std::endl;
position += 2;
stock_entries = std::string(
buffer.begin() + position, buffer.begin() + position + 2);
position += 2;
stock_anomaly_code = TwseUtils::decodePackBCD(&buffer[position], 1);
position += 1;
board_code = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
today_currency_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
rise_stop_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
fall_stop_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
non_10_face_value_indicator = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
abnormal_recommendation_indicator = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
abnormal_securities_indicator = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
day_trading_indicator = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
exemption_unchanged_market_margin_sale_indicator = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
exemption_unchanged_market_securities_lending_sale_indicator =
std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
matching_cycle_seconds =
TwseUtils::decodePackBCD(&buffer[position], 3);
position += 3;
warrant_id = std::string(
buffer.begin() + position, buffer.begin() + position + 1);
position += 1;
exercise_strike_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
prev_business_day_exercise_volume =
TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
prev_business_day_cancellation_volume =
TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
issuing_balance_volume =
TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
strike_ratio = TwseUtils::decodePackBCD(&buffer[position], 4);
position += 4;
upper_limit_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
lower_limit_price = TwseUtils::decodePackBCD(&buffer[position], 5);
position += 5;
maturity_date = TwseUtils::decodePackBCD(&buffer[position], 4);
position += 4;
foreign_stock_id = TwseUtils::decodePackBCD(&buffer[position], 1);
position += 1;
trading_unit = TwseUtils::decodePackBCD(&buffer[position], 3);
position += 3;
trading_currency_code = TwseUtils::decodePackBCD(&buffer[position], 3);
position += 3;
market_information_note =
TwseUtils::decodePackBCD(&buffer[position], 1);
position += 1;
}
friend std::ostream &operator<<(
std::ostream &os, const Format_1 &format) {
os << "\nSEC Code: " << format.sec_code << "\n"
<< "Stock Abbreviation: " << format.stock_abbreviation << "\n"
<< "Industry Category: " << format.industry_category << "\n"
<< "Stock Category(can be blank): " << format.stock_category << "\n"
<< "Stock Entries(can be blank): " << format.stock_entries << "\n"
<< "Stock Anomaly code: " << format.stock_anomaly_code << "\n"
<< "Board Code: " << format.board_code << "\n"
<< "Today Currency Price: " << format.today_currency_price << "\n"
<< "Rise Stop Price: " << format.rise_stop_price << "\n"
<< "Fall Stop Price: " << format.fall_stop_price << "\n"
<< "Non-$10 Face Value Indicator: "
<< format.non_10_face_value_indicator << "\n"
<< "Abnormal Recommendation Indicator: "
<< format.abnormal_recommendation_indicator << "\n"
<< "Abnormal Securities Indicator: "
<< format.abnormal_securities_indicator << "\n"
<< "Day Trading Indicator: " << format.day_trading_indicator << "\n"
<< "Exemption of Unchanged Market Margin Sale Indicator: "
<< format.exemption_unchanged_market_margin_sale_indicator << "\n"
<< "Exemption of Unchanged Market Securities Lending Sale "
"Indicator: "
<< format
.exemption_unchanged_market_securities_lending_sale_indicator
<< "\n"
<< "Matching Cycle Seconds: " << format.matching_cycle_seconds
<< "\n"
<< "Warrant ID: " << format.warrant_id << "\n"
<< "Exercise (Strike) Price: " << format.exercise_strike_price
<< "\n"
<< "Previous Business Day Exercise Volume: "
<< format.prev_business_day_exercise_volume << "\n"
<< "Previous Business Day Cancellation Volume: "
<< format.prev_business_day_cancellation_volume << "\n"
<< "Issuing Balance Volume: " << format.issuing_balance_volume
<< "\n"
<< "Strike Ratio: " << format.strike_ratio << "\n"
<< "Upper Limit Price: " << format.upper_limit_price << "\n"
<< "Lower Limit Price: " << format.lower_limit_price << "\n"
<< "Maturity Date: " << format.maturity_date << "\n"
<< "Foreign Stock ID: " << format.foreign_stock_id << "\n"
<< "Trading Unit: " << format.trading_unit << "\n"
<< "Trading Currency Code: " << format.trading_currency_code << "\n"
<< "Market Information Note: " << format.market_information_note
<< "\n";
return os;
}
};
};
} //namespace bts::md::twse
#endif // TWSE_MESSAGES_H
@@ -0,0 +1,13 @@
// TwseSecurityDetailsMapper.h
#ifndef TWSE_SECURITY_DETAILS_MAPPER_H
#define TWSE_SECURITY_DETAILS_MAPPER_H
namespace TWSE {
class TwseSecurityDetailsMapper {
public:
TwseSecurityDetailsMapper() = default;
~TwseSecurityDetailsMapper() = default;
};
}
#endif // TWSE_SECURITY_DETAILS_MAPPER_H
+124
View File
@@ -0,0 +1,124 @@
// TwseUtils.h
#include <boost/date_time/posix_time/ptime.hpp>
#include <boost/date_time/posix_time/time_parsers.hpp>
#include <chrono>
#include <sstream>
#ifndef TWSE_UTILS_H
#define TWSE_UTILS_H
namespace bts::md::twse {
class TwseUtils {
public:
// Function to trim whitespace from a string
static std::string trim(const std::string &str) {
size_t first = str.find_first_not_of(' ');
if (std::string::npos == first) {
return str;
}
size_t last = str.find_last_not_of(' ');
return str.substr(first, (last - first + 1));
}
static std::string getCurrentDate() {
auto now = std::chrono::system_clock::now();
std::time_t now_c = std::chrono::system_clock::to_time_t(now);
std::tm local_tm = *std::localtime(&now_c);
char buffer[11]; // Buffer to hold formatted date
std::strftime(buffer, sizeof(buffer), "%Y-%m-%d", &local_tm);
return std::string(buffer);
}
static std::string convertToISO(
const std::string &match_time,
const std::string &format = "datetime_no_timezone") {
// Ensure match_time is not longer than 15 characters
if (match_time.length() > 15) {
throw std::invalid_argument(
"in function convertToISO: match_time must not be longer than 15 "
"characters: -> " +
match_time);
}
// If match_time is shorter than 12 characters, append '0's to the end (for microseconds)
std::string adjusted_match_time = match_time;
while (adjusted_match_time.length() < 12) {
adjusted_match_time += '0'; // Append '0' for microseconds
}
// Remove non-numeric characters (e.g., ":" and ".")
adjusted_match_time.erase(
std::remove_if(
adjusted_match_time.begin(), adjusted_match_time.end(),
[](char c) { return !std::isdigit(c); }),
adjusted_match_time.end());
// Validate time components
try {
if (adjusted_match_time.length() != 12) {
throw std::invalid_argument(
"Invalid length for time format: " + match_time);
}
std::string hours = adjusted_match_time.substr(0, 2);
std::string minutes = adjusted_match_time.substr(2, 2);
std::string seconds = adjusted_match_time.substr(4, 2);
std::string microseconds =
adjusted_match_time.substr(6, 6); // Ensure this is 6 digits
// Now safely convert to integers
int h = std::abs(std::stoi(hours)) % 24;
int m = std::abs(std::stoi(minutes)) % 60;
int s = std::abs(std::stoi(seconds)) % 60;
// Get the current date dynamically
std::string current_date = getCurrentDate();
// Construct the desired ISO format
std::ostringstream iso_stream;
if (format == "datetime_with_timezone") {
iso_stream << current_date << "T" << std::setfill('0')
<< std::setw(2) << h << ":" << std::setfill('0')
<< std::setw(2) << m << ":" << std::setfill('0')
<< std::setw(2) << s << "." << microseconds
<< "Z"; // Assuming UTC for now
} else if (format == "datetime_no_timezone") {
iso_stream << current_date << "T" << std::setfill('0')
<< std::setw(2) << h << ":" << std::setfill('0')
<< std::setw(2) << m << ":" << std::setfill('0')
<< std::setw(2) << s << "." << microseconds;
} else if (format == "date_only") {
iso_stream << current_date;
} else {
throw std::invalid_argument(
"Unknown format specified for convertToISO: " + format);
}
return iso_stream.str();
} catch (const std::exception &e) {
std::cerr << "Error in convertToISO: " << e.what() << std::endl;
throw;
}
}
static std::string decodePackBCD(const unsigned char *data, size_t length) {
std::stringstream ss;
for (size_t i = 0; i < length; ++i) {
// Extract the upper and lower nibble (4 bits each)
int upper = (data[i] >> 4) & 0x0F;
int lower = data[i] & 0x0F;
// Append both nibbles to the stringstream
ss << upper << lower;
}
std::string result = ss.str();
// Remove leading zeros
// result.erase(0, result.find_first_not_of('0'));
// If the result is empty (all zeros), return "0"
return result.empty() ? "0" : result;
}
};
} //namespace bts::md::twse
#endif // TWSE_UTILS_H
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
tools_path=$(dirname $(readlink -f $0))
eval "$tools_path/ensure_venv.sh" 1> /dev/stdout 2> /dev/stderr
eval "$tools_path/venv_exec.sh python $tools_path/py/publish_api_server.py $@" 1> /dev/stdout 2> /dev/stderr
+1 -5
View File
@@ -24,11 +24,7 @@ def _workspace_root():
def _default_build():
if sys.platform == 'win32':
return _workspace_root().joinpath('build')
elif sys.platform == 'linux':
return _workspace_root().joinpath('build', 'gcc', 'release')
raise ValueError(f"Unknown platform '{sys.platform}'")
return _workspace_root().joinpath('build')
class SparkPaths:
+208
View File
@@ -0,0 +1,208 @@
import argparse
import os
import subprocess
import sys
from shutil import copytree
from typing import Optional
from build_spark import SparkPaths
from core.iter_utils import at_bounded
def _dotnet_verbosity(level):
names = ["quiet", "minimal", "normal", "detailed", "diagnostic"]
return at_bounded(names, level - 1)
def _cmake_verbosity(level):
# Skip 'WARNING' and 'NOTICE' levels, since the default CMake verbosity,
# 'STATUS', doesn't produce that much output. This also better normalizes
# numeric representation of verbosity w/ dotnet, which only has 5 levels.
names = [
"ERROR",
# 'WARNING',
# 'NOTICE',
"STATUS",
"VERBOSE",
"DEBUG",
"TRACE",
]
return at_bounded(names, level - 1)
def _cmake_preset():
match sys.platform:
case "win32":
return "spark-api-server-windows"
case "linux":
return "spark-api-server-linux"
case _:
raise ValueError(f"Unsupported platform {sys.platform}")
def _dotnet_runtime():
match sys.platform:
case "win32":
return "win-x64"
case "linux":
return "linux-x64"
case _:
raise ValueError(f"Unsupported platform {sys.platform}")
class PublishArgs:
def __init__(
self,
configuration: str = "release",
cmake_jobs: Optional[int] = None,
clean: bool = False,
verbosity: int = 2,
dry_run: bool = False,
output: Optional[str] = None,
framework="net7.0",
runtime=_dotnet_runtime(),
):
self.configuration = configuration
self.cmake_jobs = cmake_jobs
self.clean = clean
self.verbosity = verbosity
self.dry_run = dry_run
self.dotnet_verbosity = at_bounded(
["quiet", "minimal", "normal", "detailed", "diagnostic"], verbosity
)
# Leave out WARNING and NOTICE to normalize cmake log level and dotnet verbosity
# (so both can be expressed as an int 1-5)
self.cmake_log_level = at_bounded(
[
"ERROR",
# 'WARNING',
# 'NOTICE',
"STATUS",
"VERBOSE",
"DEBUG",
"TRACE",
],
verbosity,
)
self.output = output
self.framework = framework
self.runtime = runtime
def _get_arg_parser():
parser = argparse.ArgumentParser(
description="Publish a self-contined spark client application"
)
parser.add_argument(
"--configuration",
metavar="debug|release",
help="The build configuration",
)
parser.add_argument(
"--cmake-jobs",
type=int,
help="The number of cmake parallel jobs",
)
parser.add_argument(
"--clean",
action="store_true",
help="Perform a clean build (remove artifacts from previous build)",
)
parser.add_argument(
"-o", "--output", type=str, help="The output directory for published artifacts."
)
parser.add_argument(
"--verbosity",
metavar="{0-5}",
choices=range(1, 6),
type=int,
help="The output verbosity level",
)
parser.add_argument(
"--dry-run",
action="store_true",
help="Preview the build commands without running them",
)
defaults = PublishArgs()
parser.set_defaults(
configuration=defaults.configuration,
clean=defaults.clean,
output=defaults.output,
verbosity=defaults.verbosity,
dry_run=defaults.dry_run,
)
return parser
def publish(args: PublishArgs):
def run(cmd):
print(cmd)
if args.dry_run:
return
subprocess.run(cmd, shell=True).check_returncode()
sln = SparkPaths.root().joinpath("Spark.Api.Server.sln")
cmake_preset = _cmake_preset()
cmake_config = args.configuration.title()
cmake_jobs = args.cmake_jobs
cmake_verbosity = _cmake_verbosity(args.verbosity)
dotnet_config = args.configuration.title()
dotnet_verbosity = _dotnet_verbosity(args.verbosity)
publish_dir = SparkPaths.default_build().joinpath(
dotnet_config,
"bin",
args.framework,
args.runtime,
"publish",
)
os.chdir(SparkPaths.root())
if args.clean:
run(
f"cmake --build build/{cmake_preset} --config {cmake_config} --target clean"
)
run(f"dotnet clean {sln} -c {dotnet_config} -v {dotnet_verbosity}")
run(f"cmake --preset {cmake_preset} -DCMAKE_MESSAGE_LOG_LEVEL={cmake_verbosity}")
cmake_build_cmd = (
f"cmake --build build/{cmake_preset} --config {cmake_config} --target install"
)
if cmake_jobs:
cmake_build_cmd += f" -j {cmake_jobs}"
run(cmake_build_cmd)
run(
f"dotnet publish {sln} -c {dotnet_config} -v {dotnet_verbosity} -f {args.framework} -r {args.runtime} --sc"
)
# Copy cpp bins
print(f"[pseudo shell] cp -r install/{cmake_preset}/bin/* {publish_dir}")
if not args.dry_run:
copytree(f"install/{cmake_preset}/bin", publish_dir, dirs_exist_ok=True)
if args.output:
# Move to '--output' dir
print(f"[pseudo shell] mv {publish_dir} {args.output}")
if not args.dry_run:
os.rename(publish_dir, args.output)
def _main():
parser = _get_arg_parser()
args = parser.parse_args()
publish(
PublishArgs(
configuration=args.configuration,
clean=args.clean,
cmake_jobs=args.cmake_jobs,
verbosity=args.verbosity,
dry_run=args.dry_run,
output=args.output,
)
)
if __name__ == "__main__":
try:
_main()
except Exception as e:
print(f"publish_api_server.py failed: {e}")
exit(1)