mirror of
https://github.com/StockSharp/StockSharp.git
synced 2026-12-04 00:21:31 +00:00
1890 lines
62 KiB
C#
1890 lines
62 KiB
C#
namespace StockSharp.Tests;
|
|
|
|
[TestClass]
|
|
public class StrategyPositionManagerTests : BaseTestClass
|
|
{
|
|
private static long _tx;
|
|
|
|
private static void AssertCalcFieldsNonNull(Position p)
|
|
{
|
|
p.AssertNotNull();
|
|
p.RealizedPnL.AssertNotNull();
|
|
p.LocalTime.AssertNotNull();
|
|
p.ServerTime.AssertNotNull();
|
|
p.AveragePrice.AssertNotNull();
|
|
p.CurrentValue.AssertNotNull();
|
|
// CurrentPrice is allowed to be null; do not assert here.
|
|
p.Commission.AssertNotNull();
|
|
p.BlockedValue.AssertNotNull();
|
|
p.BuyOrdersCount.AssertNotNull();
|
|
p.SellOrdersCount.AssertNotNull();
|
|
}
|
|
|
|
private static (Order order, Security sec, Portfolio pf) CreateOrder(Sides side, decimal volume)
|
|
{
|
|
var sec = new Security { Id = "TEST" };
|
|
var pf = new Portfolio { Name = "TEST_PF" };
|
|
|
|
var order = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = side,
|
|
Volume = volume,
|
|
Balance = volume, // nothing matched yet
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Pending, // explicit initial state
|
|
TransactionId = ++_tx,
|
|
};
|
|
|
|
return (order, sec, pf);
|
|
}
|
|
|
|
// Same order as it arrives through a second route: a new instance carrying the same
|
|
// transaction id and the same cumulative state.
|
|
private static Order Resend(Order order)
|
|
{
|
|
return new Order
|
|
{
|
|
Security = order.Security,
|
|
Portfolio = order.Portfolio,
|
|
Side = order.Side,
|
|
Type = order.Type,
|
|
Price = order.Price,
|
|
Volume = order.Volume,
|
|
Balance = order.Balance,
|
|
AveragePrice = order.AveragePrice,
|
|
Commission = order.Commission,
|
|
State = order.State,
|
|
Time = order.Time,
|
|
LocalTime = order.LocalTime,
|
|
ServerTime = order.ServerTime,
|
|
TransactionId = order.TransactionId,
|
|
};
|
|
}
|
|
|
|
[TestMethod]
|
|
public void IncrementalAveragePnLCommissionFlow()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "STRAT");
|
|
Position lastPos = null;
|
|
bool? lastIsNew = null;
|
|
mgr.PositionProcessed += (p, n) => { lastPos = p; lastIsNew = n; };
|
|
|
|
// 1) BUY order partial fills
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
// initial call (no matches) - ignored (Pending)
|
|
buy.State = OrderStates.Pending;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.InvalidStatus);
|
|
lastPos.AssertNull(); // No position should be created before any fill.
|
|
|
|
// First partial fill: 3 @100, commission 1 (still Active)
|
|
buy.Balance = 7m; // matched 3
|
|
buy.AveragePrice = 100m; // cumulative avg
|
|
buy.Commission = 1m; // cumulative commission
|
|
buy.State = OrderStates.Active;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.AssertNotNull();
|
|
(lastIsNew == true).AssertTrue(); // First fill must create position.
|
|
lastPos.CurrentValue.AssertEqual(3m);
|
|
lastPos.AveragePrice.AssertEqual(100m);
|
|
(lastPos.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
(lastPos.Commission ?? 0m).AssertEqual(1m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Second partial fill: +5 @110 (new cumulative 8 @106.25), commission -> 1.8
|
|
buy.Balance = 2m; // matched now 8
|
|
buy.AveragePrice = 106.25m; // cumulative avg ((3*100 + 5*110)/8)
|
|
buy.Commission = 1.8m; // cumulative
|
|
buy.State = OrderStates.Active;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
(lastIsNew == false).AssertTrue(); // Second fill updates existing position.
|
|
lastPos.CurrentValue.AssertEqual(8m);
|
|
lastPos.AveragePrice.AssertEqual(106.25m);
|
|
(lastPos.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
(lastPos.Commission ?? 0m).AssertEqual(1.8m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Duplicate (no change) - should not alter
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
lastPos.CurrentValue.AssertEqual(8m);
|
|
lastPos.AveragePrice.AssertEqual(106.25m);
|
|
|
|
// 2) Partial close: SELL 5 @120 commission delta 0.5 => cumulative commissions 1.8 + 0.5 = 2.3 (Done)
|
|
var sell = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Sell,
|
|
Volume = 5m,
|
|
Balance = 0m, // fully matched
|
|
AveragePrice = 120m,
|
|
Commission = 0.5m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
// Realized PnL for closed 5: (120 - 106.25)*5 = 68.75
|
|
lastPos.CurrentValue.AssertEqual(3m); // 8 - 5
|
|
lastPos.AveragePrice.AssertEqual(106.25m); // unchanged after partial close
|
|
(lastPos.RealizedPnL ?? 0).Round(5).AssertEqual(68.75m);
|
|
(lastPos.Commission ?? 0).Round(5).AssertEqual(2.3m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// 3) Reversal: SELL 10 @105 commission 1.2 -> delta commission 1.2 (Done)
|
|
var sellRev = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Sell,
|
|
Volume = 10m,
|
|
Balance = 0m,
|
|
AveragePrice = 105m,
|
|
Commission = 1.2m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
|
|
mgr.ProcessOrder(sellRev).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
// Additional realized: closing remaining 3 long at 105 => (105 - 106.25)*3 = -3.75
|
|
// Total realized = 68.75 - 3.75 = 65.0
|
|
lastPos.CurrentValue.AssertEqual(-7m); // reversed to short 7
|
|
lastPos.AveragePrice.AssertEqual(105m); // new basis
|
|
(lastPos.RealizedPnL ?? 0).Round(5).AssertEqual(65m);
|
|
(lastPos.Commission ?? 0).Round(5).AssertEqual(3.5m); // 2.3 + 1.2
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// 4) Full close of short: BUY 7 @100 (Done)
|
|
var buyClose = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 7m,
|
|
Balance = 0m,
|
|
AveragePrice = 100m,
|
|
Commission = 0.2m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
|
|
mgr.ProcessOrder(buyClose).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
// Closing 7 short: average short 105, cover at 100 => PnL += (105 - 100)*7 = 35
|
|
lastPos.CurrentValue.AssertEqual(0m);
|
|
// Average should be initialized even after flat (new rule)
|
|
lastPos.AveragePrice.AssertNotNull();
|
|
// Do not assert CurrentPrice here (it can be null by rule)
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Set last market price to compute position market value (qty=0 -> value=0)
|
|
var secId = sec.ToSecurityId();
|
|
mgr.UpdateCurrentPrice(secId, 100m, buyClose.ServerTime, buyClose.LocalTime);
|
|
(lastPos.CurrentPrice ?? 0m).Round(5).AssertEqual(0m);
|
|
(lastPos.RealizedPnL ?? 0m).Round(5).AssertEqual(100m); // 65 + 35
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ShortPositionFlow()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "SHORT_STRAT");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (sell, sec, pf) = CreateOrder(Sides.Sell, 10m);
|
|
|
|
// Open short: SELL 10 @100 (Done)
|
|
sell.Balance = 0m;
|
|
sell.AveragePrice = 100m;
|
|
sell.Commission = 0.5m;
|
|
sell.State = OrderStates.Done;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.CurrentValue.AssertEqual(-10m);
|
|
lastPos.AveragePrice.AssertEqual(100m);
|
|
(lastPos.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
(lastPos.Commission ?? 0m).AssertEqual(0.5m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Partial cover: BUY 4 @95 (Done)
|
|
var buy = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 4m,
|
|
Balance = 0m,
|
|
AveragePrice = 95m,
|
|
Commission = 0.2m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// Realized PnL: (100 - 95) * 4 = 20
|
|
lastPos.CurrentValue.AssertEqual(-6m);
|
|
lastPos.AveragePrice.AssertEqual(100m);
|
|
(lastPos.RealizedPnL ?? 0).Round(5).AssertEqual(20m);
|
|
(lastPos.Commission ?? 0).Round(5).AssertEqual(0.7m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void BlockedVolumeAndOrderCounts()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "BLOCK_STRAT");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (buy1, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy1.State = OrderStates.Active;
|
|
|
|
// Register active buy order
|
|
mgr.ProcessOrder(buy1).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.AssertNotNull();
|
|
lastPos.BlockedValue.AssertEqual(10m); // Blocked buy = 10
|
|
lastPos.BuyOrdersCount.AssertEqual(1);
|
|
lastPos.SellOrdersCount.AssertEqual(0);
|
|
|
|
// Add another buy order
|
|
var buy2 = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 5m,
|
|
Balance = 5m,
|
|
State = OrderStates.Active,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(buy2).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.BlockedValue.AssertEqual(15m); // 10 + 5
|
|
lastPos.BuyOrdersCount.AssertEqual(2);
|
|
|
|
// Add sell order
|
|
var sell = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Sell,
|
|
Volume = 7m,
|
|
Balance = 7m,
|
|
State = OrderStates.Active,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.BlockedValue.AssertEqual(22m); // 15 buy + 7 sell (no netting)
|
|
lastPos.BuyOrdersCount.AssertEqual(2);
|
|
lastPos.SellOrdersCount.AssertEqual(1);
|
|
|
|
// Partial fill on buy1: matched 3, balance 7 (still Active)
|
|
buy1.Balance = 7m;
|
|
buy1.AveragePrice = 100m;
|
|
buy1.State = OrderStates.Active;
|
|
mgr.ProcessOrder(buy1).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.BlockedValue.AssertEqual(19m); // 7 + 5 + 7 (no netting)
|
|
lastPos.BuyOrdersCount.AssertEqual(2);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Cancel buy2 (Done + Balance>0 indicates cancellation)
|
|
buy2.State = OrderStates.Done;
|
|
// keep remaining balance 5 to indicate cancelled remainder
|
|
buy2.Balance = 5m;
|
|
mgr.ProcessOrder(buy2).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.BlockedValue.AssertEqual(14m); // (7 buy1) + (7 sell)
|
|
lastPos.BuyOrdersCount.AssertEqual(1);
|
|
lastPos.SellOrdersCount.AssertEqual(1);
|
|
|
|
// Cancel sell (Done + Balance>0 indicates cancellation)
|
|
sell.State = OrderStates.Done;
|
|
// keep remaining balance 7 to indicate cancelled remainder
|
|
sell.Balance = 7m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.BlockedValue.AssertEqual(7m); // Only buy1 remains
|
|
lastPos.BuyOrdersCount.AssertEqual(1);
|
|
lastPos.SellOrdersCount.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void CurrentPriceUpdate()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_STRAT");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.State = OrderStates.Done;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
lastPos.CurrentPrice.AssertNull(); // No current price yet
|
|
|
|
var secId = sec.ToSecurityId();
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(secId, 105m, now, now);
|
|
|
|
lastPos.CurrentPrice.AssertEqual(1050m); // 10 * 105
|
|
lastPos.ServerTime.AssertEqual(now);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Update to different price
|
|
var later = now.AddMinutes(1);
|
|
mgr.UpdateCurrentPrice(secId, 110m, later, later);
|
|
|
|
lastPos.CurrentPrice.AssertEqual(1100m); // 10 * 110
|
|
lastPos.ServerTime.AssertEqual(later);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void MultiplePositions()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "MULTI");
|
|
|
|
var sec1 = new Security { Id = "SEC1" };
|
|
var sec2 = new Security { Id = "SEC2" };
|
|
var pf1 = new Portfolio { Name = "PF1" };
|
|
var pf2 = new Portfolio { Name = "PF2" };
|
|
|
|
// Create position for SEC1/PF1 (Done)
|
|
var order1 = new Order
|
|
{
|
|
Security = sec1,
|
|
Portfolio = pf1,
|
|
Side = Sides.Buy,
|
|
Volume = 10m,
|
|
Balance = 0m,
|
|
AveragePrice = 100m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order1).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// Create position for SEC2/PF1 (Done)
|
|
var order2 = new Order
|
|
{
|
|
Security = sec2,
|
|
Portfolio = pf1,
|
|
Side = Sides.Sell,
|
|
Volume = 5m,
|
|
Balance = 0m,
|
|
AveragePrice = 200m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order2).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// Create position for SEC1/PF2 (Done)
|
|
var order3 = new Order
|
|
{
|
|
Security = sec1,
|
|
Portfolio = pf2,
|
|
Side = Sides.Buy,
|
|
Volume = 7m,
|
|
Balance = 0m,
|
|
AveragePrice = 105m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order3).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
mgr.Positions.Length.AssertEqual(3);
|
|
|
|
var pos1 = mgr.TryGetPosition(sec1, pf1);
|
|
pos1.AssertNotNull();
|
|
pos1.CurrentValue.AssertEqual(10m);
|
|
pos1.AveragePrice.AssertEqual(100m);
|
|
AssertCalcFieldsNonNull(pos1);
|
|
|
|
var pos2 = mgr.TryGetPosition(sec2, pf1);
|
|
pos2.AssertNotNull();
|
|
pos2.CurrentValue.AssertEqual(-5m);
|
|
pos2.AveragePrice.AssertEqual(200m);
|
|
AssertCalcFieldsNonNull(pos2);
|
|
|
|
var pos3 = mgr.TryGetPosition(sec1, pf2);
|
|
pos3.AssertNotNull();
|
|
pos3.CurrentValue.AssertEqual(7m);
|
|
pos3.AveragePrice.AssertEqual(105m);
|
|
AssertCalcFieldsNonNull(pos3);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NullOrderThrowsException()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NULL_TEST");
|
|
ThrowsExactly<ArgumentNullException>(() => mgr.ProcessOrder(null));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NullSecurityOrPortfolioThrows()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NULL_TEST");
|
|
|
|
ThrowsExactly<ArgumentNullException>(() => mgr.TryGetPosition(null, new Portfolio()));
|
|
ThrowsExactly<ArgumentNullException>(() => mgr.TryGetPosition(new Security(), null));
|
|
ThrowsExactly<ArgumentNullException>(() => mgr.SetPosition(null, new Portfolio(), 10m, DateTime.UtcNow));
|
|
ThrowsExactly<ArgumentNullException>(() => mgr.SetPosition(new Security(), null, 10m, DateTime.UtcNow));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ResetClearsAllData()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "RESET");
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 100m;
|
|
order.State = OrderStates.Done;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
mgr.Positions.Length.AssertEqual(1);
|
|
mgr.TryGetPosition(sec, pf).AssertNotNull();
|
|
|
|
mgr.Reset();
|
|
|
|
mgr.Positions.Length.AssertEqual(0);
|
|
mgr.TryGetPosition(sec, pf).AssertNull();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void SetPositionManually()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "MANUAL");
|
|
|
|
var sec = new Security { Id = "TEST" };
|
|
var pf = new Portfolio { Name = "PF" };
|
|
|
|
mgr.SetPosition(sec, pf, 15m, DateTime.UtcNow);
|
|
|
|
var pos = mgr.TryGetPosition(sec, pf);
|
|
pos.AssertNotNull();
|
|
pos.CurrentValue.AssertEqual(15m);
|
|
// No assertion on AveragePrice per new rule enforcement happens via AssertCalcFieldsNonNull when processing orders
|
|
|
|
// Update manual position
|
|
mgr.SetPosition(sec, pf, -5m, DateTime.UtcNow);
|
|
pos.CurrentValue.AssertEqual(-5m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ZeroCommissionHandling()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "ZERO_COMM");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 100m;
|
|
order.Commission = null; // No commission
|
|
order.State = OrderStates.Done;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
(lastPos.Commission ?? 0m).AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Add order with commission (Done)
|
|
var sell = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Sell,
|
|
Volume = 10m,
|
|
Balance = 0m,
|
|
AveragePrice = 110m,
|
|
Commission = 1.5m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
(lastPos.Commission ?? 0m).AssertEqual(1.5m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NullAveragePriceHandling()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NULL_PRICE");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
order.Balance = 0m;
|
|
order.AveragePrice = null;
|
|
order.State = OrderStates.Done;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.NoMarketPrice);
|
|
|
|
lastPos.AssertNull();
|
|
mgr.TryGetPosition(sec, pf).AssertNull();
|
|
mgr.TrackedOrderExecInfosCount.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void StrategyIdAssignment()
|
|
{
|
|
var strategyId = "MY_STRATEGY_123";
|
|
var mgr = new StrategyPositionManager(() => strategyId);
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 100m;
|
|
order.State = OrderStates.Done;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.StrategyId.AssertEqual(strategyId);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void OrderStateTransitions()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "STATE_TEST");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
// Pending order - ignored (no exchange ack yet)
|
|
order.State = OrderStates.Pending;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.InvalidStatus);
|
|
lastPos.AssertNull();
|
|
|
|
// Active order
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
lastPos.AssertNotNull();
|
|
lastPos.BlockedValue.AssertEqual(10m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Partial fill (still Active)
|
|
order.Balance = 6m;
|
|
order.AveragePrice = 100m;
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
lastPos.BlockedValue.AssertEqual(6m);
|
|
lastPos.CurrentValue.AssertEqual(4m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Order done (Done + Balance=0)
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 101m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
lastPos.BlockedValue.AssertEqual(0m);
|
|
lastPos.CurrentValue.AssertEqual(10m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NegativeBalance()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NEG_BAL");
|
|
Position lastPos = null;
|
|
mgr.PositionProcessed += (p, _) => lastPos = p;
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
order.Balance = 5m;
|
|
order.AveragePrice = 100m;
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
lastPos.CurrentValue.AssertEqual(5m);
|
|
AssertCalcFieldsNonNull(lastPos);
|
|
|
|
// Zero volume (invalid data)
|
|
order.Volume = 0;
|
|
ThrowsExactly<ArgumentException>(() => mgr.ProcessOrder(order));
|
|
|
|
// Zero balance with active state (invalid data)
|
|
order.Balance = 0;
|
|
ThrowsExactly<ArgumentException>(() => mgr.ProcessOrder(order));
|
|
|
|
// Negative balance (invalid data)
|
|
order.Balance = -1m;
|
|
ThrowsExactly<ArgumentException>(() => mgr.ProcessOrder(order));
|
|
|
|
// Position unchanged
|
|
lastPos.CurrentValue.AssertEqual(5m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void CurrentPriceUpdateMultiplePositions()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "MULTI_PRICE");
|
|
var positions = new List<Position>();
|
|
mgr.PositionProcessed += (p, _) => positions.Add(p);
|
|
|
|
var sec = new Security { Id = "AAPL" };
|
|
var pf1 = new Portfolio { Name = "PF1" };
|
|
var pf2 = new Portfolio { Name = "PF2" };
|
|
|
|
// Create two positions with same security, different portfolios (Done)
|
|
var order1 = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf1,
|
|
Side = Sides.Buy,
|
|
Volume = 10m,
|
|
Balance = 0m,
|
|
AveragePrice = 100m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order1).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var order2 = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf2,
|
|
Side = Sides.Sell,
|
|
Volume = 5m,
|
|
Balance = 0m,
|
|
AveragePrice = 100m,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
State = OrderStates.Done,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order2).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
positions.Clear();
|
|
|
|
// Update current price for security
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 105m, now, now);
|
|
|
|
// Both positions should be updated
|
|
positions.Count.AssertEqual(2);
|
|
positions.Count(p => p.CurrentValue == 10m && p.CurrentPrice == 1050m).AssertEqual(1);
|
|
positions.Count(p => p.CurrentValue == -5m && p.CurrentPrice == 525m).AssertEqual(1);
|
|
positions.All(p => p.ServerTime == now && p.LocalTime == now).AssertTrue();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Constructor_Null_Throws()
|
|
{
|
|
ThrowsExactly<ArgumentNullException>(() => new StrategyPositionManager(null));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NoneAndFailedStatesIgnored()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "IGNORED");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
order.State = OrderStates.None;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.InvalidStatus);
|
|
last.AssertNull();
|
|
|
|
order.State = OrderStates.Failed;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.InvalidStatus);
|
|
last.AssertNull();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ActiveWithZeroBalanceThrows()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "ACTIVE_ZERO");
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 0m;
|
|
ThrowsExactly<ArgumentException>(() => mgr.ProcessOrder(order));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void TimestampsSetOnProcessing()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "TS");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
var lt = DateTime.UtcNow.AddMinutes(-1);
|
|
var st = DateTime.UtcNow;
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 6m; // matched 4
|
|
order.AveragePrice = 100m;
|
|
order.LocalTime = lt;
|
|
order.ServerTime = st;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.LocalTime.AssertEqual(lt);
|
|
last.ServerTime.AssertEqual(st);
|
|
AssertCalcFieldsNonNull(last);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void UsesCachedPriceDuringProcessOrder()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "CACHED_PRICE");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
var (order, sec, _) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
// set last price before fills
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 50m, now, now);
|
|
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 100m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.CurrentPrice.AssertEqual(500m); // 10 * 50
|
|
AssertCalcFieldsNonNull(last);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ReactivationUpdatesAggregates()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "REACT");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.BlockedValue.AssertEqual(10m);
|
|
|
|
// cancel (Done + Balance>0)
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 10m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.BlockedValue.AssertEqual(0m);
|
|
last.BuyOrdersCount.AssertEqual(0);
|
|
|
|
// re-activate
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.BlockedValue.AssertEqual(10m);
|
|
last.BuyOrdersCount.AssertEqual(1);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NonMonotonicCommissionHandled()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "COMM");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
// first partial: matched 4, comm 1.0
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 6m;
|
|
order.AveragePrice = 100m;
|
|
order.Commission = 1.0m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
(last.Commission ?? 0m).AssertEqual(1.0m);
|
|
AssertCalcFieldsNonNull(last);
|
|
|
|
// provider corrected cumulative commission downwards to 0.8
|
|
order.Balance = 2m; // matched 8 total
|
|
order.AveragePrice = 105m;
|
|
order.Commission = 0.8m; // cumulative decreased => delta -0.2
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
(last.Commission ?? 0m).Round(5).AssertEqual(0.8m);
|
|
AssertCalcFieldsNonNull(last);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void UpdateCurrentPrice_NoPositions_NoEvents()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NOPOS");
|
|
var count = 0;
|
|
mgr.PositionProcessed += (_, __) => count++;
|
|
var sec = new Security { Id = "S" };
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 10m, now, now);
|
|
count.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void BlockedValueInitializedWithoutActiveOrders()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "BLK_NULL");
|
|
var sec = new Security { Id = "S" };
|
|
var pf = new Portfolio { Name = "P" };
|
|
mgr.SetPosition(sec, pf, 1m, DateTime.UtcNow);
|
|
var pos = mgr.TryGetPosition(sec, pf);
|
|
// New rule: BlockedValue should be initialized (even if logically zero)
|
|
pos.BlockedValue.AssertNotNull();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void NegativePricesValidation()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "NEG_PRICE");
|
|
var (_, sec, _) = CreateOrder(Sides.Buy, 1m);
|
|
|
|
// negative market price should throw
|
|
var now = DateTime.UtcNow;
|
|
ThrowsExactly<ArgumentOutOfRangeException>(() => mgr.UpdateCurrentPrice(sec.ToSecurityId(), -10m, now, now));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ProcessOrder_Throws_When_NoTransactionId()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "TX");
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
order.TransactionId = 0;
|
|
order.State = OrderStates.Active;
|
|
ThrowsExactly<ArgumentException>(() => mgr.ProcessOrder(order));
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Aggregates_Use_TransactionId_As_Key()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "TX_AGG");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var sec = new Security { Id = "S" };
|
|
var pf = new Portfolio { Name = "P" };
|
|
|
|
var order1 = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 10m,
|
|
Balance = 10m,
|
|
State = OrderStates.Active,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
TransactionId = ++_tx,
|
|
};
|
|
mgr.ProcessOrder(order1).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.BlockedValue.AssertEqual(10m);
|
|
last.BuyOrdersCount.AssertEqual(1);
|
|
|
|
// simulate provider creating new Order instance for same TransactionId
|
|
var order1b = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 10m,
|
|
Balance = 6m, // partial fill happened (matched 4)
|
|
AveragePrice = 100m,
|
|
State = OrderStates.Active,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
TransactionId = order1.TransactionId, // same id
|
|
};
|
|
mgr.ProcessOrder(order1b).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// aggregates updated by diff (10 -> 6)
|
|
last.BlockedValue.AssertEqual(6m);
|
|
last.BuyOrdersCount.AssertEqual(1);
|
|
last.CurrentValue.AssertEqual(4m); // matched 4
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecInfos_Use_TransactionId_As_Key()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "TX_EXEC");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
order.State = OrderStates.Active;
|
|
order.TransactionId = ++_tx;
|
|
|
|
// first snapshot: matched 3
|
|
order.Balance = 7m;
|
|
order.AveragePrice = 100m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.CurrentValue.AssertEqual(3m);
|
|
|
|
// new instance but same tx id: matched 8 total
|
|
var order2 = new Order
|
|
{
|
|
Security = sec,
|
|
Portfolio = pf,
|
|
Side = Sides.Buy,
|
|
Volume = 10m,
|
|
Balance = 2m,
|
|
AveragePrice = 106.25m,
|
|
State = OrderStates.Active,
|
|
LocalTime = DateTime.UtcNow,
|
|
ServerTime = DateTime.UtcNow,
|
|
TransactionId = order.TransactionId,
|
|
};
|
|
mgr.ProcessOrder(order2).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
last.CurrentValue.AssertEqual(8m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void CommissionCorrectionWithoutNewExecution()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "COMM_CORR");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 6m; // matched 4
|
|
order.AveragePrice = 100m;
|
|
order.Commission = 1.0m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
(last.Commission ?? 0m).AssertEqual(1.0m);
|
|
|
|
// Provider sends commission correction only (no new executions)
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 6m; // matched stays 4
|
|
order.AveragePrice = 100m;
|
|
order.Commission = 0.8m; // corrected cumulative commission
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// Expected: commission reflects correction even without new executions
|
|
(last.Commission ?? 0m).AssertEqual(0.8m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Cleanup_OrderExecInfos_On_Done()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "CLN");
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
|
|
order.State = OrderStates.Active;
|
|
order.Balance = 7m; // matched 3
|
|
order.AveragePrice = 100m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
mgr.TrackedOrderExecInfosCount.AssertEqual(1);
|
|
|
|
order.State = OrderStates.Done; // finish
|
|
order.Balance = 0m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
mgr.TrackedOrderExecInfosCount.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void Cleanup_Aggregates_When_Empty()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "CLN_AGG");
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 5m);
|
|
order.State = OrderStates.Active;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
mgr.TrackedAggsCount.AssertEqual(1);
|
|
mgr.TrackedOrderTracksCount.AssertEqual(1);
|
|
|
|
// cancel active (Done + balance>0 means cancellation path used in tests)
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 5m;
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// after cleanup, no tracks and empty aggs removed
|
|
mgr.TrackedOrderTracksCount.AssertEqual(0);
|
|
mgr.TrackedAggsCount.AssertEqual(0);
|
|
}
|
|
|
|
// New tests for execution price selection logic
|
|
[TestMethod]
|
|
public void ExecPrice_AveragePrice_Preferred()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_PREF");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = 123m;
|
|
order.Price = 111m; // should be ignored because AveragePrice exists
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.AveragePrice.AssertEqual(123m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Fallback_To_OrderPrice_For_Limit()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_FALLBACK");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, _, _) = CreateOrder(Sides.Buy, 5m);
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = null; // no avg
|
|
order.Type = OrderTypes.Limit;
|
|
order.Price = 77.77m; // fallback to order price
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.AveragePrice.AssertEqual(77.77m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Zero_Order_Price_Is_Not_A_Fill_Price()
|
|
{
|
|
// A conditional order keeps its trigger in the condition and leaves Price at zero, so the
|
|
// fallback to Price has nothing to fall back to. Nothing ever fills at zero: the manager may
|
|
// price the fill from the last price or refuse it, but it must not book stock at a zero basis.
|
|
var mgr = new StrategyPositionManager(() => "PRICE_ZERO");
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 5m);
|
|
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 10m, now, now);
|
|
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = null; // provider reported no average
|
|
order.Type = OrderTypes.Conditional;
|
|
order.Price = 0m; // price lives in Condition, not here
|
|
|
|
mgr.ProcessOrder(order);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
var qty = position is null ? 0m : position.CurrentValue ?? 0m;
|
|
var avg = position is null ? 0m : position.AveragePrice ?? 0m;
|
|
|
|
(qty == 0m || avg > 0m).AssertTrue();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Limit_Fallback_Never_Prices_A_Slice_Beyond_The_Limit()
|
|
{
|
|
// A buy limit can only fill at or below its limit price. When an earlier snapshot reported a
|
|
// better average and a later one drops it, the fallback recomputes the whole order cost at the
|
|
// limit and charges the difference to the new slice, pricing it above the limit the order set.
|
|
var mgr = new StrategyPositionManager(() => "PRICE_LIMIT_BAND");
|
|
|
|
// Open a short 2 @ 100 so the buy below closes against a known basis.
|
|
var (sell, sec, pf) = CreateOrder(Sides.Sell, 2m);
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m;
|
|
sell.Type = OrderTypes.Limit;
|
|
sell.Price = 100m;
|
|
sell.AveragePrice = 100m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var (buy, _, _) = CreateOrder(Sides.Buy, 5m);
|
|
buy.Security = sec;
|
|
buy.Portfolio = pf;
|
|
buy.Type = OrderTypes.Limit;
|
|
buy.Price = 100m;
|
|
|
|
// First lot filled with price improvement, and the provider says so.
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 4m; // matched 1
|
|
buy.AveragePrice = 90m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// Final snapshot arrives without the average; the remaining 4 lots are unpriced.
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m; // matched 5
|
|
buy.AveragePrice = null;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
|
|
// Whatever the unreported lots filled at, it was not above 100, so the long that remains
|
|
// cannot have cost more than 100 and buying the last short lot back cannot have lost money.
|
|
((position.AveragePrice ?? 0m) <= 100m).AssertTrue();
|
|
((position.RealizedPnL ?? 0m) >= 10m).AssertTrue();
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Market_Uses_LastPrice_When_No_Average()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_MARKET_LAST");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, sec, _) = CreateOrder(Sides.Buy, 2m);
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = null; // no avg
|
|
order.Type = OrderTypes.Market;
|
|
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 10.5m, now, now);
|
|
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.AveragePrice.AssertEqual(10.5m);
|
|
last.CurrentValue.AssertEqual(2m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Market_Ignored_When_No_Average_And_No_Last()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_MARKET_IGN");
|
|
Position last = null;
|
|
var events = 0;
|
|
mgr.PositionProcessed += (p, _) => { last = p; events++; };
|
|
|
|
var (order, sec, pf) = CreateOrder(Sides.Buy, 3m);
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.AveragePrice = null; // no avg
|
|
order.Type = OrderTypes.Market;
|
|
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.NoMarketPrice);
|
|
|
|
// No position should be created since there is no way to determine exec price
|
|
events.AssertEqual(0);
|
|
last.AssertNull();
|
|
mgr.Positions.Length.AssertEqual(0);
|
|
mgr.TryGetPosition(sec, pf).AssertNull();
|
|
mgr.TrackedOrderExecInfosCount.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ExecPrice_Market_Average_Takes_Priority_Over_Last()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "PRICE_MARKET_AVG");
|
|
Position last = null;
|
|
mgr.PositionProcessed += (p, _) => last = p;
|
|
|
|
var (order, sec, _) = CreateOrder(Sides.Buy, 1m);
|
|
order.State = OrderStates.Done;
|
|
order.Balance = 0m;
|
|
order.Type = OrderTypes.Market;
|
|
order.AveragePrice = 9.99m; // present -> should be used
|
|
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 20m, now, now);
|
|
|
|
mgr.ProcessOrder(order).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
last.AveragePrice.AssertEqual(9.99m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedFinalSnapshotChangesNothing()
|
|
{
|
|
// Orders arrive as cumulative snapshots, and the same final snapshot can arrive more than once.
|
|
// Every call after the first one carries no new execution, so it must leave the position alone.
|
|
var mgr = new StrategyPositionManager(() => "REPEATED_DONE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 4m);
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.5m;
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(4m);
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(4m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0).AssertEqual(0.5m);
|
|
(position.RealizedPnL ?? 0).AssertEqual(0m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FinalSnapshotAppliesLateCommissionCorrectionWithoutRepeatingTheFill()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "LATE_COMMISSION");
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 4m);
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.5m;
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var correction = Resend(buy);
|
|
correction.Commission = 0.75m;
|
|
|
|
mgr.ProcessOrder(correction).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(correction).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(4m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.75m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FinalSnapshotWithoutCommissionDoesNotEraseKnownCommission()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "MISSING_COMMISSION");
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 2m);
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.5m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var replay = Resend(buy);
|
|
replay.Commission = null;
|
|
|
|
mgr.ProcessOrder(replay).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(2m);
|
|
(position.Commission ?? 0m).AssertEqual(0.5m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void FinishedReplayStateCanBePrunedWithTheOrderRetentionWindow()
|
|
{
|
|
var mgr = new StrategyPositionManager(() => "FINISHED_RETENTION");
|
|
var (buy, _, _) = CreateOrder(Sides.Buy, 1m);
|
|
var orderTime = new DateTime(2026, 1, 1, 12, 0, 0, DateTimeKind.Utc);
|
|
|
|
buy.Time = orderTime;
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.TrackedFinishedOrdersCount.AssertEqual(1);
|
|
|
|
mgr.RemoveFinishedBefore(orderTime.AddTicks(1));
|
|
|
|
mgr.TrackedFinishedOrdersCount.AssertEqual(0);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedFinalSnapshotDoesNotReverseThePosition()
|
|
{
|
|
// The doubling this guards against is not visible on one order: a repeated snapshot of the
|
|
// closing order reopened the position on the other side and every following order doubled again.
|
|
var mgr = new StrategyPositionManager(() => "REPEATED_DONE_CLOSE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 2m);
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var (sell, _, _) = CreateOrder(Sides.Sell, 2m);
|
|
sell.Security = sec;
|
|
sell.Portfolio = pf;
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m;
|
|
sell.AveragePrice = 110m;
|
|
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(0m);
|
|
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0).AssertEqual(20m);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void PartiallyFilledActiveSnapshotDeliveredTwiceChangesNothing()
|
|
{
|
|
// A snapshot of a partially filled order repeats whenever the order is reported twice.
|
|
// Nothing the caller reads off the position may move on the second delivery.
|
|
var mgr = new StrategyPositionManager(() => "DUP_ACTIVE");
|
|
Position processed = null;
|
|
mgr.PositionProcessed += (p, _) => processed = p;
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 6m; // matched 4
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.4m;
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.AssertNotNull();
|
|
processed.AssertSame(position);
|
|
position.CurrentValue.AssertEqual(4m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.4m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
|
|
mgr.ProcessOrder(buy);
|
|
|
|
position.CurrentValue.AssertEqual(4m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.4m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(6m);
|
|
position.BuyOrdersCount.AssertEqual(1);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedDoneSnapshotOnShortChangesNothingHoweverManyTimes()
|
|
{
|
|
// The final snapshot of a sell can be replayed any number of times and the short stays
|
|
// the one short that was actually filled.
|
|
var mgr = new StrategyPositionManager(() => "DUP_DONE_SELL");
|
|
|
|
var (sell, sec, pf) = CreateOrder(Sides.Sell, 6m);
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m;
|
|
sell.AveragePrice = 100m;
|
|
sell.Commission = 0.6m;
|
|
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(-6m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.6m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.SellOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedDoneCancelWithPartialFillChangesNothing()
|
|
{
|
|
// A cancelled order still carries the volume it managed to fill. Replaying that final
|
|
// snapshot must not add the fill again, nor block volume for an order that is over.
|
|
var mgr = new StrategyPositionManager(() => "DUP_DONE_CANCEL");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 4m; // matched 6
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.6m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
// cancelled with 6 of 10 filled
|
|
buy.State = OrderStates.Done;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(6m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.6m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.BuyOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedIntermediateSnapshotDoesNotDisturbLaterFills()
|
|
{
|
|
// An order filling in steps: repeating one step leaves the position where it was, and the
|
|
// step after it is counted from that point instead of being added on top of a doubled one.
|
|
var mgr = new StrategyPositionManager(() => "DUP_STEPS");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 7m; // matched 3 @100
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.3m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
|
|
mgr.ProcessOrder(buy);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.3m);
|
|
|
|
buy.Balance = 2m; // matched 8, cumulative average (3*100 + 5*110)/8
|
|
buy.AveragePrice = 106.25m;
|
|
buy.Commission = 0.8m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
position.CurrentValue.AssertEqual(8m);
|
|
position.AveragePrice.AssertEqual(106.25m);
|
|
(position.Commission ?? 0m).AssertEqual(0.8m);
|
|
|
|
mgr.ProcessOrder(buy);
|
|
position.CurrentValue.AssertEqual(8m);
|
|
position.AveragePrice.AssertEqual(106.25m);
|
|
(position.Commission ?? 0m).AssertEqual(0.8m);
|
|
|
|
buy.Balance = 0m; // matched 10, last 2 @110
|
|
buy.AveragePrice = 107m;
|
|
buy.Commission = 1m;
|
|
buy.State = OrderStates.Done;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(107m);
|
|
(position.Commission ?? 0m).AssertEqual(1m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void ReactivatedOrderContinuesFromWhereItStopped()
|
|
{
|
|
// An order that comes back to life after a final snapshot keeps what it had already filled,
|
|
// so the fills that follow count from that point and not from zero.
|
|
var mgr = new StrategyPositionManager(() => "REACTIVATED");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 7m; // matched 3 @100
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.3m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
|
|
// finishes with 3 of 10 filled
|
|
buy.State = OrderStates.Done;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
|
|
// and is reported active again with the very same cumulative fill
|
|
buy.State = OrderStates.Active;
|
|
mgr.ProcessOrder(buy);
|
|
position.CurrentValue.AssertEqual(3m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.3m);
|
|
|
|
// 5 more at 110 make 8 at 106.25 - not 13 and not a fresh basis
|
|
buy.Balance = 2m;
|
|
buy.AveragePrice = 106.25m;
|
|
buy.Commission = 0.8m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
position.CurrentValue.AssertEqual(8m);
|
|
position.AveragePrice.AssertEqual(106.25m);
|
|
(position.Commission ?? 0m).AssertEqual(0.8m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void SameOrderFromAnotherRouteChangesNothing()
|
|
{
|
|
// The same order can arrive as a different Order instance with the same transaction id and
|
|
// the same cumulative state; the instance identity must not turn it into a new fill.
|
|
var mgr = new StrategyPositionManager(() => "DUP_INSTANCE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 8m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 3m; // matched 5 @100
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.5m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(5m);
|
|
|
|
mgr.ProcessOrder(Resend(buy));
|
|
position.CurrentValue.AssertEqual(5m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(0.5m);
|
|
position.BlockedValue.AssertEqual(3m);
|
|
position.BuyOrdersCount.AssertEqual(1);
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m; // matched 8, cumulative average 101
|
|
buy.AveragePrice = 101m;
|
|
buy.Commission = 0.8m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
position.CurrentValue.AssertEqual(8m);
|
|
|
|
mgr.ProcessOrder(Resend(buy)).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(8m);
|
|
position.AveragePrice.AssertEqual(101m);
|
|
(position.Commission ?? 0m).AssertEqual(0.8m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.BuyOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedClosingDoneSnapshotDoesNotReopenLong()
|
|
{
|
|
// The closing order is where a repeat costs most: selling the same volume twice takes the
|
|
// position through flat into a short that was never ordered.
|
|
var mgr = new StrategyPositionManager(() => "DUP_CLOSE_LONG");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 1m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var (sell, _, _) = CreateOrder(Sides.Sell, 10m);
|
|
sell.Security = sec;
|
|
sell.Portfolio = pf;
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m;
|
|
sell.AveragePrice = 110m;
|
|
sell.Commission = 1m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(2m);
|
|
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(2m);
|
|
(position.AveragePrice ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.SellOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedClosingDoneSnapshotDoesNotReopenShort()
|
|
{
|
|
// The same promise from the short side: covering twice must not leave a long behind.
|
|
var mgr = new StrategyPositionManager(() => "DUP_CLOSE_SHORT");
|
|
|
|
var (sell, sec, pf) = CreateOrder(Sides.Sell, 10m);
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m;
|
|
sell.AveragePrice = 100m;
|
|
sell.Commission = 1m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var (buy, _, _) = CreateOrder(Sides.Buy, 10m);
|
|
buy.Security = sec;
|
|
buy.Portfolio = pf;
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 90m;
|
|
buy.Commission = 1m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(100m);
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(2m);
|
|
(position.AveragePrice ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.BuyOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedActiveSnapshotDuringPartialCloseKeepsRealizedPnLAndCommission()
|
|
{
|
|
// Realized PnL and commission are as cumulative as the quantity: a repeated snapshot of a
|
|
// partially filled closing order must not realize the same profit or charge the same fee twice.
|
|
var mgr = new StrategyPositionManager(() => "DUP_CLOSE_ACTIVE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 1m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var (sell, _, _) = CreateOrder(Sides.Sell, 10m);
|
|
sell.Security = sec;
|
|
sell.Portfolio = pf;
|
|
sell.State = OrderStates.Active;
|
|
sell.Balance = 6m; // matched 4 @110
|
|
sell.AveragePrice = 110m;
|
|
sell.Commission = 0.4m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(6m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(40m);
|
|
(position.Commission ?? 0m).AssertEqual(1.4m);
|
|
|
|
mgr.ProcessOrder(sell);
|
|
mgr.ProcessOrder(Resend(sell));
|
|
|
|
position.CurrentValue.AssertEqual(6m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(40m);
|
|
(position.Commission ?? 0m).AssertEqual(1.4m);
|
|
|
|
// the rest of the close still lands exactly once
|
|
sell.Balance = 0m; // matched 10 @110
|
|
sell.Commission = 1m;
|
|
sell.State = OrderStates.Done;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(2m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void StaleSnapshotWithLowerMatchedVolumeChangesNothing()
|
|
{
|
|
// Snapshots can overtake each other. One reporting less filled than is already applied
|
|
// describes the past: it must neither unwind the position nor re-block the volume it names.
|
|
var mgr = new StrategyPositionManager(() => "STALE_ACTIVE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 7m; // matched 3 @100
|
|
buy.AveragePrice = 100m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var stale = Resend(buy);
|
|
|
|
buy.Balance = 2m; // matched 8 @106.25
|
|
buy.AveragePrice = 106.25m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(8m);
|
|
|
|
mgr.ProcessOrder(stale).AssertEqual(StrategyPositionManager.OrderResults.Inconsistent);
|
|
|
|
position.CurrentValue.AssertEqual(8m);
|
|
position.AveragePrice.AssertEqual(106.25m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(2m);
|
|
position.BuyOrdersCount.AssertEqual(1);
|
|
|
|
// the next real fill still applies from 8, not from the stale 3
|
|
buy.Balance = 0m; // matched 10 @107
|
|
buy.AveragePrice = 107m;
|
|
buy.State = OrderStates.Done;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(107m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void StaleActiveSnapshotAfterDoneChangesNothing()
|
|
{
|
|
// A late Active snapshot of an order that has already finished repeats fills that are
|
|
// applied and volume that is no longer blocked, and so must a repeat of the final one
|
|
// arriving behind it.
|
|
var mgr = new StrategyPositionManager(() => "STALE_AFTER_DONE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 4m; // matched 6 @100
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.6m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var done = Resend(buy);
|
|
done.State = OrderStates.Done;
|
|
done.Balance = 0m; // matched 10 @100
|
|
done.Commission = 1m;
|
|
mgr.ProcessOrder(done).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(10m);
|
|
(position.Commission ?? 0m).AssertEqual(1m);
|
|
|
|
// the earlier snapshot finally arrives
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.Inconsistent);
|
|
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(1m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.BuyOrdersCount.AssertEqual(0);
|
|
|
|
// and the final snapshot repeats behind it
|
|
mgr.ProcessOrder(done);
|
|
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(1m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedDoneSnapshotWithLowerMatchedVolumeChangesNothing()
|
|
{
|
|
// A final snapshot repeating with less filled than was applied is a stale copy of the
|
|
// order's own history and must not take part of the position back.
|
|
var mgr = new StrategyPositionManager(() => "STALE_DONE");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 4m; // matched 6 @100
|
|
buy.AveragePrice = 100m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var stalePartial = Resend(buy);
|
|
stalePartial.State = OrderStates.Done;
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m; // matched 10 @100
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(10m);
|
|
|
|
mgr.ProcessOrder(stalePartial).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void RepeatedMarketOrderDoneSnapshotDoesNotRefillAtNewPrice()
|
|
{
|
|
// A market order with no average price of its own is valued at the last known price.
|
|
// Replaying its final snapshot after the market moved must not fill it again at the new one.
|
|
var mgr = new StrategyPositionManager(() => "DUP_MARKET");
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 5m);
|
|
var now = DateTime.UtcNow;
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 100m, now, now);
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m;
|
|
buy.Type = OrderTypes.Market;
|
|
buy.AveragePrice = null;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(5m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
|
|
var later = now.AddMinutes(1);
|
|
mgr.UpdateCurrentPrice(sec.ToSecurityId(), 200m, later, later);
|
|
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
position.CurrentValue.AssertEqual(5m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(0m);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
|
|
[TestMethod]
|
|
public void DuplicatedSnapshotsThroughoutRoundTripEndFlat()
|
|
{
|
|
// The property end to end: every snapshot of an open-and-close round trip delivered twice.
|
|
// The result must be the flat position, PnL and commission of a single round trip.
|
|
var mgr = new StrategyPositionManager(() => "DUP_ROUND_TRIP");
|
|
Position processed = null;
|
|
mgr.PositionProcessed += (p, _) => processed = p;
|
|
|
|
var (buy, sec, pf) = CreateOrder(Sides.Buy, 10m);
|
|
buy.State = OrderStates.Active;
|
|
buy.Balance = 6m; // matched 4 @100
|
|
buy.AveragePrice = 100m;
|
|
buy.Commission = 0.4m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(Resend(buy));
|
|
|
|
buy.State = OrderStates.Done;
|
|
buy.Balance = 0m; // matched 10 @100
|
|
buy.Commission = 1m;
|
|
mgr.ProcessOrder(buy).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(Resend(buy)).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
var position = mgr.TryGetPosition(sec, pf);
|
|
position.CurrentValue.AssertEqual(10m);
|
|
position.AveragePrice.AssertEqual(100m);
|
|
(position.Commission ?? 0m).AssertEqual(1m);
|
|
|
|
var (sell, _, _) = CreateOrder(Sides.Sell, 10m);
|
|
sell.Security = sec;
|
|
sell.Portfolio = pf;
|
|
sell.State = OrderStates.Active;
|
|
sell.Balance = 4m; // matched 6 @120
|
|
sell.AveragePrice = 120m;
|
|
sell.Commission = 0.6m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(Resend(sell));
|
|
|
|
position.CurrentValue.AssertEqual(4m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(120m);
|
|
|
|
sell.State = OrderStates.Done;
|
|
sell.Balance = 0m; // matched 10 @120
|
|
sell.Commission = 1m;
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.OK);
|
|
mgr.ProcessOrder(Resend(sell)).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
mgr.ProcessOrder(sell).AssertEqual(StrategyPositionManager.OrderResults.AlreadyFinished);
|
|
|
|
mgr.Positions.Length.AssertEqual(1);
|
|
processed.AssertSame(position);
|
|
position.CurrentValue.AssertEqual(0m);
|
|
(position.AveragePrice ?? 0m).AssertEqual(0m);
|
|
(position.RealizedPnL ?? 0m).AssertEqual(200m);
|
|
(position.Commission ?? 0m).AssertEqual(2m);
|
|
position.BlockedValue.AssertEqual(0m);
|
|
position.BuyOrdersCount.AssertEqual(0);
|
|
position.SellOrdersCount.AssertEqual(0);
|
|
AssertCalcFieldsNonNull(position);
|
|
}
|
|
}
|