Adding to position and moving stop loss

Created at 15 Dec 2024, 15:34
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!
AL

algobeginner

Joined 15.12.2024

Adding to position and moving stop loss
15 Dec 2024, 15:34


Hello 

I'm currently starting to write Algo , I found very useful the examples (sometimes a little bit confusing as it evolves through versions)

I tried to use ChatGPT to modify Three Crows/Soldiers example to get desired result of :

 Logic what I would like to add in script : 0.01 position open at 1.1000 with buy after 3rd positive bar , the price reach 1.1005 so another position 0.01 open and modify stop loss by 5 pips on first position ,with open second position same stop loss level as 1st position  )

This is error I'm getting in built :

Error CS0029: Cannot implicitly convert type 'cAlgo.API.TradeResult' to 'cAlgo.API.Position' (/Users//cAlgo/Sources/Robots/Three Crow Soldiers Adding/Three Crow Soldiers Adding/Three Crow Soldiers Adding.cs, line: 45, column: 37)

Error CS0029: Cannot implicitly convert type 'cAlgo.API.TradeResult' to 'cAlgo.API.Position' (/Users/cAlgo/Sources/Robots/Three Crow Soldiers Adding/Three Crow Soldiers Adding/Three Crow Soldiers Adding.cs, line: 73, column: 37)

The code is here generated by ChatGPT as update for my request and what I used :

using System;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None, AddIndicators = true)]
    public class ThreeWhiteSoldiersandThreeCrows : Robot
    {
        [Parameter(DefaultValue = 1000)]
        public double Volume { get; set; }
        
        [Parameter(DefaultValue = 10)]
        public double TakeProfit { get; set; }
        
        [Parameter(DefaultValue = 10)]
        public double StopLoss { get; set; }

        [Parameter(DefaultValue = 5)]
        public double ProfitTargetPips { get; set; }  // Parameter for 5 pips profit trigger

        private Position firstPosition = null;

        protected override void OnStart()
        {
            // Initialize any necessary parameters
        }

        protected override void OnTick()
        {
            // Handle price updates here
        }

        protected override void OnBar()
        {
            // Three White Soldiers
            if (Bars.ClosePrices.Last(1) > Bars.OpenPrices.Last(1) 
                && Bars.ClosePrices.Last(2) > Bars.OpenPrices.Last(2)  
                && Bars.ClosePrices.Last(3) > Bars.OpenPrices.Last(3))
            {
                if (firstPosition == null)  // No position open yet
                {
                    firstPosition = ExecuteMarketOrder(TradeType.Buy, SymbolName, Volume, "Three White Soldiers", StopLoss, TakeProfit);
                }
                else
                {
                    // Check if the position has moved 5 pips in profit
                    double currentPrice = Symbol.Bid;
                    double entryPrice = firstPosition.EntryPrice;
                    double priceDifference = currentPrice - entryPrice;

                    if (priceDifference >= ProfitTargetPips * Symbol.PipSize)
                    {
                        // Open a new position with the same size
                        ExecuteMarketOrder(TradeType.Buy, SymbolName, Volume, "Three White Soldiers", StopLoss, TakeProfit);

                        // Move the stop loss of the first position
                        double newStopLoss = entryPrice + (ProfitTargetPips * Symbol.PipSize);
                        ModifyPosition(firstPosition, newStopLoss, firstPosition.TakeProfit);
                    }
                }
            }

            // Three Black Crows
            if (Bars.ClosePrices.Last(1) < Bars.OpenPrices.Last(1) 
                && Bars.ClosePrices.Last(2) < Bars.OpenPrices.Last(2)  
                && Bars.ClosePrices.Last(3) < Bars.OpenPrices.Last(3))
            {
                if (firstPosition == null)  // No position open yet
                {
                    firstPosition = ExecuteMarketOrder(TradeType.Sell, SymbolName, Volume, "Three Black Crows", StopLoss, TakeProfit);
                }
                else
                {
                    // Check if the position has moved 5 pips in profit
                    double currentPrice = Symbol.Ask;
                    double entryPrice = firstPosition.EntryPrice;
                    double priceDifference = entryPrice - currentPrice;

                    if (priceDifference >= ProfitTargetPips * Symbol.PipSize)
                    {
                        // Open a new position with the same size
                        ExecuteMarketOrder(TradeType.Sell, SymbolName, Volume, "Three Black Crows", StopLoss, TakeProfit);

                        // Move the stop loss of the first position
                        double newStopLoss = entryPrice - (ProfitTargetPips * Symbol.PipSize);
                        ModifyPosition(firstPosition, newStopLoss, firstPosition.TakeProfit);
                    }
                }
            }
        }

        protected override void OnStop()
        {
            // Handle cBot stop here
        }
    }
}

@algobeginner
Replies

algobeginner
16 Dec 2024, 11:31

I tried to update it and make it only buy for example on three white soldiers

I have tried to simplify it and make it easier but still struggling to make logic of existingBuyPosition or existingSellPositions with some label and find function, 

 

private void HandleBuyOrder()
        {
            var existingBuyPositions = Positions.FindAll(BuyLabel, TradeType.Buy);
            if (existingBuyPositions.Length > 0)
            {
                // Check if the first position has reached 5 pips profit
                var firstPosition = existingBuyPositions[0];
                if (firstPosition.GrossProfit >= 5 * PipSize)
                {
                    // Adjust the stop loss of the first position
                    adjustedStopLoss = firstPosition.StopLoss + 5 * PipSize;
                    var modifyResult = ModifyPosition(firstPosition, adjustedStopLoss, firstPosition.TakeProfit);
                    if (!modifyResult.IsSuccessful)
                    {
                        Print("Failed to modify position: " + modifyResult.Error);
                    }
                    
                    // Open a new position
                    var orderResult = ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, BuyLabel, StopLoss, TakeProfit);
                    if (!orderResult.IsSuccessful)
                    {
                        Print("Failed to execute market order: " + orderResult.Error);
                    }
                }
            }
            else
            {
                // No existing buy positions, open a new one
                var orderResult = ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, BuyLabel, StopLoss, TakeProfit);
                if (!orderResult.IsSuccessful)
                {
                    Print("Failed to execute market order: " + orderResult.Error);
                }

@algobeginner

algobeginner
16 Dec 2024, 11:31 ( Updated at: 16 Dec 2024, 11:53 )

I tried to update it and make it only buy for example on three white soldiers

This code seem to work , can someone make it better to use less resources ?

 

using System;
using cAlgo.API;
using cAlgo.API.Collections;
using cAlgo.API.Indicators;
using cAlgo.API.Internals;

namespace cAlgo.Robots
{
    [Robot(AccessRights = AccessRights.None, AddIndicators = true)]
    public class ThreeWhiteSoldiersandThreeCrows : Robot
    {
        [Parameter(DefaultValue = 1000)]
        public double Volume { get; set; }

        [Parameter(DefaultValue = 10)]
        public double TakeProfit { get; set; }

        [Parameter(DefaultValue = 10)]
        public double StopLoss { get; set; }

        private const double PipSize = 0.0001; // Adjust this for different instruments (e.g., 0.01 for JPY pairs)
        private double adjustedStopLoss;

        // Define string constants for position labels
        private const string BuyLabel = "Three White Soldiers";

        protected override void OnBar()
        {
            // Three White Soldiers
            if (Bars.ClosePrices.Last(1) > Bars.OpenPrices.Last(1)
                && Bars.ClosePrices.Last(2) > Bars.OpenPrices.Last(2)
                && Bars.ClosePrices.Last(3) > Bars.OpenPrices.Last(3))
            {
                HandleBuyOrder();
            }
        }

        private void HandleBuyOrder()
        {
            var existingBuyPositions = Positions.FindAll(BuyLabel); // Fix: Use string label here
            if (existingBuyPositions.Length > 0)
            {
                // Check if the first position has reached 5 pips profit
                var firstPosition = existingBuyPositions[0];
                if (firstPosition.GrossProfit >= 5 * PipSize)
                {
                    // Adjust the stop loss of the first position
                    adjustedStopLoss = (firstPosition.StopLoss ?? 0) + 5 * PipSize; // Fix: Handle nullable StopLoss
                    var modifyResult = ModifyPosition(firstPosition, adjustedStopLoss, firstPosition.TakeProfit);
                    if (!modifyResult.IsSuccessful)
                    {
                        Print("Failed to modify position: " + modifyResult.Error);
                    }

                    // Open a new position
                    var orderResult = ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, BuyLabel, StopLoss, TakeProfit);
                    if (!orderResult.IsSuccessful)
                    {
                        Print("Failed to execute market order: " + orderResult.Error);
                    }
                }
            }
            else
            {
                // No existing buy positions, open a new one
                var orderResult = ExecuteMarketOrder(TradeType.Buy, Symbol.Name, Volume, BuyLabel, StopLoss, TakeProfit);
                if (!orderResult.IsSuccessful)
                {
                    Print("Failed to execute market order: " + orderResult.Error);
                }
            }
        }
    }
}

@algobeginner