Issue Closing positions from an Indicator

Created at 11 Jun 2024, 16:46
How’s your experience with the cTrader Platform?
Your feedback is crucial to cTrader's development. Please take a few seconds to share your opinion and help us improve your trading experience. Thanks!
JI

jim.tollan

Joined 23.02.2023

Issue Closing positions from an Indicator
11 Jun 2024, 16:46


Hello all - first off, I searched to see if I could find any references that stated that open positions could NOT be closed from an indicator and found none. However, I'm suspecting that this may be the case and have supplied a small test example below.

Basically, as part of bigger functionality, i'd like to have a very simple indicator that basically sows 2 buttons (one for long one for short trades) which wehn clicked, would close all open trades of the given trade type on the target currency on the chart. The example below does almost everything apart from closing the position and I wondered if anyone could chip and advise why this isn't working as expected:

using cAlgo.API;
using System;
using System.Linq;


namespace cAlgo
{
    [Indicator(IsOverlay = true, TimeZone = TimeZones.UTC, AccessRights = AccessRights.FullAccess)]
    public class OpenPositions : Indicator
    {
        private int longPositions;
        private int shortPositions;
        private Button longTextBlock;
        private Button shortTextBlock;
        private MessageBoxResult result;

        protected override void Initialize()
        {
            longTextBlock = new Button
            {
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                Margin = "5 5 5 5",
                BackgroundColor = Color.Green,
            };

            shortTextBlock = new Button
            {
                HorizontalAlignment = HorizontalAlignment.Right,
                VerticalAlignment = VerticalAlignment.Top,
                Margin = "5 25 5 5",
                BackgroundColor = Color.Red
            };

            longTextBlock.Click += LongTextBlock_Click;
            shortTextBlock.Click += ShortTextBlock_Click;

            Chart.AddControl(longTextBlock);
            Chart.AddControl(shortTextBlock);
        }

        private void ShortTextBlock_Click(ButtonClickEventArgs args)
        {
            result = MessageBox.Show(args.Button.Text, "Close Short Trades",
                MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);

            if (result == MessageBoxResult.Yes)
                ClosePositions(TradeType.Sell);
        }

        private void LongTextBlock_Click(ButtonClickEventArgs args)
        {
            result = MessageBox.Show(args.Button.Text, "Close Long Trades",
                MessageBoxButton.YesNo, MessageBoxImage.Warning, MessageBoxResult.No);

            if (result == MessageBoxResult.Yes)
                ClosePositions(TradeType.Buy);
        }

        private void ClosePositions(TradeType tradeType)
        {
            try
            {
                var openPositions = Positions.Where(x => x.Symbol == Symbol
                    && x.TradeType == tradeType);

                foreach (var position in openPositions)
                {
                    // this causes an error due to context
                    // and state of object
                    var apiResult = position.Close();

                    Print(apiResult.IsSuccessful);
                }
            }
            catch (Exception ex)
            {
                Print("Error during position closing: " + ex.Message);
            }
        }
        public override void Calculate(int index)
        {
            longPositions = 0;
            shortPositions = 0;

            double longProfit = 0;
            double shortProfit = 0;

            foreach (var position in Positions)
            {
                if (position.Symbol == Symbol)
                {
                    if (position.TradeType == TradeType.Buy)
                    {
                        longPositions++;
                        longProfit += position.NetProfit;
                    }
                    else if (position.TradeType == TradeType.Sell)
                    {
                        shortPositions++;
                        shortProfit += position.NetProfit;
                    }
                }
            }

            var longTextBlockText = $"Long Positions: {longPositions.ToString().PadRight(3, ' ')} " +
                $"[{longProfit.ToString("0.0").PadLeft(10, ' ')}]";

            var shortTextBlockText = $"Shrt Positions: {shortPositions.ToString().PadRight(3, ' ')} " +
                $"[{shortProfit.ToString("0.0").PadLeft(10, ' ')}]";

            longTextBlock.Text = string.Format("{0,-36}", longTextBlockText);
            shortTextBlock.Text = string.Format("{0,-36}", shortTextBlockText);
        }
    }
}

@jim.tollan
Replies

PanagiotisCharalampous
12 Jun 2024, 06:14

Hi Jim,

I tried this and works fine for me. Can you please provide more information demonstrating what you report e.g. screenshots, videos, logs etc?

Best regards,

Panagiotis


@PanagiotisCharalampous

jim.tollan
12 Jun 2024, 08:20 ( Updated at: 12 Jun 2024, 08:26 )

RE: Issue Closing positions from an Indicator

PanagiotisCharalampous said: 

Hi Jim,

I tried this and works fine for me. Can you please provide more information demonstrating what you report e.g. screenshots, videos, logs etc?

Best regards,

Panagiotis

Sure, when I click (for example), the Green button to close the longs, I get the messagebox window popping up, which is as expected. However, the action on closing the Position(s) doesn't appear to be working.

Action trail:

Then:

 

The log reports the following error:

From previous experiences, this can sometimes indicate that an action is being attempted across different threads (UI and worker). I can't say for sure what this might be the issue or not. All I can say is that it's consistent across a number of different charts/forex pairs. Would be great to figure this out as it's part of a larger piece using this type of approach.

Thanks again

jim

btw - I'm using the Raw Trader version of the software, but the same thing still occurs on v4.8.30


@jim.tollan

PanagiotisCharalampous
12 Jun 2024, 08:27

RE: RE: Issue Closing positions from an Indicator

jim.tollan said: 

PanagiotisCharalampous said: 

Hi Jim,

I tried this and works fine for me. Can you please provide more information demonstrating what you report e.g. screenshots, videos, logs etc?

Best regards,

Panagiotis

Sure, when I click (for example), the Green button to close the longs, I get the messagebox window poping up, which is as expected. However, the action on closing the Position(s) doesn't appear to be working.

Action trail:

Then:

 

The log reports the following error:

From previous experiences, this can sometimes indicate that an action is being attempted across different threads (UI and worker). I can't say for sure what this might be the issue or not. All I can say is that it's consistent across a number of different charts/forex pairs. Would be great to figure this out as it's part of a larger piece using this type of approach.

Thanks again

jim

btw - I'm using the Raw Trader version of the software, but the smae thing still occurs on v4.8.30

Hi Jim,

This option is only available in cTrader v5.0.

Best regards,

Panagiotis


@PanagiotisCharalampous

jim.tollan
12 Jun 2024, 08:30

RE: RE: RE: Issue Closing positions from an Indicator

PanagiotisCharalampous said: 

Hi Jim,This option is only available in cTrader v5.0.

Best regards,

Panagiotis

Problem solved then :). I knew it must be a simple fix. I won't be updating to v5 until my broker does, so I guess I'll have to wait for that.

Thanks for your speedy response and for saving me going round the houses trying fixes on this.

Cheers

jim


@jim.tollan

jim.tollan
13 Jun 2024, 09:27 ( Updated at: 13 Jun 2024, 09:30 )

RE: RE: RE: RE: Issue Closing positions from an Indicator

jim.tollan said: 

PanagiotisCharalampous said: 

Hi Jim,This option is only available in cTrader v5.0.

Best regards,

Panagiotis

Problem solved then :). I knew it must be a simple fix. I won't be updating to v5 until my broker does, so I guess I'll have to wait for that.

Thanks for your speedy response and for saving me going round the houses trying fixes on this.

Cheers

jim

can confirm that this all works with v5.x. and did ask for additional permissions before actioning it. I know that v4.xx development will have ceased, but is there any chance of a hotfix for this on the broker versions that will be on v4.xx for some time to come?? it's such a useful feature to have all position based actions available via the indicator.


@jim.tollan

PanagiotisCharalampous
13 Jun 2024, 10:23

RE: RE: RE: RE: RE: Issue Closing positions from an Indicator

jim.tollan said: 

jim.tollan said: 

PanagiotisCharalampous said: 

Hi Jim,This option is only available in cTrader v5.0.

Best regards,

Panagiotis

Problem solved then :). I knew it must be a simple fix. I won't be updating to v5 until my broker does, so I guess I'll have to wait for that.

Thanks for your speedy response and for saving me going round the houses trying fixes on this.

Cheers

jim

can confirm that this all works with v5.x. and did ask for additional permissions before actioning it. I know that v4.xx development will have ceased, but is there any chance of a hotfix for this on the broker versions that will be on v4.xx for some time to come?? it's such a useful feature to have all position based actions available via the indicator.

Nope :) You would need to wait for 5.0


@PanagiotisCharalampous

jim.tollan
13 Jun 2024, 10:39

RE: RE: RE: RE: RE: RE: Issue Closing positions from an Indicator

PanagiotisCharalampous said: 

jim.tollan said: 

jim.tollan said: 

PanagiotisCharalampous said: 

Hi Jim,This option is only available in cTrader v5.0.

Best regards,

Panagiotis

Problem solved then :). I knew it must be a simple fix. I won't be updating to v5 until my broker does, so I guess I'll have to wait for that.

Thanks for your speedy response and for saving me going round the houses trying fixes on this.

Cheers

jim

can confirm that this all works with v5.x. and did ask for additional permissions before actioning it. I know that v4.xx development will have ceased, but is there any chance of a hotfix for this on the broker versions that will be on v4.xx for some time to come?? it's such a useful feature to have all position based actions available via the indicator.

Nope :) You would need to wait for 5.0

got it!! :) :)


@jim.tollan