Files
zszq-trs/YLErpDAL/Modules/TQuoteModule/OptionStrategyCodeParser.cs
T
2024-05-09 14:06:26 +08:00

64 lines
2.2 KiB
C#

using System.Text.RegularExpressions;
namespace YLErp.Modules.TQuoteModule
{
public class OptionStrategyCodeParser
{
private static readonly Regex codePattern = new Regex(@"(?<sign>[\+-]?)\s*((?<notional>\d+)\*)?(?<underlying>[a-zA-Z]{1,2}[0-9]{3,4})(?<optionType>C|P)(?<maturity>\d+[DMWY]{1})(?<strike>[0-9]+(?:\.[0-9]*)?)");
public static OptionStrategyCodeParts[] ParseOptionStrategyCode(string code)
{
var mc = codePattern.Matches(code);
if (mc.Count == 0)
{
throw new ArgumentException(string.Format("不合法的策略代码:{0}", code));
}
return mc.Cast<Match>().Select(m => ParseOneMatch(m)).ToArray();
}
private static OptionStrategyCodeParts ParseOneMatch(Match m)
{
var parts = new OptionStrategyCodeParts();
var groups = m.Groups;
parts.UnderlyingCode = groups["underlying"].Value;
parts.Strike = double.Parse(groups["strike"].Value);
parts.Maturity = groups["maturity"].Value;
var optionType = groups["optionType"].Value;
if (optionType == "C")
{
parts.OptionType = "Call";
}
else if (optionType == "P")
{
parts.OptionType = "Put";
}
else
{ // Shouldn't come to here, the regex ensured only C|P is matched
throw new ArgumentException(string.Format("不合法的期权类型{0}. 合法值为[CP]", optionType));
}
if (groups["notional"].Length > 0)
{
parts.Notional = int.Parse(groups["notional"].Value);
}
else
{
parts.Notional = 1;
}
if (groups["sign"].Length > 0)
{
if (groups["sign"].Value == "-")
{
parts.IsSell = true;
}
else
{
parts.IsSell = false;
}
}
else
{
parts.IsSell = false;
}
return parts;
}
}
}