How to close all opened positions
Please place C# example (HowTo) close all positions.
Hi, Eugeny!
You have next options to do it:
1. Directly from code:
- To close all positions
foreach (var position in Positions.GetPositions()) position.Close();
- To close all positions which belong to specific instrument by name, for example EUR/USD:
foreach (var position in Positions.GetPositions().Where(position => position.Instrument.BaseName == "EUR/USD")) position.Close();
2. Use macros example "ClosePosition" which will perfectly fit:
using System; using System.Collections.Generic; using PTLRuntime.NETScript; using System.Drawing; using System.Linq; using System.Text; namespace ClosePosition { /// <summary> /// ClosePosition /// </summary> public class ClosePosition : NETStrategy { #region Patameters [InputParameter("Close position", 0)] public PositionSide OperationType = PositionSide.All; [InputParameter("PL type", 1)] public ProfitLossType PlType = ProfitLossType.Positive; [InputParameter("Instrument", 2, 141)] public Instrument SelectedInstument; #endregion public ClosePosition() : base() { } /// <summary> /// This function will be called for macros activation /// </summary> public override void OnQuote() { Position[] positions = Positions.GetPositions(); if (SelectedInstument != null) positions = positions.Where(position => position.Instrument == SelectedInstument).ToArray(); // Select positions according to instrument if (OperationType != PositionSide.All) positions = positions.Where(position => position.Side == (Operation)OperationType).ToArray(); // Select positions according to side if (PlType == ProfitLossType.Positive) positions = positions.Where(position => position.GetProfitGross() > 0).ToArray(); // Select profitable positions else if (PlType == ProfitLossType.Negative) positions = positions.Where(position => position.GetProfitGross() < 0).ToArray(); // Select losing positions foreach (var position in positions) position.Close(); } } public enum ProfitLossType { Positive, Negative } public enum PositionSide { Buy = 10000, Sell = 10001, All = 10002 } }
Macros is a some kind of one lap running strategy. You can run it by attaching some specific short-key:
1. Crate a new blank "ClosePosition,cs" file and place into it given code.
2. Select Enviroment -> General Settings -> Hotkeys
3. Click on "+" -> "Run Macros"(after pressing hotkey the macros properties window will appear) / "Quick run macros"(without settings window appearing, it will launch with default settings)
4. In "Script lookup" window click on "Import" button and select "ClosePosition,cs" file
5. In "General settings" under the "User action" row will appear row with your macros. You just need to attach to it hotkey by clicking on <None> cell.
After this manipulation you can run it directly from terminal by pressing shortkey.
Regards!