Hi all,
I am trying to create a strategy that sell an existing position at a certain level. It’s not really a strategy, but I am using it as a tool for me to sell my position.
When I turn on the strategy, the Sync column would show False. If I set my StartBehavior to Sync, then it would submit an order to buy the position instead of detecting my existing position.
I have attached the strategy for your reference.
else if (State == State.Realtime)
{
var pos = Account.Positions.FirstOrDefault(p => p.Instrument == Instrument);
if (pos != null)
Print("Account position found: " + pos.MarketPosition + " Qty: " + pos.Quantity);
else
Print("No account position found for " + Instrument.FullName);
}
protected override void OnBarUpdate()
{
if (CurrentBar < BarsRequiredToTrade)
return;
// Get actual account position instead of strategy position
int accountQty = 0;
MarketPosition accountPosition = MarketPosition.Flat;
var pos = Account.Positions.FirstOrDefault(p => p.Instrument == Instrument);
if (pos != null)
{
accountQty = pos.Quantity;
accountPosition = pos.MarketPosition;
}
// Use account position for checks
if (accountPosition == MarketPosition.Flat)
return;
else if (accountPosition == MarketPosition.Long)
{
if (Direction != SellTradeDirection.Sell)
return;
}
else if (accountPosition == MarketPosition.Short)
{
if (Direction != SellTradeDirection.Cover)
return;
}
if (_sts == 0)
return;
// cancel the order after X minutes if it was not executed
if (this._limitOrder != null &&
Time[0] > this._limitOrder.Time.AddMinutes(CancelAfterMinutes))
{
CancelOrder(this._limitOrder);
this._limitOrder = null;
Print("Cancelled: replace order " + CancelAfterMinutes + " minutes");
return;
}
if (BarsInProgress == 1) // seconds
{
// Don't submit if we already have a pending order
if (_limitOrder != null)
return;
if (_sts > 0)
{
if (accountPosition == MarketPosition.Long && Direction == SellTradeDirection.Sell)
{
if (SellNow)
{
_limitOrder = ExitLongLimit(0, true, _sts, Close[0], "ExitLong", "");
return;
}
else if (SellAt > 0 && Close[0] >= SellAt)
{
_limitOrder = ExitLongLimit(0, true, _sts, SellAt, "ExitLong", "");
return;
}
}
else if (accountPosition == MarketPosition.Short && Direction == SellTradeDirection.Cover)
{
if (SellNow)
{
_limitOrder = ExitShortLimit(0, true, _sts, Close[0], "ExitShort", "");
return;
}
if (SellAt > 0 && Close[0] <= SellAt)
{
_limitOrder = ExitShortLimit(0, true, _sts, SellAt, "ExitShort", "");
return;
}
}
}
return;
}
}
