Compare commits

..
Author SHA1 Message Date
Kevin Darby e0fdf74a73 fix crash where account name > 12 chars, tested with long account name 2019-07-11 17:51:45 -04:00
Kevin Darby ebedd17129 Merge branch 'master' of bitbucket.org:bluetradesys/spark into excel_algos 2019-07-11 14:59:19 -04:00
Kevin Darby 0f8ed5dacb range to vector mapping 2019-07-11 14:15:06 -04:00
Kevin Darby 14f4452599 . 2019-07-10 23:21:56 -04:00
Kevin Darby 22002c43cf getting there 2019-07-10 18:43:09 -04:00
Kevin Darby 7551e23877 spreadsheet 2019-07-10 00:06:27 -04:00
Kevin Darby 22c92c3e17 ranges... 2019-07-10 00:05:24 -04:00
Kevin Darby 613823e7c5 arrays starting to work 2019-07-09 23:22:18 -04:00
Kevin Darby f0a9a2415d adding notion of bts_parameters 2019-07-09 18:31:05 -04:00
Kevin Darby 708e63e36e almost have C 2019-07-09 14:39:11 -04:00
Kevin Darby 53990297e8 parsing right along 2019-07-08 23:54:55 -04:00
Kevin Darby 9570be8bfa it builds, ship it. 2019-07-08 23:16:31 -04:00
Kevin Darby 0b15570d00 more parser 2019-07-08 18:22:12 -04:00
Kevin Darby 5fbc1397b5 messing with proj 2019-07-08 14:59:12 -04:00
Kevin Darby 38bd2ef321 Merge branch 'master' of bitbucket.org:bluetradesys/spark into excel_algos 2019-07-08 14:29:03 -04:00
Kevin Darby 59c00203a9 Merge branch 'master' of bitbucket.org:bluetradesys/spark into excel_algos 2019-07-08 13:10:23 -04:00
Kevin Darby 706e5bc73b excel 2019-07-08 11:22:53 -04:00
Kevin Darby 6cf395199e working on visitor 2019-07-06 23:25:51 -04:00
Kevin Darby 1707c3268f excel formula grammar, antlr4 integration. Successful parse tree 2019-07-05 18:24:41 -04:00
Kevin Darby 9b73ad2486 playing with excel parsing 2019-07-05 11:06:19 -04:00
Kevin Darby 205eebb7da excel formulae 2019-07-04 23:43:22 -04:00
Kevin Darby ef4dc1fc65 more excel 2019-07-04 23:25:28 -04:00
Kevin Darby 474401cddc new spreadsheet 2019-07-01 17:59:18 -04:00
Kevin Darby 3ebcf9a270 example of join in excel 2019-07-01 16:21:38 -04:00
93 changed files with 2876 additions and 669 deletions

No files matched your search

+4 -4
View File
@@ -104,7 +104,7 @@
"request": "launch",
"program": "C:/Program Files/Microsoft Office/Office14/EXCEL.EXE",
"args": [
"${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64-packed.xll"
"${workspaceRoot}/build/Debug/bin/net471/spark_excel-addin64.xll"
],
"cwd": "${workspaceRoot}",
"stopAtEntry": false,
@@ -135,13 +135,13 @@
"name": "Spreader Tests",
"type": "cppdbg",
"request": "launch",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"args": [
"test",
"[spreader]"
],
"stopAtEntry": false,
"cwd": "/home/bts/spark/build/ninja_debug/server",
"cwd": "/home/bts/spark/build/ninja_debug/src/server/sparkd/",
"environment": [],
"externalConsole": true,
"MIMode": "gdb",
@@ -288,7 +288,7 @@
"name": "SparkVM attach",
"type": "cppdbg",
"request": "attach",
"program": "/home/bts/spark/build/ninja_debug/server/sparkd",
"program": "/home/bts/spark/build/ninja_debug/src/server/sparkd/sparkd",
"processId": "${command:pickRemoteProcess}",
"MIMode": "gdb",
"pipeTransport": {
@@ -3,4 +3,5 @@ using System.Runtime.CompilerServices;
[assembly: InternalsVisibleTo("spark_core")]
[assembly: InternalsVisibleTo("sparkcmd")]
[assembly: InternalsVisibleTo("spark_test")]
[assembly: InternalsVisibleTo("spark_excel")]
+1 -1
View File
@@ -223,7 +223,7 @@ namespace bts.md
{
if (!timeout.HasValue)
{
timeout = TimeSpan.FromMilliseconds(10000);
timeout = TimeSpan.FromHours(24);
}
CancellationTokenSource src = new CancellationTokenSource(timeout.Value);
SecurityImmutable? security = await Task.Run<SecurityImmutable?>(async () =>
Binary file not shown.
+297
View File
@@ -0,0 +1,297 @@
using System;
using System.Diagnostics;
using System.Text;
using bts.excel.extensions;
namespace bts.excel
{
/// <summary>
/// Defines a reference to some Cell instance, whether it exists or not.
/// </summary>
/// <remarks>
/// Static methods are provided for conversion of column names etc.
/// </remarks>
public sealed class CellRef : IComparable, IComparable<CellRef>
{
public CellRef(ExcelDna.Integration.ExcelReference rref) : this(rref.GetSheetName(),
(rref.ColumnFirst + 1, rref.RowFirst + 1) )
{
}
/// <summary>
/// Constructor for the class: CellRef
/// </summary>
/// <param name="sheetName">Name of the sheet where the cell belongs.</param>
/// <param name="coordinate">Coordinate (column, row) for the cell in the sheet.</param>
public CellRef(string sheetName, (int col1, int row1) coordinate)
{
SheetName = sheetName;
SimpleSheetName = simple_sheet_name(SheetName);
Coordinate = coordinate;
LocalAddress = ConvertCoordToAddress(coordinate);
}
static string simple_sheet_name(string sn)
{
int open = sn.IndexOf('[');
int close = sn.IndexOf(']', open + 1);
var ssn = sn.Substring(0, open) + sn.Substring(close + 1);
ssn = ssn.Replace("[", "").Replace("]", "_").Replace(".", "_");
return ssn;
}
public string named_range { get; set;}
public bool in_vector {get; set;} = false;
public (int col, int row) vector_coordinates {get; set;}
/// <summary>
/// Maximum number of rows, to e compatible with Excel.
/// </summary>
private const int MaxRows = 1048576;
/// <summary>
/// Maximum number of columns, to be compatible with Excel.
/// </summary>
private const int MaxColumns = 16384;
// NOTE: Worksheet and workbook specifications and limits
// http://office.microsoft.com/en-gb/excel-help/excel-specifications-and-limits-HP010342495.aspx
//
// Worksheet size: 1,048,576 rows by 16,384 columns.
// * 1048575 is the highest number representable in 20 bits.
// * 16383 is the highest number representable in 14 bits. That leaves 2 spare bits in a 16-bit word.
// Column width: 255 characters (I'm not sure what the real significance of this is).
// Total number of characters that a cell can contain: 32,767 characters
// * 32766 is the highest number representable in 15 bits. That leaves 1 spare bit in a 16-bit word.
//
/// <summary>
/// Name of the sheet where the cell belongs.
/// </summary>
/// <remarks>
/// All cells belong to some Sheet instance, so this name must never be null or empty.
/// </remarks>
public string SheetName { get; }
public string SimpleSheetName { get; }
/// <summary>
/// Coordinate (column, row) for the cell in the sheet.
/// </summary>
public (int col1, int row1) Coordinate { get; }
public CellRef Offset(int columnOffset, int rowOffset)
{
return new CellRef(SheetName, (Column + columnOffset, Row + rowOffset));
}
public int Column => Coordinate.col1;
public int Row => Coordinate.row1;
public string LocalAddress { get; internal set; }
#region Address conversion
/// <summary>
/// Converts a column identifier, using letters, to a column number.
/// </summary>
/// <param name="columnName">Column identifier using letters.</param>
/// <returns>Column number.</returns>
/// <exception cref="ArgumentOutOfRangeException">When column number exceeds maximum.</exception>
public static int ConvertToColumnNumber(string columnName)
{
var number = 0;
var pow = 1;
for (var i = columnName.Length - 1; i >= 0; i--)
{
number += (columnName[i] - 'A' + 1) * pow;
pow *= 26;
}
if (number > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(columnName),
"Column number from columnName exceeds maximum");
}
return number;
}
/// <summary>
/// Converts a column number to a column identifier using letters.
/// </summary>
/// <param name="columnNumber">Column number.</param>
/// <returns>Column identifier using letters.</returns>
/// <exception cref="ArgumentOutOfRangeException">When column number is invalid.</exception>
public static string ConvertToColumnName(int columnNumber)
{
if (columnNumber < 1 || columnNumber > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(columnNumber),
"Invalid column number");
}
var dividend = columnNumber;
var columnName = string.Empty;
while (dividend > 0)
{
var modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo) + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
/// <summary>
/// Converts an address, like "A1", to a cell coordinate.
/// </summary>
/// <param name="address">Cell address, like "A1".</param>
/// <returns>Coordinate of cell on sheet.</returns>
/// <exception cref="ArgumentNullException">When address argument is null.</exception>
/// <exception cref="ArgumentException">When address is invalid.</exception>
public static (int col1, int row1) ConvertAddressToCoord(string address)
{
if (address == null)
{
throw new ArgumentNullException(nameof(address));
}
address = address.Replace("$", string.Empty);
address = address.ToUpper();
var letters = new StringBuilder();
foreach (var c in address)
{
if (c < 'A' || c > 'Z')
{
break;
}
letters.Append(c);
}
if (letters.Length == 0 || letters.Length > 3)
{
throw new ArgumentException(
"Column name requires 1 to 3 letters",
nameof(address));
}
var numbers = address.Substring(letters.Length);
if (numbers.Length == 0)
{
throw new ArgumentException("Row number is required", nameof(address));
}
Debug.Assert(letters.Length + numbers.Length == address.Length);
var row1 = int.Parse(numbers);
var col1 = ConvertToColumnNumber(letters.ToString());
return (col1, row1);
}
/// <summary>
/// Convert cell coordinate to cell address, like "A1".
/// </summary>
/// <param name="coordinate">Coordinate of cell on sheet.</param>
/// <param name="absolute">Provide absolute address, like "$A$1".</param>
/// <returns>Cell address, like "A1", or optionally like "$A$1".</returns>
/// <exception cref="ArgumentOutOfRangeException"></exception>
public static string ConvertCoordToAddress((int col1, int row1) coordinate, bool absolute = false)
{
if (coordinate.row1 < 1 || coordinate.row1 > MaxRows ||
coordinate.col1 < 1 || coordinate.col1 > MaxColumns)
{
throw new ArgumentOutOfRangeException(nameof(coordinate),
"Invalid coordinate");
}
var (col1, row1) = coordinate;
return absolute
? $"${ConvertToColumnName(col1)}${row1}"
: $"{ConvertToColumnName(col1)}{row1}";
}
#endregion
#region IComparable
public int CompareTo(CellRef other)
{
if (other == null) return -1;
return string.Compare(ToString(), other.ToString(),
StringComparison.Ordinal);
}
public int CompareTo(object obj)
{
if (obj.GetType() != GetType()) return -1;
return CompareTo((CellRef)obj);
}
#endregion
#region HashCode & Equals
/// <returns>Unique key</returns>
public override string ToString()
{
return to_name();
}
public string to_address()
{
if (!string.IsNullOrEmpty(SheetName))
return $"'{SheetName}'!{LocalAddress}";
else
return $"{LocalAddress}";
}
public string to_name()
{
if(!string.IsNullOrEmpty(named_range))
return named_range;
else
{
if (!string.IsNullOrEmpty(SheetName))
{
return $"{SimpleSheetName}_{LocalAddress}".ToLowerInvariant();
}
else
return $"{LocalAddress}".ToLowerInvariant();
}
}
public string r1_c1_include_sheet()
{
if (!string.IsNullOrEmpty(SheetName))
return $"'{SimpleSheetName}'!R{this.Row}C{this.Column}";
else
return $"R{this.Row}C{this.Column}";
}
public string r1_c1()
{
return $"R{this.Row}C{this.Column}";
}
public override int GetHashCode()
{
return ToString().GetHashCode();
}
public override bool Equals(object obj)
{
if (obj == null) return false;
if (obj != null && !(obj is CellRef))
throw new ArgumentException("Object must be of type CellRef.");
return GetHashCode().Equals(obj.GetHashCode());
}
#endregion
}
}
@@ -0,0 +1,104 @@
using System;
namespace bts.excel
{
public class ErrorValue : IComparable, IComparable<ErrorValue>
{
private enum ErrorType
{
Null,
Div0,
Value,
Ref,
Name,
Num,
NA
}
public static ErrorValue Null => new ErrorValue(ErrorType.Null);
public static ErrorValue Div0 => new ErrorValue(ErrorType.Div0);
public static ErrorValue Value => new ErrorValue(ErrorType.Value);
public static ErrorValue Ref => new ErrorValue(ErrorType.Ref);
public static ErrorValue Name => new ErrorValue(ErrorType.Name);
public static ErrorValue Num => new ErrorValue(ErrorType.Num);
public static ErrorValue NA => new ErrorValue(ErrorType.NA);
private const string HashNull = "#NULL!";
private const string HashDiv0 = "#DIV/0!";
private const string HashValue = "#VALUE!";
private const string HashRef = "#REF!";
private const string HashName = "#NAME?";
private const string HashNum = "#NUM!";
private const string HashNA = "#N/A";
private readonly ErrorType _errorType;
public ErrorValue(string token)
: this(GetErrorType(token))
{ }
private ErrorValue(ErrorType errorType)
{
_errorType = errorType;
}
private static ErrorType GetErrorType(string token)
{
switch (token)
{
case HashNull: return ErrorType.Null;
case HashDiv0: return ErrorType.Div0;
case HashValue: return ErrorType.Value;
case HashRef: return ErrorType.Ref;
case HashName: return ErrorType.Name;
case HashNum: return ErrorType.Num;
case HashNA: return ErrorType.NA;
default: throw new Exception("Unrecongised error token");
}
}
public static bool IsErrorToken(string token)
{
switch (token)
{
case HashNull:
case HashDiv0:
case HashValue:
case HashRef:
case HashName:
case HashNum:
case HashNA:
return true;
default:
return false;
}
}
public override string ToString()
{
switch (_errorType)
{
case ErrorType.Null: return HashNull;
case ErrorType.Div0: return HashDiv0;
case ErrorType.Value: return HashValue;
case ErrorType.Ref: return HashRef;
case ErrorType.Name: return HashName;
case ErrorType.Num: return HashNum;
case ErrorType.NA: return HashNA;
default: throw new Exception("Unexpected condition");
}
}
public int CompareTo(ErrorValue other)
{
if (other == null) return -1;
return _errorType.CompareTo(other._errorType);
}
public int CompareTo(object obj)
{
if (obj.GetType() != GetType()) return -1;
return CompareTo(obj as ErrorValue);
}
}
}
@@ -0,0 +1,26 @@
using spark_excel.grammar;
namespace bts.excel
{
public interface IExpression
{
object evaluate();
}
internal class Expression<T> : IExpression
{
private readonly ExcelFormulaParser.ExprContext _context;
private readonly IExcelFormulaVisitor<T> _visitor;
public Expression(ExcelFormulaParser.ExprContext context, IExcelFormulaVisitor<T> visitor)
{
_context = context;
_visitor = visitor;
}
public object evaluate()
{
return _context.Accept(_visitor);
}
}
}
@@ -0,0 +1,82 @@
using System;
using System.Collections.Concurrent;
using ExcelDna.Integration;
using spark_excel.grammar;
using Antlr4.Runtime;
namespace bts.excel
{
internal class ExcelFormulaErrorListener : BaseErrorListener
{
public bool IsValid { get; private set; } = true;
public string offendingSymbol { get; private set;}
public int line { get; private set; }
public int charPositionInLine { get; private set; }
public string msg { get; private set; }
public RecognitionException exception { get; private set;}
public override void SyntaxError(IRecognizer recognizer, IToken offendingSymbol, int line, int charPositionInLine, string msg, RecognitionException e)
{
IsValid = false;
this.offendingSymbol = offendingSymbol.Text;
this.line = line;
this.charPositionInLine = charPositionInLine;
this.msg = msg;
this.exception = e;
}
}
//https://theantlrguy.atlassian.net/wiki/spaces/ST/pages/1409118/Language+Translation+Using+ANTLR+and+StringTemplate
//https://stackoverflow.com/questions/31511610/antlr-source-to-target-language-conversion
public class Generate
{
[ExcelFunction(IsMacroType = true)]
static public string bts_generate_code([ExcelArgument(AllowReference=true)] object sink, string function_name = null)
{
ExcelReference rref = (ExcelReference)sink;
var formula = XlCall.Excel(XlCall.xlfGetCell, 41, rref);
var antlrstream = new AntlrInputStream(formula.ToString());
var lexer = new ExcelFormulaLexer(antlrstream);
var tokens = new CommonTokenStream(lexer);
var parser = new ExcelFormulaParser(tokens);
var error_listener = new ExcelFormulaErrorListener();
//parser.RemoveErrorListeners();
parser.AddErrorListener(error_listener);
var parsetree = parser.main();
if (!error_listener.IsValid)
{
write_file(function_name, error_listener.offendingSymbol + error_listener.msg + error_listener.exception?.ToString());
throw new Exception(error_listener.offendingSymbol + error_listener.msg, error_listener.exception);
}
//AbstractParseTreeVisitor
GeneratorVisitor visitor = new GeneratorVisitor(rref);
object val = visitor.VisitMain(parsetree);
if(string.IsNullOrEmpty(function_name))
function_name = new CellRef(rref).to_name();
string ret = $"auto {function_name}() {Environment.NewLine}{{{Environment.NewLine}";
visitor.get_defs().ForEach(x => ret += " " + x + Environment.NewLine);
ret += " return " + val.ToString() + " ;";
ret += $"{Environment.NewLine} }}";
write_file(function_name, ret);
return ret;
}
static void write_file(string function_name, string text)
{
using(System.IO.StreamWriter file =
new System.IO.StreamWriter($"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}\\{function_name}.function"))
{
file.WriteLine(text);
}
}
}
}
@@ -0,0 +1,410 @@
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using spark_excel.grammar;
using Antlr4.Runtime;
using ExcelDna.Integration;
using bts.excel.extensions;
namespace bts.excel
{
public interface IDefinitionVisitor
{
void add_def(string def);
List<string> get_defs();
}
public class GeneratorVisitor : ExcelFormulaBaseVisitor<object>, IDefinitionVisitor
{
ExcelReference _ref;
functions.lib.FunctionLibrary _library = new functions.lib.FunctionLibrary();
ExcelFormulaErrorListener _error_listener = new ExcelFormulaErrorListener();
List<string> _defs = new List<string>();
Dictionary<string, string> _def_map = new Dictionary<string, string>();
public GeneratorVisitor(ExcelReference rref)
{
_ref = rref;
}
public void add_def(string def)
{
_defs.Add(def);
}
public void map_def(string def, string mapped)
{
_def_map[def] = mapped;
}
public List<string> get_defs()
{
var list = _defs.Distinct();
List<string> defs = new List<string>();
foreach(var d in list)
defs.Add( _def_map.TryGetValue(d, out string mapped) ? mapped : d );
return defs;
}
#region Context visitors overrides
static ConcurrentDictionary<string, string> _algo_params = new ConcurrentDictionary<string, string>();
public static void register_algo_parameter(string sheet, string name)
{
_algo_params[name] = sheet;
}
public override object VisitName(ExcelFormulaParser.NameContext context)
{
var name = context.GetText();
var lookup = name;
if(!lookup.Contains("!"))
lookup = "!" + lookup;
object value = XlCall.Excel(XlCall.xlfGetName, lookup);
if(value != null && !(value is ExcelError))
{
string[] par = value.ToString().Split(new[] {'=', 'R', 'C'}, StringSplitOptions.RemoveEmptyEntries);
int r = int.Parse(par[0]) - 1;
int c = int.Parse(par[1]) - 1;
var rref = new ExcelReference(r, r, c, c, _ref.GetSheetName());
process_cell(rref);
}
return name;
}
private object process_cell(ExcelReference rref)
{
var formula = XlCall.Excel(XlCall.xlfGetCell, 41, rref);
var formstring = formula.ToString();
if(string.IsNullOrEmpty(formstring))
formstring = "0.0";
if (!formstring.StartsWith("="))
formstring = "=" + formstring;
var cellref = new CellRef(rref);
string r1c1 = cellref.r1_c1();
var cellname = XlCall.Excel(XlCall.xlfGetDef, r1c1, cellref.SheetName);
bool named = false;
if (!(cellname is ExcelError))
{
named = true;
cellref.named_range = cellname.ToString();
}
var antlrstream = new AntlrInputStream(formstring);
var lexer = new ExcelFormulaLexer(antlrstream);
var tokens = new CommonTokenStream(lexer);
var parser = new ExcelFormulaParser(tokens);
parser.AddErrorListener(_error_listener);
var parsetree = parser.main();
if (!_error_listener.IsValid)
{
//throw new ExcelFormulaException(_error_listener.ErrorLocation, _error_listener.ErrorMessage);
var def = $"{cellref.ToString()} = Error parsing cell {_error_listener.offendingSymbol } {_error_listener.exception?.ToString()} ;";
add_def(def);
}
else
{
var def = $"auto&& {cellref.ToString()} = {this.VisitMain(parsetree)} ;";
add_def(def);
if (named && _algo_params.ContainsKey(cellref.named_range))
{
map_def(def, $"auto&& {cellref.named_range} = spark_algo_parameter(\"{cellref.named_range}\");");
}
}
return cellref;
}
public override object VisitMain(ExcelFormulaParser.MainContext context)
{
return context.expr().Accept(this);
}
public override object VisitMulDiv(ExcelFormulaParser.MulDivContext context)
{
var expr = context.expr();
var arg1 = expr[0].Accept(this);
if (arg1 is ErrorValue)
return arg1;
var arg2 = expr[1].Accept(this);
if (arg2 is ErrorValue)
return arg2;
string code = $"{arg1} {context.op.Text} {arg2}";
return code;
}
public override object VisitAddSub(ExcelFormulaParser.AddSubContext context)
{
var expr = context.expr();
var arg1 = expr[0].Accept(this);
if (arg1 is ErrorValue)
return arg1;
var arg2 = expr[1].Accept(this);
if (arg2 is ErrorValue)
return arg2;
string code = $"{arg1} {context.op.Text} {arg2}";
return code;
}
public override object VisitPercentage(ExcelFormulaParser.PercentageContext context)
{
var expr = context.expr();
var arg1 = expr.Accept(this);
if (arg1 is ErrorValue)
return arg1;
return $"( {arg1} / 100.0 )";
}
public override object VisitRelational(ExcelFormulaParser.RelationalContext context)
{
var expr = context.expr();
var arg1 = expr[0].Accept(this);
if (arg1 is ErrorValue)
return arg1;
var arg2 = expr[1].Accept(this);
if (arg2 is ErrorValue)
return arg2;
return $"{arg1} {context.op.Text} {arg2}";
}
public override object VisitError(ExcelFormulaParser.ErrorContext context)
{
return new ErrorValue(context.GetText());
}
public override object VisitString(ExcelFormulaParser.StringContext context)
{
var str = context.GetText();
return $"std::string({str})";
}
public override object VisitUnary(ExcelFormulaParser.UnaryContext context)
{
var expr = context.expr();
if(context.sign.Text == "-")
return "-" + expr.Accept(this);
else
return expr.Accept(this);
}
public override object VisitFunction(ExcelFormulaParser.FunctionContext context)
{
var name = context.name.Text;
if (!_library.is_defined(name))
return ErrorValue.Name;
var expr = context.expr();
var args = new IExpression[expr.Length];
for (var i = 0; i < expr.Length; i++)
args[i] = new Expression<object>(expr[i], this);
return _library.call_function(name, args, this);
}
public override object VisitParenthesis(ExcelFormulaParser.ParenthesisContext context)
{
return context.expr().Accept(this);
}
public override object VisitNumber(ExcelFormulaParser.NumberContext context)
{
var num = context.GetText();
if(double.TryParse(num, out double res))
return res.ToString("0.0############");
return num;
}
public override object VisitConcatenate(ExcelFormulaParser.ConcatenateContext context)
{
var expr = context.expr();
var arg1 = "std::to_string(" + expr[0].Accept(this) + ")";
var arg2 = "std::to_string(" + expr[1].Accept(this) + ")";
return $"{arg1}+{arg2}";
}
public override object VisitRange(ExcelFormulaParser.RangeContext context)
{
var rng = context.rng();
return rng.Accept(this);
}
public override object VisitRangeList(ExcelFormulaParser.RangeListContext context)
{
var result = new List<RangeRef>();
foreach (var range in context.rng())
{
var obj = range.Accept(this);
switch (obj)
{
case ErrorValue err:
result.Add(null);
break;
case RangeRef rangeRef:
result.Add(rangeRef);
break;
case null:
result.Add(null);
break;
default:
throw new ArgumentOutOfRangeException($"Unexpected type: {obj.GetType()}");
}
}
return result;
}
public override object VisitRangeRef(ExcelFormulaParser.RangeRefContext context)
{
var obj = context.@ref().Accept(this);
switch (obj)
{
case ErrorValue _:
return obj;
case CellRef start:
var (column, row) = CellRef.ConvertAddressToCoord(context.end.Text);
var rng = new RangeRef(start, column, row);
if(rng.IsOneCell())
{
var rref = new ExcelReference(row - 1, row - 1, column - 1, column - 1, start.SheetName);
process_cell(rref);
}
else
{
var def =
$@"std::vector<auto> {rng.to_name()};
auto {rng.to_name()}_load = [=](auto&& val)
{{
}};
";
var rref = new ExcelReference(rng.Start.Row - 1, rng.End.Row - 1,
rng.Start.Column- 1, rng.End.Column - 1, start.SheetName);
//process_cell(rref);
}
return rng;
case null:
return null;
default:
throw new ArgumentOutOfRangeException($"Unexpected type: {obj.GetType()}");
}
}
public override object VisitCell(ExcelFormulaParser.CellContext context)
{
return context.@ref().Accept(this);
}
public override object VisitCellList(ExcelFormulaParser.CellListContext context)
{
var result = new List<CellRef>();
foreach (var @ref in context.@ref())
{
var obj = @ref.Accept(this);
switch (obj)
{
case ErrorValue _:
// TODO: Warn that error has been replaced with null here?
result.Add(null);
break;
case CellRef cellRef:
result.Add(cellRef);
break;
case null:
result.Add(null);
break;
default:
throw new ArgumentOutOfRangeException($"Unexpected type: {obj.GetType()}");
}
}
return result;
}
public override object VisitCellRef(ExcelFormulaParser.CellRefContext context)
{
var colRow = context.colRow.Text;
var (col1, row1) = CellRef.ConvertAddressToCoord(colRow);
var sheetname = context.sheet?.Text ?? _ref.GetSheetName();
var rref = new ExcelReference(row1 - 1, row1 - 1, col1 - 1, col1 - 1, sheetname);
return process_cell(rref);
}
// public override object VisitRangeRef(ExcelFormulaParser.RangeRefContext context)
// {
// var obj = context.@ref().Accept(this);
// var end = context.COL_ROW();
//return obj;
// var result = new List<CellRef>();
// var rng = context.GetRuleContexts<spark_excel.grammar.ExcelFormulaParser.RngContext>();
// foreach(var r in rng)
// {
// var obj = r.Accept(this);
// switch (obj)
// {
// case ErrorValue err:
// result.Add(null);
// break;
// case CellRef rangeRef:
// result.Add(rangeRef);
// break;
// case null:
// result.Add(null);
// break;
// default:
// throw new ArgumentOutOfRangeException($"Unexpected type: {obj.GetType()}");
// }
// }
// return result;
// var colRow = context.COL_ROW();
// var colrowstring = colRow.ToString();
// var (col1, row1) = CellRef.ConvertAddressToCoord(colrowstring);
// var sheetname = !colrowstring.Contains("!") ? _simple_sheetname : _simple_sheetname;
// var rref = new ExcelReference(row1 - 1, row1 - 1, col1 - 1, col1 - 1, sheetname);
// return process_cell(rref, sheetname);
// switch (obj)
// {
// case ErrorValue _:
// return obj;
// case CellRef start:
// var (column, row) = CellRef.ConvertAddressToCoord(context.end.Text);
// return new RangeRef(start, column, row);
// case null:
// return null;
// default:
// throw new ArgumentOutOfRangeException($"Unexpected type: {obj.GetType()}");
// }
// }
#endregion
}
}
+149
View File
@@ -0,0 +1,149 @@
using System.Collections.Generic;
using System.Diagnostics;
namespace bts.excel
{
public class RangeRef
{
public RangeRef(CellRef start, CellRef end)
{
Start = start;
End = end;
}
public string named_range { get; set;}
public RangeRef(CellRef start, int endColumn, int endRow)
: this(start, new CellRef(start.SheetName, (endColumn, endRow)))
{ }
public RangeRef Offset(int columnOffset, int rowOffset)
{
var start = Start.Offset(columnOffset, rowOffset);
var end = End.Offset(columnOffset, rowOffset);
return new RangeRef(start, end);
}
public CellRef Start { get; }
public CellRef End { get; }
public override string ToString()
{
return to_name();
}
public string SheetName => Start.SheetName;
public string SimpleSheetName => Start.SimpleSheetName;
public string to_address()
{
return string.Format("'{0}'!{1}:{2}",
SheetName,
CellRef.ConvertCoordToAddress((Start.Column, Start.Row)),
CellRef.ConvertCoordToAddress((End.Column, End.Row)));
}
public string to_name()
{
if (!string.IsNullOrEmpty(named_range))
return named_range;
else
{
return string.Format("{0}_{1}_{2}",
Start.SimpleSheetName,
CellRef.ConvertCoordToAddress((Start.Column, Start.Row)),
CellRef.ConvertCoordToAddress((End.Column, End.Row)));
}
}
public bool IsVector()
{
return IsSingleRow() || IsSingleColumn();
}
public bool IsOneCell()
{
return IsSingleRow() && IsSingleColumn();
}
internal List<CellRef> Get2DVector()
{
var result = new List<CellRef>();
var sheetName = Start.SheetName;
var numRows = NumRows();
var lastRow = Start.Row + numRows - 1;
for (var row = Start.Row; row <= lastRow; row++)
{
var numCols = NumCols();
var lastCol = Start.Column + numCols - 1;
for (var col = Start.Column; col <= lastCol; col++)
{
result.Add(new CellRef(sheetName, (col, row)));
}
}
return result;
}
internal List<CellRef> GetVector()
{
Debug.Assert(IsVector());
var result = new List<CellRef>();
if (IsSingleColumn())
{
var col = Start.Column;
var sheetName = Start.SheetName;
var numRows = NumRows();
var lastRow = Start.Row + numRows - 1;
for (var row = Start.Row; row <= lastRow; row++)
{
result.Add(new CellRef(sheetName, (col, row)));
}
}
else
{
Debug.Assert(IsSingleRow());
var row = Start.Row;
var sheetName = Start.SheetName;
var numCols = NumCols();
var lastCol = Start.Column + numCols - 1;
for (var col = Start.Column; col <= lastCol; col++)
{
result.Add(new CellRef(sheetName, (col, row)));
}
}
return result;
}
public bool IsSingleColumn()
{
Debug.Assert(Start.SheetName == End.SheetName);
return Start.Column == End.Column;
}
public bool IsSingleRow()
{
Debug.Assert(Start.SheetName == End.SheetName);
return Start.Row == End.Row;
}
public int NumRows()
{
Debug.Assert(Start.SheetName == End.SheetName);
return End.Row - Start.Row + 1;
}
public int NumCols()
{
Debug.Assert(Start.SheetName == End.SheetName);
return End.Column - Start.Column + 1;
}
}
}
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using bts.excel.functions;
using ExcelDna.Registration;
namespace bts.excel.functions.lib
{
public interface IFunction
{
object function(IExpression[] args, IDefinitionVisitor dv);
}
public class FunctionLibrary
{
private readonly Dictionary<string, IFunction> _functions =
new Dictionary<string, IFunction>(StringComparer.OrdinalIgnoreCase);
private readonly Dictionary<string, Delegate> _dnafunctions =
new Dictionary<string, Delegate>(StringComparer.OrdinalIgnoreCase);
public FunctionLibrary()
{
add_functions(Logical.functions);
add_functions(Mathematics.functions);
add_functions(Stat.functions);
var dna = ExcelRegistration.GetExcelFunctions();
foreach(var xl in dna)
{
_dnafunctions[xl.FunctionAttribute.Name] =
xl.FunctionLambda.Compile();
}
}
public bool is_defined(string name) => _functions.ContainsKey(name) || _dnafunctions.ContainsKey(name);
public void add_function(string name, IFunction function)
{
_functions.Add(name, function);
}
public void add_functions(Dictionary<string, IFunction> delegates)
{
foreach (var f in delegates)
_functions.Add(f.Key, f.Value);
}
public object call_function(string name, IExpression[] args, IDefinitionVisitor dv)
{
if(_functions.TryGetValue(name, out IFunction func))
return func.function(args, dv);
else
return call_dna_function(name, args, dv);
}
object call_dna_function(string name, IExpression[] args, IDefinitionVisitor dv)
{
if(_dnafunctions.TryGetValue(name, out Delegate func))
{
object[] param = args.Select(x => x.evaluate()).ToArray();
// var pp = func.Method.GetParameters();
// if(pp.Length -1 != param.Length)
// throw new ArgumentException("invalide args to dna function " + name);
string code = $"{name} ( "; int i = 0;
foreach(var p in param)
code += p.ToString() + (i++ < param.Length-1 ? ", " : "");
code += ")";
return code;
}
else
return ErrorValue.Name;
}
}
}
@@ -0,0 +1,55 @@
using System;
using System.Collections.Generic;
namespace bts.excel.functions.lib
{
public static class Logical
{
public static Dictionary<string, IFunction> functions { get; }
static Logical()
{
functions = new Dictionary<string, IFunction>(StringComparer.OrdinalIgnoreCase)
{
{"AND", new And()},
{"IF", new If()},
{"IFERROR", new IfError()},
{"OR", new Or()},
};
}
}
public static class Mathematics
{
public static Dictionary<string, IFunction> functions { get; }
static Mathematics()
{
functions = new Dictionary<string, IFunction>(StringComparer.OrdinalIgnoreCase)
{
{"LN", new Ln()},
{"LOG", new Log()},
{"POWER", new Power()},
{"PI", new Pi()},
{"SQRT", new Sqrt()},
{"SUM", new Sum()},
{"SIN", new Sin()},
};
}
}
public static class Stat
{
public static Dictionary<string, IFunction> functions { get; }
static Stat()
{
functions = new Dictionary<string, IFunction>(StringComparer.OrdinalIgnoreCase)
{
{"AVERAGE", new Average()},
{"MAX", new Max()},
{"MIN", new Min()},
};
}
}
}
@@ -0,0 +1,32 @@
using System;
namespace bts.excel.functions.lib
{
public class And : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: AND(logical1, [logical2], ...)
// https://support.office.com/en-gb/article/AND-function-5f19b2e8-e1df-4408-897a-ce285a19e9d9
if (args.Length < 2)
{
throw new ArgumentException(
$"AND function requires at least 2 arguments, got {args.Length}",
nameof(args));
}
string code = "(";
foreach (var fx in args)
{
var arg = fx.evaluate();
if (arg is ErrorValue)
return arg;
code += arg + " && ";
}
code += "true)";
return code;
}
}
}
@@ -0,0 +1,39 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.excel.functions.lib
{
public class Average : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: Average(number1,[number2],...)
// https://support.office.com/en-GB/article/AVERAGE-function-047bac88-d466-426c-a32b-8f33eb960cf6
if (args.Length < 1)
{
throw new ArgumentException(
$"Average function takes at least 1 arguments, got {args.Length}",
nameof(args));
}
string name = "avg_" + new Random().Next(0, int.MaxValue);
string def = ($"auto {name} = 0.0;{Environment.NewLine}");
int count = 0;
foreach (var arg in args)
{
var argv = arg.evaluate();
if (arg is ErrorValue)
return arg;
count++;
def += $" {name} += {argv};{Environment.NewLine}";
}
if(count > 1)
def += $" {name} /= {count}";
dv.add_def(def);
return name;
}
}
}
@@ -0,0 +1,35 @@
using System;
namespace bts.excel.functions.lib
{
public class If : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: IF(logical_test, value_if_true, [value_if_false])
// https://support.office.com/en-gb/article/IF-function-69aed7c9-4e8a-4755-a9bc-aa8bbff73be2
if (args.Length != 2 && args.Length != 3)
{
throw new ArgumentException(
"IF function takes 2 or 3 arguments",
nameof(args));
}
var arg = args[0].evaluate();
if (arg is ErrorValue)
return arg;
string code = string.Empty;
if (args.Length == 3)
{
code += $"( {arg} ? ({ args[1].evaluate() }) : ({args[2].evaluate()}) ) ";
}
else
{
code += $"( {arg} ? ({ args[1].evaluate() }) : false) ";
}
return code;
}
}
}
@@ -0,0 +1,32 @@
using System;
namespace bts.excel.functions.lib
{
public class IfError : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: IFERROR(value, value_if_error)
// https://support.office.com/en-gb/article/IFERROR-function-c526fd07-caeb-47b8-8bb6-63f3e417f611
if (args.Length != 2)
{
throw new ArgumentException(
"IFERROR function takes exactly 2 arguments",
nameof(args));
}
try
{
var arg = args[0].evaluate();
if (arg is ErrorValue)
return arg;
return arg;
}
catch (Exception)
{
return args[1].evaluate();
}
}
}
}
@@ -0,0 +1,26 @@
using System;
namespace bts.excel.functions.lib
{
public class Ln : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: LN(number)
// https://support.office.com/en-gb/article/LN-function-81fe1ed7-dac9-4acd-ba1d-07a142c6118f
if (args.Length != 1)
{
throw new ArgumentException(
$"LN function takes only 1 argument, got {args.Length}");
}
var arg = args[0].evaluate();
if (arg is ErrorValue)
return arg;
string code = $"log({arg})";
return code;
}
}
}
@@ -0,0 +1,40 @@
using System;
namespace bts.excel.functions.lib
{
public class Log : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: LOG(number, [base])
// https://support.office.com/en-gb/article/LOG-function-4e82f196-1ca9-4747-8fb0-6c4a3abb3280
switch (args.Length)
{
case 1:
var arg = args[0].evaluate();
if (arg is ErrorValue)
return arg;
string code = $"log10({arg})";
return code;
case 2:
var arg1 = args[0].evaluate();
if (arg1 is ErrorValue)
return arg1;
var arg2 = args[1].evaluate();
if (arg2 is ErrorValue)
return arg2;
string code2 = $"log({arg1}, {arg2})";
return code2;
default:
throw new ArgumentException(
$"LOG function takes only 1 or 2 arguments, got {args.Length}",
nameof(args));
}
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.excel.functions.lib
{
public class Max : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: MAX(number1, [number2], ...)
// https://support.office.com/en-GB/article/MAX-function-e0012414-9ac8-4b34-9a47-73e662c08098
if (args.Length < 1)
{
throw new ArgumentException(
$"MAX function takes at least 1 arguments, got {args.Length}",
nameof(args));
}
string code = $"std::max(\n";
foreach (var arg in args)
{
var argv = arg.evaluate();
if (argv is ErrorValue)
return argv;
code += $"{argv},";
}
code += $"{ args[args.Length-1].evaluate()} );\n";
return code;
}
}
}
@@ -0,0 +1,35 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.excel.functions.lib
{
public class Min : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: MIN(number1, [number2], ...)
// https://support.office.com/en-GB/article/MIN-function-61635d12-920f-4ce2-a70f-96f202dcc152
if (args.Length < 1)
{
throw new ArgumentException(
$"MIN function takes at least 1 arguments, got {args.Length}",
nameof(args));
}
string code = $"std::min(\n";
foreach (var arg in args)
{
var argv = arg.evaluate();
if (argv is ErrorValue)
return argv;
code += $"{argv},";
}
code += $"{ args[args.Length - 1].evaluate()} );\n";
return code;
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace bts.excel.functions.lib
{
public class Or : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: OR(logical1, [logical2], ...)
// https://support.office.com/en-gb/article/OR-function-7d17ad14-8700-4281-b308-00b131e22af0
string code = "(";
foreach (var fx in args)
{
var arg = fx.evaluate();
if (arg is ErrorValue)
return arg;
code += arg + " || ";
}
code += "false)";
return code;
}
}
}
@@ -0,0 +1,22 @@
using System;
namespace bts.excel.functions.lib
{
public class Pi : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: PI()
// https://support.office.com/en-gb/article/PI-function-264199d0-a3ba-46b8-975a-c4a04608989b
if (args.Length != 0)
{
throw new ArgumentException(
$"PI function takes no arguments, got {args.Length}",
nameof(args));
}
return Math.PI.ToString();
}
}
}
@@ -0,0 +1,30 @@
using System;
namespace bts.excel.functions.lib
{
public class Power : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: POWER(number, power)
// https://support.office.com/en-gb/article/POWER-function-d3f2908b-56f4-4c3f-895a-07fb519c362a
if (args.Length != 2)
{
throw new ArgumentException(
$"POWER function takes 2 arguments, got {args.Length}",
nameof(args));
}
var arg1 = args[0].evaluate();
if (arg1 is ErrorValue)
return arg1;
var arg2 = args[1].evaluate();
if (arg2 is ErrorValue)
return arg2;
return $"pow({arg1}, {arg2})";
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace bts.excel.functions.lib
{
public class Sin : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: SIN(number)
// https://support.office.com/en-gb/article/SIN-function-654975c2-05c4-4831-9a24-2c65e4040fdf
if (args.Length != 1)
{
throw new ArgumentException(
$"Sin function takes only 1 argument, got {args.Length}");
}
var arg1 = args[0].evaluate();
if (arg1 is ErrorValue)
return arg1;
return $"sin({arg1})";
}
}
}
@@ -0,0 +1,25 @@
using System;
namespace bts.excel.functions.lib
{
public class Sqrt : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: SQRT(number)
// https://support.office.com/en-gb/article/SQRT-function-654975c2-05c4-4831-9a24-2c65e4040fdf
if (args.Length != 1)
{
throw new ArgumentException(
$"SQRT function takes only 1 argument, got {args.Length}");
}
var arg1 = args[0].evaluate();
if (arg1 is ErrorValue)
return arg1;
return $"sqrt({arg1})";
}
}
}
@@ -0,0 +1,36 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace bts.excel.functions.lib
{
public class Sum : IFunction
{
public object function(IExpression[] args, IDefinitionVisitor dv)
{
// Syntax: SUM(number1,[number2],...)
// https://support.office.com/en-GB/article/SUM-function-043e1c7d-7726-4e80-8f32-07b23e057f89
if (args.Length < 1)
{
throw new ArgumentException(
$"SUM function takes at least 1 arguments, got {args.Length}",
nameof(args));
}
string name = "sum_" + new Random().Next(0, int.MaxValue);
string def = ($"auto {name} = 0.0;{Environment.NewLine}");
foreach (var arg in args)
{
var argv = arg.evaluate();
if (arg is ErrorValue)
return arg;
def += $" {name} += {argv};{Environment.NewLine}";
}
dv.add_def(def);
return name;
}
}
}
@@ -0,0 +1,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;
using ExcelDna.Integration;
namespace bts.excel.extensions
{
public static class ExcelDNAExtensions
{
public static string GetSheetName(this ExcelReference rref)
{
string sheetname = (string)XlCall.Excel(XlCall.xlSheetNm, rref);
return sheetname;
}
}
}
@@ -11,6 +11,7 @@ using bts.excel;
using bts.excel.extensions;
using bts.excel.rtd;
using Newtonsoft.Json;
using bts.api;
namespace bts.api.orderman
@@ -20,6 +21,14 @@ namespace bts.api.orderman
readonly static Lazy<user.AuthService> _users = new Lazy<user.AuthService>(() => Locator.locate<user.AuthService>(), true);
readonly static Lazy<admin.AdminService> _admin = new Lazy<admin.AdminService>(() => Locator.locate<admin.AdminService>(), true);
struct OrderDef
{
public Create create;
public Response response;
}
static ConcurrentDictionary<long, OrderDef> _orders = new ConcurrentDictionary<long, OrderDef>();
[ExcelFunction(Category = "BTS", Description = "Get All Accessible Accounts")]
async public static void spark_get_accounts(string login_token, ExcelAsyncHandle handle)
{
@@ -42,48 +51,66 @@ namespace bts.api.orderman
}
}
static Response cancel_order(long order_id)
{
var resp = _service.Value.cancel_order(new Cancel() { OrderKey = Convert.ToUInt32(order_id) });
return resp;
}
[ExcelFunction(Category = "BTS", Description = "Cancel an Order by Order ID", IsMacroType = true)]
public static object spark_orderservice_cancel_order(long order_id)
{
var resp = _service.Value.cancel_order(new Cancel() { OrderKey = Convert.ToUInt32(order_id) });
var resp = cancel_order(order_id);
return parse_response(resp);
}
static Response update_order(long order_id, double price, long quantity, CustomOrderDefinition cust = null)
{
var resp = _service.Value.update_order(new Update()
{
OrderKey = Convert.ToUInt32(order_id),
Price = price,
Quantity = Convert.ToUInt32(quantity) ,
Custom = cust
});
return resp;
}
[ExcelFunction(Category = "BTS", Description = "Update an Order by Order ID", IsMacroType = true)]
public static object spark_orderservice_update_order(long order_id, double price, long quantity)
{
var resp = _service.Value.update_order(new Update() { OrderKey = Convert.ToUInt32(order_id), Price = price, Quantity = Convert.ToUInt32(quantity) });
var resp = update_order(order_id, price, quantity);
return parse_response(resp);
}
[ExcelFunction(Category = "BTS", Description = "Send an Order to Spark via security_key", IsMacroType = true)]
public static object spark_orderservice_send_order_key(
[ExcelArgument("Required. Only send the order if > last")] long local_order_id,
[ExcelArgument("Required. Only send the order if > 1")] long on_off,
[ExcelArgument("Required. Local Order ID used to differentiate between create / update")] long local_order_id,
[ExcelArgument("Required. Security key")] long security_key,
[ExcelArgument("Required. Side BUY or SELL")] string side,
[ExcelArgument("Required. User")] string user,
[ExcelArgument("Required. Account")] string account,
[ExcelArgument("Required. Price")] double price,
[ExcelArgument("Required. Quantity")] long quantity,
[ExcelArgument("Required. OrderType (Limit, Stop, Stop_Limit, Iceberg) - Default Limit")] string order_type,
[ExcelArgument("Required. OrderType (Limit, Stop, Stop_Limit, Iceberg) - Default Limit")] string order_type = null,
[ExcelArgument("OPTIONAL. Order Params JSON (\"stop_price\" : 51.88)")] string order_params = null,
[ExcelArgument("OPTIONAL. (DAY,GTC,IOC) - Default DAY")] string time_in_force = null,
[ExcelArgument("OPTIONAL. (YES,NO) - Default YES")] string manual_order_indicator = null,
[ExcelArgument("OPTIONAL. (1,2,3,4) - Default 1")] string cti_code = null,
[ExcelArgument("OPTIONAL. (CUSTOMER,FIRM) - Default FIRM")] string customer_or_firm = null)
[ExcelArgument("OPTIONAL. (DAY,GTC,IOC) - Default DAY")] string time_in_force = null)
{
if (local_order_id <= _local_order_id)
return "local_order_id must be greater than " + _local_order_id;
if(on_off <= 0)
return "this order is turned off";
if(_orders.ContainsKey(local_order_id))
return "use a new local order id per order";
Create cr = new Create();
cr.NewOrder = new OrderDefinition()
{
SecurityKey = Convert.ToUInt32(security_key),
Side = EnumParser.ToEnum<api.Side>(side),
TimeInForce = time_in_force.ToEnum<TimeInForce>(TimeInForce.Day),
ManualOrderIndicator = manual_order_indicator.ToEnum<ManualOrderIndicator>(ManualOrderIndicator.Yes),
CtiCode = cti_code.ToEnum<CTICode>(CTICode.CtiCode1),
CustomerOrFirm = customer_or_firm.ToEnum<CustomerOrFirm>(CustomerOrFirm.Firm),
// ManualOrderIndicator = manual_order_indicator.ToEnum<ManualOrderIndicator>(ManualOrderIndicator.Yes),
// CtiCode = cti_code.ToEnum<CTICode>(CTICode.CtiCode1),
// CustomerOrFirm = customer_or_firm.ToEnum<CustomerOrFirm>(CustomerOrFirm.Firm),
};
cr.Price = price;
cr.Quantity = Convert.ToUInt32(quantity);
@@ -98,12 +125,14 @@ namespace bts.api.orderman
return "Could not resolve account: " + account;
cr.NewOrder.Account = btaccount.Name;
cr.NewOrder.AccountId = btaccount.Id;
if(string.IsNullOrEmpty(order_type))
order_type = "Limit";
cr.NewOrder.CustomDef = custom_def(order_type, order_params);
if(cr.NewOrder.CustomDef == null || cr.NewOrder.CustomDef.CustomCase == CustomOrderDefinition.CustomOneofCase.None)
return "Could not parse order_type and/or order_params info";
var resp = _service.Value.create_order(cr);
_local_order_id = local_order_id;
_orders[local_order_id] = new OrderDef { create = cr, response = resp };
return parse_response(resp, true);
}
@@ -129,7 +158,7 @@ namespace bts.api.orderman
}
static CustomOrderDefinition custom_def(string order_type, string order_params)
{
{
var member = ReflectionExtensions.get_fields_or_properties(typeof(CustomOrderDefinition))
.Where(x => x.Name.ToLower() == order_type.ToLower()).FirstOrDefault();
if (member != null)
@@ -142,13 +171,13 @@ namespace bts.api.orderman
}
else
return null;
}
}
static long _local_order_id = 0;
[ExcelFunction(Category = "BTS", Description = "Send an Order to Spark via security_key", IsMacroType = true)]
public static object spark_orderservice_send_order(
[ExcelArgument("Required. Only send the order if > last")] long local_order_id,
[ExcelFunction(Category = "BTS", Description = "Send or Modify or Cancel a Spark Order ")]
public async static void spark_send_or_update_order(
[ExcelArgument("Required. Only send the order if > 1")] long on_off,
[ExcelArgument("Required. Local Order ID used to differentiate between create / update")] long local_order_id,
[ExcelArgument("Required. Exchange (GLBX,SIM)")] string exchange,
[ExcelArgument("Required. Security Desc (ZNZ9 or ZNZ9-ZNH0)")] string security_desc,
[ExcelArgument("Required. Side BUY or SELL")] string side,
@@ -156,29 +185,64 @@ namespace bts.api.orderman
[ExcelArgument("Required. Account")] string account,
[ExcelArgument("Required. Price")] double price,
[ExcelArgument("Required. Quantity")] long quantity,
[ExcelArgument("Required. OrderType (Limit, Stop, Stop_Limit, Iceberg) - Default Limit")] string order_type,
[ExcelArgument("Required. OrderType (Limit, Stop, Stop_Limit, Iceberg) - Default Limit")] string order_type = null,
[ExcelArgument("OPTIONAL. Order Params JSON (\"stop_price\" : 51.88)")] string order_params = null,
[ExcelArgument("OPTIONAL. (DAY,GTC,IOC) - Default DAY")] string time_in_force = null,
[ExcelArgument("OPTIONAL. (YES,NO) - Default YES")] string manual_order_indicator = null,
[ExcelArgument("OPTIONAL. (1,2,3,4) - Default 1")] string cti_code = null,
[ExcelArgument("OPTIONAL. (CUSTOMER,FIRM) - Default FIRM")] string customer_or_firm = null)
{
if (local_order_id <= _local_order_id)
return "local_order_id must be greater than " + _local_order_id;
Venue ven;
if (!Utilities.parse_venue(exchange, out ven))
return "Can't Parse Exchange: " + (exchange ?? string.Empty);
uint key;
if (MDSubscribe.market_data(ven).lookup_security_key_from_desc(security_desc, out key))
[ExcelArgument("OPTIONAL. (DAY,GTC,IOC) - Default DAY")] string time_in_force = null,
ExcelAsyncHandle handle = null)
{
try
{
return spark_orderservice_send_order_key(local_order_id, (long)key, side, user, account, price, quantity, order_type, order_params,
time_in_force, manual_order_indicator, cti_code, customer_or_firm);
Venue ven;
if (!Utilities.parse_venue(exchange, out ven))
handle.SetResult("Can't Parse Exchange: " + (exchange ?? string.Empty));
if (on_off <= 0)
handle.SetResult("this order is turned off");
var sec = await MDSubscribe.market_data(ven).find_security_async(x => x.security_desc() == security_desc);
if (sec == null)
{
handle.SetResult("Can't find security desc " + security_desc);
}
else
{
if (_orders.TryGetValue(local_order_id, out OrderDef def) && def.response.OrderKey > 0)
{
if(quantity > 0)
{
if (string.IsNullOrEmpty(order_type))
order_type = "Limit";
var cust = custom_def(order_type, order_params);
if (cust == null || cust.CustomCase == CustomOrderDefinition.CustomOneofCase.None)
handle.SetResult("Could not parse order_type and/or order_params info");
if(def.create.Price != price || def.create.Quantity != Convert.ToUInt32(quantity) ||
(cust != null && !cust.Equals(def.create.NewOrder.CustomDef)))
{
var resp = update_order(def.response.OrderKey, price, quantity, cust);
if(resp.ErrorCode == OrderError.Ok)
{
def.create.Price = price;
def.create.Quantity = Convert.ToUInt32(quantity);
}
handle.SetResult( parse_response(resp, true) );
}
else
handle.SetResult( parse_response(def.response, true) );
}
else
{
var resp = cancel_order(def.response.OrderKey);
handle.SetResult( parse_response(resp, true) );
}
}
else
handle.SetResult( spark_orderservice_send_order_key(on_off, local_order_id, (long)(sec.Value.Id), side, user, account, price, quantity,
order_type, order_params, time_in_force) );
}
}
else
catch (Exception ex)
{
return "Can't find security desc " + security_desc;
handle.SetException(ex);
}
}
}
Binary file not shown.
+723
View File
@@ -0,0 +1,723 @@
/*
[The "BSD licence"]
Copyright (c) 2013 Sam Harwell
All rights reserved.
Redistribution and use
in source and binary forms, with or without
modification, are permitted provided that the
following conditions
are met:
1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form
must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the
documentation and/or other materials provided with the distribution.
3. The name of the
author may not be used to endorse or promote products
derived from this software without specific
prior written permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
OF MERCHANTABILITY AND
FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT,
INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/** C 2011 grammar built from the C11 Spec */
grammar C;
primaryExpression:
Identifier
| Constant
| StringLiteral+
| '(' expression ')'
| genericSelection
| '__extension__'? '(' compoundStatement ')' // Blocks (GCC extension)
| '__builtin_va_arg' '(' unaryExpression ',' typeName ')'
| '__builtin_offsetof' '(' typeName ',' unaryExpression ')';
genericSelection:
'_Generic' '(' assignmentExpression ',' genericAssocList ')';
genericAssocList:
genericAssociation
| genericAssocList ',' genericAssociation;
genericAssociation:
typeName ':' assignmentExpression
| 'default' ':' assignmentExpression;
postfixExpression:
primaryExpression
| postfixExpression '[' expression ']'
| postfixExpression '(' argumentExpressionList? ')'
| postfixExpression '.' Identifier
| postfixExpression '->' Identifier
| postfixExpression '++'
| postfixExpression '--'
| '(' typeName ')' '{' initializerList '}'
| '(' typeName ')' '{' initializerList ',' '}'
| '__extension__' '(' typeName ')' '{' initializerList '}'
| '__extension__' '(' typeName ')' '{' initializerList ',' '}';
argumentExpressionList:
assignmentExpression
| argumentExpressionList ',' assignmentExpression;
unaryExpression:
postfixExpression
| '++' unaryExpression
| '--' unaryExpression
| unaryOperator castExpression
| 'sizeof' unaryExpression
| 'sizeof' '(' typeName ')'
| '_Alignof' '(' typeName ')'
| '&&' Identifier ; // GCC extension address of label
unaryOperator: '&' | '*' | '+' | '-' | '~' | '!';
castExpression:
'(' typeName ')' castExpression
| '__extension__' '(' typeName ')' castExpression
| unaryExpression
| DigitSequence ; // for
multiplicativeExpression:
castExpression
| multiplicativeExpression '*' castExpression
| multiplicativeExpression '/' castExpression
| multiplicativeExpression '%' castExpression;
additiveExpression:
multiplicativeExpression
| additiveExpression '+' multiplicativeExpression
| additiveExpression '-' multiplicativeExpression;
shiftExpression:
additiveExpression
| shiftExpression '<<' additiveExpression
| shiftExpression '>>' additiveExpression;
relationalExpression:
shiftExpression
| relationalExpression '<' shiftExpression
| relationalExpression '>' shiftExpression
| relationalExpression '<=' shiftExpression
| relationalExpression '>=' shiftExpression;
equalityExpression:
relationalExpression
| equalityExpression '==' relationalExpression
| equalityExpression '!=' relationalExpression;
andExpression:
equalityExpression
| andExpression '&' equalityExpression;
exclusiveOrExpression:
andExpression
| exclusiveOrExpression '^' andExpression;
inclusiveOrExpression:
exclusiveOrExpression
| inclusiveOrExpression '|' exclusiveOrExpression;
logicalAndExpression:
inclusiveOrExpression
| logicalAndExpression '&&' inclusiveOrExpression;
logicalOrExpression:
logicalAndExpression
| logicalOrExpression '||' logicalAndExpression;
conditionalExpression:
logicalOrExpression (
'?' expression ':' conditionalExpression
)?;
assignmentExpression:
conditionalExpression
| unaryExpression assignmentOperator assignmentExpression
| DigitSequence ; // for
assignmentOperator:
'='
| '*='
| '/='
| '%='
| '+='
| '-='
| '<<='
| '>>='
| '&='
| '^='
| '|=';
expression:
assignmentExpression
| expression ',' assignmentExpression;
constantExpression: conditionalExpression;
declaration:
declarationSpecifiers initDeclaratorList ';'
| declarationSpecifiers ';'
| staticAssertDeclaration;
declarationSpecifiers: declarationSpecifier+;
declarationSpecifiers2: declarationSpecifier+;
declarationSpecifier:
storageClassSpecifier
| typeSpecifier
| typeQualifier
| functionSpecifier
| alignmentSpecifier;
initDeclaratorList:
initDeclarator
| initDeclaratorList ',' initDeclarator;
initDeclarator: declarator | declarator '=' initializer;
storageClassSpecifier:
'typedef'
| 'extern'
| 'static'
| '_Thread_local'
| 'auto'
| 'register';
typeSpecifier: (
'void'
| 'char'
| 'short'
| 'int'
| 'long'
| 'float'
| 'double'
| 'signed'
| 'unsigned'
| '_Bool'
| '_Complex'
| '__m128'
| '__m128d'
| '__m128i'
)
| '__extension__' '(' ('__m128' | '__m128d' | '__m128i') ')'
| atomicTypeSpecifier
| structOrUnionSpecifier
| enumSpecifier
| typedefName
| '__typeof__' '(' constantExpression ')' // GCC extension
| typeSpecifier pointer;
structOrUnionSpecifier:
structOrUnion Identifier? '{' structDeclarationList '}'
| structOrUnion Identifier;
structOrUnion: 'struct' | 'union';
structDeclarationList:
structDeclaration
| structDeclarationList structDeclaration;
structDeclaration:
specifierQualifierList structDeclaratorList? ';'
| staticAssertDeclaration;
specifierQualifierList:
typeSpecifier specifierQualifierList?
| typeQualifier specifierQualifierList?;
structDeclaratorList:
structDeclarator
| structDeclaratorList ',' structDeclarator;
structDeclarator:
declarator
| declarator? ':' constantExpression;
enumSpecifier:
'enum' Identifier? '{' enumeratorList '}'
| 'enum' Identifier? '{' enumeratorList ',' '}'
| 'enum' Identifier;
enumeratorList: enumerator | enumeratorList ',' enumerator;
enumerator:
enumerationConstant
| enumerationConstant '=' constantExpression;
enumerationConstant: Identifier;
atomicTypeSpecifier: '_Atomic' '(' typeName ')';
typeQualifier: 'const' | 'restrict' | 'volatile' | '_Atomic';
functionSpecifier: (
'inline'
| '_Noreturn'
| '__inline__' // GCC extension
| '__stdcall'
)
| gccAttributeSpecifier
| '__declspec' '(' Identifier ')';
alignmentSpecifier:
'_Alignas' '(' typeName ')'
| '_Alignas' '(' constantExpression ')';
declarator: pointer? directDeclarator gccDeclaratorExtension*;
directDeclarator:
Identifier
| '(' declarator ')'
| directDeclarator '[' typeQualifierList? assignmentExpression? ']'
| directDeclarator '[' 'static' typeQualifierList? assignmentExpression ']'
| directDeclarator '[' typeQualifierList 'static' assignmentExpression ']'
| directDeclarator '[' typeQualifierList? '*' ']'
| directDeclarator '(' parameterTypeList ')'
| directDeclarator '(' identifierList? ')'
| Identifier ':' DigitSequence // bit field
| '(' typeSpecifier? pointer directDeclarator ')' ; // function pointer like: (__cdecl *f)
gccDeclaratorExtension:
'__asm' '(' StringLiteral+ ')'
| gccAttributeSpecifier;
gccAttributeSpecifier:
'__attribute__' '(' '(' gccAttributeList ')' ')';
gccAttributeList:
gccAttribute (',' gccAttribute)*
| ; // empty
gccAttribute:
~(
','
| '('
| ')'
) // relaxed def for "identifier or reserved word"
('(' argumentExpressionList? ')')?
| ; // empty
nestedParenthesesBlock: (
~('(' | ')')
| '(' nestedParenthesesBlock ')'
)*;
pointer:
'*' typeQualifierList?
| '*' typeQualifierList? pointer
| '^' typeQualifierList? // Blocks language extension
| '^' typeQualifierList? pointer ; // Blocks language extension
typeQualifierList:
typeQualifier
| typeQualifierList typeQualifier;
parameterTypeList: parameterList | parameterList ',' '...';
parameterList:
parameterDeclaration
| parameterList ',' parameterDeclaration;
parameterDeclaration:
declarationSpecifiers declarator
| declarationSpecifiers2 abstractDeclarator?;
identifierList: Identifier | identifierList ',' Identifier;
typeName: specifierQualifierList abstractDeclarator?;
abstractDeclarator:
pointer
| pointer? directAbstractDeclarator gccDeclaratorExtension*;
directAbstractDeclarator:
'(' abstractDeclarator ')' gccDeclaratorExtension*
| '[' typeQualifierList? assignmentExpression? ']'
| '[' 'static' typeQualifierList? assignmentExpression ']'
| '[' typeQualifierList 'static' assignmentExpression ']'
| '[' '*' ']'
| '(' parameterTypeList? ')' gccDeclaratorExtension*
| directAbstractDeclarator '[' typeQualifierList? assignmentExpression? ']'
| directAbstractDeclarator '[' 'static' typeQualifierList? assignmentExpression ']'
| directAbstractDeclarator '[' typeQualifierList 'static' assignmentExpression ']'
| directAbstractDeclarator '[' '*' ']'
| directAbstractDeclarator '(' parameterTypeList? ')' gccDeclaratorExtension*;
typedefName: Identifier;
initializer:
assignmentExpression
| '{' initializerList '}'
| '{' initializerList ',' '}';
initializerList:
designation? initializer
| initializerList ',' designation? initializer;
designation: designatorList '=';
designatorList: designator | designatorList designator;
designator: '[' constantExpression ']' | '.' Identifier;
staticAssertDeclaration:
'_Static_assert' '(' constantExpression ',' StringLiteral+ ')' ';';
statement:
labeledStatement
| compoundStatement
| expressionStatement
| selectionStatement
| iterationStatement
| jumpStatement
| ('__asm' | '__asm__') ('volatile' | '__volatile__') '(' (
logicalOrExpression (',' logicalOrExpression)*
)? (':' (logicalOrExpression (',' logicalOrExpression)*)?)* ')' ';';
labeledStatement:
Identifier ':' statement
| 'case' constantExpression ':' statement
| 'default' ':' statement;
compoundStatement: '{' blockItemList? '}';
blockItemList: blockItem | blockItemList blockItem;
blockItem: statement | declaration;
expressionStatement: expression? ';';
selectionStatement:
'if' '(' expression ')' statement ('else' statement)?
| 'switch' '(' expression ')' statement;
iterationStatement:
While '(' expression ')' statement
| Do statement While '(' expression ')' ';'
| For '(' forCondition ')' statement;
// | 'for' '(' expression? ';' expression? ';' forUpdate? ')' statement | For '(' declaration
// expression? ';' expression? ')' statement
forCondition:
forDeclaration ';' forExpression? ';' forExpression?
| expression? ';' forExpression? ';' forExpression?;
forDeclaration:
declarationSpecifiers initDeclaratorList
| declarationSpecifiers;
forExpression:
assignmentExpression
| forExpression ',' assignmentExpression;
jumpStatement:
'goto' Identifier ';'
| 'continue' ';'
| 'break' ';'
| 'return' expression? ';'
| 'goto' unaryExpression ';' ; // GCC extension
compilationUnit: translationUnit? EOF;
translationUnit:
externalDeclaration
| translationUnit externalDeclaration;
externalDeclaration:
functionDefinition
| declaration
| ';' ; // stray ;
functionDefinition:
declarationSpecifiers? declarator declarationList? compoundStatement;
declarationList: declaration | declarationList declaration;
Auto: 'auto';
Break: 'break';
Case: 'case';
Char: 'char';
Const: 'const';
Continue: 'continue';
Default: 'default';
Do: 'do';
Double: 'double';
Else: 'else';
Enum: 'enum';
Extern: 'extern';
Float: 'float';
For: 'for';
Goto: 'goto';
If: 'if';
Inline: 'inline';
Int: 'int';
Long: 'long';
Register: 'register';
Restrict: 'restrict';
Return: 'return';
Short: 'short';
Signed: 'signed';
Sizeof: 'sizeof';
Static: 'static';
Struct: 'struct';
Switch: 'switch';
Typedef: 'typedef';
Union: 'union';
Unsigned: 'unsigned';
Void: 'void';
Volatile: 'volatile';
While: 'while';
Alignas: '_Alignas';
Alignof: '_Alignof';
Atomic: '_Atomic';
Bool: '_Bool';
Complex: '_Complex';
Generic: '_Generic';
Imaginary: '_Imaginary';
Noreturn: '_Noreturn';
StaticAssert: '_Static_assert';
ThreadLocal: '_Thread_local';
LeftParen: '(';
RightParen: ')';
LeftBracket: '[';
RightBracket: ']';
LeftBrace: '{';
RightBrace: '}';
Less: '<';
LessEqual: '<=';
Greater: '>';
GreaterEqual: '>=';
LeftShift: '<<';
RightShift: '>>';
Plus: '+';
PlusPlus: '++';
Minus: '-';
MinusMinus: '--';
Star: '*';
Div: '/';
Mod: '%';
And: '&';
Or: '|';
AndAnd: '&&';
OrOr: '||';
Caret: '^';
Not: '!';
Tilde: '~';
Question: '?';
Colon: ':';
Semi: ';';
Comma: ',';
Assign: '=';
// '*=' | '/=' | '%=' | '+=' | '-=' | '<<=' | '>>=' | '&=' | '^=' | '|='
StarAssign: '*=';
DivAssign: '/=';
ModAssign: '%=';
PlusAssign: '+=';
MinusAssign: '-=';
LeftShiftAssign: '<<=';
RightShiftAssign: '>>=';
AndAssign: '&=';
XorAssign: '^=';
OrAssign: '|=';
Equal: '==';
NotEqual: '!=';
Arrow: '->';
Dot: '.';
Ellipsis: '...';
Identifier: IdentifierNondigit ( IdentifierNondigit | Digit)*;
fragment IdentifierNondigit:
Nondigit
| UniversalCharacterName
; //| // other implementation-defined characters...
fragment Nondigit: [a-zA-Z_];
fragment Digit: [0-9];
fragment UniversalCharacterName:
'\\u' HexQuad
| '\\U' HexQuad HexQuad;
fragment HexQuad:
HexadecimalDigit HexadecimalDigit HexadecimalDigit HexadecimalDigit;
Constant:
IntegerConstant
| FloatingConstant
//| EnumerationConstant
| CharacterConstant;
fragment IntegerConstant:
DecimalConstant IntegerSuffix?
| OctalConstant IntegerSuffix?
| HexadecimalConstant IntegerSuffix?
| BinaryConstant;
fragment BinaryConstant: '0' [bB] [0-1]+;
fragment DecimalConstant: NonzeroDigit Digit*;
fragment OctalConstant: '0' OctalDigit*;
fragment HexadecimalConstant:
HexadecimalPrefix HexadecimalDigit+;
fragment HexadecimalPrefix: '0' [xX];
fragment NonzeroDigit: [1-9];
fragment OctalDigit: [0-7];
fragment HexadecimalDigit: [0-9a-fA-F];
fragment IntegerSuffix:
UnsignedSuffix LongSuffix?
| UnsignedSuffix LongLongSuffix
| LongSuffix UnsignedSuffix?
| LongLongSuffix UnsignedSuffix?;
fragment UnsignedSuffix: [uU];
fragment LongSuffix: [lL];
fragment LongLongSuffix: 'll' | 'LL';
fragment FloatingConstant:
DecimalFloatingConstant
| HexadecimalFloatingConstant;
fragment DecimalFloatingConstant:
FractionalConstant ExponentPart? FloatingSuffix?
| DigitSequence ExponentPart FloatingSuffix?;
fragment HexadecimalFloatingConstant:
HexadecimalPrefix HexadecimalFractionalConstant BinaryExponentPart FloatingSuffix?
| HexadecimalPrefix HexadecimalDigitSequence BinaryExponentPart FloatingSuffix?;
fragment FractionalConstant:
DigitSequence? '.' DigitSequence
| DigitSequence '.';
fragment ExponentPart:
'e' Sign? DigitSequence
| 'E' Sign? DigitSequence;
fragment Sign: '+' | '-';
DigitSequence: Digit+;
fragment HexadecimalFractionalConstant:
HexadecimalDigitSequence? '.' HexadecimalDigitSequence
| HexadecimalDigitSequence '.';
fragment BinaryExponentPart:
'p' Sign? DigitSequence
| 'P' Sign? DigitSequence;
fragment HexadecimalDigitSequence: HexadecimalDigit+;
fragment FloatingSuffix: 'f' | 'l' | 'F' | 'L';
fragment CharacterConstant:
'\'' CCharSequence '\''
| 'L\'' CCharSequence '\''
| 'u\'' CCharSequence '\''
| 'U\'' CCharSequence '\'';
fragment CCharSequence: CChar+;
fragment CChar: ~['\\\r\n] | EscapeSequence;
fragment EscapeSequence:
SimpleEscapeSequence
| OctalEscapeSequence
| HexadecimalEscapeSequence
| UniversalCharacterName;
fragment SimpleEscapeSequence: '\\' ['"?abfnrtv\\];
fragment OctalEscapeSequence:
'\\' OctalDigit
| '\\' OctalDigit OctalDigit
| '\\' OctalDigit OctalDigit OctalDigit;
fragment HexadecimalEscapeSequence: '\\x' HexadecimalDigit+;
StringLiteral: EncodingPrefix? '"' SCharSequence? '"';
fragment EncodingPrefix: 'u8' | 'u' | 'U' | 'L';
fragment SCharSequence: SChar+;
fragment SChar:
~["\\\r\n]
| EscapeSequence
| '\\\n' // Added line
| '\\\r\n' ; // Added line
ComplexDefine: '#' Whitespace? 'define' ~[#]* -> skip;
IncludeDirective:
'#' Whitespace? 'include' Whitespace? (
('"' ~[\r\n]* '"')
| ('<' ~[\r\n]* '>')
) Whitespace? Newline -> skip;
// ignore the following asm blocks:
/*
asm
{
mfspr x, 286;
}
*/
AsmBlock: 'asm' ~'{'* '{' ~'}'* '}' -> skip;
// ignore the lines generated by c preprocessor sample line : '#line 1 "/home/dm/files/dk1.h" 1'
LineAfterPreprocessing: '#line' Whitespace* ~[\r\n]* -> skip;
LineDirective:
'#' Whitespace? DecimalConstant Whitespace? StringLiteral ~[\r\n]* -> skip;
PragmaDirective:
'#' Whitespace? 'pragma' Whitespace ~[\r\n]* -> skip;
Whitespace: [ \t]+ -> skip;
Newline: ( '\r' '\n'? | '\n') -> skip;
BlockComment: '/*' .*? '*/' -> skip;
LineComment: '//' ~[\r\n]* -> skip;
@@ -0,0 +1,93 @@
grammar ExcelFormula;
/* Parser rules */
main: '=' expr EOF;
expr:
sign = ('+' | '-') expr # Unary
| expr '%' # Percentage
| <assoc=right> expr '^' expr # Pow
| expr op = ('*' | '/') expr # MulDiv
| expr op = ('+' | '-') expr # AddSub
| expr '&' expr # Concatenate
| expr op = ('=' | '<>') expr # Equality
| expr op = ('<' | '>' | '<=' | '>=') expr # Relational
| '(' expr ')' # Parenthesis
| name = NAME '(' (expr (',' expr)*)? ')' # Function
| rng # Range
| rng (',' rng)+ # RangeList
| ref # Cell
| ref (',' ref)+ # CellList
| BOOLEAN # Boolean
| NUMBER # Number
| NAME # Name
| STRING # String
| ERROR # Error;
ref: sheet = SHEET? colRow = COL_ROW # CellRef;
rng: start = ref ':' end = COL_ROW # RangeRef;
/* Lexer rules */
COL_ROW: '$'? COL '$'? DIGIT+;
STRING: '"' ~["]* '"';
BOOLEAN: T R U E | F A L S E;
NUMBER: FLOAT | DIGIT+;
NAME: [a-zA-Z_\\] ([0-9a-zA-Z_.\\])*;
ERROR:
E_NULL
| E_DIV0
| E_VALUE
| E_NAME
| E_NUM
| E_NA
| E_REF;
E_NULL: '#' N U L L '!';
E_DIV0: '#' D I V '/0';
E_VALUE: '#' V A L U E '!';
E_NAME: '#' N A M E '?';
E_NUM: '#' N U M '!';
E_NA: '#' N '/' A;
E_REF: '#' R E F '!';
SHEET:
SHEET_C+ '!'
| SHEET_C+ ':'+ SHEET_C+ '!'
| '\'' Q_SHEET_C+ '\'!'
| '\'' Q_SHEET_C+ ':' Q_SHEET_C+ '\'!';
SPACE: (' ' | '\t' | '\r' | '\n' | '\u000C') -> skip;
INVALID: .;
/* Lexer fragments */
fragment COL: [a-zA-Z]? [a-zA-Z]? [a-zA-Z]; // Max col is XFD
fragment DIGIT: [0-9];
fragment FLOAT: DIGIT+ '.' DIGIT+ EXPONENT? | DIGIT+ EXPONENT;
fragment EXPONENT: E ('+'? | '-') DIGIT+;
fragment FILE: '[' DIGIT+ ']' | '[' FILENAME_C+ ']';
fragment WIN_PATH: [A-Z] ':\\' (FILENAME_C+ '\\')*;
fragment FILENAME_C: ~["*[\]\\:/?<>|];
fragment SHEET_C: ~['*[\]\\:/?<>();{}#"=&+^%,!\u2229\u222A \-];
fragment Q_SHEET_C: ~['*[\]\\:/?];
fragment A: ('a' | 'A');
fragment B: ('b' | 'B');
fragment C: ('c' | 'C');
fragment D: ('d' | 'D');
fragment E: ('e' | 'E');
fragment F: ('f' | 'F');
fragment G: ('g' | 'G');
fragment H: ('h' | 'H');
fragment I: ('i' | 'I');
fragment J: ('j' | 'J');
fragment K: ('k' | 'K');
fragment L: ('l' | 'L');
fragment M: ('m' | 'M');
fragment N: ('n' | 'N');
fragment O: ('o' | 'O');
fragment P: ('p' | 'P');
fragment Q: ('q' | 'Q');
fragment R: ('r' | 'R');
fragment S: ('s' | 'S');
fragment T: ('t' | 'T');
fragment U: ('u' | 'U');
fragment V: ('v' | 'V');
fragment W: ('w' | 'W');
fragment X: ('x' | 'X');
fragment Y: ('y' | 'Y');
fragment Z: ('z' | 'Z');
-5
View File
@@ -1,5 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ExcelDna.AddIn" version="0.34.6" targetFramework="net471" />
<package id="ExcelDna.Integration" version="0.34.6" targetFramework="net471" />
</packages>
+29 -5
View File
@@ -15,9 +15,11 @@
<AllowUnsafeBlocks>true</AllowUnsafeBlocks>
<Platforms>x64</Platforms>
<PlatformTarget>AnyCPU</PlatformTarget>
<NoWarn>0108,3021</NoWarn>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
<WarningsAsErrors />
<Version>1.0.0</Version>
<Antlr4UseCSharpGenerator>true</Antlr4UseCSharpGenerator>
</PropertyGroup>
<ItemGroup>
@@ -28,10 +30,21 @@
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
<PackageReference Include="System.Linq.Dynamic" Version="1.0.7" />
<PackageReference Include="ExcelDna.AddIn" Version="0.34.6" />
<PackageReference Include="ExcelDna.Integration" Version="0.34.6" />
<PackageReference Include="ExcelDna.AddIn" Version="1.0.0" />
<PackageReference Include="ExcelDna.Integration" Version="1.0.0" />
<PackageReference Include="ExcelDna.IntelliSense" Version="1.1.0" />
<PackageReference Include="ExcelDna.Registration" Version="0.34.7" />
<PackageReference Include="ExcelDna.Interop" Version="14.0.1" />
<PackageReference Include="Antlr4" Version="4.6.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
<PackageReference Include="Antlr4.Runtime" Version="4.6.6" />
<PackageReference Include="Antlr4.CodeGenerator" Version="4.6.6">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
@@ -50,17 +63,28 @@
<None Include="spark_excel-AddIn.dna" />
<None Include="packages.config" />
<None Include="Properties\ExcelDna.Build.props" />
<None Include="$(IntermediateOutputPath)\*.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="../spark_api/spark_api.csproj"/>
</ItemGroup>
<!-- <ItemGroup>
<Antlr4 Include="grammar/ExcelFormula.g4">
<Generator>MSBuild:Compile</Generator>
<CustomToolNamespace>bts.excel.grammar</CustomToolNamespace>
<Listener>True</Listener>
<Visitor>True</Visitor>
</Antlr4>
</ItemGroup> -->
<ItemGroup>
<Proto3Excel Include="**/*.proto" />
<Proto3Excel Include="../../lib/api/services/*.proto" />
</ItemGroup>
<ItemGroup>
<None Include="spark_excel_example_2018.xlsm"><CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory></None>
</ItemGroup>
@@ -74,9 +98,9 @@
-->
<!-- <Import Project="$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets" Condition="Exists('$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets')" /> -->
<Import Project="$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets"/>
<!-- <Import Project="$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets"/>
<Target Name="EnsureExcelDnaTargetsImported" BeforeTargets="BeforeBuild" Condition="'$(ExcelDnaTargetsImported)' == ''">
<Error Condition="!Exists('$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets') And ('$(RunExcelDnaBuild)' != '' And $(RunExcelDnaBuild))" Text="You are trying to build with ExcelDna, but the NuGet targets file that ExcelDna depends on is not available on this computer. This is probably because the ExcelDna package has not been committed to source control, or NuGet Package Restore is not enabled. Please enable NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=317567." HelpKeyword="BCLBUILD2001" />
<Error Condition="Exists('$(NuGetPackageRoot)\ExcelDna.AddIn\0.34.6\tools\ExcelDna.AddIn.targets') And ('$(RunExcelDnaBuild)' != '' And $(RunExcelDnaBuild))" Text="ExcelDna cannot be run because NuGet packages were restored prior to the build running, and the targets file was unavailable when the build started. Please build the project again to include these packages in the build. You may also need to make sure that your build server does not delete packages prior to each build. For more information, see http://go.microsoft.com/fwlink/?LinkID=317568." HelpKeyword="BCLBUILD2002" />
</Target>
</Target> -->
</Project>
@@ -0,0 +1,91 @@
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Reflection;
using System.Text.RegularExpressions;
using ExcelDna.Integration;
using bts.api;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace bts.excel
{
public class AlgoHelpers
{
static ConcurrentDictionary<string, object> _cache = new ConcurrentDictionary<string, object>();
[ExcelFunction(IsMacroType = true)]
static public object sparkalgo_register_parameter([ExcelArgument(AllowReference = true)] object parameter)
{
ExcelReference par = (ExcelReference)parameter;
string sheetname = (string)XlCall.Excel(XlCall.xlSheetNm, par);
var cellref = new CellRef(sheetname, (par.ColumnFirst + 1, par.RowFirst + 1));
string r1c1 = cellref.r1_c1();
var cellname = XlCall.Excel(XlCall.xlfGetDef, r1c1, sheetname);
if (!(cellname is ExcelError))
{
GeneratorVisitor.register_algo_parameter(sheetname, cellname.ToString());
return true;
}
else
return $"{ErrorValue.Name}, please make algo parameters named ranges";
// ExcelReference caller = (ExcelReference)XlCall.Excel(XlCall.xlfCaller);
// var refr = $"R{caller.RowFirst+1}C{caller.ColumnFirst+1}:R{caller.RowLast+1}C{caller.ColumnLast+1}";
// var reff = new CellRef(sheetname, (caller.ColumnFirst + 1, caller.RowFirst + 1));
// refr = reff.r1_c1();
// bool hidden = false; bool local = true;
// var res = XlCall.Excel(XlCall.xlcDefineName, name, "=" + refr, Type.Missing, Type.Missing, hidden, Type.Missing, local);
}
[ExcelFunction(IsMacroType = true)]
static public object sparkalgo_take_snapshot(object data, string tag)
{
object val;
if(!_cache.TryGetValue(tag, out val))
{
_cache[tag] = val = data;
}
return val;
}
[ExcelFunction(IsMacroType = true)]
static public object sparkalgo_get_snapshot(string tag)
{
_cache.TryGetValue(tag, out object val);
return val;
}
[ExcelFunction(IsMacroType = true)]
static public object sparkalgo_snapshot_switch(string tag, int on_off)
{
object val;
if (!_cache.TryGetValue(tag, out val) && on_off > 0)
{
_cache[tag] = val = on_off;
}
return val ?? 0;
}
[ExcelFunction(IsMacroType = true)]
static public void sparkalgo_reset_all_snapshots(object _)
{
_cache.Clear();
}
static public void sparkalgo_reset_all_snapshots_no_args()
{
_cache.Clear();
}
[ExcelFunction(IsMacroType = true)]
static public void sparkalgo_reset_snapshot(string tag)
{
_cache.TryRemove(tag, out object val);
}
}
}
+1 -1
View File
@@ -108,7 +108,7 @@ where
session.session_start = event_view.session_start and
event_view.channel=trace.channel and event_view.sn=trace.sn and
event_type='hedge' and
entry_kind='NativeOrder::on_update' and
entry_kind='NativeOrder::on_activate' and
cor_event=0;
/* A view on requote events, identifying each order sent as part of the event*/
-8
View File
@@ -38,8 +38,6 @@ inline api::Side other_side(api::Side side) {
inline double market_epislon() { return 1e-10; }
// this tells which price is better from a market data
// standpoint, ie for buys the higher price is better
inline bool is_better(api::Side side, Price p1, Price p2) {
switch (side) {
case api::SIDE_BUY:
@@ -83,12 +81,6 @@ inline Price better_price (api::Side side, Price p1, Price p2){
return is_equal_or_better(side, p1, p2) ? p1 : p2;
}
// returns true if p1 is a better order price than p2
// ie lower when buying, higher when selling
inline bool same_or_better_order_price (api::Side side, Price p1, Price p2){
return is_equal_or_better(side, p2, p1);
}
inline Price decode_exchange_price(api::Security const &sec, Price in) {
return Price(in.value() * sec.contract_spec().price_multiplier());
}
@@ -130,7 +130,7 @@ public:
for (auto& o : _orders){
// is_cancelled() is checked so as not to keep
// sending cancel requests
if(!o.cancel_sent()&&o.acknowledged()&&!o.terminal_status())
if(!o.is_cancelled()&&o.acknowledged()&&!o.terminal_status())
o.cancel_order();
}
}
@@ -118,12 +118,6 @@ ChildOrder SpreaderOrder::get_new_hedge_order(size_t leg_index){
bts::orderman::ChildOrder child_order = leg_data.hedger_order_builder().build();
return child_order;
}
void SpreaderOrder::send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order){
_send_hedge(hedge_leg_index, hedge_price, hedge_qty, use_quoting_order);
}
// events from orders system ////////////////////
/////////////////////////////////////////////////
void SpreaderOrder::_on_time(const bts::mercury::TimerEvent& t_event){
@@ -374,12 +368,10 @@ bool SpreaderOrder::_quoters_can_accept_modification (){
}
void SpreaderOrder::_send_hedge(size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order){
Quantity hedge_qty){
_bookkeeping_data().add_new_hedger (hedge_leg_index,
hedge_price,
hedge_qty,
use_quoting_order);
hedge_qty);
}
void SpreaderOrder::_compute_hedge_price_quantity(size_t filled_leg_index,
Price fill_price,
@@ -140,13 +140,10 @@ public:
}
void setup_new_quoter_order (size_t leg_index) override;
ChildOrder get_new_hedge_order (size_t leg_index) override;
void send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order = false) override;
inline bool in_cache_warming_cycle() const override{
return _cw_helper.in_cache_warming_cycle;
}
private:
// events from orders system ////////////////////
/////////////////////////////////////////////////
@@ -238,8 +235,7 @@ private:
// quantity 'filled_quantity'
void _send_hedge(size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order);
Quantity hedge_qty);
void _compute_hedge_price_quantity(size_t filled_leg_index,
Price filled_price,
double filled_quantity,
@@ -7,17 +7,12 @@ namespace orderman {
class LegPropertyData;
class CacheWarmingState;
class SpreaderChildOrderState;
// The Spreader spawns a bunch of quoters and
// hedgers and hands them this interface to
// i. get data such as book and leg properties
// (in O(1) access time)
// ii. create new quoter order
class ISpreaderManager{
public:
struct OrderTransfer{
SpreaderChildOrderState* q_order;
};
public:
virtual bts::orderman::OrderKey spreader_order_key() const = 0;
virtual bts::TimeStamp current_time() const = 0;
@@ -33,14 +28,6 @@ public:
// it does not alter the state or has side effects (as
// as the spreader goes)
virtual ChildOrder get_new_hedge_order (size_t leg_index) = 0;
// sends a new hedge for the leg index at a specified
// hedge price and size. when use_quoting_order is
// set to true the hegder is passed over the quoting
// order (and its state) to hedge
virtual void send_hedge_order (size_t hedge_leg_index,
Price hedge_price,
Quantity hedge_qty,
bool use_quoting_order) = 0;
// the spreader can be in a cache warming cycle and generate
// fake updates, the quoters and hedgers should ignore them
// (however do as much as they can to keep the instruction
@@ -35,9 +35,7 @@ public:
const bts::api::Security& security() const { return _leg_contract.security(); }
double price_multiplier() const { return _leg_contract.price_multiplier(); }
double size_multiplier() const { return _leg_contract.quantity(); }
double tick_size() const {
return _leg_contract.security().contract_spec().low_tick();
}
double tick_size() const { return _leg_contract.security().contract_spec().low_tick(); }
bool is_active_quoting() const {return _leg_params.is_active_quoting();}
bool is_net_change() const{
return _price_calc==bts::api::SyntheticContract::PRICECALC_NET_CHANGE;
@@ -58,9 +56,6 @@ public:
uint32_t n_queue_holder_orders() const{
return _leg_params.quote_params().n_queue_holder_orders();
}
bts::spark::UseSpreaderQuoteForHedging use_quote_for_hedging() const{
return _leg_params.quote_params().use_quote_for_hedging();
}
};
}}
@@ -83,9 +83,8 @@ _end_state_worker (this, other._end_state_worker){
/****************************External Calls**************************/
/********************************************************************/
void SingleFillHedger::init_hedger (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order){
_worker->init(price, quantity, order);
Quantity quantity){
_worker->init(price,quantity);
}
void SingleFillHedger::on_order_update(const SpreaderChildOrderState& u){
//bts_assert (u.order_key() == _order.order_key());
@@ -139,9 +138,7 @@ void SingleFillHedger::transform_to_WAITING_FOR_FIRST_ACK_CANCELLED () {
_switch_state (&_waiting_for_first_ack_cancelled_state_worker);
}
void SingleFillHedger::transform_to_WORKING() {
bts_assert(_worker->state() == HedgerState::WAITING_FOR_FIRST_ACK ||
// in case of quoting orders assigned to hedger
_worker->state() == HedgerState::START);
bts_assert(_worker->state() == HedgerState::WAITING_FOR_FIRST_ACK);
_switch_state (&_working_state_worker);
}
void SingleFillHedger::transform_to_WAITING_FOR_CANCEL_ACK(){
@@ -58,9 +58,6 @@ private:
void _modify_order (Price new_price){
_child_order_state.modify_order(new_price);
}
void _modify_order (Price new_price, Quantity qty){
_child_order_state.modify_order(new_price, qty);
}
void _cancel_order () {
_child_order_state.cancel_order();
}
@@ -96,9 +93,7 @@ public:
//that live in the START state until...
//iii.until init_hedger is called which sets the price
//qty and causes the order to be submitted
void init_hedger (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr);
void init_hedger (Price price, Quantity quantity);
//b. called by the spreader when there is an order update
// reported by the exchange
void on_order_update(const SpreaderChildOrderState& order_update_message);
@@ -112,17 +112,13 @@ void SingleLegQuoter::on_book(size_t leg_index,
_worker->on_book (leg_index, book);
}
void SingleLegQuoter::update_other_leg_fills(size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
Quantity filled_quantity){
bts_assert(_active_quoting);
if(hedge_qty.value()>0)
LOG(OrderMan, Info, "SingleLegQuoter::update_other_leg_fills "
"spread_key:{} leg_idx:{} fill_idx:{} filled_quantity:{}",
_spreader.spreader_order_key(), _this_leg_data.leg_index(),
leg_index, filled_quantity);
_worker->on_other_leg_quoter_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
LOG(OrderMan, Info, "SingleLegQuoter::update_other_leg_fills "
"spread_key:{} leg_idx:{} fill_idx:{} filled_quantity:{}",
_spreader.spreader_order_key(), _this_leg_data.leg_index(),
leg_index, filled_quantity);
_worker->on_other_leg_quoter_fill (leg_index, filled_quantity);
}
void SingleLegQuoter::update_order_price_quantity(Price price,
Quantity quantity){
@@ -165,18 +161,8 @@ bool SingleLegQuoter::accept_modifications() const {
return _worker->state() == QuoterState::WAITING_FOR_SIZE ||
_worker->state() == QuoterState::WORKING;
}
void SingleLegQuoter::_incorporate_other_leg_fill (size_t,
Quantity hedge_reduction,
Price hedge_price,
Quantity hedge_qty,
bool send_new_hedge,
bool use_quoting_order){
void SingleLegQuoter::_incorporate_other_leg_fill (size_t, Quantity hedge_reduction){
_price_quantity_state.add_hedged_reduction (hedge_reduction);
if(send_new_hedge)
_spreader.send_hedge_order(_this_leg_data.leg_index(),
hedge_price,
hedge_qty,
use_quoting_order);
}
void SingleLegQuoter::_compute_quote(
Quantity target_qty,
@@ -15,7 +15,6 @@
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForCancelAckStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWorkingStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterEndStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForOrderTransferStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/QuoteLegDriver.h"
#include "lib/orderman/actors/order_manager/ChildOrder.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
@@ -36,7 +35,6 @@ friend QuoterWaitingForIOCWorker;
friend QuoterWaitingForFirstAckCancelledWorker;
friend QuoterWaitingForCancelAckStateWorker;
friend QuoterWorkingStateWorker;
friend QuoterWaitingForOrderTransferStateWorker;
friend QuoterEndStateWorker;
private:
const bool _two_legged;
@@ -117,9 +115,7 @@ public:
//g. this is called by the spreader when a quoting fill
// (ie not hedging fill) happens on one of the quoting
// legs
void update_other_leg_fills(size_t leg_index, Quantity filled_quantity,
Price hedge_price = Price(0),
Quantity hedge_qty = Quantity(0));
void update_other_leg_fills(size_t leg_index, Quantity filled_quantity);
//h. called when the user modified the spreader order price or quantity
void update_order_price_quantity(Price price, Quantity quantity);
// true if the quoter has an active working order. the order can
@@ -185,12 +181,7 @@ private:
}
void _cancel_order () {_child_order_state.cancel_order();}
// this updates the hedge reduction in _price_quantity_state
void _incorporate_other_leg_fill (size_t leg_index,
Quantity hedge_reduction,
Price hedge_price,
Quantity hedge_qty,
bool send_new_hedge = true,
bool use_quoting_order_to_hedge = false);
void _incorporate_other_leg_fill (size_t leg_index, Quantity hedge_reduction);
// given a target quoting qty
// this figures out the price and the actual
// qty that can be quoted.
@@ -103,16 +103,12 @@ public:
// and returns a ref to it
// (dont keep pointers to hedgers since the vector
// can resize)
inline SingleFillHedger& add_new_hedger(
size_t leg_index,
inline SingleFillHedger& add_new_hedger(size_t leg_index,
Price hedge_price,
Quantity hedge_quantity,
bool use_quoting_order = false){
Quantity hedge_quantity){
bts_assert(leg_index < _leg_data.size());
SpreaderLegData& leg_data=_leg_data[leg_index];
return leg_data.add_new_hedger(hedge_price,
hedge_quantity,
use_quoting_order);
return leg_data.add_new_hedger(hedge_price,hedge_quantity);
}
// finds the spreader fill, price (ie averages it out, using
// the size and price ratio, across all legs)
@@ -10,20 +10,18 @@ _is_live(src._is_live),
_sec_key(src._sec_key),
_is_quoting (src._is_quoting),
_test_only_order_key(src._test_only_order_key),
_base_price(src._base_price),
_base_quantity(src._base_quantity),
_n_place_orders(src._n_place_orders),
_n_cancel_orders(src._n_cancel_orders),
_n_modify_orders(src._n_modify_orders),
_base_price(src._base_price),
_base_quantity(src._base_quantity),
_child_order(std::move(src._child_order)),
_handover_filled_qty(Quantity(0)),
_status(src._status),
_filled_price(src._filled_price),
_filled_quantity(src._filled_quantity),
_last_update_filled_price(src._last_update_filled_price),
_last_update_filled_quantity(src._last_update_filled_quantity),
_last_filled_price(src._last_filled_price),
_last_reported_order_price(src._last_reported_order_price),
_last_reported_order_qty(src._last_reported_order_qty),
_last_filled_quantity(src._last_filled_quantity),
_out_price(src._out_price),
_out_quantity(src._out_quantity),
_order_place_time(src._order_place_time)
@@ -42,8 +40,7 @@ _base_quantity(0){
ChildOrder& empty_order=_empty_order();
re_init(empty_order);
}
void SpreaderChildOrderState::re_init (ChildOrder& child_order,
Quantity handover_filled_qty){
void SpreaderChildOrderState::re_init (ChildOrder& child_order){
SpreaderUtils::compute_average_price(_base_price, _base_quantity,
_filled_price, _filled_quantity,
_base_price, _base_quantity);
@@ -51,14 +48,12 @@ void SpreaderChildOrderState::re_init (ChildOrder& child_order,
_n_cancel_orders = _n_modify_orders = 0;
_child_order = ChildOrder();
_child_order = std::move(child_order);
_handover_filled_qty = handover_filled_qty;
_status = bts::api::orderman::OrderStatus::ORDER_STATUS_INACTIVE;
_filled_price = Price(0);
_filled_quantity = Quantity (0);
_last_update_filled_price = Price(0);
_last_update_filled_quantity = Quantity(0);
_last_filled_price = Price(0);
_last_reported_order_price=Price(0);
_last_reported_order_qty=Quantity(0);
_last_filled_quantity = Quantity(0);
_out_price = Price(0);
_out_quantity = Quantity(0);
_order_place_time=bts::TimeStamp();
@@ -4,7 +4,6 @@
#include "lib/api/services/OrderService.pb.h"
#include "lib/orderman/events/OrderStateUpdateEvent.h"
#include "SpreaderUtils.h"
#include "lib/domain_model/Security.h"
namespace bts {
namespace orderman {
@@ -21,22 +20,17 @@ private:
const SecurityKey _sec_key;
const bool _is_quoting;
const OrderKey _test_only_order_key;
// Since SpreaderChildOrderState can be assigned
// multiple ChildOrders during its lifetime, the
// accumulated fills and fill price from previous
// orders is kept here
Price _base_price;
Quantity _base_quantity;
// just for statistics
uint16_t _n_place_orders, _n_cancel_orders;
uint32_t _n_modify_orders;
ChildOrder _child_order;
// If the child order handled through re_init already
// is in a working state with fills
Quantity _handover_filled_qty;
// while child orders can recycle, their
// accumulated price, qty is kept here
Price _base_price;
Quantity _base_quantity;
ChildOrder _child_order;
api::orderman::OrderStatus _status;
// this is the total filled qty and
// average filled price for the active order
// average price for the active order
Price _filled_price;
Quantity _filled_quantity;
// this is the fill price, qty reported
@@ -44,23 +38,16 @@ private:
// (if no fill was reported but it was
// merely an order update, the qty
// here will be 0).
Price _last_update_filled_price;
Quantity _last_update_filled_quantity;
// these are the order price and qty reported
// in the last update (this is the best knowledge
// of what is out there)
Price _last_reported_order_price;
Quantity _last_reported_order_qty;
// this is last price, qty sent out through
// the place_order or modify_order calls
// _last_reported_order_price is the
// the working order price as it was
// last reported
Price _last_filled_price;
Price _last_reported_order_price;
Quantity _last_filled_quantity;
// this is latest price, qty sent out
Price _out_price;
Quantity _out_quantity;
Quantity _out_quantity;
bts::TimeStamp _order_place_time;
private:
bool _change_in_flight() const{
return !securities::is_same(_out_price, _last_reported_order_price) ||
_out_quantity != _last_reported_order_qty;
}
public:
// constructors ///////////////////
///////////////////////////////////
@@ -69,52 +56,37 @@ public:
SpreaderChildOrderState(SecurityKey sec_key,
bool is_live,
bool is_quoting);
SpreaderChildOrderState (SpreaderChildOrderState&& src);
SpreaderChildOrderState (SpreaderChildOrderState&& src);
SpreaderChildOrderState& operator=(const SpreaderChildOrderState&) = delete;
SpreaderChildOrderState& operator=(SpreaderChildOrderState&&) = delete;
////////////////////////////////////////////////////////////////////////////
// const direct accessors //////////////////////////////////////////////////
////////////////////////////////////////////////////////////////////////////
SpreaderChildOrderState& operator=(SpreaderChildOrderState&&) = delete;
// const accessors ////////////////////
///////////////////////////////////////
OrderKey order_key() const {
if (_is_live)
// TODO
return _child_order.empty() ? OrderKey(0) : _child_order.key();
return _child_order.key();
else
return _test_only_order_key;
}
api::orderman::OrderStatus status() const {
}
api::orderman::OrderStatus status () const {
return _status;
}
// this is the fills from the current active order
Quantity current_fills() const {
return _filled_quantity;
}
Price last_update_filled_price() const {
return _last_update_filled_price;
}
// if the last fill was a status change
// this will be zero
Quantity last_update_filled_quantity () const {
return _last_update_filled_quantity;
Price last_update_filled_price() const {
return _last_filled_price;
}
Price last_reported_order_price() const{
return _last_reported_order_price;
}
Quantity last_reported_order_quantity() const{
return _last_reported_order_qty;
// if the last fill was a status change
// this will be zero
Quantity last_update_filled_quantity () const {
return _last_filled_quantity;
}
Price out_price() const {
return _out_price;
}
Quantity out_quantity () const {
return _out_quantity;
}
bts::TimeStamp order_place_time() const{
return _order_place_time;
}
// status accessors ////////////////////////////////////////////////////////
// all the status calls are based on the
// current order (and not the subsumed ones)
bool terminal_status() const {
return SpreaderUtils::order_in_terminal_state(_status);
return SpreaderUtils::order_in_terminal_state(_status);
}
bool acknowledged() const {
return SpreaderUtils::order_acknowledged (_status);
@@ -128,13 +100,8 @@ public:
bool errored() const{
return SpreaderUtils::order_in_error_state(_status);
}
bool working() const{
return SpreaderUtils::order_in_working_state(_status);
}
bool cancel_sent() const{
return _n_cancel_orders > 0;
}
// total across multiple orders ////////////////////////////////////////////
// this is total fills across current and
// previous orders
Quantity total_fills() const {
return Quantity(_base_quantity.value() + _filled_quantity.value());
}
@@ -144,29 +111,30 @@ public:
_filled_price, _filled_quantity,
out_price, out_filled);
}
// returns true is there are no cancels
// or modifies in flight
bool stable_state() const{
return !cancel_in_flight() && !_change_in_flight();
// this is the fills from the current active order
Quantity current_fills () const {
return _filled_quantity;
}
Price out_price() const {
return _out_price;
}
// in-flight accessors /////////////////////////////////////////////////////
bool cancel_in_flight() const{
return cancel_sent() && !terminal_status();
Quantity out_quantity () const {
return _out_quantity;
}
bts::TimeStamp order_place_time() const{
return _order_place_time;
}
// returns true if the current order has been
// cancelled
bool is_cancelled() const{
return _n_cancel_orders>0;
}
// init ///////////////////
ChildOrder& active_order(){
return _child_order;
}
void re_init (){
ChildOrder empty_order;
re_init(empty_order);
}
///////////////////////////
// this assignes a new order, and subsumes the earlier order's
// fills and filled price into the base quantity and
// base filled price
void re_init (ChildOrder& child_order,
Quantity handover_filled_qty = Quantity(0));
void re_init (ChildOrder& child_order);
ChildOrder& _empty_order(){
_child_order = ChildOrder();
return _child_order;
@@ -176,20 +144,16 @@ public:
// last filled price
void on_order_update(const OrderStateUpdateEvent& e){
bts_assert(!_is_live || e.key == order_key());
bts_assert(e.filled_quantity >= _handover_filled_qty.value());
uint32_t effective_filled_qty = e.filled_quantity -
_handover_filled_qty.value();
bts_assert(effective_filled_qty >= _filled_quantity.value());
bts_assert(e.filled_quantity >= _filled_quantity.value());
_status = e.status;
_last_update_filled_quantity = Quantity(effective_filled_qty
_last_filled_quantity = Quantity(e.filled_quantity
- _filled_quantity.value());
_last_update_filled_price = Price(e.last_price);
_last_reported_order_price = Price(e.price);
_last_reported_order_qty = Quantity(e.quantity);
_last_filled_price = Price(e.last_price);
_last_reported_order_price=Price(e.price);
SpreaderUtils::compute_average_price(_filled_price,
_filled_quantity,
_last_update_filled_price,
_last_update_filled_quantity,
_last_filled_price,
_last_filled_quantity,
_filled_price,
_filled_quantity);
}
@@ -181,16 +181,9 @@ public:
return _hedger_manager.test_only_get_hedger_at(index);
}
SingleFillHedger& add_new_hedger(bts::Price hedge_price,
bts::Quantity hedge_quantity,
bool quote_as_hedge){
bts::Quantity hedge_quantity){
SingleFillHedger& rv = _hedger_manager.get_hedger();
ISpreaderManager::OrderTransfer* order_transfer = nullptr;
ISpreaderManager::OrderTransfer order_transfer_arg;
if(quote_as_hedge){
order_transfer_arg.q_order = _quoter_child_order_state;
order_transfer = &order_transfer_arg;
}
rv.init_hedger (hedge_price, hedge_quantity, order_transfer);
rv.init_hedger (hedge_price,hedge_quantity);
return rv;
}
};
@@ -114,9 +114,6 @@ public:
static bool order_in_cancelled_state (bts::api::orderman::OrderStatus order_status){
return order_status == api::orderman::OrderStatus::ORDER_STATUS_CANCELED;
}
static bool order_in_working_state(bts::api::orderman::OrderStatus order_status){
return order_status == api::orderman::OrderStatus::ORDER_STATUS_WORKING;
}
////////////////////////////////////////////////////
// market data /////////////////////////////////////
////////////////////////////////////////////////////
@@ -655,24 +652,6 @@ public:
out_cum_qty);
quantity = Quantity(std::min(quantity.value(),out_cum_qty.value()));
}
// given an order's filled and out qty, and the desired target
// from now on, this function finds the adjusted qty of the order
// example 1 : working order is 3/10, and we want to use
// this working order to get 9 from here on, this function
// will return 12, to make this 3/12, to allow for 9
// fills.
// example 2 : working order is 3/10, and we want 2 more fills,
// it will output 5
// increments are guarded by allow_inc
static uint32_t adjust_qty_to_target (uint32_t filled_qty,
uint32_t order_qty,
uint32_t target,
bool allow_inc){
uint32_t rv = filled_qty + target;
if (rv > order_qty && !allow_inc)
rv = order_qty;
return rv;
}
////////////////////////2 legged spreads
// given a quoting target qty, finds the "driver" price
// and qty, thats needed to hedge the quote. It also
@@ -4,7 +4,6 @@
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/orderman/orders/spreader_orders/spreader/hedger/hedger_states/HedgerState.h"
#include "lib/orderman/actors/order_manager/ChildOrder.h"
#include "lib/orderman/orders/spreader_orders/spreader/ISpreaderManager.h"
namespace bts {
namespace trace {struct CorID;}
@@ -23,8 +22,7 @@ public:
virtual const std::string state_text () const = 0;
// called once and only once, before any other calls.
virtual void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) = 0;
Quantity quantity) = 0;
// called only when this hedger's order is updated
virtual void on_order_update (const SpreaderChildOrderState& order_update) = 0;
// called only when the security that the hedger is working on
@@ -9,21 +9,12 @@ void HedgerEndStateWorker::on_transition (){
// this is to allow the hedger to be re-used.
// the state is cleared and the hedger returns
// to the start state, waiting for the init call
if(!_hedger->_is_permenantly_cancelled){
Quantity rem_to_fill = _hedger->_price_quantity_state.remaining_to_fill();
if(rem_to_fill.value() > 0)
_hedger->_spreader.send_hedge_order(
_hedger->_leg_property_data.leg_index(),
_hedger->_child_order_state.out_price(),
rem_to_fill,
false);
if(!_hedger->_is_permenantly_cancelled)
_hedger->transform_to_START();
}
}
void HedgerEndStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerEndStateWorker::init illegal operation");
}
void HedgerEndStateWorker::on_order_update(const SpreaderChildOrderState&){
@@ -23,9 +23,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::END;}
const std::string state_text () const override {return "END";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -14,31 +14,11 @@ void HedgerStartStateWorker::on_transition (){
}
void HedgerStartStateWorker::init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order_ptr){
Quantity quantity){
_hedger->_price_quantity_state.re_init(price,quantity);
if(quantity.value() > 0){
if(order_ptr==nullptr){
_hedger->_place_order (price, quantity);
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
}
else{
SpreaderChildOrderState& q_order = *(order_ptr->q_order);
bts_assert(q_order.working());
//bts_assert(q_order.active_order().is_active());
uint32_t hedge_order_qty = SpreaderUtils::adjust_qty_to_target(
q_order.current_fills().value(),
q_order.out_quantity().value(),
quantity.value(),
true);
ChildOrder& existing_order = q_order.active_order();
_hedger->_child_order_state.re_init(existing_order,
q_order.current_fills());
_hedger->_modify_order (price, Quantity(hedge_order_qty));
_hedger->transform_to_WORKING();
// figure out how many have been filled
// reinit the SCO and modify the price/qty
}
_hedger->_place_order (price, quantity);
_hedger->transform_to_WAITING_FOR_FIRST_ACK ();
}
}
void HedgerStartStateWorker::on_order_update(const SpreaderChildOrderState&){
@@ -21,9 +21,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::START;}
const std::string state_text () const override {return "START";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -6,20 +6,17 @@ namespace bts{
namespace orderman{
void HedgerWaitingForCancelAckStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForCancelAckStateWorker::init "
"illegal operation");
}
void HedgerWaitingForCancelAckStateWorker::on_order_update(
const SpreaderChildOrderState& order_update){
void HedgerWaitingForCancelAckStateWorker::on_order_update(const SpreaderChildOrderState& order_update){
bts_assert (order_update.acknowledged());
_hedger->_price_quantity_state.update_fill (
order_update.last_update_filled_quantity());
_hedger->_price_quantity_state.update_fill (order_update.last_update_filled_quantity());
if (order_update.terminal_status())
_hedger->transform_to_END ();
}
void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&){
void HedgerWaitingForCancelAckStateWorker::on_book(const bts::orderman::Book&){
}
void HedgerWaitingForCancelAckStateWorker::cancel(){
}
@@ -25,9 +25,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_CANCEL_ACK";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -8,8 +8,7 @@ namespace orderman{
void HedgerWaitingForFirstAckCancelledStateWorker::init(
Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForFirstAckCancelledStateWorker::init "
"illegal operation");
}
@@ -27,8 +26,8 @@ void HedgerWaitingForFirstAckCancelledStateWorker::on_order_update(
_hedger->transform_to_WAITING_FOR_CANCEL_ACK ();
}
}
void HedgerWaitingForFirstAckCancelledStateWorker::on_book(
const bts::orderman::Book&){
void HedgerWaitingForFirstAckCancelledStateWorker::on_book(const bts::orderman::Book&){
}
void HedgerWaitingForFirstAckCancelledStateWorker::cancel(){
}
@@ -25,9 +25,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_FIRST_ACK_CANCELLED";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -5,8 +5,7 @@ namespace bts{
namespace orderman{
void HedgerWaitingForFirstAckStateWorker::init (Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWaitingForFirstAckStateWorker::init "
"illegal operation");
}
@@ -26,9 +26,7 @@ public:
const std::string state_text () const override {
return "WAITING_FOR_FIRST_ACK";
}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -10,8 +10,7 @@ void HedgerWorkingStateWorker::on_transition(){
_order_touch_time = _hedger->_current_time();
}
void HedgerWorkingStateWorker::init(Price,
Quantity,
ISpreaderManager::OrderTransfer*){
Quantity){
bts_assert_msg (false, "HedgerWorkingStateWorker::init illegal operation");
}
void HedgerWorkingStateWorker::on_order_update(
@@ -43,15 +42,12 @@ void HedgerWorkingStateWorker::terminate(){
}
void HedgerWorkingStateWorker::on_time(const TimeStamp& ts){
double new_price;
const auto& book =
_hedger->_spreader.get_book (_hedger->_leg_property_data.leg_index());
if (SpreaderUtils::post_hedge_time_based_price_action (
_order_touch_time,
ts,
_hedger->_leg_property_data,
book,
new_price))
{
_order_touch_time,
ts,
_hedger->_leg_property_data,
_hedger->_spreader.get_book (_hedger->_leg_property_data.leg_index()),
new_price)){
_hedger->_modify_order (Price(new_price));
_order_touch_time = _hedger->_current_time();
}
@@ -23,9 +23,7 @@ public:
void on_transition () override;
HedgerState state () const override {return HedgerState::WORKING;}
const std::string state_text () const override {return "WORKING";}
void init (Price price,
Quantity quantity,
ISpreaderManager::OrderTransfer* order = nullptr) override;
void init (Price price,Quantity quantity) override;
void on_order_update (const SpreaderChildOrderState& order_update) override;
void on_book (const bts::orderman::Book& book) override;
void cancel() override;
@@ -35,10 +35,7 @@ public:
// time update from the infrastructure
virtual void on_time(const TimeStamp&) = 0;
// on a quoting fill on one of the other legs
virtual void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) = 0;
virtual void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) = 0;
// when a spreader order gets updated, it could be that the one of
// the price or quantity does not change
virtual void update_spreader_order (Price price, Quantity quantity) = 0;
@@ -18,8 +18,7 @@ void QuoterEndStateWorker::on_transition (){
_quoter->irrecoverable_error();
if (!is_final){
// getting new order
_quoter->_spreader.setup_new_quoter_order(
_quoter->_this_leg_data.leg_index());
_quoter->_spreader.setup_new_quoter_order(_quoter->_this_leg_data.leg_index());
_quoter->_transform_to_WAITING_FOR_SIZE ();
}
}
@@ -38,10 +37,8 @@ void QuoterEndStateWorker::terminate()
{}
void QuoterEndStateWorker::on_time(const TimeStamp&)
{}
void QuoterEndStateWorker::on_other_leg_quoter_fill (size_t,
Quantity,
Price,
Quantity){}
void QuoterEndStateWorker::on_other_leg_quoter_fill (size_t, Quantity)
{}
void QuoterEndStateWorker::update_spreader_order (Price, Quantity)
{}
}}
@@ -29,10 +29,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -43,11 +43,8 @@ void QuoterStartStateWorker::on_time(const TimeStamp&){
// however for the purpose of this state, we can hide that detail and deal
// with it all !
void QuoterStartStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
// same as above, but we can deal with it like one_time_activate
void QuoterStartStateWorker::update_spreader_order (Price price, Quantity quantity){
@@ -27,10 +27,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -10,7 +10,6 @@ enum class QuoterState
WAITING_FOR_IOC,
WAITING_FOR_FIRST_ACK_CANCELLED,
WORKING,
WAITING_FOR_ORDER_TRANSFER,
WAITING_FOR_CANCEL_ACK,
END
};
@@ -30,13 +30,9 @@ void QuoterWaitingForCancelAckStateWorker::terminate(){
void QuoterWaitingForCancelAckStateWorker::on_time(const TimeStamp&){
// TODO check threshold
}
void QuoterWaitingForCancelAckStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForCancelAckStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForCancelAckStateWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -28,10 +28,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -34,13 +34,8 @@ void QuoterWaitingForFirstAckCancelledWorker::terminate(){
}
void QuoterWaitingForFirstAckCancelledWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForFirstAckCancelledWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForFirstAckCancelledWorker::on_other_leg_quoter_fill (size_t leg_index, Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForFirstAckCancelledWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -34,10 +34,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -34,11 +34,8 @@ void QuoterWaitingForFirstAckWorker::terminate(){
void QuoterWaitingForFirstAckWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForFirstAckWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_analyze_and_act ();
}
void QuoterWaitingForFirstAckWorker::update_spreader_order (Price price,
@@ -32,10 +32,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// checks if the target is reached, and cancels
@@ -34,13 +34,9 @@ void QuoterWaitingForIOCWorker::terminate(){
}
void QuoterWaitingForIOCWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForIOCWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
void QuoterWaitingForIOCWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
}
void QuoterWaitingForIOCWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -35,10 +35,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
};
}}
@@ -1,60 +0,0 @@
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterWaitingForOrderTransferStateWorker.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterState.h"
#include "lib/orderman/orders/spreader_orders/spreader/SingleLegQuoter.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderChildOrderState.h"
namespace bts{
namespace orderman{
QuoterState QuoterWaitingForOrderTransferStateWorker::state () const {
return QuoterState::WAITING_FOR_ORDER_TRANSFER;
}
void QuoterWaitingForOrderTransferStateWorker::one_time_activate (Price,
Quantity){
bts_assert_msg (false,
"QuoterWaitingForOrderTransferStateWorker::one_time_activate "
"is an illegal operation");
}
void QuoterWaitingForOrderTransferStateWorker::on_order_update (
const SpreaderChildOrderState& u){
bts_assert (u.acknowledged());
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::on_book (
size_t,
const bts::orderman::Book&){
}
void QuoterWaitingForOrderTransferStateWorker::cancel(){
_quoter->_cancel_order();
_quoter->_transform_to_WAITING_FOR_CANCEL_ACK ();
}
void QuoterWaitingForOrderTransferStateWorker::terminate(){
_quoter->_transform_to_END ();
}
void QuoterWaitingForOrderTransferStateWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForOrderTransferStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::update_spreader_order (
Price price,
Quantity quantity){
_quoter->_price_quantity_state.update_target_price_quantity (price, quantity);
_analyze_and_act();
}
void QuoterWaitingForOrderTransferStateWorker::_analyze_and_act(){
const auto& u = _quoter->_child_order_state;
if(u.terminal_status() ||
_quoter->_price_quantity_state.target_reached()){
_quoter->_transform_to_END ();
return;
}
}
}}
@@ -1,43 +0,0 @@
#pragma once
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/utils/bts_chrono.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/quoter_states/QuoterState.h"
#include "lib/orderman/orders/spreader_orders/spreader/quoter/IQuoterStateWorker.h"
namespace bts {
namespace orderman {
class SpreaderChildOrderState;
class Book;
class SingleLegQuoter;
// Quoter order is in the process of transferring ownership
// to thehedger
// exit:
class QuoterWaitingForOrderTransferStateWorker : public IQuoterStateWorker
{
private:
SingleLegQuoter* const _quoter;
public:
QuoterWaitingForOrderTransferStateWorker (SingleLegQuoter* quoter)
:_quoter(quoter){}
QuoterState state () const override;
const std::string state_text () const override {
return "WAITING_FOR_ORDER_TRANSFER";
}
virtual void on_transition () override {}
void one_time_activate (Price, Quantity) override;
void on_order_update (
const SpreaderChildOrderState& order_update) override;
void on_book (size_t leg_id, const bts::orderman::Book& book) override;
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
void _analyze_and_act ();
};
}}
@@ -34,11 +34,8 @@ void QuoterWaitingForSizeStateWorker::on_time(const TimeStamp&){
}
void QuoterWaitingForSizeStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity,
hedge_price, hedge_qty);
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_longpath_analyze_and_act ();
}
void QuoterWaitingForSizeStateWorker::update_spreader_order (Price price,
@@ -34,10 +34,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// checks to see if target has reached and goes to end
@@ -5,7 +5,6 @@
#include "lib/orderman/orders/spreader_orders/spreader/ISpreaderManager.h"
#include "lib/orderman/orderman_utils/orderman_common.h"
#include "lib/orderman/orders/spreader_orders/spreader/SpreaderCacheWarmingState.h"
#include "lib/domain_model/Security.h"
namespace bts{
namespace orderman{
@@ -42,28 +41,12 @@ void QuoterWorkingStateWorker::cancel(){
void QuoterWorkingStateWorker::terminate(){
_quoter->_transform_to_END ();
}
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
void QuoterWorkingStateWorker::on_time(const TimeStamp&){
}
void QuoterWorkingStateWorker::on_other_leg_quoter_fill (
size_t leg_index,
Quantity filled_quantity,
Price hedge_price,
Quantity hedge_qty){
bool q_to_h = hedge_qty.value() > 0 &&
_use_quoting_order_to_hedge(hedge_price,hedge_qty);
// decide how to send hedge
_quoter->_incorporate_other_leg_fill (leg_index,
filled_quantity,
hedge_price,
hedge_qty,
true,
q_to_h);
if(q_to_h){
_quoter->_child_order_state.re_init();
_quoter->_transform_to_END();
}
else
_longpath_analyze_and_act ();
void QuoterWorkingStateWorker::on_other_leg_quoter_fill (size_t leg_index,
Quantity filled_quantity){
_quoter->_incorporate_other_leg_fill (leg_index, filled_quantity);
_longpath_analyze_and_act ();
}
void QuoterWorkingStateWorker::update_spreader_order (Price price,
Quantity quantity){
@@ -116,51 +99,4 @@ void QuoterWorkingStateWorker::_modify_order (Price price, Quantity quantity){
_quoter->_modify_order(price, quantity);
}
}
bool QuoterWorkingStateWorker::_use_quoting_order_to_hedge(Price h_price,
Quantity h_qty) const{
const LegPropertyData& leg = _quoter->_this_leg_data;
const SpreaderChildOrderState& q_ord = _quoter->_child_order_state;
// check to see if the order is in transition ?
auto q_for_h = leg.use_quote_for_hedging();
bool q_better = securities::same_or_better_order_price(
_quoter->_this_leg_data.trading_side(),
q_ord.last_reported_order_price(),
h_price) &&
// this is to make sure that the hedge price
// is also worse than anything in flight
securities::same_or_better_order_price(
_quoter->_this_leg_data.trading_side(),
q_ord.out_price(),
h_price);
bool rv;
switch(q_for_h){
case spark::UseSpreaderQuoteForHedging::NEVER:
rv = false;
break;
case spark::UseSpreaderQuoteForHedging::WHEN_CANT_OVERHEDGE:
rv = q_better &&
// max fill potential <= hedge qty
h_qty.value() >= SpreaderUtils::subtract_quanitities(
q_ord.out_quantity().value(),
q_ord.current_fills().value()) &&
h_qty.value() >= SpreaderUtils::subtract_quanitities(
q_ord.last_reported_order_quantity().value(),
q_ord.current_fills().value());
break;
case spark::UseSpreaderQuoteForHedging::ALWAYS:
rv = q_better;
break;
default:
bts_assert(false);
rv = false;
break;
}
LOG(OrderMan, Info, "QuoterWorkingStateWorker::_use_quoting_order_to_hedge "
"res: leg:{} hp:{} hq:{}",
rv,
leg.leg_index(),
h_price,
h_qty);
return rv;
}
}}
@@ -27,10 +27,7 @@ public:
void cancel() override;
void terminate() override;
void on_time(const TimeStamp& ts) override;
void on_other_leg_quoter_fill (size_t leg_id,
Quantity fill_quantity,
Price hedge_price,
Quantity hedge_qty) override;
void on_other_leg_quoter_fill (size_t leg_id, Quantity fill_quantity) override;
void update_spreader_order (Price price, Quantity quantity) override;
private:
// this does the following in this order
@@ -39,7 +36,5 @@ private:
// iii. if reprice (ie qty changed or price changed beyond the threshold) => requote
void _longpath_analyze_and_act ();
void _modify_order (Price price, Quantity quantity);
bool _use_quoting_order_to_hedge(Price h_price,
Quantity h_qty) const;
};
}}
@@ -123,25 +123,17 @@ void SpreaderWorkingStateWorker::on_quoter_order_fill(SpreaderLegData& leg_data)
LOG(OrderMan,cw.llevel,"h_p delta {} {}", q_idx, _spreader->_diff_ns());
// if it is an actively quoting leg, inform the quoter about it
// so it can decrease the proportional size
// if (!cw.in_cache_warming_cycle &&
// other_leg_data.leg_property_data().is_active_quoting()){
// if this leg is an active quoting leg, let it deal with
// hedging since it can use its own order to hedge
if (other_leg_data.leg_property_data().is_active_quoting()){
if (!cw.in_cache_warming_cycle &&
other_leg_data.leg_property_data().is_active_quoting()){
other_leg_data.quoter().update_other_leg_fills(
leg_data.leg_property_data().leg_index(),
Quantity(total_unhedged_qty),
hedge_price,
Quantity(total_unhedged_qty));
LOG(OrderMan,cw.llevel,"h_p q minus {} {}", q_idx, _spreader->_diff_ns());
}
else
// if it is not a quoting leg, the hedge needs to be
// sent explictely from here
_spreader->_send_hedge(other_leg_data.leg_property_data().leg_index(),
hedge_price,
Quantity(total_unhedged_qty),
false);
// a hedge is sent regardless
_spreader->_send_hedge(other_leg_data.leg_property_data().leg_index(),
hedge_price,
Quantity(total_unhedged_qty));
LOG(OrderMan,cw.llevel,"h_p send hedge {} {}", q_idx, _spreader->_diff_ns());
}
}
@@ -90,11 +90,6 @@ public:
ChildOrder rv;
return rv;
}
void send_hedge_order (size_t,
Price,
Quantity,
bool){
}
bool in_cache_warming_cycle() const override{
return false;
}
+2 -9
View File
@@ -31,12 +31,6 @@ message RulePriority
int32 priority = 20;
}
enum UseSpreaderQuoteForHedging
{
NEVER = 0;
WHEN_CANT_OVERHEDGE = 1;
ALWAYS = 2;
}
message LegSpreaderParams
{
@@ -52,7 +46,7 @@ message LegSpreaderParams
PreHedgeParams pre_hedge_params = 50;
PostHedgeParams post_hedge_params = 60;
MarketDataType market_data_type = 70;
//reserve LegMarketDataCalculation leg_md_calc = 80;
//reserve LegMarketDataCalculation leg_md_calc = 80;
}
// /*************************************************************************************************
@@ -80,8 +74,7 @@ message QuoteParams
// and the user can embed a QHO here)
uint32 n_queue_holder_orders=2000;
// this is the show quantity on the quoter order
NullableQuantity show_quantity = 2010;
UseSpreaderQuoteForHedging use_quote_for_hedging = 2020;
NullableQuantity show_quantity = 2010;
}
/*************************************Quote MuteZone***********************************
+1 -1
View File
@@ -33,7 +33,7 @@ int Span::execute(const std::vector<std::string>&)
auto& disp = utils::Dispatcher::current();
MarginServiceCore core(disp);
auto acct = orderman::to<orderman::AccountName>("ACC A");
auto acct = std::string("ACC A");
Position p;
p.security_desc = "ESU9";
p.account = acct;
@@ -28,7 +28,7 @@ namespace bts
namespace position
{
using MarginMap = boost::container::flat_map<orderman::AccountName, MarginResult>;
using MarginMap = boost::container::flat_map<std::string, MarginResult>;
struct MarginServiceCore::PImpl
{
@@ -314,10 +314,9 @@ struct MarginServiceCore::PImpl
}
};
bool compute_margin(const orderman::AccountName& acct, const std::string& portfolid_id,
bool compute_margin(const std::string& account_name, const std::string& portfolid_id,
const std::vector<Position>& pos, std::function<void(const MarginResult&)> cb)
{
auto account_name = orderman::to_trim_str(acct);
pugi::xml_document doc;
pugi::xml_node trades_node;
create_margin_request(portfolid_id, doc, trades_node);
@@ -384,7 +383,7 @@ MarginServiceCore::MarginServiceCore(utils::Dispatcher& disp) : me(new PImpl(dis
MarginServiceCore::~MarginServiceCore() {}
void MarginServiceCore::compute_margin(const orderman::AccountName& acct, const std::vector<Position>& pos,
void MarginServiceCore::compute_margin(const std::string& acct, const std::vector<Position>& pos,
std::function<void(const MarginResult&)> cb)
{
me->dispatcher.post([=] ()
@@ -393,7 +392,7 @@ void MarginServiceCore::compute_margin(const orderman::AccountName& acct, const
}, me->throttle);
}
bool MarginServiceCore::query_margin_webapi(const orderman::AccountName& acct, const std::vector<Position>& pos,
bool MarginServiceCore::query_margin_webapi(const std::string& acct, const std::vector<Position>& pos,
std::function<void(const MarginResult&)> cb)
{
utils::Uuid guid;
@@ -425,7 +424,7 @@ void MarginServiceCore::set_verbose_debugging(bool verb)
me->verbose = verb;
}
bool MarginServiceCore::get_last_valid_result(const orderman::AccountName& acct, MarginResult& result)
bool MarginServiceCore::get_last_valid_result(const std::string& acct, MarginResult& result)
{
auto it = me->last_valid_results.find(acct);
if(it != me->last_valid_results.end())
@@ -436,7 +435,7 @@ bool MarginServiceCore::get_last_valid_result(const orderman::AccountName& acct,
return false;
}
bool MarginServiceCore::get_last_result(const orderman::AccountName& acct, MarginResult& result)
bool MarginServiceCore::get_last_result(const std::string& acct, MarginResult& result)
{
auto it = me->last_results.find(acct);
if(it != me->last_results.end())
@@ -22,18 +22,18 @@ public:
MarginServiceCore(utils::Dispatcher&);
~MarginServiceCore();
void compute_margin(const orderman::AccountName&, const std::vector<Position>&,
void compute_margin(const std::string&, const std::vector<Position>&,
std::function<void(const api::position::MarginResult&)>);
void set_verbose_debugging(bool);
bool get_last_valid_result(const orderman::AccountName&, api::position::MarginResult&);
bool get_last_result(const orderman::AccountName&, api::position::MarginResult&);
bool get_last_valid_result(const std::string&, api::position::MarginResult&);
bool get_last_result(const std::string&, api::position::MarginResult&);
private:
friend class PositionTests;
//This is a blocking call to a WebAPI. Very Slow.
bool query_margin_webapi(const orderman::AccountName&, const std::vector<Position>&,
bool query_margin_webapi(const std::string&, const std::vector<Position>&,
std::function<void(const api::position::MarginResult&)>);
private:
@@ -43,9 +43,6 @@ MarginServiceServer::MarginServiceServer(bts::api::ServiceContext& context, md::
_last_report(),
_first_time(true)
{
if(!config::get<bts::config::SpanMargin>().enabled())
return;
LOG(Gen, Info, "MarginServiceServer: service started");
// _admin_service.get_admin_data(api::VoidMessage(),
@@ -94,8 +91,7 @@ void MarginServiceServer::publish_all()
if(_position->query_positions(acct, pos, pnl, &since) && pos.size())
{
LOG(Gen, Info, "MarginServiceServer: requesting margin for {} ", acct);
auto aname = orderman::to<orderman::AccountName>(acct);
_margin->compute_margin(aname, pos, [this, since, acct, pnl](const MarginResult& m)
_margin->compute_margin(acct, pos, [this, since, acct, pnl](const MarginResult& m)
{
std::scoped_lock<std::recursive_mutex> l(_lock);
publish_margin(m);
@@ -120,11 +116,9 @@ void MarginServiceServer::get_margin(const api::position::MarginRequest& request
}
else
{
orderman::AccountName acct;
orderman::str_to(request.account(), &acct);
std::vector<Position> pos; AccountPNL pnl;
_position->query_positions(request.account(), pos, pnl);
_margin->compute_margin(acct, pos, [=](const MarginResult& m)
_margin->compute_margin(request.account(), pos, [=](const MarginResult& m)
{
reply(m);
});
@@ -186,7 +180,7 @@ void MarginServiceServer::incremental_update_report(const std::string& account,
std::scoped_lock<std::recursive_mutex> l(_lock);
MarginResult margin;
if(!_margin->get_last_valid_result(orderman::to<orderman::AccountName>(account), margin))
if(!_margin->get_last_valid_result(account, margin))
{
margin.Clear();
margin.set_account(account);
+1 -1
View File
@@ -6,7 +6,7 @@ namespace bts {
namespace position {
struct Position
{
orderman::AccountName account;
std::string account;
std::string security_desc;
Quantity position;
api::Side side;
@@ -112,7 +112,7 @@ bool PositionAggregator::query_positions(const std::string& account, std::vector
if(sec && sec->has_glbx() && sec->has_future())
{
Position pos;
pos.account = orderman::to<orderman::AccountName>(account);
pos.account = account;
pos.security_desc = securities::descriptor(*sec);
eraseSubStr(pos.security_desc, "SIM:");
int32_t totalpos = unit.sod_long_pos() + unit.day_long_pos() - unit.sod_short_pos() - unit.day_short_pos();
@@ -84,12 +84,16 @@ me(new PImpl(context,
rxcpp::operators::subscribe<api::orderman::FillsUpdate>(
[this](auto const& update) {
for (const auto& f : update.removed())
me->publisher.add_or_update(_on_fill(*f,false));
if(_valid_account_id(*f))
me->publisher.add_or_update(_on_fill(*f,false));
for (const auto& f : update.added())
me->publisher.add_or_update(_on_fill(*f,true));
if(_valid_account_id(*f))
me->publisher.add_or_update(_on_fill(*f,true));
for (const auto& f : update.changed()) {
me->publisher.add_or_update(_on_fill(*f.previous(),false));
me->publisher.add_or_update(_on_fill(*f.current(),true));
if(_valid_account_id(*f.previous()) && _valid_account_id(*f.current())){
me->publisher.add_or_update(_on_fill(*f.previous(),false));
me->publisher.add_or_update(_on_fill(*f.current(),true));
}
}
me->publisher.flush();
_compute_pnl_and_publish();