Example of the basic strategy of posting a stop loss and take profit.
Whenever the current position changes, the strategy cancels previous orders and posts new ones at the 20 tick distance from the position price.
public class SampleStopProfit : ATMStrategy
{
protected override void OnActivated()
{
Process();
}
protected override void OnCurrentPositionChanged()
{
Process();
}
private void Process()
{
if (!IsActivated)
return;
CancelAllOrders();
if (CurrentPosition == 0)
return;
var take = new Order
{
Security = Security,
Portfolio = Portfolio,
Type = OrderTypes.Limit,
Direction = CurrentPosition > 0 ? OrderDirections.Sell : OrderDirections.Buy,
Price = AveragePrice + 20 * Security.TickSize * (CurrentPosition > 0 ? 1 : -1),
QuantityToFill = Math.Abs(CurrentPosition),
Comment = "TP",
};
OpenOrder(take);
var stop = new Order
{
Security = Security,
Portfolio = Portfolio,
Type = OrderTypes.Stop,
Direction = CurrentPosition > 0 ? OrderDirections.Sell : OrderDirections.Buy,
TriggerPrice = AveragePrice - 20 * Security.TickSize * (CurrentPosition > 0 ? 1 : -1),
QuantityToFill = Math.Abs(CurrentPosition),
Comment = "TP",
};
OpenOrder(stop);
}
private void CancelAllOrders()
{
foreach (var order in Orders.Where(t=>t.State==OrderStates.Active))
{
CancelOrder(order);
}
}
}
Was this article helpful?
That’s Great!
Thank you for your feedback
Sorry! We couldn't be helpful
Thank you for your feedback
Feedback sent
We appreciate your effort and will try to fix the article